diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 000000000..91bdfb44f
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,1466 @@
+// Avoid looking for .editorconfig files in parent directories
+root=true
+
+[*]
+
+insert_final_newline = true
+indent_style = space
+indent_size = 4
+tab_width = 4
+end_of_line = crlf
+
+[*.{xml,csproj,props}]
+
+indent_size = 2
+tab_width = 2
+
+[*.cs]
+
+#### Sonar rules ####
+
+# S101: Types should be named in PascalCase
+# https://rules.sonarsource.com/csharp/RSPEC-101
+#
+# TODO: Remove this when code has been updated!
+dotnet_diagnostic.S101.severity = none
+
+# S112: General exceptions should never be thrown
+# https://rules.sonarsource.com/csharp/RSPEC-112
+#
+# This is a duplicate of CA2201 and MA0012.
+dotnet_diagnostic.S112.severity = none
+
+# S907: Remove use of 'goto'
+# https://rules.sonarsource.com/csharp/RSPEC-907
+#
+# Limited use of 'goto' is accepted when performance is critical.
+dotnet_diagnostic.S907.severity = none
+
+# S1066: Collapsible "if" statements should be merged
+# https://rules.sonarsource.com/csharp/RSPEC-1066
+#
+dotnet_diagnostic.S1066.severity = none
+
+# S1075: URIs should not be hardcoded
+# https://rules.sonarsource.com/csharp/RSPEC-1075
+#
+# The rule reports false positives for XML namespaces.
+dotnet_diagnostic.S1075.severity = none
+
+# S1104: Fields should not have public accessibility
+# https://rules.sonarsource.com/csharp/RSPEC-1104
+#
+# This is a duplicate of SA1401 and CA1051.
+dotnet_diagnostic.S1104.severity = none
+
+# S1125: Boolean literals should not be redundant
+# https://rules.sonarsource.com/csharp/RSPEC-1125
+#
+# This is a duplicate of MA0073.
+dotnet_diagnostic.S1125.severity = none
+
+# S1135: Track uses of "TODO" tags
+#
+# This is a duplicate of MA0026.
+dotnet_diagnostic.S1135.severity = none
+
+# S1168: Empty arrays and collections should be returned instead of null
+# https://rules.sonarsource.com/csharp/RSPEC-1168
+#
+# We sometimes return null to avoid allocating an empty List.
+dotnet_diagnostic.S1168.severity = none
+
+# S1144: Unused private types or members should be removed
+# https://rules.sonarsource.com/csharp/RSPEC-1144
+#
+# This is a duplicate of IDE0051.
+dotnet_diagnostic.S1144.severity = none
+
+# S1172: Unused method parameters should be removed
+# https://rules.sonarsource.com/csharp/RSPEC-1172
+#
+# This is a duplicate of IDE0060.
+dotnet_diagnostic.S1172.severity = none
+
+# S1481: Unused local variables should be removed
+# https://rules.sonarsource.com/csharp/RSPEC-1481
+#
+# This is a duplicate of IDE0059.
+dotnet_diagnostic.S1481.severity = none
+
+# S1854: Unused assignments should be removed
+# https://rules.sonarsource.com/csharp/RSPEC-1854
+#
+# This is a duplicate of IDE0059.
+dotnet_diagnostic.S1854.severity = none
+
+# S1944: Invalid casts should be avoided
+# https://rules.sonarsource.com/csharp/RSPEC-1944/
+#
+# Disabled due to build performance impact.
+dotnet_diagnostic.S1944.severity = none
+
+# S2053: Hashes should include an unpredictable salt
+# https://rules.sonarsource.com/csharp/RSPEC-2053/
+#
+# Disabled due to build performance impact /
+# We need to specify the salt.
+dotnet_diagnostic.S2053.severity = none
+
+# S2259: Null pointers should not be dereferenced
+# https://rules.sonarsource.com/csharp/RSPEC-2259
+#
+# The analysis is not precise enough, leading to false positives.
+dotnet_diagnostic.S2259.severity = none
+
+# S2292: Trivial properties should be auto-implemented
+# https://rules.sonarsource.com/csharp/RSPEC-2292
+#
+# This is a duplicate of IDE0032.
+dotnet_diagnostic.S2292.severity = none
+
+# S2445: Blocks should be synchronized on read-only fields
+# https://rules.sonarsource.com/csharp/RSPEC-2445
+#
+# This is a (partial) duplicate of MA0064.
+dotnet_diagnostic.S2445.severity = none
+
+# S2551: Shared resources should not be used for locking
+# https://rules.sonarsource.com/csharp/RSPEC-2551
+#
+# This is a duplicate of CA2002, and partial duplicate of MA0064.
+dotnet_diagnostic.S2551.severity = none
+
+# S2583: Conditionally executed code should be reachable
+# https://rules.sonarsource.com/csharp/RSPEC-2583
+#
+# Disabled due to build performance impact /
+# This rule produces false errors in, for example, for loops.
+dotnet_diagnostic.S2583.severity = none
+
+# S2699: Tests should include assertions
+# https://rules.sonarsource.com/csharp/RSPEC-2699
+#
+# Sometimes you want a test in which you invoke a method and just want to verify that it does not throw.
+# For example:
+# [TestMethod]
+# public void InvokeDisposeWithoutNotifyObjectShouldNotThrow()
+# {
+# _timer.Dispose();
+# }
+dotnet_diagnostic.S2699.severity = none
+
+# S2930: "IDisposables" should be disposed
+# https://rules.sonarsource.com/csharp/RSPEC-2930/
+#
+# Duplicate of CA2000.
+dotnet_diagnostic.S2930.severity = none
+
+# S2933: Fields that are only assigned in the constructor should be "readonly"
+# https://rules.sonarsource.com/csharp/RSPEC-2933
+#
+# This is a duplicate of IDE0044, but IDE0044 is not reported when targeting .NET Framework 4.8.
+dotnet_diagnostic.S2933.severity = none
+
+# S2971: "IEnumerable" LINQs should be simplified
+# https://rules.sonarsource.com/csharp/RSPEC-2971
+#
+# This is a duplicate of MA0020.
+dotnet_diagnostic.S2971.severity = none
+
+# S3218: Inner class members should not shadow outer class "static" or type members
+# https://rules.sonarsource.com/csharp/RSPEC-3218
+#
+# This is rather harmless.
+dotnet_diagnostic.S3218.severity = none
+
+# S3267: Loops should be simplified with "LINQ" expressions
+# https://rules.sonarsource.com/csharp/RSPEC-3267
+#
+# LINQ is the root of all evil :p
+dotnet_diagnostic.S3267.severity = none
+
+# S3329: Cipher Block Chaining IVs should be unpredictable
+# https://rules.sonarsource.com/csharp/RSPEC-3329/
+dotnet_diagnostic.S3329.severity = none
+
+# S3376: Attribute, EventArgs, and Exception type names should end with the type being extended
+# https://rules.sonarsource.com/csharp/RSPEC-3376
+#
+# This is a partial duplicate of MA0058. If we enable the Sonar in all repositories, we should
+# consider enabling S3376 in favor of MA0058.
+dotnet_diagnostic.S3376.severity = none
+
+# S3442: "abstract" classes should not have "public" constructors
+# https://rules.sonarsource.com/csharp/RSPEC-3442
+#
+# This is a duplicate of MA0017.
+dotnet_diagnostic.S3442.severity = none
+
+# S3450: Parameters with "[DefaultParameterValue]" attributes should also be marked "[Optional]"
+# https://rules.sonarsource.com/csharp/RSPEC-3450
+#
+# This is a duplicate of MA0087.
+dotnet_diagnostic.S3450.severity = none
+
+# S3459: Unassigned members should be removed
+# https://rules.sonarsource.com/csharp/RSPEC-3459/
+#
+# Duplicate of IDE0051/IDE0052
+dotnet_diagnostic.S3459.severity = none
+
+# S3626: Jump statements should not be redundant
+# https://rules.sonarsource.com/csharp/RSPEC-3626/
+#
+# Disabled due to build performance impact.
+dotnet_diagnostic.S3626.severity = none
+
+# S3655: Empty nullable value should not be accessed
+# https://rules.sonarsource.com/csharp/RSPEC-3655/
+#
+# Disabled due to build performance impact.
+dotnet_diagnostic.S3655.severity = none
+
+# S3871: Exception types should be "public"
+# https://rules.sonarsource.com/csharp/RSPEC-3871
+#
+# This is a duplicate of CA1064.
+dotnet_diagnostic.S3871.severity = none
+
+# S3900: Arguments of public methods should be validated against null
+# https://rules.sonarsource.com/csharp/RSPEC-3900/
+#
+# This is a duplicate of CA1062.
+dotnet_diagnostic.S3900.severity = none
+
+# S3903: Types should be defined in named namespaces
+# https://rules.sonarsource.com/csharp/RSPEC-3903
+#
+# This is a duplicate of MA0047.
+dotnet_diagnostic.S3903.severity = none
+
+# S3925: "ISerializable" should be implemented correctly
+# https://rules.sonarsource.com/csharp/RSPEC-3925
+#
+# This is a duplicate of CA2229.
+dotnet_diagnostic.S3925.severity = none
+
+# S3928: Parameter names used into ArgumentException constructors should match an existing one
+# https://rules.sonarsource.com/csharp/RSPEC-3928
+#
+# This is a duplicate of MA0015.
+dotnet_diagnostic.S3928.severity = none
+
+# S3949: Calculations should not overflow
+# https://rules.sonarsource.com/csharp/RSPEC-3949/
+#
+# Disabled due to build performance impact.
+dotnet_diagnostic.S3949.severity = none
+
+# S3998: Threads should not lock on objects with weak identity
+# https://rules.sonarsource.com/csharp/RSPEC-3998
+#
+# This is a duplicate of CA2002, and partial duplicate of MA0064.
+dotnet_diagnostic.S3998.severity = none
+
+# S4070: Non-flags enums should not be marked with "FlagsAttribute"
+# https://rules.sonarsource.com/csharp/RSPEC-4070
+#
+# This is a duplicate of MA0062.
+dotnet_diagnostic.S4070.severity = none
+
+# S4158: Empty collections should not be accessed or iterated
+# https://rules.sonarsource.com/csharp/RSPEC-4158/
+#
+# Disabled due to build performance impact.
+dotnet_diagnostic.S4158.severity = none
+
+# S4423: Weak SSL/TLS protocols should not be used
+# https://rules.sonarsource.com/csharp/RSPEC-4423/
+dotnet_diagnostic.S4423.severity = none
+
+# S4456: Parameter validation in yielding methods should be wrapped
+# https://rules.sonarsource.com/csharp/RSPEC-4456
+#
+# This is a duplicate of MA0050.
+dotnet_diagnostic.S4456.severity = none
+
+# S4487: Unread "private" fields should be removed
+# https://rules.sonarsource.com/csharp/RSPEC-4487
+#
+# This is a duplicate of IDE0052.
+dotnet_diagnostic.S4487.severity = none
+
+# S4581: "new Guid()" should not be used
+# https://rules.sonarsource.com/csharp/RSPEC-4581
+#
+# This is a partial duplicate of MA0067, and we do not want to report the use of 'default' for a Guid as error.
+dotnet_diagnostic.S4581.severity = none
+
+# S4830: Server certificates should be verified during SSL/TLS connections
+# https://rules.sonarsource.com/csharp/RSPEC-4830/
+dotnet_diagnostic.S4830.severity = none
+
+# S5542: Encryption algorithms should be used with secure mode and padding scheme
+# https://rules.sonarsource.com/csharp/RSPEC-5542/
+dotnet_diagnostic.S5542.severity = none
+
+# S5547: Cipher algorithms should be robust
+# https://rules.sonarsource.com/csharp/RSPEC-5547/
+dotnet_diagnostic.S5547.severity = none
+
+# S5659: JWT should be signed and verified with strong cipher algorithms
+# https://rules.sonarsource.com/csharp/RSPEC-5659/
+dotnet_diagnostic.S5659.severity = none
+
+# S5773: Types allowed to be deserialized should be restricted
+# https://rules.sonarsource.com/csharp/RSPEC-5773/
+dotnet_diagnostic.S4581.severity = none
+
+#### StyleCop rules ####
+
+# SA1003: Symbols must be spaced correctly
+#
+# When enabled, a diagnostic is produced when there's a space after a cast.
+# For example:
+# var x = (int) z;
+dotnet_diagnostic.SA1003.severity = none
+
+# SA1008: Opening parenthesis should not be preceded by a space
+#
+# When enabled, a diagnostic is produce when a cast precedes braces.
+# For example:
+# (long) (a * b)
+dotnet_diagnostic.SA1008.severity = none
+
+# SA1009: Closing parenthesis should not be followed by a space
+#
+# When enabled, a diagnostic is produced when there's a space after a cast.
+# For example:
+# var x = (int) z;
+dotnet_diagnostic.SA1009.severity = none
+
+# SA1101: Prefix local calls with this
+dotnet_diagnostic.SA1101.severity = none
+
+# SA1116: Split parameters must start on line after declaration
+#
+# When enabled, a diagnostic is produced when the first parameter is on the same line as the method or constructor.
+# For example:
+# arrayBuilder.Add(new StatisticsCallInfo(callsByType.Key,
+# callsForType.Count);
+dotnet_diagnostic.SA1116.severity = none
+
+# SA1121: Use built-in type alias
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1121.md
+#
+# Duplicate of IDE0049.
+dotnet_diagnostic.SA1121.severity = none
+
+# SA1200: Using directives must be placed correctly
+#
+# This is already verified by the .NET compiler platform analyzers (csharp_using_directive_placement option and IDE0065 rule).
+dotnet_diagnostic.SA1200.severity = none
+
+# SA1201: Elements must appear in the correct order
+dotnet_diagnostic.SA1201.severity = none
+
+# SA1206: Modifiers are not ordered
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1206.md
+#
+# This is a duplicate of IDE0036, except that it cannot be configured and expects the required modifier to be before the
+# accessibility modifier.
+dotnet_diagnostic.SA1206.severity = none
+
+# SA1309: Field names must not begin with underscore
+dotnet_diagnostic.SA1309.severity = none
+
+# SA1405: Debug.Assert should provide message text
+#
+# To be discussed if we want to enable this.
+dotnet_diagnostic.SA1405.severity = none
+
+# SA1413: Use trailing comma in multi-line initializers
+dotnet_diagnostic.SA1413.severity = none
+
+# SA1503: Braces should not be omitted
+#
+# This is a duplicate of IDE0011.
+dotnet_diagnostic.SA1503.severity = none
+
+# SA1512: Single-line comments should not be followed by a blank line
+#
+# Blank lines can improve readability.
+dotnet_diagnostic.SA1512.severity = none
+
+# SA1516: Elements must be separated by blank line
+#
+# When enabled, a diagnostic is produced for properties with both a get and set accessor.
+# For example:
+# public bool EnableStatistics
+# {
+# get
+# {
+# return _enableStatistics;
+# }
+# set
+# {
+# _enableStatistics = value;
+# }
+# }
+dotnet_diagnostic.SA1516.severity = none
+
+# SA1520: Use braces consistently
+#
+# Since we always require braces (configured via csharp_prefer_braces and reported as IDE0011), it does not make sense to check if braces
+# are used consistently.
+dotnet_diagnostic.SA1520.severity = none
+
+# SA1633: File must have header
+#
+# We do not use file headers.
+dotnet_diagnostic.SA1633.severity = none
+
+# SA1601: Partial elements should be documented
+dotnet_diagnostic.SA1601.severity = none
+
+# SA1648: must be used with inheriting class
+#
+# This rule is disabled by default, hence we need to explicitly enable it.
+dotnet_diagnostic.SA1648.severity = error
+
+# SX1101: Do not prefix local members with 'this.'
+#
+# This rule is disabled by default, hence we need to explicitly enable it.
+dotnet_diagnostic.SX1101.severity = error
+
+# SX1309: Field names must begin with underscore
+#
+# This rule is disabled by default, hence we need to explicitly enable it.
+dotnet_diagnostic.SX1309.severity = error
+
+# SX1309S: Static field names must begin with underscore
+#
+# This rule is disabled by default, hence we need to explicitly enable it.
+dotnet_diagnostic.SX1309S.severity = error
+
+#### Meziantou.Analyzer rules ####
+
+# MA0002: Use an overload that has a IEqualityComparer or IComparer parameter
+#
+# In .NET (Core) there have been quite some optimizations for EqualityComparer.Default (eg. https://github.com/dotnet/coreclr/pull/14125)
+# and Comparer.Default (eg. https://github.com/dotnet/runtime/pull/48160).
+#
+# We'll have to verify impact on performance before we decide to use specific comparers (eg. StringComparer.InvariantCultureIgnoreCase).
+dotnet_diagnostic.MA0002.severity = none
+
+# MA0006: Use string.Equals instead of Equals operator
+#
+# We almost always want ordinal comparison, and using the explicit overload adds a little overhead
+# and is more chatty.
+dotnet_diagnostic.MA0006.severity = none
+
+# MA0007: Add a comma after the last value
+#
+# We do not add a comma after the last value in multi-line initializers.
+# For example:
+# public enum Sex
+# {
+# Male = 1,
+# Female = 2 // No comma here
+# }
+#
+# Note:
+# This is a duplicate of SA1413.
+dotnet_diagnostic.MA0007.severity = none
+
+# MA0009: Add regex evaluation timeout
+#
+# We do not see a need guard our regex's against a DOS attack.
+dotnet_diagnostic.MA0009.severity = none
+
+# MA0011: IFormatProvider is missing
+#
+# Also report diagnostic in ToString(...) methods
+MA0011.exclude_tostring_methods = false
+
+# MA0012: Do not raise reserved exception type
+#
+# This is a duplicate of CA2201.
+dotnet_diagnostic.MA0012.severity = none
+
+# MA0014: Do not raise System.ApplicationException type
+#
+# This is a duplicate of CA2201.
+dotnet_diagnostic.MA0014.severity = none
+
+# MA0016: Prefer returning collection abstraction instead of implementation
+#
+# This is a duplicate of CA1002.
+dotnet_diagnostic.MA0016.severity = none
+
+# MA0018: Do not declare static members on generic types
+#
+# This is a duplicate of CA1000.
+dotnet_diagnostic.MA0018.severity = none
+
+# MA0021: Use StringComparer.GetHashCode instead of string.GetHashCode
+#
+# No strong need for this, and may negatively affect performance.
+dotnet_diagnostic.MA0021.severity = none
+
+# MA0025: Implement the functionality instead of throwing NotImplementedException
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0031.md
+dotnet_diagnostic.MA0025.severity = none
+
+# MA0026: Fix TODO comment
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0026.md
+dotnet_diagnostic.MA0026.severity = suggestion
+
+# MA0031: Optimize Enumerable.Count() usage
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0031.md
+#
+# The proposed code is less readable.
+#
+# For example:
+#
+# the following code fragment:
+# enumerable.Count() > 10;
+#
+# would become:
+# enumerable.Skip(10).Any();
+dotnet_diagnostic.MA0031.severity = none
+
+# MA0036: Make class static
+#
+# This is a partial duplicate of CA1052.
+dotnet_diagnostic.MA0036.severity = none
+
+# MA0038: Make method static
+#
+# This is a partial duplicate of, and deprecated in favor of, CA1822.
+dotnet_diagnostic.MA0038.severity = none
+
+# MA0041: Make property static
+#
+# This is a partial duplicate of, and deprecated in favor of, CA1822.
+dotnet_diagnostic.MA0041.severity = none
+
+# MA0048: File name must match type name
+#
+# This is a duplicate of SA1649.
+dotnet_diagnostic.MA0048.severity = none
+
+# MA0049: Type name should not match containing namespace
+#
+# This is a duplicate of CA1724
+dotnet_diagnostic.MA0049.severity = none
+
+# MA0051: Method is too long
+#
+# We do not want to limit the number of lines or statements per method.
+dotnet_diagnostic.MA0051.severity = none
+
+# MA0053: Make class sealed
+#
+# Also report diagnostic for public types.
+MA0053.public_class_should_be_sealed = true
+
+# MA0053: Make class sealed
+#
+# Also report diagnostic for types that derive from System.Exception.
+MA0053.exceptions_should_be_sealed = true
+
+# MA0053: Make class sealed
+#
+# Also report diagnostic for types that define (new) virtual members.
+MA0053.class_with_virtual_member_shoud_be_sealed = true
+
+# MA0112: Use 'Count > 0' instead of 'Any()'
+#
+# This rule is disabled by default, hence we need to explicitly enable it.
+dotnet_diagnostic.MA0112.severity = error
+
+#### .NET Compiler Platform code quality rules ####
+
+# CA1002: Do not expose generic lists
+#
+# For performance reasons - to avoid interface dispatch - we expose generic lists
+# instead of a base class or interface.
+dotnet_diagnostic.CA1002.severity = none
+
+# CA1003: Use generic event handler instances
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1003
+#
+# Similar to MA0046.
+dotnet_diagnostic.CA1003.severity = none
+
+# CA1008: Enums should have zero value
+#
+# TODO: To be discussed. Having a zero value offers a performance advantage.
+dotnet_diagnostic.CA1008.severity = none
+
+# CA1014: Mark assemblies with CLSCompliantAttribute
+#
+# This rule is disabled by default, hence we need to explicitly enable it.
+#
+# Even when enabled, this diagnostic does not appear to be reported for assemblies without CLSCompliantAttribute.
+# We reported this issue as https://github.com/dotnet/roslyn-analyzers/issues/6563.
+dotnet_diagnostic.CA1014.severity = error
+
+# CA1051: Do not declare visible instance fields
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1051
+#
+# This is a duplicate of S1104 and SA1401.
+dotnet_diagnostic.CA1051.severity = none
+
+# CA1052: Static holder types should be Static or NotInheritable
+#
+# By default, this diagnostic is only reported for public types.
+dotnet_code_quality.CA1052.api_surface = all
+
+# CA1065: Do not raise exceptions in unexpected locations
+# https://learn.microsoft.com/en-US/dotnet/fundamentals/code-analysis/quality-rules/ca1065
+dotnet_diagnostic.CA1065.severity = none
+
+# CA1303: Do not pass literals as localized parameters
+#
+# We don't care about localization.
+dotnet_diagnostic.CA1303.severity = none
+
+# CA1305: Specify IFormatProvider
+#
+# This is a an equivalent of MA0011, except that it does not report a diagnostic for the use of
+# DateTime.TryParse(string s, out DateTime result).
+#
+# Submitted https://github.com/dotnet/roslyn-analyzers/issues/6096 to fix CA1305.
+dotnet_diagnostic.CA1305.severity = none
+
+# CA1309: Use ordinal StringComparison
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1309
+dotnet_diagnostic.CA1309.severity = none
+
+# CA1510: Use ArgumentNullException throw helper
+#
+# This is only available in .NET 6.0 and higher. We'd need to use conditional compilation to only
+# use these throw helper when targeting a framework that supports it.
+dotnet_diagnostic.CA1510.severity = none
+
+# CA1725: Parameter names should match base declaration
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1725
+#
+# This is a duplicate of S927, but contains at least one bug:
+# https://github.com/dotnet/roslyn-analyzers/issues/6461
+dotnet_diagnostic.CA1725.severity = none
+
+# CA1825: Avoid zero-length array allocations
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1825
+#
+# This is a duplicate of MA0005.
+dotnet_diagnostic.CA1825.severity = none
+
+# CA1819: Properties should not return arrays
+#
+# Arrays offer better performance than collections.
+dotnet_diagnostic.CA1819.severity = none
+
+# CA1828: Mark members as static
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1822
+#
+# Documentation does not mention which API surface(s) this rule runs on, so we explictly configure it.
+dotnet_code_quality.CA1828.api_surface = all
+
+# CA1852: Seal internal types
+#
+# Similar to MA0053, but does not support public types and types that define (new) virtual members.
+dotnet_diagnostic.CA1852.severity = none
+
+# CA1859: Change return type for improved performance
+#
+# By default, this diagnostic is only reported for private members.
+dotnet_code_quality.CA1859.api_surface = all
+
+# CA2208: Instantiate argument exceptions correctly
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2208
+#
+# This is similar to, but less powerful than, MA0015.
+dotnet_diagnostic.CA2208.severity = none
+
+# CA5358: Do Not Use Unsafe Cipher Modes / Review cipher mode usage with cryptography experts
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca5358
+#
+# We use ECB mode as the basis for other modes (e.g. CTR)
+dotnet_diagnostic.CA5358.severity = none
+
+# CA5389: Do not add archive item's path to the target file system path
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca5389
+dotnet_diagnostic.CA5389.severity = none
+
+# CA5390: Do not hard-code encryption key
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca5390
+dotnet_diagnostic.CA5390.severity = none
+
+# CA5401: Do not use CreateEncryptor with non-default IV
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca5401
+dotnet_diagnostic.CA5401.severity = none
+
+# CA5402: Use CreateEncryptor with the default IV
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca5402
+dotnet_diagnostic.CA5402.severity = none
+
+# CA5403: Do not hard-code certificate
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca5403
+dotnet_diagnostic.CA5403.severity = none
+
+#### Roslyn IDE analyser rules ####
+
+# IDE0028: Simplify collection initialization; and
+# IDE0305: Simplify collection initialization
+#
+# Temporarily suppressing collection expression recommendations coming from .NET 8 SDK
+dotnet_diagnostic.IDE0028.severity = none
+dotnet_diagnostic.IDE0305.severity = none
+
+# IDE0032: Use auto-implemented property
+#
+# For performance reasons, we do not always want to enforce the use of
+# auto-implemented properties.
+dotnet_diagnostic.IDE0032.severity = suggestion
+
+# IDE0045: Use conditional expression for assignment
+#
+# This does not always result in cleaner/clearer code.
+dotnet_diagnostic.IDE0045.severity = none
+
+# IDE0046: Use conditional expression for return
+#
+# Using a conditional expression is not always a clear win for readability.
+#
+# Configured using 'dotnet_style_prefer_conditional_expression_over_return'
+dotnet_diagnostic.IDE0046.severity = suggestion
+
+# IDE0047: Remove unnecessary parentheses
+#
+# Removing "unnecessary" parentheses is not always a clear win for readability.
+dotnet_diagnostic.IDE0047.severity = suggestion
+
+# IDE0055: Fix formatting
+#
+# When enabled, diagnostics are reported for indented object initializers.
+# For example:
+# _content = new Person
+# {
+# Name = "\u13AAlarm"
+# };
+#
+# There are no settings to configure this correctly, unless https://github.com/dotnet/roslyn/issues/63256 (or similar) is ever implemented.
+dotnet_diagnostic.IDE0055.severity = none
+
+# IDE0130: Namespace does not match folder structure
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0130
+#
+# TODO: Remove when https://github.com/sshnet/SSH.NET/issues/1129 is fixed
+dotnet_diagnostic.IDE0130.severity = none
+
+# IDE0270: Null check can be simplified
+#
+# var inputPath = originalDossierPathList.Find(x => x.id == updatedPath.id);
+# if (inputPath is null)
+# {
+# throw new PcsException($"Path id ({updatedPath.id}) unknown in PCS for dossier id {dossierFromTs.dossier.id}", updatedPath.id);
+# }
+#
+# We do not want to modify the code using a null coalescing operator:
+#
+# var inputPath = originalDossierPathList.Find(x => x.id == updatedPath.id) ?? throw new PcsException($"Path id ({updatedPath.id}) unknown in PCS for dossier id {dossierFromTs.dossier.id}", updatedPath.id);
+dotnet_diagnostic.IDE0270.severity = none
+
+# IDE0290: Use primary constructor
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0290
+dotnet_diagnostic.IDE0290.severity = none
+
+# IDE0300: Collection initialization can be simplified
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0300
+#
+# TODO: Discuss whether we want to start using this
+dotnet_diagnostic.IDE0300.severity = none
+
+# IDE0301: Simplify collection initialization
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0301
+#
+# TODO: Discuss whether we want to start using this
+dotnet_diagnostic.IDE0301.severity = none
+
+#### .NET Compiler Platform code style rules ####
+
+### Language rules ###
+
+## Modifier preferences
+
+dotnet_style_require_accessibility_modifiers = true
+dotnet_style_readonly_field = true
+csharp_prefer_static_local_function = true
+
+## Parentheses preferences
+
+dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity
+dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity
+dotnet_style_parentheses_in_other_binary_operators = always_for_clarity
+dotnet_style_parentheses_in_other_operators = never_if_unnecessary
+
+# Expression-level preferences
+
+dotnet_style_object_initializer = true
+csharp_style_inlined_variable_declaration = true
+dotnet_style_collection_initializer = true
+dotnet_style_prefer_auto_properties = true
+dotnet_style_explicit_tuple_names = true
+csharp_prefer_simple_default_expression = true
+dotnet_style_prefer_inferred_tuple_names = true
+dotnet_style_prefer_inferred_anonymous_type_member_names = true
+csharp_style_prefer_local_over_anonymous_function = true
+csharp_style_deconstructed_variable_declaration = false
+dotnet_style_prefer_conditional_expression_over_assignment = true
+dotnet_style_prefer_conditional_expression_over_return = true
+dotnet_style_prefer_compound_assignment = true
+csharp_style_prefer_index_operator = false
+csharp_style_prefer_range_operator = false
+dotnet_style_prefer_simplified_interpolation = false
+dotnet_style_prefer_simplified_boolean_expressions = true
+csharp_style_implicit_object_creation_when_type_is_apparent = false
+csharp_style_prefer_tuple_swap = false
+
+# Namespace declaration preferences
+
+csharp_style_namespace_declarations = block_scoped
+
+# Null-checking preferences
+
+csharp_style_throw_expression = false
+dotnet_style_coalesce_expression = true
+dotnet_style_null_propagation = true
+dotnet_style_prefer_is_null_check_over_reference_equality_method = true
+csharp_style_prefer_null_check_over_type_check = true
+csharp_style_conditional_delegate_call = true
+
+# 'var' preferences
+
+csharp_style_var_for_built_in_types = true
+csharp_style_var_when_type_is_apparent = true
+csharp_style_var_elsewhere = true
+
+# Expression-bodies members
+
+csharp_style_expression_bodied_methods = false
+csharp_style_expression_bodied_constructors = false
+csharp_style_expression_bodied_operators = false
+csharp_style_expression_bodied_properties = false
+csharp_style_expression_bodied_indexers = false
+csharp_style_expression_bodied_accessors = false
+csharp_style_expression_bodied_lambdas = false
+csharp_style_expression_bodied_local_functions = false
+
+# Pattern matching preferences
+
+csharp_style_pattern_matching_over_as_with_null_check = true
+csharp_style_pattern_matching_over_is_with_cast_check = true
+csharp_style_prefer_switch_expression = false
+csharp_style_prefer_pattern_matching = true
+csharp_style_prefer_not_pattern = true
+csharp_style_prefer_extended_property_pattern = true
+
+# Code block preferences
+
+csharp_prefer_braces = true
+csharp_prefer_simple_using_statement = false
+
+# Using directive preferences
+
+csharp_using_directive_placement = outside_namespace
+
+# Namespace naming preferences
+
+dotnet_style_namespace_match_folder = true
+
+# Undocumented preferences
+
+csharp_style_prefer_method_group_conversion = false
+csharp_style_prefer_top_level_statements = false
+
+### Formatting rules ###
+
+## .NET formatting options ##
+
+# Using directive options
+
+dotnet_sort_system_directives_first = true
+dotnet_separate_import_directive_groups = true
+
+## C# formatting options ##
+
+# New-line options
+
+# TNIS-13005: Enabling this setting breaks Resharper indentation for lambdas
+#csharp_new_line_before_open_brace = accessors, anonymous_methods, anonymous_types, control_blocks, events, indexers, lambdas, local_functions, methods, object_collection_array_initializers, properties, types
+csharp_new_line_before_else = true
+csharp_new_line_before_catch = true
+csharp_new_line_before_finally = true
+# Enabling this setting breaks Resharper formatting for an enum field reference that is
+# deeply nested in an object initializer.
+#
+# For an example, see TDataExchangeGeneralEnricher_CernInfrastructureObstruction.
+#csharp_new_line_before_members_in_object_initializers = true
+csharp_new_line_before_members_in_anonymous_types = true
+csharp_new_line_between_query_expression_clauses = true
+
+# Indentation options
+
+csharp_indent_case_contents = true
+csharp_indent_switch_labels = true
+csharp_indent_labels = one_less_than_current
+csharp_indent_block_contents = true
+# TNIS-13005: Enabling this setting breaks Resharper indentation for lambdas
+#csharp_indent_braces = false
+# TNIS-13005: Enabling this setting breaks Resharper indentation for lambdas
+#csharp_indent_case_contents_when_block = true
+
+# Spacing options
+
+csharp_space_after_cast = true
+csharp_space_after_keywords_in_control_flow_statements = true
+csharp_space_between_parentheses = false
+csharp_space_before_colon_in_inheritance_clause = true
+csharp_space_after_colon_in_inheritance_clause = true
+csharp_space_around_binary_operators = before_and_after
+csharp_space_between_method_declaration_parameter_list_parentheses = false
+csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
+csharp_space_between_method_declaration_name_and_open_parenthesis = false
+csharp_space_between_method_call_parameter_list_parentheses = false
+csharp_space_between_method_call_empty_parameter_list_parentheses = false
+csharp_space_between_method_call_name_and_opening_parenthesis = false
+csharp_space_after_comma = true
+csharp_space_before_comma = false
+csharp_space_after_dot = false
+csharp_space_before_dot = false
+csharp_space_after_semicolon_in_for_statement = true
+csharp_space_before_semicolon_in_for_statement = false
+csharp_space_around_declaration_statements = false
+csharp_space_before_open_square_brackets = false
+csharp_space_between_empty_square_brackets = false
+csharp_space_between_square_brackets = false
+
+# Wrap options
+
+csharp_preserve_single_line_statements = false
+csharp_preserve_single_line_blocks = true
+
+### Naming styles ###
+
+# Naming rules
+
+dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
+dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
+dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
+
+dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
+dotnet_naming_rule.types_should_be_pascal_case.symbols = types
+dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
+
+dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
+dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
+dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
+
+dotnet_naming_rule.private_fields_camel_case_begins_with_underscore.symbols = private_fields
+dotnet_naming_rule.private_fields_camel_case_begins_with_underscore.style = camel_case_begins_with_underscore
+dotnet_naming_rule.private_fields_camel_case_begins_with_underscore.severity = error
+
+dotnet_naming_rule.private_static_fields_camel_case_begins_with_underscore.symbols = private_static_fields
+dotnet_naming_rule.private_static_fields_camel_case_begins_with_underscore.style = camel_case_begins_with_underscore
+dotnet_naming_rule.private_static_fields_camel_case_begins_with_underscore.severity = error
+
+dotnet_naming_rule.private_static_readonly_fields_pascal_case.symbols = private_static_readonly_fields
+dotnet_naming_rule.private_static_readonly_fields_pascal_case.style = pascal_case
+dotnet_naming_rule.private_static_readonly_fields_pascal_case.severity = error
+
+dotnet_naming_rule.private_const_fields_pascal_case.symbols = private_const_fields
+dotnet_naming_rule.private_const_fields_pascal_case.style = pascal_case
+dotnet_naming_rule.private_const_fields_pascal_case.severity = error
+
+# Symbol specifications
+
+dotnet_naming_symbols.interface.applicable_kinds = interface
+dotnet_naming_symbols.interface.applicable_accessibilities = *
+dotnet_naming_symbols.interface.required_modifiers =
+
+dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
+dotnet_naming_symbols.types.applicable_accessibilities = *
+dotnet_naming_symbols.types.required_modifiers =
+
+dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
+dotnet_naming_symbols.non_field_members.applicable_accessibilities = *
+dotnet_naming_symbols.non_field_members.required_modifiers =
+
+dotnet_naming_symbols.private_fields.applicable_kinds = field
+dotnet_naming_symbols.private_fields.applicable_accessibilities = private
+dotnet_naming_symbols.private_fields.required_modifiers =
+
+dotnet_naming_symbols.private_static_fields.applicable_kinds = field
+dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private
+dotnet_naming_symbols.private_static_fields.required_modifiers = static
+
+dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field
+dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private
+dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = static, readonly
+
+dotnet_naming_symbols.private_const_fields.applicable_kinds = field
+dotnet_naming_symbols.private_const_fields.applicable_accessibilities = private
+dotnet_naming_symbols.private_const_fields.required_modifiers = const
+
+# Naming styles
+
+dotnet_naming_style.begins_with_i.required_prefix = I
+dotnet_naming_style.begins_with_i.required_suffix =
+dotnet_naming_style.begins_with_i.word_separator =
+dotnet_naming_style.begins_with_i.capitalization = pascal_case
+
+dotnet_naming_style.pascal_case.required_prefix =
+dotnet_naming_style.pascal_case.required_suffix =
+dotnet_naming_style.pascal_case.word_separator =
+dotnet_naming_style.pascal_case.capitalization = pascal_case
+
+dotnet_naming_style.camel_case_begins_with_underscore.required_prefix = _
+dotnet_naming_style.camel_case_begins_with_underscore.required_suffix =
+dotnet_naming_style.camel_case_begins_with_underscore.word_separator =
+dotnet_naming_style.camel_case_begins_with_underscore.capitalization = camel_case
+
+#### .NET Compiler Platform general options ####
+
+# Change the default rule severity for all analyzer rules that are enabled by default
+dotnet_analyzer_diagnostic.severity = error
+
+#### .NET Compiler Platform code refactoring rules ####
+
+dotnet_style_operator_placement_when_wrapping = end_of_line
+
+#### ReSharper code style for C# ####
+
+## Blank Lines
+
+resharper_csharp_blank_lines_around_region = 1
+resharper_csharp_blank_lines_inside_region = 1
+resharper_csharp_blank_lines_before_single_line_comment = 1
+resharper_csharp_keep_blank_lines_in_declarations = 1
+resharper_csharp_remove_blank_lines_near_braces_in_declarations = true
+resharper_csharp_blank_lines_after_start_comment = 1
+resharper_csharp_blank_lines_between_using_groups = 1
+resharper_csharp_blank_lines_after_using_list = 1
+resharper_csharp_blank_lines_around_namespace = 1
+resharper_csharp_blank_lines_inside_namespace = 0
+resharper_csharp_blank_lines_after_file_scoped_namespace_directive = 1
+resharper_csharp_blank_lines_around_type = 1
+resharper_csharp_blank_lines_around_single_line_type = 1
+resharper_csharp_blank_lines_inside_type = 0
+resharper_csharp_blank_lines_around_field = 0
+resharper_csharp_blank_lines_around_single_line_field = 0
+resharper_csharp_blank_lines_around_property = 1
+resharper_csharp_blank_lines_around_single_line_property = 1
+resharper_csharp_blank_lines_around_auto_property = 1
+resharper_csharp_blank_lines_around_single_line_auto_property = 1
+resharper_csharp_blank_lines_around_accessor = 0
+resharper_csharp_blank_lines_around_single_line_accessor = 0
+resharper_csharp_blank_lines_around_invocable = 1
+resharper_csharp_blank_lines_around_single_line_invocable = 1
+resharper_csharp_keep_blank_lines_in_code = 1
+resharper_csharp_remove_blank_lines_near_braces_in_code = true
+resharper_csharp_blank_lines_around_local_method = 1
+resharper_csharp_blank_lines_around_single_line_local_method = 1
+resharper_csharp_blank_lines_before_control_transfer_statements = 0
+resharper_csharp_blank_lines_after_control_transfer_statements = 0
+resharper_csharp_blank_lines_before_block_statements = 0
+resharper_csharp_blank_lines_after_block_statements = 1
+resharper_csharp_blank_lines_before_multiline_statements = 0
+resharper_csharp_blank_lines_after_multiline_statements = 0
+resharper_csharp_blank_lines_around_block_case_section = 0
+resharper_csharp_blank_lines_around_multiline_case_section = 0
+resharper_csharp_blank_lines_before_case = 0
+resharper_csharp_blank_lines_after_case = 0
+
+## Braces Layout
+
+resharper_csharp_type_declaration_braces = next_line
+resharper_csharp_indent_inside_namespace = true
+resharper_csharp_invocable_declaration_braces = next_line
+resharper_csharp_anonymous_method_declaration_braces = next_line_shifted_2
+resharper_csharp_accessor_owner_declaration_braces = next_line
+resharper_csharp_accessor_declaration_braces = next_line
+resharper_csharp_case_block_braces = next_line_shifted_2
+resharper_csharp_initializer_braces = next_line_shifted_2
+resharper_csharp_use_continuous_indent_inside_initializer_braces = true
+resharper_csharp_other_braces = next_line
+resharper_csharp_allow_comment_after_lbrace = false
+resharper_csharp_empty_block_style = multiline
+
+## Syntax Style
+
+# 'var' usage in declarations
+
+resharper_csharp_for_built_in_types = use_var
+resharper_csharp_for_simple_types = use_var
+resharper_csharp_for_other_types = use_var
+
+# Instance members qualification
+
+resharper_csharp_instance_members_qualify_members = none
+resharper_csharp_instance_members_qualify_declared_in = base_class
+
+# Static members qualification
+
+resharper_csharp_static_members_qualify_with = declared_type
+resharper_csharp_static_members_qualify_members = none
+
+# Built-in types
+
+resharper_csharp_builtin_type_reference_style = use_keyword
+resharper_csharp_builtin_type_reference_for_member_access_style = use_keyword
+
+# Reference qualification and 'using' directives
+
+resharper_csharp_prefer_qualified_reference = false
+resharper_csharp_add_imports_to_deepest_scope = false
+resharper_csharp_qualified_using_at_nested_scope = false
+resharper_csharp_allow_alias = true
+resharper_csharp_can_use_global_alias = true
+
+# Modifiers
+
+resharper_csharp_default_private_modifier = explicit
+resharper_csharp_default_internal_modifier = explicit
+resharper_csharp_modifiers_order = public private protected internal file static extern new virtual abstract sealed override readonly unsafe required volatile async
+
+# Braces
+
+resharper_csharp_braces_for_ifelse = required
+resharper_csharp_braces_for_for = required
+resharper_csharp_braces_for_foreach = required
+resharper_csharp_braces_for_while = required
+resharper_csharp_braces_for_dowhile = required
+resharper_csharp_braces_for_using = required
+resharper_csharp_braces_for_lock = required
+resharper_csharp_braces_for_fixed = required
+resharper_csharp_braces_redundant = false
+
+# Code body
+
+resharper_csharp_method_or_operator_body = block_body
+resharper_csharp_local_function_body = block_body
+resharper_csharp_constructor_or_destructor_body = block_body
+resharper_csharp_accessor_owner_body = accessors_with_block_body
+resharper_csharp_namespace_body = block_scoped
+resharper_csharp_use_heuristics_for_body_style = false
+
+# Trailing comma
+
+resharper_csharp_trailing_comma_in_multiline_lists = false
+resharper_csharp_trailing_comma_in_singleline_lists = false
+
+# Object creation
+
+resharper_csharp_object_creation_when_type_evident = explicitly_typed
+resharper_csharp_object_creation_when_type_not_evident = explicitly_typed
+
+# Default value
+
+resharper_csharp_default_value_when_type_evident = default_literal
+resharper_csharp_default_value_when_type_not_evident = default_literal
+
+## Tabs, Indents, Alignment
+
+# Nested statements
+
+resharper_csharp_indent_nested_usings_stmt = false
+resharper_csharp_indent_nested_fixed_stmt = false
+resharper_csharp_indent_nested_lock_stmt = false
+resharper_csharp_indent_nested_for_stmt = true
+resharper_csharp_indent_nested_foreach_stmt = true
+resharper_csharp_indent_nested_while_stmt = true
+
+# Parenthesis
+
+resharper_csharp_use_continuous_indent_inside_parens = true
+resharper_csharp_indent_method_decl_pars = outside_and_inside
+resharper_csharp_indent_invocation_pars = outside_and_inside
+resharper_csharp_indent_statement_pars = outside_and_inside
+resharper_csharp_indent_typeparam_angles = outside_and_inside
+resharper_csharp_indent_typearg_angles = outside_and_inside
+resharper_csharp_indent_pars = outside_and_inside
+
+# Preprocessor directives
+
+resharper_csharp_indent_preprocessor_if = no_indent
+resharper_csharp_indent_preprocessor_region = usual_indent
+resharper_csharp_indent_preprocessor_other = no_indent
+
+# Other indents
+
+resharper_indent_switch_labels = true
+resharper_csharp_outdent_statement_labels = true
+resharper_csharp_indent_type_constraints = true
+resharper_csharp_stick_comment = false
+resharper_csharp_place_comments_at_first_column = false
+resharper_csharp_use_indent_from_previous_element = true
+resharper_csharp_indent_braces_inside_statement_conditions = true
+
+# Align multiline constructs
+
+resharper_csharp_alignment_tab_fill_style = use_spaces
+resharper_csharp_allow_far_alignment = true
+resharper_csharp_align_multiline_parameter = true
+resharper_csharp_align_multiline_extends_list = true
+resharper_csharp_align_linq_query = true
+resharper_csharp_align_multiline_binary_expressions_chain = true
+resharper_csharp_outdent_binary_ops = false
+resharper_csharp_align_multiline_calls_chain = true
+resharper_csharp_outdent_dots = false
+resharper_csharp_align_multiline_array_and_object_initializer = false
+resharper_csharp_align_multiline_switch_expression = false
+resharper_csharp_align_multiline_property_pattern = false
+resharper_csharp_align_multiline_list_pattern = false
+resharper_csharp_align_multiline_binary_patterns = false
+resharper_csharp_outdent_binary_pattern_ops = false
+resharper_csharp_indent_anonymous_method_block = true
+resharper_csharp_align_first_arg_by_paren = false
+resharper_csharp_align_multiline_argument = true
+resharper_csharp_align_tuple_components = true
+resharper_csharp_align_multiline_expression = true
+resharper_csharp_align_multiline_statement_conditions = true
+resharper_csharp_align_multiline_for_stmt = true
+resharper_csharp_align_multiple_declaration = true
+resharper_csharp_align_multline_type_parameter_list = true
+resharper_csharp_align_multline_type_parameter_constrains = true
+resharper_csharp_outdent_commas = false
+
+## Line Breaks
+
+# General
+
+resharper_csharp_keep_user_linebreaks = true
+resharper_csharp_max_line_length = 140
+resharper_csharp_wrap_before_comma = false
+resharper_csharp_wrap_before_eq = false
+resharper_csharp_special_else_if_treatment = true
+resharper_csharp_insert_final_newline = true
+
+# Arrangement of attributes
+
+resharper_csharp_keep_existing_attribute_arrangement = false
+resharper_csharp_place_type_attribute_on_same_line = false
+resharper_csharp_place_method_attribute_on_same_line = false
+resharper_csharp_place_accessorholder_attribute_on_same_line = false
+resharper_csharp_place_accessor_attribute_on_same_line = false
+resharper_csharp_place_field_attribute_on_same_line = false
+resharper_csharp_place_record_field_attribute_on_same_line = true
+
+# Arrangement of method signatures
+
+resharper_csharp_place_constructor_initializer_on_same_line = false
+resharper_csharp_place_expr_method_on_single_line = true
+resharper_csharp_place_expr_property_on_single_line = true
+resharper_csharp_place_expr_accessor_on_single_line = true
+
+# Arrangement of type parameters, constraints, and base types
+
+resharper_csharp_place_type_constraints_on_same_line = false
+resharper_csharp_wrap_before_first_type_parameter_constraint = true
+
+# Arrangement of declaration blocks
+
+resharper_csharp_place_abstract_accessorholder_on_single_line = true
+
+# Arrangement of statements
+
+resharper_new_line_before_else = true
+resharper_new_line_before_while = true
+resharper_new_line_before_catch = true
+resharper_new_line_before_finally = true
+resharper_wrap_for_stmt_header_style = chop_if_long
+resharper_wrap_multiple_declaration_style = chop_always
+
+## Spaces
+
+# Preserve existing formatting
+
+resharper_csharp_extra_spaces = remove_all
+
+# Before parentheses in statements
+
+resharper_csharp_space_before_if_parentheses = true
+resharper_csharp_space_before_while_parentheses = true
+resharper_csharp_space_before_catch_parentheses = true
+resharper_csharp_space_before_switch_parentheses = true
+resharper_csharp_space_before_for_parentheses = true
+resharper_csharp_space_before_foreach_parentheses = true
+resharper_csharp_space_before_using_parentheses = true
+resharper_csharp_space_before_lock_parentheses = true
+resharper_csharp_space_before_fixed_parentheses = true
+
+# Before other parentheses
+
+resharper_csharp_space_before_method_call_parentheses = false
+resharper_csharp_space_before_empty_method_call_parentheses = false
+resharper_csharp_space_before_method_parentheses = false
+resharper_csharp_space_before_empty_method_parentheses = false
+resharper_csharp_space_before_typeof_parentheses = false
+resharper_csharp_space_before_default_parentheses = false
+resharper_csharp_space_before_checked_parentheses = false
+resharper_csharp_space_before_sizeof_parentheses = false
+resharper_csharp_space_before_nameof_parentheses = false
+resharper_csharp_space_before_new_parentheses = false
+resharper_csharp_space_between_keyword_and_expression = true
+resharper_csharp_space_between_keyword_and_type = false
+
+# Within parentheses in statements
+
+resharper_csharp_space_within_if_parentheses = false
+resharper_csharp_space_within_while_parentheses = false
+resharper_csharp_space_within_catch_parentheses = false
+resharper_csharp_space_within_switch_parentheses = false
+resharper_csharp_space_within_for_parentheses = false
+resharper_csharp_space_within_foreach_parentheses = false
+resharper_csharp_space_within_using_parentheses = false
+resharper_csharp_space_within_lock_parentheses = false
+resharper_csharp_space_within_fixed_parentheses = false
+
+# Within other parentheses
+
+resharper_csharp_space_within_parentheses = false
+resharper_csharp_space_between_typecast_parentheses = false
+resharper_csharp_space_between_method_declaration_parameter_list_parentheses = false
+resharper_csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
+resharper_csharp_space_between_method_call_parameter_list_parentheses = false
+resharper_csharp_space_between_method_call_empty_parameter_list_parentheses = false
+resharper_csharp_space_within_typeof_parentheses = false
+resharper_csharp_space_within_default_parentheses = false
+resharper_csharp_space_within_checked_parentheses = false
+resharper_csharp_space_within_sizeof_parentheses = false
+resharper_csharp_space_within_nameof_parentheses = false
+resharper_csharp_space_within_new_parentheses = false
+
+# Around array brackets
+
+resharper_csharp_space_before_array_access_brackets = false
+resharper_csharp_space_before_open_square_brackets = false
+resharper_csharp_space_before_array_rank_brackets = false
+resharper_csharp_space_within_array_access_brackets = false
+resharper_csharp_space_between_square_brackets = false
+resharper_csharp_space_within_array_rank_brackets = false
+resharper_csharp_space_within_array_rank_empty_brackets = false
+resharper_csharp_space_between_empty_square_bracket = false
+
+# Around angle brackets
+
+resharper_csharp_space_before_type_parameter_angle = false
+resharper_csharp_space_before_type_argument_angle = false
+resharper_csharp_space_within_type_parameter_angles = false
+resharper_csharp_space_within_type_argument_angles = false
+
+### ReSharper code style for XMLDOC ###
+
+## Tabs and indents
+
+resharper_xmldoc_indent_style = space
+# ReSharper currently ignores this setting. See https://youtrack.jetbrains.com/issue/RSRP-465678/XMLDOC-indent-settings-ignored.
+resharper_xmldoc_indent_size = 2
+resharper_xmldoc_tab_width = 2
+resharper_xmldoc_alignment_tab_fill_style = use_spaces
+resharper_xmldoc_allow_far_alignment = true
+
+## Line wrapping
+
+resharper_xmldoc_max_line_length = 140
+resharper_xmldoc_wrap_tags_and_pi = false
+
+## Processing instructions
+
+resharper_xmldoc_spaces_around_eq_in_pi_attribute = false
+resharper_xmldoc_space_after_last_pi_attribute = false
+resharper_xmldoc_pi_attribute_style = on_single_line
+resharper_xmldoc_pi_attributes_indent = align_by_first_attribute
+resharper_xmldoc_blank_line_after_pi = false
+
+## Inside of tag header
+
+resharper_xmldoc_spaces_around_eq_in_attribute = false
+resharper_xmldoc_space_after_last_attribute = false
+resharper_xmldoc_space_before_self_closing = false
+resharper_xmldoc_attribute_style = do_not_touch
+resharper_xmldoc_attribute_indent = align_by_first_attribute
+
+## Tag content
+
+resharper_xmldoc_keep_user_linebreaks = true
+resharper_xmldoc_linebreaks_inside_tags_for_multiline_elements = true
+resharper_xmldoc_linebreaks_inside_tags_for_elements_with_child_elements = false
+resharper_xmldoc_spaces_inside_tags = false
+resharper_xmldoc_wrap_text = false
+resharper_xmldoc_wrap_around_elements = false
+# ReSharper currently ignores the 'resharper_xmldoc_indent_size' setting. Once https://youtrack.jetbrains.com/issue/RSRP-465678/XMLDOC-indent-settings-ignored
+# is fixed, we should change the value of this setting to 'one_indent'.
+resharper_xmldoc_indent_child_elements = zero_indent
+resharper_xmldoc_indent_text = zero_indent
+
+## Around tags
+
+resharper_xmldoc_max_blank_lines_between_tags = 1
+resharper_xmldoc_linebreak_before_multiline_elements = true
+resharper_xmldoc_linebreak_before_singleline_elements = false
+
+[*.{xml,xsd,csproj,targets,proj,props,runsettings,config}]
+
+#### ReSharper code style for XML ####
+
+## Tabs and indents
+
+resharper_xml_indent_style = space
+resharper_xml_indent_size = 4
+resharper_xml_tab_width = 4
+resharper_xml_alignment_tab_fill_style = use_spaces
+resharper_xml_allow_far_alignment = true
+
+## Line wrapping
+
+resharper_xml_wrap_tags_and_pi = false
+
+## Processing instructions
+
+resharper_xml_spaces_around_eq_in_pi_attribute = false
+resharper_xml_space_after_last_pi_attribute = false
+resharper_xml_pi_attribute_style = on_single_line
+resharper_xml_pi_attributes_indent = align_by_first_attribute
+resharper_xml_blank_line_after_pi = false
+
+## Inside of tag header
+
+resharper_xml_spaces_around_eq_in_attribute = false
+resharper_xml_space_after_last_attribute = false
+resharper_xml_space_before_self_closing = true
+resharper_xml_attribute_style = do_not_touch
+resharper_xml_attribute_indent = align_by_first_attribute
+
+## Tag content
+
+resharper_xml_keep_user_linebreaks = true
+resharper_xml_linebreaks_inside_tags_for_multiline_elements = false
+resharper_xml_linebreaks_inside_tags_for_elements_with_child_elements = false
+resharper_xml_linebreaks_inside_tags_for_elements_longer_than = false
+resharper_xml_spaces_inside_tags = false
+resharper_xml_wrap_text = false
+resharper_xml_wrap_around_elements = false
+resharper_xml_indent_child_elements = one_indent
+resharper_xml_indent_text = zero_indent
+resharper_xml_max_blank_lines_between_tags = 1
+resharper_xml_linebreak_before_multiline_elements = false
+resharper_xml_linebreak_before_singleline_elements = false
+
+## Other
+
+resharper_xml_insert_final_newline = true
diff --git a/.gitattributes b/.gitattributes
index 700825a76..83d35b020 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -15,3 +15,6 @@
*.nupkg binary
*.pdf binary
*.snk binary
+
+# Ensure key files have LF endings for easier usage with ssh-keygen
+test/Data/* eol=lf
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 7d6bdbf60..483a79904 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,7 +5,7 @@ test/**/bin/**
test/**/obj/**
# MSTest test Results
-src/TestResults/
+TestResults/
# User-specific files
*.suo
@@ -15,10 +15,13 @@ src/TestResults/
packages/
# Visual Studio 2015 cache/options directory
-src/.vs/
+.vs/
# Expanded/resolved project.json files
project.lock.json
# Build outputs
build/target/
+
+# Benchmark results
+BenchmarkDotNet.Artifacts/
diff --git a/CODEOWNERS b/CODEOWNERS
new file mode 100644
index 000000000..31f99465e
--- /dev/null
+++ b/CODEOWNERS
@@ -0,0 +1 @@
+* @drieseng @WojciechNagorski
diff --git a/Directory.Build.props b/Directory.Build.props
new file mode 100644
index 000000000..639770b43
--- /dev/null
+++ b/Directory.Build.props
@@ -0,0 +1,41 @@
+
+
+
+
+
+ true
+ $(MSBuildThisFileDirectory)Renci.SshNet.snk
+ true
+ latest
+ 9999
+ true
+ false
+
+
+
+
+ true
+ preview-All
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/LICENSE b/LICENSE
index d13cc4b26..f2aef4f38 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,5 +1,7 @@
The MIT License (MIT)
+Copyright (c) Renci, Oleg Kapeljushnik, Gert Driesen and contributors
+
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
diff --git a/README.md b/README.md
index b44ae97bb..9ab4978f2 100644
--- a/README.md
+++ b/README.md
@@ -80,7 +80,7 @@ the missing test once you figure things out. 🤓
* RSA in OpenSSL PEM and ssh.com format
* DSA in OpenSSL PEM and ssh.com format
* ECDSA 256/384/521 in OpenSSL PEM format
-* ED25519 in OpenSSH key format
+* ECDSA 256/384/521, ED25519 and RSA in OpenSSH key format
Private keys can be encrypted using one of the following cipher methods:
* DES-EDE3-CBC
@@ -97,6 +97,8 @@ Private keys can be encrypted using one of the following cipher methods:
* ecdsa-sha2-nistp256
* ecdsa-sha2-nistp384
* ecdsa-sha2-nistp521
+* rsa-sha2-512
+* rsa-sha2-256
* ssh-rsa
* ssh-dss
@@ -116,15 +118,9 @@ Private keys can be encrypted using one of the following cipher methods:
## Framework Support
**SSH.NET** supports the following target frameworks:
-* .NET Framework 3.5
-* .NET Framework 4.0 (and higher)
-* .NET Standard 1.3
-* .NET Standard 2.0
-* Silverlight 4
-* Silverlight 5
-* Windows Phone 7.1
-* Windows Phone 8.0
-* Universal Windows Platform 10
+* .NETFramework 4.6.2 (and higher)
+* .NET Standard 2.0 and 2.1
+* .NET 6 (and higher)
## Usage
@@ -149,45 +145,18 @@ using (var client = new SftpClient(connectionInfo))
Establish a SSH connection using user name and password, and reject the connection if the fingerprint of the server does not match the expected fingerprint:
```cs
-byte[] expectedFingerPrint = new byte[] {
- 0x66, 0x31, 0xaf, 0x00, 0x54, 0xb9, 0x87, 0x31,
- 0xff, 0x58, 0x1c, 0x31, 0xb1, 0xa2, 0x4c, 0x6b
- };
+string expectedFingerPrint = "LKOy5LvmtEe17S4lyxVXqvs7uPMy+yF79MQpHeCs/Qo";
using (var client = new SshClient("sftp.foo.com", "guest", "pwd"))
{
client.HostKeyReceived += (sender, e) =>
{
- if (expectedFingerPrint.Length == e.FingerPrint.Length)
- {
- for (var i = 0; i < expectedFingerPrint.Length; i++)
- {
- if (expectedFingerPrint[i] != e.FingerPrint[i])
- {
- e.CanTrust = false;
- break;
- }
- }
- }
- else
- {
- e.CanTrust = false;
- }
+ e.CanTrust = expectedFingerPrint.Equals(e.FingerPrintSHA256);
};
client.Connect();
}
```
-## Building SSH.NET
-
-Software | net35 | net40 | netstandard1.3 | netstandard2.0 | sl4 | sl5 | wp71 | wp8 | uap10.0 |
---------------------------------- | :---: | :---: | :------------: | :------------: | :-: | :-: | :--: | :-: | :-----: |
-Windows Phone SDK 8.0 | | | | | x | x | x | x |
-Visual Studio 2012 Update 5 | x | x | | | x | x | x | x |
-Visual Studio 2015 Update 3 | x | x | | | | x | | x | x
-Visual Studio 2017 | x | x | x | x | | | | |
-Visual Studio 2019 | x | x | x | x | | | | |
-
## Supporting SSH.NET
Do you or your company rely on **SSH.NET** in your projects? If you want to encourage us to keep on going and show us that you appreciate our work, please consider becoming a [sponsor](https://github.com/sponsors/sshnet) through GitHub Sponsors.
diff --git a/Renci.SshNet.sln b/Renci.SshNet.sln
new file mode 100644
index 000000000..0ca62c338
--- /dev/null
+++ b/Renci.SshNet.sln
@@ -0,0 +1,222 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.5.33326.253
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "nuget", "nuget", "{94EE3919-19FA-4D9B-8DA9-249050B15232}"
+ ProjectSection(SolutionItems) = preProject
+ build\nuget\SSH.NET.nuspec = build\nuget\SSH.NET.nuspec
+ EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sandcastle", "sandcastle", "{A6C3FFD3-16A5-44D3-8C1F-3613D6DD17D1}"
+ ProjectSection(SolutionItems) = preProject
+ build\sandcastle\SSH.NET.shfbproj = build\sandcastle\SSH.NET.shfbproj
+ EndProjectSection
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Renci.SshNet", "src\Renci.SshNet\Renci.SshNet.csproj", "{2F5F8C90-0BD1-424F-997C-7BC6280919D1}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{04E8CC26-116E-4116-9558-7ED542548E70}"
+ ProjectSection(SolutionItems) = preProject
+ .editorconfig = .editorconfig
+ .gitattributes = .gitattributes
+ .gitignore = .gitignore
+ appveyor.yml = appveyor.yml
+ CODEOWNERS = CODEOWNERS
+ Directory.Build.props = Directory.Build.props
+ global.json = global.json
+ LICENSE = LICENSE
+ README.md = README.md
+ stylecop.json = stylecop.json
+ THIRD-PARTY-NOTICES.TXT = THIRD-PARTY-NOTICES.TXT
+ EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{D21A4D03-0AC2-4613-BB6D-74D2D16A72CC}"
+ ProjectSection(SolutionItems) = preProject
+ test\.editorconfig = test\.editorconfig
+ test\Directory.Build.props = test\Directory.Build.props
+ EndProjectSection
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Renci.SshNet.IntegrationTests", "test\Renci.SshNet.IntegrationTests\Renci.SshNet.IntegrationTests.csproj", "{F17A24ED-4DC3-450C-A2AF-820CCD169828}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Renci.SshNet.Tests", "test\Renci.SshNet.Tests\Renci.SshNet.Tests.csproj", "{86238589-CCDF-4423-A007-989987A783D6}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Renci.SshNet.TestTools.OpenSSH", "test\Renci.SshNet.TestTools.OpenSSH\Renci.SshNet.TestTools.OpenSSH.csproj", "{01AE231E-5D28-4743-A95E-81EE15A823D0}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{2F4155AA-750A-4D33-B2E6-ED06660016CE}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "References", "References", "{47CAF831-32E1-49AD-8E24-6A8732CC2F35}"
+ ProjectSection(SolutionItems) = preProject
+ src\References\How the SCP protocol works.pdf = src\References\How the SCP protocol works.pdf
+ src\References\X.690-0207.pdf = src\References\X.690-0207.pdf
+ src\References\X.690-0207.txt = src\References\X.690-0207.txt
+ EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "images", "images", "{296365E4-2EC8-4762-9640-618867AE3F53}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "logo", "logo", "{1E46D4B6-EE87-4D29-8641-0AE8CD8ED0F0}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ai", "ai", "{19895BAF-F946-470D-8497-7034F9F2A8A7}"
+ ProjectSection(SolutionItems) = preProject
+ images\logo\ai\SS-NET-icon-white.ai = images\logo\ai\SS-NET-icon-white.ai
+ images\logo\ai\SS-NET-icon.ai = images\logo\ai\SS-NET-icon.ai
+ images\logo\ai\SS-NET-white.ai = images\logo\ai\SS-NET-white.ai
+ images\logo\ai\SS-NET.ai = images\logo\ai\SS-NET.ai
+ EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "png", "png", "{3572019A-3A57-4578-B5A2-6280576EB508}"
+ ProjectSection(SolutionItems) = preProject
+ images\logo\png\SS-NET-1280x640.png = images\logo\png\SS-NET-1280x640.png
+ images\logo\png\SS-NET-h50.png = images\logo\png\SS-NET-h50.png
+ images\logo\png\SS-NET-h500.png = images\logo\png\SS-NET-h500.png
+ images\logo\png\SS-NET-icon-h50.png = images\logo\png\SS-NET-icon-h50.png
+ images\logo\png\SS-NET-icon-h500.png = images\logo\png\SS-NET-icon-h500.png
+ images\logo\png\SS-NET-icon-white-h50.png = images\logo\png\SS-NET-icon-white-h50.png
+ images\logo\png\SS-NET-icon-white-h500.png = images\logo\png\SS-NET-icon-white-h500.png
+ images\logo\png\SS-NET-white-h50.png = images\logo\png\SS-NET-white-h50.png
+ images\logo\png\SS-NET-white-h500.png = images\logo\png\SS-NET-white-h500.png
+ EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "svg", "svg", "{92E7B1B8-4C70-4138-9970-433B2FC2E3EB}"
+ ProjectSection(SolutionItems) = preProject
+ images\logo\svg\SS-NET-icon-white.svg = images\logo\svg\SS-NET-icon-white.svg
+ images\logo\svg\SS-NET-icon.svg = images\logo\svg\SS-NET-icon.svg
+ images\logo\svg\SS-NET-white.svg = images\logo\svg\SS-NET-white.svg
+ images\logo\svg\SS-NET.svg = images\logo\svg\SS-NET.svg
+ EndProjectSection
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Renci.SshNet.Benchmarks", "test\Renci.SshNet.Benchmarks\Renci.SshNet.Benchmarks.csproj", "{CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Debug|ARM = Debug|ARM
+ Debug|Mixed Platforms = Debug|Mixed Platforms
+ Debug|x64 = Debug|x64
+ Debug|x86 = Debug|x86
+ Release|Any CPU = Release|Any CPU
+ Release|ARM = Release|ARM
+ Release|Mixed Platforms = Release|Mixed Platforms
+ Release|x64 = Release|x64
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|ARM.ActiveCfg = Debug|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Any CPU.Build.0 = Release|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|ARM.ActiveCfg = Release|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|x64.ActiveCfg = Release|Any CPU
+ {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|x86.ActiveCfg = Release|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Debug|ARM.ActiveCfg = Debug|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Debug|ARM.Build.0 = Debug|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Debug|x64.Build.0 = Debug|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Debug|x86.Build.0 = Debug|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Release|ARM.ActiveCfg = Release|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Release|ARM.Build.0 = Release|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Release|x64.ActiveCfg = Release|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Release|x64.Build.0 = Release|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Release|x86.ActiveCfg = Release|Any CPU
+ {F17A24ED-4DC3-450C-A2AF-820CCD169828}.Release|x86.Build.0 = Release|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Debug|ARM.ActiveCfg = Debug|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Debug|ARM.Build.0 = Debug|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Debug|x64.Build.0 = Debug|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Debug|x86.Build.0 = Debug|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Release|Any CPU.Build.0 = Release|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Release|ARM.ActiveCfg = Release|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Release|ARM.Build.0 = Release|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Release|x64.ActiveCfg = Release|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Release|x64.Build.0 = Release|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Release|x86.ActiveCfg = Release|Any CPU
+ {86238589-CCDF-4423-A007-989987A783D6}.Release|x86.Build.0 = Release|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Debug|ARM.ActiveCfg = Debug|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Debug|ARM.Build.0 = Debug|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Debug|x64.Build.0 = Debug|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Debug|x86.Build.0 = Debug|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Release|Any CPU.Build.0 = Release|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Release|ARM.ActiveCfg = Release|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Release|ARM.Build.0 = Release|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Release|x64.ActiveCfg = Release|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Release|x64.Build.0 = Release|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Release|x86.ActiveCfg = Release|Any CPU
+ {01AE231E-5D28-4743-A95E-81EE15A823D0}.Release|x86.Build.0 = Release|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Debug|ARM.ActiveCfg = Debug|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Debug|ARM.Build.0 = Debug|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Debug|x64.Build.0 = Debug|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Debug|x86.Build.0 = Debug|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Release|Any CPU.Build.0 = Release|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Release|ARM.ActiveCfg = Release|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Release|ARM.Build.0 = Release|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Release|x64.ActiveCfg = Release|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Release|x64.Build.0 = Release|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Release|x86.ActiveCfg = Release|Any CPU
+ {CF6CA77F-E4B8-4522-B267-E3F555E2E7B1}.Release|x86.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D} = {04E8CC26-116E-4116-9558-7ED542548E70}
+ {94EE3919-19FA-4D9B-8DA9-249050B15232} = {2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}
+ {A6C3FFD3-16A5-44D3-8C1F-3613D6DD17D1} = {2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}
+ {D21A4D03-0AC2-4613-BB6D-74D2D16A72CC} = {04E8CC26-116E-4116-9558-7ED542548E70}
+ {2F4155AA-750A-4D33-B2E6-ED06660016CE} = {04E8CC26-116E-4116-9558-7ED542548E70}
+ {47CAF831-32E1-49AD-8E24-6A8732CC2F35} = {2F4155AA-750A-4D33-B2E6-ED06660016CE}
+ {296365E4-2EC8-4762-9640-618867AE3F53} = {04E8CC26-116E-4116-9558-7ED542548E70}
+ {1E46D4B6-EE87-4D29-8641-0AE8CD8ED0F0} = {296365E4-2EC8-4762-9640-618867AE3F53}
+ {19895BAF-F946-470D-8497-7034F9F2A8A7} = {1E46D4B6-EE87-4D29-8641-0AE8CD8ED0F0}
+ {3572019A-3A57-4578-B5A2-6280576EB508} = {1E46D4B6-EE87-4D29-8641-0AE8CD8ED0F0}
+ {92E7B1B8-4C70-4138-9970-433B2FC2E3EB} = {1E46D4B6-EE87-4D29-8641-0AE8CD8ED0F0}
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {BAD6019D-4AF7-4E15-99A0-8036E16FC0E5}
+ EndGlobalSection
+ GlobalSection(TestCaseManagementSettings) = postSolution
+ CategoryFile = Renci.SshNet1.vsmdi
+ EndGlobalSection
+EndGlobal
diff --git a/src/Renci.SshNet.snk b/Renci.SshNet.snk
similarity index 100%
rename from src/Renci.SshNet.snk
rename to Renci.SshNet.snk
diff --git a/appveyor.yml b/appveyor.yml
index c5bb4a18e..56f84c117 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -1,14 +1,59 @@
-os: Visual Studio 2019
+image:
+ - Ubuntu2204
+ - Visual Studio 2022
-before_build:
- - nuget restore src\Renci.SshNet.VS2019.sln
+services:
+ - docker
-build:
- project: src\Renci.SshNet.VS2019.sln
- verbosity: minimal
+for:
+-
+ matrix:
+ only:
+ - image: Ubuntu2204
-test_script:
-- cmd: >-
- vstest.console /logger:Appveyor src\Renci.SshNet.Tests\bin\Debug\net40\Renci.SshNet.Tests.dll /TestCaseFilter:"TestCategory!=integration&TestCategory!=LongRunning"
+ install:
+ - sh: sudo apt-get update && sudo apt-get install -y dotnet-sdk-8.0=8.0.100-1
+
+ before_build:
+ - sh: mkdir artifacts -p
+
+ build_script:
+ - echo build
+ - dotnet build Renci.SshNet.sln -c Debug -f net8.0
- vstest.console /logger:Appveyor src\Renci.SshNet.Tests\bin\Debug\net35\Renci.SshNet.Tests.dll /TestCaseFilter:"TestCategory!=integration&TestCategory!=LongRunning"
\ No newline at end of file
+ test_script:
+ - sh: echo "Run unit tests"
+ - sh: dotnet test -f net8.0 -c Debug --no-restore --no-build --results-directory artifacts --logger Appveyor --logger "console;verbosity=normal" --logger "liquid.md;LogFileName=linux_unit_test_net_8_report.md" -p:CollectCoverage=true -p:CoverletOutputFormat=cobertura -p:CoverletOutput=../../artifacts/linux_unit_test_net_8_coverage.xml test/Renci.SshNet.Tests/Renci.SshNet.Tests.csproj
+ - sh: echo "Run integration tests"
+ - sh: dotnet test -c Debug --no-restore --no-build --results-directory artifacts --logger Appveyor --logger "console;verbosity=normal" --logger "liquid.md;LogFileName=linux_integration_test_net_8_report.md" -p:CollectCoverage=true -p:CoverletOutputFormat=cobertura -p:CoverletOutput=../../artifacts/linux_integration_test_net_8_coverage.xml test/Renci.SshNet.IntegrationTests/Renci.SshNet.IntegrationTests.csproj
+
+# on_failure:
+# - sh: appveyor PushArtifact artifacts/tcpdump.pcap
+
+-
+ matrix:
+ only:
+ - image: Visual Studio 2022
+
+ install:
+ - ps: choco install dotnet-8.0-sdk --version=8.0.100
+
+ before_build:
+ - ps: mkdir artifacts -f
+
+ build_script:
+ - echo build
+ - dotnet build Renci.SshNet.sln -c Debug
+
+ test_script:
+ - ps: echo "Run unit tests for .NET 8.0"
+ - ps: dotnet test -f net8.0 -c Debug --no-restore --no-build --results-directory artifacts --logger Appveyor --logger "console;verbosity=normal" --logger "liquid.md;LogFileName=windows_unit_test_net_8_report.md" -p:CollectCoverage=true -p:CoverletOutputFormat=cobertura -p:CoverletOutput=../../artifacts/windows_unit_test_net_8_coverage.xml test/Renci.SshNet.Tests/Renci.SshNet.Tests.csproj
+ - ps: echo "Run unit tests for .NET Framework 4.6.2"
+ - ps: dotnet test -f net462 -c Debug --no-restore --no-build --results-directory artifacts --logger Appveyor --logger "console;verbosity=normal" --logger "liquid.md;LogFileName=windows_unit_test_net_4_6_2_report.md" -p:CollectCoverage=true -p:CoverletOutputFormat=cobertura -p:CoverletOutput=../../artifacts/windows_unit_test_net_4_6_2_coverage.xml test/Renci.SshNet.Tests/Renci.SshNet.Tests.csproj
+
+# on_failure:
+# - ps: Push-AppveyorArtifact artifacts/tcpdump.pcap
+
+artifacts:
+ - path: artifacts
+ name: artifacts
diff --git a/build/build.proj b/build/build.proj
index 40ef012b6..00dc2dc12 100644
--- a/build/build.proj
+++ b/build/build.proj
@@ -8,86 +8,45 @@
MSBuildTasks
1.5.0.214
-
-
-
- $(MSBuildThisFileDirectory)..\src\Renci.SshNet.VS2012.sln
- 14.0
- 14.0
-
-
- $(MSBuildThisFileDirectory)..\src\Renci.SshNet.VS2015.sln
- 14.0
- 14.0
-
-
-
-
-
- $(MSBuildThisFileDirectory)..\src\Renci.SshNet.VS2019.sln
- 16.0
-
-
-
- Renci.SshNet.WindowsPhone\bin\$(Configuration)
- wp71
-
-
- Renci.SshNet.WindowsPhone8\bin\$(Configuration)
- wp8
-
-
- Renci.SshNet.Silverlight\bin\$(Configuration)
- sl4
-
-
- Renci.SshNet.Silverlight5\bin\$(Configuration)
- sl5
-
-
- Renci.SshNet.UAP10\bin\$(Configuration)
- uap10
-
+
+ $(MSBuildThisFileDirectory)..\src\Renci.SshNet.sln
+ 17.0
+
-
- Renci.SshNet\bin\$(Configuration)\net35
- net35
-
-
- Renci.SshNet\bin\$(Configuration)\net40
- net40
-
-
- Renci.SshNet\bin\$(Configuration)\netstandard1.3
- netstandard1.3
+
+ Renci.SshNet\bin\$(Configuration)\net462
+ net462
Renci.SshNet\bin\$(Configuration)\netstandard2.0
netstandard2.0
+
+ Renci.SshNet\bin\$(Configuration)\netstandard2.1
+ netstandard2.1
+
+
+ Renci.SshNet\bin\$(Configuration)\net6.0
+ net6.0
+
+
+ Renci.SshNet\bin\$(Configuration)\net7.0
+ net7.0
+
+
+ Renci.SshNet\bin\$(Configuration)\net8.0
+ net8.0
+
-
-
-
-
-
+
-
-
-
-
- Configuration=Release;VisualStudioVersion=%(VisualStudioVersionClassic.VisualStudioVersion)
-
-
-
-
@@ -99,26 +58,11 @@
-
-
-
-
-
-
-
-
-
-
- Configuration=Release;VisualStudioVersion=%(VisualStudioVersionClassic.VisualStudioVersion)
-
-
-
-
-
+
@@ -131,12 +75,7 @@
-
-
-
-
-
-
+
@@ -153,16 +92,6 @@
-
-
-
-
-
-
-
-
-
-
diff --git a/build/nuget/SSH.NET.nuspec b/build/nuget/SSH.NET.nuspec
index 038305832..50074d866 100644
--- a/build/nuget/SSH.NET.nuspec
+++ b/build/nuget/SSH.NET.nuspec
@@ -6,7 +6,7 @@
SSH.NET
Renci
olegkap,drieseng
- https://github.com/sshnet/SSH.NET/blob/master/LICENSE
+ MIT
https://github.com/sshnet/SSH.NET/
false
SSH.NET is a Secure Shell (SSH) library for .NET, optimized for parallelism and with broad framework support.
@@ -16,38 +16,25 @@
en-US
ssh scp sftp
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
-
-
-
-
-
+
+
-
+
-
+
-
+
-
-
\ No newline at end of file
+
diff --git a/build/sandcastle/SSH.NET.shfbproj b/build/sandcastle/SSH.NET.shfbproj
index 29fff93e0..15d8dc2f2 100644
--- a/build/sandcastle/SSH.NET.shfbproj
+++ b/build/sandcastle/SSH.NET.shfbproj
@@ -1,21 +1,22 @@
-
+
+ v4.6.2
+
Debug
AnyCPU
+
2.0
{f7266fb1-f50a-4a5b-b35a-5ea8ebdc1be9}
- 2015.6.5.0
+ 2017.9.26.0
Documentation
Documentation
Documentation
- .NET Framework 4.0
+ .NET Framework 4.6.2
..\target\help
SshNet.Help
en-US
@@ -24,25 +25,15 @@
C#
Blank
False
- VS2010
+ VS2013
False
Guid
- SSH.NET Client Library Documenation
+ SSH.NET Client Library Documentation
AboveNamespaces
-
-
-
-
- {@HelpFormatOutputPaths}
-
-
-
-
-
-
+
-
-
+
+
Summary, Parameter, Returns, AutoDocumentCtors, TypeParameter, AutoDocumentDispose
OnlyWarningsAndErrors
@@ -54,7 +45,7 @@
True
+ the build. The others are optional common platform types that may appear. -->
@@ -73,4 +64,4 @@
-
\ No newline at end of file
+
diff --git a/global.json b/global.json
new file mode 100644
index 000000000..d07970ac2
--- /dev/null
+++ b/global.json
@@ -0,0 +1,6 @@
+{
+ "sdk": {
+ "version": "8.0.100",
+ "rollForward": "latestMajor"
+ }
+}
diff --git a/images/logo/png/SS-NET-1280x640.png b/images/logo/png/SS-NET-1280x640.png
new file mode 100644
index 000000000..d2e5bfd4c
Binary files /dev/null and b/images/logo/png/SS-NET-1280x640.png differ
diff --git a/src/Renci.SshNet.Silverlight/Properties/AssemblyInfo.cs b/src/Renci.SshNet.Silverlight/Properties/AssemblyInfo.cs
deleted file mode 100644
index f9c8d3244..000000000
--- a/src/Renci.SshNet.Silverlight/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,5 +0,0 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-[assembly: AssemblyTitle("SSH.NET Silverlight 4")]
-[assembly: Guid("2b3f6251-8079-48aa-a76b-df70e40092e2")]
\ No newline at end of file
diff --git a/src/Renci.SshNet.Silverlight/Renci.SshNet.Silverlight.csproj b/src/Renci.SshNet.Silverlight/Renci.SshNet.Silverlight.csproj
deleted file mode 100644
index beeef21a0..000000000
--- a/src/Renci.SshNet.Silverlight/Renci.SshNet.Silverlight.csproj
+++ /dev/null
@@ -1,1456 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 8.0.50727
- 2.0
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}
- {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}
- Library
- Properties
- Renci.SshNet
- Renci.SshNet
- Silverlight
- v4.0
- $(TargetFrameworkVersion)
- false
- true
- true
-
-
-
- v3.5
-
-
- true
- full
- false
- Bin\Debug
- TRACE;DEBUG;FEATURE_DIRECTORYINFO_ENUMERATEFILES;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_HASH_SHA1_MANAGED;FEATURE_HASH_SHA256_MANAGED;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256;FEATURE_MEMORYSTREAM_GETBUFFER
- true
- true
- prompt
- 4
- Bin\Debug\Renci.SshNet.xml
-
-
- none
- true
- Bin\Release
- TRACE;FEATURE_DIRECTORYINFO_ENUMERATEFILES;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_HASH_SHA1_MANAGED;FEATURE_HASH_SHA256_MANAGED;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256;FEATURE_MEMORYSTREAM_GETBUFFER
- true
- true
- prompt
- 4
- Bin\Release\Renci.SshNet.xml
- 1591
-
-
- true
-
-
- ..\Renci.SshNet.snk
-
-
-
-
- ..\..\packages\SshNet.Security.Cryptography.1.2.0\lib\sl4\SshNet.Security.Cryptography.dll
-
-
-
-
-
-
-
-
- Abstractions\CryptoAbstraction.cs
-
-
- Abstractions\DiagnosticAbstraction.cs
-
-
- Abstractions\DnsAbstraction.cs
-
-
- Abstractions\FileSystemAbstraction.cs
-
-
- Abstractions\ReflectionAbstraction.cs
-
-
- Abstractions\SocketAbstraction.cs
-
-
- Abstractions\ThreadAbstraction.cs
-
-
- AuthenticationMethod.cs
-
-
- AuthenticationResult.cs
-
-
- BaseClient.cs
-
-
- Channels\Channel.cs
-
-
- Channels\ChannelDirectTcpip.cs
-
-
- Channels\ChannelForwardedTcpip.cs
-
-
- Channels\ChannelSession.cs
-
-
- Channels\ChannelTypes.cs
-
-
- Channels\ClientChannel.cs
-
-
- Channels\IChannel.cs
-
-
- Channels\IChannelDirectTcpip.cs
-
-
- Channels\IChannelForwardedTcpip.cs
-
-
- Channels\IChannelSession.cs
-
-
- Channels\ServerChannel.cs
-
-
- CipherInfo.cs
-
-
- ClientAuthentication.cs
-
-
- CommandAsyncResult.cs
-
-
- Common\Array.cs
-
-
- Common\ASCIIEncoding.cs
-
-
- Common\AsyncResult.cs
-
-
- Common\AuthenticationBannerEventArgs.cs
-
-
- Common\AuthenticationEventArgs.cs
-
-
- Common\AuthenticationPasswordChangeEventArgs.cs
-
-
- Common\AuthenticationPrompt.cs
-
-
- Common\AuthenticationPromptEventArgs.cs
-
-
- Common\BigInteger.cs
-
-
- Common\ChannelDataEventArgs.cs
-
-
- Common\ChannelEventArgs.cs
-
-
- Common\ChannelExtendedDataEventArgs.cs
-
-
- Common\ChannelOpenConfirmedEventArgs.cs
-
-
- Common\ChannelOpenFailedEventArgs.cs
-
-
- Common\ChannelRequestEventArgs.cs
-
-
- Common\CountdownEvent.cs
-
-
- Common\DerData.cs
-
-
- Common\ExceptionEventArgs.cs
-
-
- Common\Extensions.cs
-
-
- Common\HostKeyEventArgs.cs
-
-
- Common\ObjectIdentifier.cs
-
-
- Common\Pack.cs
-
-
- Common\PacketDump.cs
-
-
- Common\PipeStream.cs
-
-
- Common\PortForwardEventArgs.cs
-
-
- Common\PosixPath.cs
-
-
- Common\ProxyException.cs
-
-
- Common\ScpDownloadEventArgs.cs
-
-
- Common\ScpException.cs
-
-
- Common\ScpUploadEventArgs.cs
-
-
- Common\SemaphoreLight.cs
-
-
- Common\SftpPathNotFoundException.cs
-
-
- Common\SftpPermissionDeniedException.cs
-
-
- Common\ShellDataEventArgs.cs
-
-
- Common\SshAuthenticationException.cs
-
-
- Common\SshConnectionException.cs
-
-
- Common\SshData.cs
-
-
- Common\SshDataStream.cs
-
-
- Common\SshException.cs
-
-
- Common\SshOperationTimeoutException.cs
-
-
- Common\SshPassPhraseNullOrEmptyException.cs
-
-
- Common\TerminalModes.cs
-
-
- Compression\CompressionMode.cs
-
-
- Compression\Compressor.cs
-
-
- Compression\Zlib.cs
-
-
- Compression\ZlibOpenSsh.cs
-
-
- Compression\ZlibStream.cs
-
-
- ConnectionInfo.cs
-
-
- Connection\ConnectorBase.cs
-
-
- Connection\DirectConnector.cs
-
-
- Connection\HttpConnector.cs
-
-
- Connection\IConnector.cs
-
-
- Connection\IProtocolVersionExchange.cs
-
-
- Connection\ISocketFactory.cs
-
-
- Connection\ProtocolVersionExchange.cs
-
-
- Connection\SocketFactory.cs
-
-
- Connection\Socks4Connector.cs
-
-
- Connection\Socks5Connector.cs
-
-
- Connection\SshIdentification.cs
-
-
- ExpectAction.cs
-
-
- ExpectAsyncResult.cs
-
-
- ForwardedPort.cs
-
-
- ForwardedPortDynamic.cs
-
-
- ForwardedPortLocal.cs
-
-
- ForwardedPortRemote.cs
-
-
- ForwardedPortStatus.cs
-
-
- HashInfo.cs
-
-
- IAuthenticationMethod.cs
-
-
- IClientAuthentication.cs
-
-
- IConnectionInfo.cs
-
-
- IForwardedPort.cs
-
-
- IRemotePathTransformation.cs
-
-
- IServiceFactory.cs
-
-
- ISession.cs
-
-
- ISubsystemSession.cs
-
-
- KeyboardInteractiveAuthenticationMethod.cs
-
-
- KeyboardInteractiveConnectionInfo.cs
-
-
- MessageEventArgs.cs
-
-
- Messages\Authentication\BannerMessage.cs
-
-
- Messages\Authentication\FailureMessage.cs
-
-
- Messages\Authentication\InformationRequestMessage.cs
-
-
- Messages\Authentication\InformationResponseMessage.cs
-
-
- Messages\Authentication\PasswordChangeRequiredMessage.cs
-
-
- Messages\Authentication\PublicKeyMessage.cs
-
-
- Messages\Authentication\RequestMessage.cs
-
-
- Messages\Authentication\RequestMessageHost.cs
-
-
- Messages\Authentication\RequestMessageKeyboardInteractive.cs
-
-
- Messages\Authentication\RequestMessageNone.cs
-
-
- Messages\Authentication\RequestMessagePassword.cs
-
-
- Messages\Authentication\RequestMessagePublicKey.cs
-
-
- Messages\Authentication\SuccessMessage.cs
-
-
- Messages\Connection\CancelTcpIpForwardGlobalRequestMessage.cs
-
-
- Messages\Connection\ChannelCloseMessage.cs
-
-
- Messages\Connection\ChannelDataMessage.cs
-
-
- Messages\Connection\ChannelEofMessage.cs
-
-
- Messages\Connection\ChannelExtendedDataMessage.cs
-
-
- Messages\Connection\ChannelFailureMessage.cs
-
-
- Messages\Connection\ChannelMessage.cs
-
-
- Messages\Connection\ChannelOpenConfirmationMessage.cs
-
-
- Messages\Connection\ChannelOpenFailureMessage.cs
-
-
- Messages\Connection\ChannelOpenFailureReasons.cs
-
-
- Messages\Connection\ChannelOpen\ChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelOpen\ChannelOpenMessage.cs
-
-
- Messages\Connection\ChannelOpen\DirectTcpipChannelInfo.cs
-
-
- Messages\Connection\ChannelOpen\ForwardedTcpipChannelInfo.cs
-
-
- Messages\Connection\ChannelOpen\SessionChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelOpen\X11ChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelRequest\BreakRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ChannelRequestMessage.cs
-
-
- Messages\Connection\ChannelRequest\EndOfWriteRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\EnvironmentVariableRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExecRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExitSignalRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExitStatusRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\KeepAliveRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\PseudoTerminalInfo.cs
-
-
- Messages\Connection\ChannelRequest\RequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ShellRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\SignalRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\SubsystemRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\WindowChangeRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\X11ForwardingRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\XonXoffRequestInfo.cs
-
-
- Messages\Connection\ChannelSuccessMessage.cs
-
-
- Messages\Connection\ChannelWindowAdjustMessage.cs
-
-
- Messages\Connection\GlobalRequestMessage.cs
-
-
- Messages\Connection\GlobalRequestName.cs
-
-
- Messages\Connection\RequestFailureMessage.cs
-
-
- Messages\Connection\RequestSuccessMessage.cs
-
-
- Messages\Connection\TcpIpForwardGlobalRequestMessage.cs
-
-
- Messages\Message.cs
-
-
- Messages\MessageAttribute.cs
-
-
- Messages\ServiceName.cs
-
-
- Messages\Transport\DebugMessage.cs
-
-
- Messages\Transport\DisconnectMessage.cs
-
-
- Messages\Transport\DisconnectReason.cs
-
-
- Messages\Transport\IgnoreMessage.cs
-
-
- Messages\Transport\IKeyExchangedAllowed.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeGroup.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeInit.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeReply.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeRequest.cs
-
-
- Messages\Transport\KeyExchangeDhInitMessage.cs
-
-
- Messages\Transport\KeyExchangeDhReplyMessage.cs
-
-
- Messages\Transport\KeyExchangeEcdhInitMessage.cs
-
-
- Messages\Transport\KeyExchangeEcdhReplyMessage.cs
-
-
- Messages\Transport\KeyExchangeInitMessage.cs
-
-
- Messages\Transport\NewKeysMessage.cs
-
-
- Messages\Transport\ServiceAcceptMessage.cs
-
-
- Messages\Transport\ServiceRequestMessage.cs
-
-
- Messages\Transport\UnimplementedMessage.cs
-
-
- NoneAuthenticationMethod.cs
-
-
- PasswordAuthenticationMethod.cs
-
-
- PasswordConnectionInfo.cs
-
-
- PrivateKeyAuthenticationMethod.cs
-
-
- PrivateKeyConnectionInfo.cs
-
-
- PrivateKeyFile.cs
-
-
- ProxyTypes.cs
-
-
- RemotePathDoubleQuoteTransformation.cs
-
-
- RemotePathNoneTransformation.cs
-
-
- RemotePathShellQuoteTransformation.cs
-
-
- RemotePathTransformation.cs
-
-
- ScpClient.cs
-
-
- Security\Algorithm.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\sec\SECNamedCurves.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9Curve.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECParameters.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECParametersHolder.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECPoint.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\agreement\ECDHCBasicAgreement.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\AsymmetricCipherKeyPair.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\AsymmetricKeyParameter.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\digests\GeneralDigest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\digests\Sha256Digest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\generators\ECKeyPairGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\IAsymmetricCipherKeyPairGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\IDigest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\KeyGenerationParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECDomainParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECKeyGenerationParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECPrivateKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECPublicKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\CryptoApiRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\DigestRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\IRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\util\Pack.cs
-
-
- Security\Cryptography\BouncyCastle\math\BigInteger.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\SimpleBigDecimal.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\Tnaf.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\ZTauElement.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECAlgorithms.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECCurve.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECFieldElement.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECLookupTable.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECPoint.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECPointMap.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\endo\ECEndomorphism.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\endo\GlvEndomorphism.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\LongArray.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\AbstractECMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\ECMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointCombMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\GlvMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\IPreCompCallback.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\PreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\ValidityPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafL2RMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WTauNafMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WTauNafPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\FiniteFields.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\GenericPolynomialExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\GF2Polynomial.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IFiniteField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IPolynomial.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IPolynomialExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\PrimeField.cs
-
-
- Security\Cryptography\BouncyCastle\math\raw\Mod.cs
-
-
- Security\Cryptography\BouncyCastle\math\raw\Nat.cs
-
-
- Security\Cryptography\BouncyCastle\security\DigestUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\security\SecureRandom.cs
-
-
- Security\Cryptography\BouncyCastle\security\SecurityUtilityException.cs
-
-
- Security\Cryptography\BouncyCastle\util\Arrays.cs
-
-
- Security\Cryptography\BouncyCastle\util\BigIntegers.cs
-
-
- Security\Cryptography\BouncyCastle\util\encoders\Hex.cs
-
-
- Security\Cryptography\BouncyCastle\util\encoders\HexEncoder.cs
-
-
- Security\Cryptography\BouncyCastle\util\IMemoable.cs
-
-
- Security\Cryptography\BouncyCastle\util\Integers.cs
-
-
- Security\Cryptography\BouncyCastle\util\MemoableResetException.cs
-
-
- Security\Cryptography\BouncyCastle\util\Times.cs
-
-
- Security\CertificateHostAlgorithm.cs
-
-
- Security\Cryptography\Chaos.NaCl\CryptoBytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Ed25519.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Array16.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Array8.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\ByteIntegerConverter.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\base.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\base2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\d.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\d2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_1.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_cmov.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_cswap.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_frombytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_invert.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_isnegative.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_isnonzero.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_mul.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_mul121666.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_neg.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_pow22523.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sq.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sq2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\FieldElement.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_double_scalarmult.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_frombytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_madd.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_msub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p1p1_to_p2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p1p1_to_p3.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p2_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p2_dbl.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_dbl.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_to_cached.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_to_p2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_precomp_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_scalarmult_base.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_sub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\GroupElement.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\keypair.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\open.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\scalarmult.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_clamp.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_mul_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_reduce.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sign.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sqrtm1.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\InternalAssert.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Poly1305Donna.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Salsa\Salsa20.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Salsa\SalsaCore.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Sha512Internal.cs
-
-
- Security\Cryptography\Chaos.NaCl\MontgomeryCurve25519.cs
-
-
- Security\Cryptography\Chaos.NaCl\Sha512.cs
-
-
- Security\Cryptography\AsymmetricCipher.cs
-
-
- Security\Cryptography\Bcrypt.cs
-
-
- Security\Cryptography\BlockCipher.cs
-
-
- Security\Cryptography\Cipher.cs
-
-
- Security\Cryptography\CipherDigitalSignature.cs
-
-
- Security\Cryptography\Ciphers\AesCipher.cs
-
-
- Security\Cryptography\Ciphers\Arc4Cipher.cs
-
-
- Security\Cryptography\Ciphers\BlowfishCipher.cs
-
-
- Security\Cryptography\Ciphers\CastCipher.cs
-
-
- Security\Cryptography\Ciphers\CipherMode.cs
-
-
- Security\Cryptography\Ciphers\CipherPadding.cs
-
-
- Security\Cryptography\Ciphers\DesCipher.cs
-
-
- Security\Cryptography\Ciphers\Modes\CbcCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\CfbCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\CtrCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\OfbCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Paddings\PKCS7Padding.cs
-
-
- Security\Cryptography\Ciphers\Paddings\PKCS5Padding.cs
-
-
- Security\Cryptography\Ciphers\RsaCipher.cs
-
-
- Security\Cryptography\Ciphers\SerpentCipher.cs
-
-
- Security\Cryptography\Ciphers\TripleDesCipher.cs
-
-
- Security\Cryptography\Ciphers\TwofishCipher.cs
-
-
- Security\Cryptography\DigitalSignature.cs
-
-
- Security\Cryptography\DsaDigitalSignature.cs
-
-
- Security\Cryptography\DsaKey.cs
-
-
- Security\Cryptography\ED25519DigitalSignature.cs
-
-
- Security\Cryptography\ED25519Key.cs
-
-
- Security\Cryptography\HMACMD5.cs
-
-
- Security\Cryptography\HMACSHA1.cs
-
-
- Security\Cryptography\HMACSHA256.cs
-
-
- Security\Cryptography\HMACSHA384.cs
-
-
- Security\Cryptography\HMACSHA512.cs
-
-
- Security\Cryptography\Key.cs
-
-
- Security\Cryptography\RsaDigitalSignature.cs
-
-
- Security\Cryptography\RsaKey.cs
-
-
- Security\Cryptography\StreamCipher.cs
-
-
- Security\Cryptography\SymmetricCipher.cs
-
-
- Security\GroupExchangeHashData.cs
-
-
- Security\HostAlgorithm.cs
-
-
- Security\IKeyExchange.cs
-
-
- Security\KeyExchange.cs
-
-
- Security\KeyExchangeDiffieHellman.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup14Sha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup14Sha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup16Sha512.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup1Sha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeSha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeSha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeShaBase.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha512.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupShaBase.cs
-
-
- Security\KeyExchangeEC.cs
-
-
- Security\KeyExchangeECCurve25519.cs
-
-
- Security\KeyExchangeECDH.cs
-
-
- Security\KeyExchangeECDH256.cs
-
-
- Security\KeyExchangeECDH384.cs
-
-
- Security\KeyExchangeECDH521.cs
-
-
- Security\KeyExchangeHash.cs
-
-
- Security\KeyHostAlgorithm.cs
-
-
- ServiceFactory.cs
-
-
- Session.cs
-
-
- SftpClient.cs
-
-
- ISftpClient.cs
-
-
- Sftp\Flags.cs
-
-
- Sftp\ISftpFileReader.cs
-
-
- Sftp\ISftpResponseFactory.cs
-
-
- Sftp\ISftpSession.cs
-
-
- Sftp\Requests\ExtendedRequests\FStatVfsRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\HardLinkRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\PosixRenameRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\StatVfsRequest.cs
-
-
- Sftp\Requests\SftpBlockRequest.cs
-
-
- Sftp\Requests\SftpCloseRequest.cs
-
-
- Sftp\Requests\SftpExtendedRequest.cs
-
-
- Sftp\Requests\SftpFSetStatRequest.cs
-
-
- Sftp\Requests\SftpFStatRequest.cs
-
-
- Sftp\Requests\SftpInitRequest.cs
-
-
- Sftp\Requests\SftpLinkRequest.cs
-
-
- Sftp\Requests\SftpLStatRequest.cs
-
-
- Sftp\Requests\SftpMkDirRequest.cs
-
-
- Sftp\Requests\SftpOpenDirRequest.cs
-
-
- Sftp\Requests\SftpOpenRequest.cs
-
-
- Sftp\Requests\SftpReadDirRequest.cs
-
-
- Sftp\Requests\SftpReadLinkRequest.cs
-
-
- Sftp\Requests\SftpReadRequest.cs
-
-
- Sftp\Requests\SftpRealPathRequest.cs
-
-
- Sftp\Requests\SftpRemoveRequest.cs
-
-
- Sftp\Requests\SftpRenameRequest.cs
-
-
- Sftp\Requests\SftpRequest.cs
-
-
- Sftp\Requests\SftpRmDirRequest.cs
-
-
- Sftp\Requests\SftpSetStatRequest.cs
-
-
- Sftp\Requests\SftpStatRequest.cs
-
-
- Sftp\Requests\SftpSymLinkRequest.cs
-
-
- Sftp\Requests\SftpUnblockRequest.cs
-
-
- Sftp\Requests\SftpWriteRequest.cs
-
-
- Sftp\Responses\ExtendedReplies\ExtendedReplyInfo.cs
-
-
- Sftp\Responses\ExtendedReplies\StatVfsReplyInfo.cs
-
-
- Sftp\Responses\SftpAttrsResponse.cs
-
-
- Sftp\Responses\SftpDataResponse.cs
-
-
- Sftp\Responses\SftpExtendedReplyResponse.cs
-
-
- Sftp\Responses\SftpHandleResponse.cs
-
-
- Sftp\Responses\SftpNameResponse.cs
-
-
- Sftp\Responses\SftpResponse.cs
-
-
- Sftp\Responses\SftpStatusResponse.cs
-
-
- Sftp\Responses\SftpVersionResponse.cs
-
-
- Sftp\SftpCloseAsyncResult.cs
-
-
- Sftp\SftpDownloadAsyncResult.cs
-
-
- Sftp\SftpFile.cs
-
-
- Sftp\SftpFileAttributes.cs
-
-
- Sftp\SftpFileReader.cs
-
-
- Sftp\SftpFileStream.cs
-
-
- Sftp\SftpFileSystemInformation.cs
-
-
- Sftp\SftpListDirectoryAsyncResult.cs
-
-
- Sftp\SftpMessage.cs
-
-
- Sftp\SftpMessageTypes.cs
-
-
- Sftp\SftpOpenAsyncResult.cs
-
-
- Sftp\SftpReadAsyncResult.cs
-
-
- Sftp\SftpRealPathAsyncResult.cs
-
-
- Sftp\SftpResponseFactory.cs
-
-
- Sftp\SftpSession.cs
-
-
- Sftp\SFtpStatAsyncResult.cs
-
-
- Sftp\SftpSynchronizeDirectoriesAsyncResult.cs
-
-
- Sftp\SftpUploadAsyncResult.cs
-
-
- Sftp\StatusCodes.cs
-
-
- Shell.cs
-
-
- ShellStream.cs
-
-
- SshClient.cs
-
-
- SshCommand.cs
-
-
- SshMessageFactory.cs
-
-
- SubsystemSession.cs
-
-
-
- Properties\CommonAssemblyInfo.cs
-
-
-
-
- Renci.SshNet.snk
-
-
- Designer
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Renci.SshNet.Silverlight/packages.config b/src/Renci.SshNet.Silverlight/packages.config
deleted file mode 100644
index c0653dc39..000000000
--- a/src/Renci.SshNet.Silverlight/packages.config
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/src/Renci.SshNet.Silverlight5/Properties/AssemblyInfo.cs b/src/Renci.SshNet.Silverlight5/Properties/AssemblyInfo.cs
deleted file mode 100644
index 7266e1543..000000000
--- a/src/Renci.SshNet.Silverlight5/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,5 +0,0 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-[assembly: AssemblyTitle("SSH.NET Silverlight 5")]
-[assembly: Guid("2b3f6251-8079-48aa-a76b-df70e40092e2")]
\ No newline at end of file
diff --git a/src/Renci.SshNet.Silverlight5/Renci.SshNet.Silverlight5.csproj b/src/Renci.SshNet.Silverlight5/Renci.SshNet.Silverlight5.csproj
deleted file mode 100644
index 93b950edc..000000000
--- a/src/Renci.SshNet.Silverlight5/Renci.SshNet.Silverlight5.csproj
+++ /dev/null
@@ -1,1460 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 8.0.50727
- 2.0
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}
- {A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}
- Library
- Properties
- Renci.SshNet
- Renci.SshNet
- Silverlight
- v5.0
- $(TargetFrameworkVersion)
- false
- true
- true
-
-
-
- v3.5
-
-
- true
- full
- false
- Bin\Debug
- TRACE;DEBUG;FEATURE_DIRECTORYINFO_ENUMERATEFILES;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_HASH_SHA1_MANAGED;FEATURE_HASH_SHA256_MANAGED;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256
- true
- true
- prompt
- 4
- false
- Bin\Debug\Renci.SshNet.xml
- true
-
-
- none
- true
- Bin\Release
- TRACE;FEATURE_DIRECTORYINFO_ENUMERATEFILES;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_HASH_SHA1_MANAGED;FEATURE_HASH_SHA256_MANAGED;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256
- true
- true
- prompt
- 4
- false
- Bin\Release\Renci.SshNet.xml
-
-
- true
-
-
- true
-
-
- ..\Renci.SshNet.snk
-
-
-
-
- ..\..\packages\SshNet.Security.Cryptography.1.2.0\lib\sl5\SshNet.Security.Cryptography.dll
- True
-
-
-
-
-
-
-
-
- Abstractions\CryptoAbstraction.cs
-
-
- Abstractions\DiagnosticAbstraction.cs
-
-
- Abstractions\DnsAbstraction.cs
-
-
- Abstractions\FileSystemAbstraction.cs
-
-
- Abstractions\ReflectionAbstraction.cs
-
-
- Abstractions\SocketAbstraction.cs
-
-
- Abstractions\ThreadAbstraction.cs
-
-
- AuthenticationMethod.cs
-
-
- AuthenticationResult.cs
-
-
- BaseClient.cs
-
-
- Channels\Channel.cs
-
-
- Channels\ChannelDirectTcpip.cs
-
-
- Channels\ChannelForwardedTcpip.cs
-
-
- Channels\ChannelSession.cs
-
-
- Channels\ChannelTypes.cs
-
-
- Channels\ClientChannel.cs
-
-
- Channels\IChannel.cs
-
-
- Channels\IChannelDirectTcpip.cs
-
-
- Channels\IChannelForwardedTcpip.cs
-
-
- Channels\IChannelSession.cs
-
-
- Channels\ServerChannel.cs
-
-
- CipherInfo.cs
-
-
- ClientAuthentication.cs
-
-
- CommandAsyncResult.cs
-
-
- Common\Array.cs
-
-
- Common\ASCIIEncoding.cs
-
-
- Common\AsyncResult.cs
-
-
- Common\AuthenticationBannerEventArgs.cs
-
-
- Common\AuthenticationEventArgs.cs
-
-
- Common\AuthenticationPasswordChangeEventArgs.cs
-
-
- Common\AuthenticationPrompt.cs
-
-
- Common\AuthenticationPromptEventArgs.cs
-
-
- Common\BigInteger.cs
-
-
- Common\ChannelDataEventArgs.cs
-
-
- Common\ChannelEventArgs.cs
-
-
- Common\ChannelExtendedDataEventArgs.cs
-
-
- Common\ChannelOpenConfirmedEventArgs.cs
-
-
- Common\ChannelOpenFailedEventArgs.cs
-
-
- Common\ChannelRequestEventArgs.cs
-
-
- Common\CountdownEvent.cs
-
-
- Common\DerData.cs
-
-
- Common\ExceptionEventArgs.cs
-
-
- Common\Extensions.cs
-
-
- Common\HostKeyEventArgs.cs
-
-
- Common\ObjectIdentifier.cs
-
-
- Common\Pack.cs
-
-
- Common\PacketDump.cs
-
-
- Common\PipeStream.cs
-
-
- Common\PortForwardEventArgs.cs
-
-
- Common\PosixPath.cs
-
-
- Common\ProxyException.cs
-
-
- Common\ScpDownloadEventArgs.cs
-
-
- Common\ScpException.cs
-
-
- Common\ScpUploadEventArgs.cs
-
-
- Common\SemaphoreLight.cs
-
-
- Common\SftpPathNotFoundException.cs
-
-
- Common\SftpPermissionDeniedException.cs
-
-
- Common\ShellDataEventArgs.cs
-
-
- Common\SshAuthenticationException.cs
-
-
- Common\SshConnectionException.cs
-
-
- Common\SshData.cs
-
-
- Common\SshDataStream.cs
-
-
- Common\SshException.cs
-
-
- Common\SshOperationTimeoutException.cs
-
-
- Common\SshPassPhraseNullOrEmptyException.cs
-
-
- Common\TerminalModes.cs
-
-
- Compression\CompressionMode.cs
-
-
- Compression\Compressor.cs
-
-
- Compression\Zlib.cs
-
-
- Compression\ZlibOpenSsh.cs
-
-
- Compression\ZlibStream.cs
-
-
- ConnectionInfo.cs
-
-
- Connection\ConnectorBase.cs
-
-
- Connection\DirectConnector.cs
-
-
- Connection\HttpConnector.cs
-
-
- Connection\IConnector.cs
-
-
- Connection\IProtocolVersionExchange.cs
-
-
- Connection\ISocketFactory.cs
-
-
- Connection\ProtocolVersionExchange.cs
-
-
- Connection\SocketFactory.cs
-
-
- Connection\Socks4Connector.cs
-
-
- Connection\Socks5Connector.cs
-
-
- Connection\SshIdentification.cs
-
-
- ExpectAction.cs
-
-
- ExpectAsyncResult.cs
-
-
- ForwardedPort.cs
-
-
- ForwardedPortDynamic.cs
-
-
- ForwardedPortLocal.cs
-
-
- ForwardedPortRemote.cs
-
-
- ForwardedPortStatus.cs
-
-
- HashInfo.cs
-
-
- IAuthenticationMethod.cs
-
-
- IClientAuthentication.cs
-
-
- IConnectionInfo.cs
-
-
- IForwardedPort.cs
-
-
- IRemotePathTransformation.cs
-
-
- IServiceFactory.cs
-
-
- ISession.cs
-
-
- ISubsystemSession.cs
-
-
- KeyboardInteractiveAuthenticationMethod.cs
-
-
- KeyboardInteractiveConnectionInfo.cs
-
-
- MessageEventArgs.cs
-
-
- Messages\Authentication\BannerMessage.cs
-
-
- Messages\Authentication\FailureMessage.cs
-
-
- Messages\Authentication\InformationRequestMessage.cs
-
-
- Messages\Authentication\InformationResponseMessage.cs
-
-
- Messages\Authentication\PasswordChangeRequiredMessage.cs
-
-
- Messages\Authentication\PublicKeyMessage.cs
-
-
- Messages\Authentication\RequestMessage.cs
-
-
- Messages\Authentication\RequestMessageHost.cs
-
-
- Messages\Authentication\RequestMessageKeyboardInteractive.cs
-
-
- Messages\Authentication\RequestMessageNone.cs
-
-
- Messages\Authentication\RequestMessagePassword.cs
-
-
- Messages\Authentication\RequestMessagePublicKey.cs
-
-
- Messages\Authentication\SuccessMessage.cs
-
-
- Messages\Connection\CancelTcpIpForwardGlobalRequestMessage.cs
-
-
- Messages\Connection\ChannelCloseMessage.cs
-
-
- Messages\Connection\ChannelDataMessage.cs
-
-
- Messages\Connection\ChannelEofMessage.cs
-
-
- Messages\Connection\ChannelExtendedDataMessage.cs
-
-
- Messages\Connection\ChannelFailureMessage.cs
-
-
- Messages\Connection\ChannelMessage.cs
-
-
- Messages\Connection\ChannelOpenConfirmationMessage.cs
-
-
- Messages\Connection\ChannelOpenFailureMessage.cs
-
-
- Messages\Connection\ChannelOpenFailureReasons.cs
-
-
- Messages\Connection\ChannelOpen\ChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelOpen\ChannelOpenMessage.cs
-
-
- Messages\Connection\ChannelOpen\DirectTcpipChannelInfo.cs
-
-
- Messages\Connection\ChannelOpen\ForwardedTcpipChannelInfo.cs
-
-
- Messages\Connection\ChannelOpen\SessionChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelOpen\X11ChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelRequest\BreakRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ChannelRequestMessage.cs
-
-
- Messages\Connection\ChannelRequest\EndOfWriteRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\EnvironmentVariableRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExecRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExitSignalRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExitStatusRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\KeepAliveRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\PseudoTerminalInfo.cs
-
-
- Messages\Connection\ChannelRequest\RequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ShellRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\SignalRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\SubsystemRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\WindowChangeRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\X11ForwardingRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\XonXoffRequestInfo.cs
-
-
- Messages\Connection\ChannelSuccessMessage.cs
-
-
- Messages\Connection\ChannelWindowAdjustMessage.cs
-
-
- Messages\Connection\GlobalRequestMessage.cs
-
-
- Messages\Connection\GlobalRequestName.cs
-
-
- Messages\Connection\RequestFailureMessage.cs
-
-
- Messages\Connection\RequestSuccessMessage.cs
-
-
- Messages\Connection\TcpIpForwardGlobalRequestMessage.cs
-
-
- Messages\Message.cs
-
-
- Messages\MessageAttribute.cs
-
-
- Messages\ServiceName.cs
-
-
- Messages\Transport\DebugMessage.cs
-
-
- Messages\Transport\DisconnectMessage.cs
-
-
- Messages\Transport\DisconnectReason.cs
-
-
- Messages\Transport\IgnoreMessage.cs
-
-
- Messages\Transport\IKeyExchangedAllowed.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeGroup.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeInit.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeReply.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeRequest.cs
-
-
- Messages\Transport\KeyExchangeDhInitMessage.cs
-
-
- Messages\Transport\KeyExchangeDhReplyMessage.cs
-
-
- Messages\Transport\KeyExchangeEcdhInitMessage.cs
-
-
- Messages\Transport\KeyExchangeEcdhReplyMessage.cs
-
-
- Messages\Transport\KeyExchangeInitMessage.cs
-
-
- Messages\Transport\NewKeysMessage.cs
-
-
- Messages\Transport\ServiceAcceptMessage.cs
-
-
- Messages\Transport\ServiceRequestMessage.cs
-
-
- Messages\Transport\UnimplementedMessage.cs
-
-
- NoneAuthenticationMethod.cs
-
-
- PasswordAuthenticationMethod.cs
-
-
- PasswordConnectionInfo.cs
-
-
- PrivateKeyAuthenticationMethod.cs
-
-
- PrivateKeyConnectionInfo.cs
-
-
- PrivateKeyFile.cs
-
-
- ProxyTypes.cs
-
-
- RemotePathDoubleQuoteTransformation.cs
-
-
- RemotePathNoneTransformation.cs
-
-
- RemotePathShellQuoteTransformation.cs
-
-
- RemotePathTransformation.cs
-
-
- ScpClient.cs
-
-
- Security\Algorithm.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\sec\SECNamedCurves.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9Curve.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECParameters.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECParametersHolder.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECPoint.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\agreement\ECDHCBasicAgreement.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\AsymmetricCipherKeyPair.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\AsymmetricKeyParameter.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\digests\GeneralDigest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\digests\Sha256Digest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\generators\ECKeyPairGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\IAsymmetricCipherKeyPairGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\IDigest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\KeyGenerationParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECDomainParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECKeyGenerationParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECPrivateKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECPublicKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\CryptoApiRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\DigestRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\IRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\util\Pack.cs
-
-
- Security\Cryptography\BouncyCastle\math\BigInteger.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\SimpleBigDecimal.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\Tnaf.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\ZTauElement.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECAlgorithms.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECCurve.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECFieldElement.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECLookupTable.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECPoint.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECPointMap.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\endo\ECEndomorphism.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\endo\GlvEndomorphism.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\LongArray.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\AbstractECMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\ECMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointCombMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\GlvMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\IPreCompCallback.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\PreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\ValidityPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafL2RMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WTauNafMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WTauNafPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\FiniteFields.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\GenericPolynomialExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\GF2Polynomial.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IFiniteField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IPolynomial.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IPolynomialExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\PrimeField.cs
-
-
- Security\Cryptography\BouncyCastle\math\raw\Mod.cs
-
-
- Security\Cryptography\BouncyCastle\math\raw\Nat.cs
-
-
- Security\Cryptography\BouncyCastle\security\DigestUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\security\SecureRandom.cs
-
-
- Security\Cryptography\BouncyCastle\security\SecurityUtilityException.cs
-
-
- Security\Cryptography\BouncyCastle\util\Arrays.cs
-
-
- Security\Cryptography\BouncyCastle\util\BigIntegers.cs
-
-
- Security\Cryptography\BouncyCastle\util\encoders\Hex.cs
-
-
- Security\Cryptography\BouncyCastle\util\encoders\HexEncoder.cs
-
-
- Security\Cryptography\BouncyCastle\util\IMemoable.cs
-
-
- Security\Cryptography\BouncyCastle\util\Integers.cs
-
-
- Security\Cryptography\BouncyCastle\util\MemoableResetException.cs
-
-
- Security\Cryptography\BouncyCastle\util\Times.cs
-
-
- Security\CertificateHostAlgorithm.cs
-
-
- Security\Cryptography\Chaos.NaCl\CryptoBytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Ed25519.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Array16.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Array8.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\ByteIntegerConverter.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\base.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\base2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\d.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\d2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_1.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_cmov.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_cswap.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_frombytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_invert.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_isnegative.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_isnonzero.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_mul.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_mul121666.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_neg.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_pow22523.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sq.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sq2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\FieldElement.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_double_scalarmult.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_frombytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_madd.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_msub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p1p1_to_p2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p1p1_to_p3.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p2_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p2_dbl.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_dbl.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_to_cached.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_to_p2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_precomp_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_scalarmult_base.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_sub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\GroupElement.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\keypair.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\open.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\scalarmult.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_clamp.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_mul_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_reduce.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sign.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sqrtm1.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\InternalAssert.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Poly1305Donna.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Salsa\Salsa20.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Salsa\SalsaCore.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Sha512Internal.cs
-
-
- Security\Cryptography\Chaos.NaCl\MontgomeryCurve25519.cs
-
-
- Security\Cryptography\Chaos.NaCl\Sha512.cs
-
-
- Security\Cryptography\AsymmetricCipher.cs
-
-
- Security\Cryptography\Bcrypt.cs
-
-
- Security\Cryptography\BlockCipher.cs
-
-
- Security\Cryptography\Cipher.cs
-
-
- Security\Cryptography\CipherDigitalSignature.cs
-
-
- Security\Cryptography\Ciphers\AesCipher.cs
-
-
- Security\Cryptography\Ciphers\Arc4Cipher.cs
-
-
- Security\Cryptography\Ciphers\BlowfishCipher.cs
-
-
- Security\Cryptography\Ciphers\CastCipher.cs
-
-
- Security\Cryptography\Ciphers\CipherMode.cs
-
-
- Security\Cryptography\Ciphers\CipherPadding.cs
-
-
- Security\Cryptography\Ciphers\DesCipher.cs
-
-
- Security\Cryptography\Ciphers\Modes\CbcCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\CfbCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\CtrCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\OfbCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Paddings\PKCS7Padding.cs
-
-
- Security\Cryptography\Ciphers\Paddings\PKCS5Padding.cs
-
-
- Security\Cryptography\Ciphers\RsaCipher.cs
-
-
- Security\Cryptography\Ciphers\SerpentCipher.cs
-
-
- Security\Cryptography\Ciphers\TripleDesCipher.cs
-
-
- Security\Cryptography\Ciphers\TwofishCipher.cs
-
-
- Security\Cryptography\DigitalSignature.cs
-
-
- Security\Cryptography\DsaDigitalSignature.cs
-
-
- Security\Cryptography\DsaKey.cs
-
-
- Security\Cryptography\ED25519DigitalSignature.cs
-
-
- Security\Cryptography\ED25519Key.cs
-
-
- Security\Cryptography\HMACMD5.cs
-
-
- Security\Cryptography\HMACSHA1.cs
-
-
- Security\Cryptography\HMACSHA256.cs
-
-
- Security\Cryptography\HMACSHA384.cs
-
-
- Security\Cryptography\HMACSHA512.cs
-
-
- Security\Cryptography\Key.cs
-
-
- Security\Cryptography\RsaDigitalSignature.cs
-
-
- Security\Cryptography\RsaKey.cs
-
-
- Security\Cryptography\StreamCipher.cs
-
-
- Security\Cryptography\SymmetricCipher.cs
-
-
- Security\GroupExchangeHashData.cs
-
-
- Security\HostAlgorithm.cs
-
-
- Security\IKeyExchange.cs
-
-
- Security\KeyExchange.cs
-
-
- Security\KeyExchangeDiffieHellman.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup14Sha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup14Sha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup16Sha512.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup1Sha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeSha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeSha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeShaBase.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha512.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupShaBase.cs
-
-
- Security\KeyExchangeEC.cs
-
-
- Security\KeyExchangeECCurve25519.cs
-
-
- Security\KeyExchangeECDH.cs
-
-
- Security\KeyExchangeECDH256.cs
-
-
- Security\KeyExchangeECDH384.cs
-
-
- Security\KeyExchangeECDH521.cs
-
-
- Security\KeyExchangeHash.cs
-
-
- Security\KeyHostAlgorithm.cs
-
-
- ServiceFactory.cs
-
-
- Session.cs
-
-
- SftpClient.cs
-
-
- ISftpClient.cs
-
-
- Sftp\Flags.cs
-
-
- Sftp\ISftpFileReader.cs
-
-
- Sftp\ISftpResponseFactory.cs
-
-
- Sftp\ISftpSession.cs
-
-
- Sftp\Requests\ExtendedRequests\FStatVfsRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\HardLinkRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\PosixRenameRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\StatVfsRequest.cs
-
-
- Sftp\Requests\SftpBlockRequest.cs
-
-
- Sftp\Requests\SftpCloseRequest.cs
-
-
- Sftp\Requests\SftpExtendedRequest.cs
-
-
- Sftp\Requests\SftpFSetStatRequest.cs
-
-
- Sftp\Requests\SftpFStatRequest.cs
-
-
- Sftp\Requests\SftpInitRequest.cs
-
-
- Sftp\Requests\SftpLinkRequest.cs
-
-
- Sftp\Requests\SftpLStatRequest.cs
-
-
- Sftp\Requests\SftpMkDirRequest.cs
-
-
- Sftp\Requests\SftpOpenDirRequest.cs
-
-
- Sftp\Requests\SftpOpenRequest.cs
-
-
- Sftp\Requests\SftpReadDirRequest.cs
-
-
- Sftp\Requests\SftpReadLinkRequest.cs
-
-
- Sftp\Requests\SftpReadRequest.cs
-
-
- Sftp\Requests\SftpRealPathRequest.cs
-
-
- Sftp\Requests\SftpRemoveRequest.cs
-
-
- Sftp\Requests\SftpRenameRequest.cs
-
-
- Sftp\Requests\SftpRequest.cs
-
-
- Sftp\Requests\SftpRmDirRequest.cs
-
-
- Sftp\Requests\SftpSetStatRequest.cs
-
-
- Sftp\Requests\SftpStatRequest.cs
-
-
- Sftp\Requests\SftpSymLinkRequest.cs
-
-
- Sftp\Requests\SftpUnblockRequest.cs
-
-
- Sftp\Requests\SftpWriteRequest.cs
-
-
- Sftp\Responses\ExtendedReplies\ExtendedReplyInfo.cs
-
-
- Sftp\Responses\ExtendedReplies\StatVfsReplyInfo.cs
-
-
- Sftp\Responses\SftpAttrsResponse.cs
-
-
- Sftp\Responses\SftpDataResponse.cs
-
-
- Sftp\Responses\SftpExtendedReplyResponse.cs
-
-
- Sftp\Responses\SftpHandleResponse.cs
-
-
- Sftp\Responses\SftpNameResponse.cs
-
-
- Sftp\Responses\SftpResponse.cs
-
-
- Sftp\Responses\SftpStatusResponse.cs
-
-
- Sftp\Responses\SftpVersionResponse.cs
-
-
- Sftp\SftpCloseAsyncResult.cs
-
-
- Sftp\SftpDownloadAsyncResult.cs
-
-
- Sftp\SftpFile.cs
-
-
- Sftp\SftpFileAttributes.cs
-
-
- Sftp\SftpFileReader.cs
-
-
- Sftp\SftpFileStream.cs
-
-
- Sftp\SftpFileSystemInformation.cs
-
-
- Sftp\SftpListDirectoryAsyncResult.cs
-
-
- Sftp\SftpMessage.cs
-
-
- Sftp\SftpMessageTypes.cs
-
-
- Sftp\SftpOpenAsyncResult.cs
-
-
- Sftp\SftpReadAsyncResult.cs
-
-
- Sftp\SftpRealPathAsyncResult.cs
-
-
- Sftp\SftpResponseFactory.cs
-
-
- Sftp\SftpSession.cs
-
-
- Sftp\SFtpStatAsyncResult.cs
-
-
- Sftp\SftpSynchronizeDirectoriesAsyncResult.cs
-
-
- Sftp\SftpUploadAsyncResult.cs
-
-
- Sftp\StatusCodes.cs
-
-
- Shell.cs
-
-
- ShellStream.cs
-
-
- SshClient.cs
-
-
- SshCommand.cs
-
-
- SshMessageFactory.cs
-
-
- SubsystemSession.cs
-
-
-
- Properties\CommonAssemblyInfo.cs
-
-
-
-
- Renci.SshNet.snk
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Renci.SshNet.Silverlight5/packages.config b/src/Renci.SshNet.Silverlight5/packages.config
deleted file mode 100644
index d4c6bef0d..000000000
--- a/src/Renci.SshNet.Silverlight5/packages.config
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/CipherInfoTest.cs b/src/Renci.SshNet.Tests/Classes/CipherInfoTest.cs
deleted file mode 100644
index 4014fc3ce..000000000
--- a/src/Renci.SshNet.Tests/Classes/CipherInfoTest.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Security.Cryptography;
-using Renci.SshNet.Tests.Common;
-using System;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Holds information about key size and cipher to use
- ///
- [TestClass]
- public class CipherInfoTest : TestBase
- {
- ///
- ///A test for CipherInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void CipherInfoConstructorTest()
- {
- int keySize = 0; // TODO: Initialize to an appropriate value
- Func cipher = null; // TODO: Initialize to an appropriate value
- CipherInfo target = new CipherInfo(keySize, cipher);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/ClientAuthenticationTest_Success_MultiList_PostponePartialAccessAuthenticationMethod.cs b/src/Renci.SshNet.Tests/Classes/ClientAuthenticationTest_Success_MultiList_PostponePartialAccessAuthenticationMethod.cs
deleted file mode 100644
index dd7c14c32..000000000
--- a/src/Renci.SshNet.Tests/Classes/ClientAuthenticationTest_Success_MultiList_PostponePartialAccessAuthenticationMethod.cs
+++ /dev/null
@@ -1,82 +0,0 @@
-using System.Collections.Generic;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-
-namespace Renci.SshNet.Tests.Classes
-{
- [TestClass]
- public class ClientAuthenticationTest_Success_MultiList_PostponePartialAccessAuthenticationMethod : ClientAuthenticationTestBase
- {
- private int _partialSuccessLimit;
- private ClientAuthentication _clientAuthentication;
-
- protected override void SetupData()
- {
- _partialSuccessLimit = 3;
- }
-
- protected override void SetupMocks()
- {
- var seq = new MockSequence();
-
- SessionMock.InSequence(seq).Setup(p => p.RegisterMessage("SSH_MSG_USERAUTH_FAILURE"));
- SessionMock.InSequence(seq).Setup(p => p.RegisterMessage("SSH_MSG_USERAUTH_SUCCESS"));
- SessionMock.InSequence(seq).Setup(p => p.RegisterMessage("SSH_MSG_USERAUTH_BANNER"));
-
- ConnectionInfoMock.InSequence(seq).Setup(p => p.CreateNoneAuthenticationMethod())
- .Returns(NoneAuthenticationMethodMock.Object);
-
- NoneAuthenticationMethodMock.InSequence(seq)
- .Setup(p => p.Authenticate(SessionMock.Object))
- .Returns(AuthenticationResult.Failure);
- ConnectionInfoMock.InSequence(seq)
- .Setup(p => p.AuthenticationMethods)
- .Returns(new List
- {
- KeyboardInteractiveAuthenticationMethodMock.Object,
- PasswordAuthenticationMethodMock.Object,
- PublicKeyAuthenticationMethodMock.Object
- });
- NoneAuthenticationMethodMock.InSequence(seq).Setup(p => p.AllowedAuthentications).Returns(new[] { "password" });
- KeyboardInteractiveAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("keyboard-interactive");
- PasswordAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("password");
- PublicKeyAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("publickey");
-
- PasswordAuthenticationMethodMock.InSequence(seq)
- .Setup(p => p.Authenticate(SessionMock.Object))
- .Returns(AuthenticationResult.PartialSuccess);
- PasswordAuthenticationMethodMock.InSequence(seq)
- .Setup(p => p.AllowedAuthentications)
- .Returns(new[] {"password", "publickey"});
- KeyboardInteractiveAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("keyboard-interactive");
- PasswordAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("password");
- PublicKeyAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("publickey");
-
- PublicKeyAuthenticationMethodMock.InSequence(seq)
- .Setup(p => p.Authenticate(SessionMock.Object))
- .Returns(AuthenticationResult.Failure);
- PublicKeyAuthenticationMethodMock.InSequence(seq)
- .Setup(p => p.Name)
- .Returns("publickey");
- PasswordAuthenticationMethodMock.InSequence(seq)
- .Setup(p => p.Authenticate(SessionMock.Object))
- .Returns(AuthenticationResult.Success);
-
- SessionMock.InSequence(seq).Setup(p => p.UnRegisterMessage("SSH_MSG_USERAUTH_FAILURE"));
- SessionMock.InSequence(seq).Setup(p => p.UnRegisterMessage("SSH_MSG_USERAUTH_SUCCESS"));
- SessionMock.InSequence(seq).Setup(p => p.UnRegisterMessage("SSH_MSG_USERAUTH_BANNER"));
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _clientAuthentication = new ClientAuthentication(_partialSuccessLimit);
- }
-
- protected override void Act()
- {
- _clientAuthentication.Authenticate(ConnectionInfoMock.Object, SessionMock.Object);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/ASCIIEncodingTest.cs b/src/Renci.SshNet.Tests/Classes/Common/ASCIIEncodingTest.cs
deleted file mode 100644
index 6e614b523..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/ASCIIEncodingTest.cs
+++ /dev/null
@@ -1,241 +0,0 @@
-using System;
-using System.Diagnostics;
-using System.Globalization;
-using System.Text;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- [TestClass]
- public class ASCIIEncodingTest : TestBase
- {
- private Random _random;
- private Encoding _ascii;
-
- [TestInitialize]
- public void SetUp()
- {
- _random = new Random();
- _ascii = SshData.Ascii;
- }
-
- [TestMethod]
- public void GetByteCount_Chars()
- {
- var chars = new[] { 'B', 'e', 'l', 'g', 'i', 'u', 'm' };
-
- var actual = _ascii.GetByteCount(chars);
-
- Assert.AreEqual(chars.Length, actual);
- }
-
- [TestMethod]
- public void GetBytes_CharArray()
- {
- var chars = new[] {'B', 'e', 'l', 'g', 'i', 'u', 'm'};
-
- var actual = _ascii.GetBytes(chars);
-
- Assert.IsNotNull(actual);
- Assert.AreEqual(7, actual.Length);
- Assert.AreEqual(0x42, actual[0]);
- Assert.AreEqual(0x65, actual[1]);
- Assert.AreEqual(0x6c, actual[2]);
- Assert.AreEqual(0x67, actual[3]);
- Assert.AreEqual(0x69, actual[4]);
- Assert.AreEqual(0x75, actual[5]);
- Assert.AreEqual(0x6d ,actual[6]);
- }
-
- [TestMethod]
- public void GetCharCount_Bytes()
- {
- var bytes = new byte[] { 0x42, 0x65, 0x6c, 0x67, 0x69, 0x75, 0x6d };
-
- var actual = _ascii.GetCharCount(bytes);
-
- Assert.AreEqual(bytes.Length, actual);
- }
-
- [TestMethod]
- public void GetChars_Bytes()
- {
- var bytes = new byte[] {0x42, 0x65, 0x6c, 0x67, 0x69, 0x75, 0x6d};
-
- var actual = _ascii.GetChars(bytes);
-
- Assert.AreEqual("Belgium", new string(actual));
- }
-
- [TestMethod]
- public void GetChars_Bytes_DefaultFallback()
- {
- var bytes = new byte[] { 0x42, 0x65, 0x6c, 0x80, 0x69, 0x75, 0x6d };
-
- var actual = _ascii.GetChars(bytes);
-
- Assert.AreEqual("Bel?ium", new string(actual));
- }
-
- [TestMethod]
- public void GetMaxByteCount_ShouldReturnCharCountPlusOneWhenCharCountIsNonNegative()
- {
- var charCount = _random.Next(0, 20000);
-
- var actual = _ascii.GetMaxByteCount(charCount);
-
- Assert.AreEqual(++charCount, actual);
- }
-
- [TestMethod]
- public void GetMaxByteCount_ShouldThrowArgumentOutOfRangeExceptionWhenCharCountIsNegative()
- {
- var charCount = _random.Next(-5000, -1);
-
- try
- {
- var actual = _ascii.GetMaxByteCount(charCount);
- Assert.Fail(actual.ToString(CultureInfo.InvariantCulture));
- }
- catch (ArgumentOutOfRangeException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("charCount", ex.ParamName);
- }
- }
-
- [TestMethod]
- public void GetMaxCharCount_ShouldReturnByteCountWhenByteCountIsNonNegative()
- {
- var byteCount = _random.Next(0, 20000);
-
- var actual = _ascii.GetMaxCharCount(byteCount);
-
- Assert.AreEqual(byteCount, actual);
- }
-
- [TestMethod]
- public void GetMaxCharCount_ShouldThrowArgumentOutOfRangeExceptionWhenByteCountIsNegative()
- {
- var byteCount = _random.Next(-5000, -1);
-
- try
- {
- var actual = _ascii.GetMaxCharCount(byteCount);
- Assert.Fail(actual.ToString(CultureInfo.InvariantCulture));
- }
- catch (ArgumentOutOfRangeException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("byteCount", ex.ParamName);
- }
- }
-
- [TestMethod]
- public void GetPreamble()
- {
- var actual = _ascii.GetPreamble();
-
- Assert.AreEqual(0, actual.Length);
- }
-
- [TestMethod]
- public void IsSingleByte()
- {
- Assert.IsTrue(_ascii.IsSingleByte);
- }
-
- [TestMethod]
- [TestCategory("LongRunning")]
- [TestCategory("Performance")]
- public void GetBytes_Performance()
- {
- const string input = "eererzfdfdsfsfsfsqdqseererzfdfdsfsfsfsqdqseererzfdfdsfsfsfsqdqseererzfdfdsfsfsfsqdqseererzfdfdsfsfsfsqdqseererzfdfdsfsfsfsqdqseererzfdfdsfsfsfsqdqseererzfdfdsfsfsfsqdqseererzfdfdsfsfsfsqdqs";
- const int loopCount = 10000000;
- var result = new byte[input.Length];
-
- var corefxAscii = new System.Text.ASCIIEncoding();
- var sshAscii = _ascii;
-
- var stopWatch = new Stopwatch();
-
- GC.Collect();
- GC.WaitForFullGCComplete();
-
- stopWatch.Start();
-
- for (var i = 0; i < loopCount; i++)
- {
- corefxAscii.GetBytes(input, 0, input.Length, result, 0);
- }
-
- stopWatch.Stop();
-
- Console.WriteLine(stopWatch.ElapsedMilliseconds);
-
- stopWatch.Reset();
-
- GC.Collect();
- GC.WaitForFullGCComplete();
-
- stopWatch.Start();
-
- for (var i = 0; i < loopCount; i++)
- {
- sshAscii.GetBytes(input, 0, input.Length, result, 0);
- }
-
- stopWatch.Stop();
-
- Console.WriteLine(stopWatch.ElapsedMilliseconds);
- }
-
- [TestMethod]
- [TestCategory("LongRunning")]
- [TestCategory("Performance")]
- public void GetChars_Performance()
- {
- var input = new byte[2000];
- new Random().NextBytes(input);
- const int loopCount = 100000;
-
- var corefxAscii = new System.Text.ASCIIEncoding();
- var sshAscii = _ascii;
-
- var stopWatch = new Stopwatch();
-
- GC.Collect();
- GC.WaitForFullGCComplete();
-
- stopWatch.Start();
-
- for (var i = 0; i < loopCount; i++)
- {
- var actual = corefxAscii.GetChars(input);
- }
-
- stopWatch.Stop();
-
- Console.WriteLine(stopWatch.ElapsedMilliseconds);
-
- stopWatch.Reset();
-
- GC.Collect();
- GC.WaitForFullGCComplete();
-
- stopWatch.Start();
-
- for (var i = 0; i < loopCount; i++)
- {
- var actual = sshAscii.GetChars(input);
- }
-
- stopWatch.Stop();
-
- Console.WriteLine(stopWatch.ElapsedMilliseconds);
- }
-
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Common/AsyncResultTest.cs b/src/Renci.SshNet.Tests/Classes/Common/AsyncResultTest.cs
deleted file mode 100644
index e000fbe6f..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/AsyncResultTest.cs
+++ /dev/null
@@ -1,140 +0,0 @@
-using System;
-using System.Threading;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for AsyncResultTest and is intended
- ///to contain all AsyncResultTest Unit Tests
- ///
- [TestClass]
- [Ignore] // placeholder for actual test
- public class AsyncResultTest : TestBase
- {
- ///
- ///A test for EndInvoke
- ///
- public void EndInvokeTest1Helper()
- {
- AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value
- TResult expected = default(TResult); // TODO: Initialize to an appropriate value
- TResult actual;
- actual = target.EndInvoke();
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- internal virtual AsyncResult CreateAsyncResult()
- {
- // TODO: Instantiate an appropriate concrete class.
- AsyncResult target = null;
- return target;
- }
-
- [TestMethod]
- public void EndInvokeTest1()
- {
- EndInvokeTest1Helper();
- }
-
- ///
- ///A test for SetAsCompleted
- ///
- public void SetAsCompletedTest1Helper()
- {
- AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value
- TResult result = default(TResult); // TODO: Initialize to an appropriate value
- bool completedSynchronously = false; // TODO: Initialize to an appropriate value
- target.SetAsCompleted(result, completedSynchronously);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- [TestMethod]
- public void SetAsCompletedTest1()
- {
- SetAsCompletedTest1Helper();
- }
-
- internal virtual AsyncResult CreateAsyncResult()
- {
- // TODO: Instantiate an appropriate concrete class.
- AsyncResult target = null;
- return target;
- }
-
- ///
- ///A test for EndInvoke
- ///
- [TestMethod]
- public void EndInvokeTest()
- {
- AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value
- target.EndInvoke();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for SetAsCompleted
- ///
- [TestMethod]
- public void SetAsCompletedTest()
- {
- AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value
- Exception exception = null; // TODO: Initialize to an appropriate value
- bool completedSynchronously = false; // TODO: Initialize to an appropriate value
- target.SetAsCompleted(exception, completedSynchronously);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for AsyncState
- ///
- [TestMethod]
- public void AsyncStateTest()
- {
- AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value
- object actual;
- actual = target.AsyncState;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for AsyncWaitHandle
- ///
- [TestMethod]
- public void AsyncWaitHandleTest()
- {
- AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value
- WaitHandle actual;
- actual = target.AsyncWaitHandle;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CompletedSynchronously
- ///
- [TestMethod]
- public void CompletedSynchronouslyTest()
- {
- AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.CompletedSynchronously;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for IsCompleted
- ///
- [TestMethod]
- public void IsCompletedTest()
- {
- AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.IsCompleted;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationBannerEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/AuthenticationBannerEventArgsTest.cs
deleted file mode 100644
index f41123f4a..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationBannerEventArgsTest.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
-
-
- ///
- ///This is a test class for AuthenticationBannerEventArgsTest and is intended
- ///to contain all AuthenticationBannerEventArgsTest Unit Tests
- ///
- [TestClass]
- public class AuthenticationBannerEventArgsTest : TestBase
- {
- ///
- ///A test for AuthenticationBannerEventArgs Constructor
- ///
- [TestMethod]
- public void AuthenticationBannerEventArgsConstructorTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string message = string.Empty; // TODO: Initialize to an appropriate value
- string language = string.Empty; // TODO: Initialize to an appropriate value
- AuthenticationBannerEventArgs target = new AuthenticationBannerEventArgs(username, message, language);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPasswordChangeEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPasswordChangeEventArgsTest.cs
deleted file mode 100644
index e381cf1b0..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPasswordChangeEventArgsTest.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
-
-
- ///
- ///This is a test class for AuthenticationPasswordChangeEventArgsTest and is intended
- ///to contain all AuthenticationPasswordChangeEventArgsTest Unit Tests
- ///
- [TestClass]
- public class AuthenticationPasswordChangeEventArgsTest : TestBase
- {
- ///
- ///A test for AuthenticationPasswordChangeEventArgs Constructor
- ///
- [TestMethod]
- public void AuthenticationPasswordChangeEventArgsConstructorTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- AuthenticationPasswordChangeEventArgs target = new AuthenticationPasswordChangeEventArgs(username);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for NewPassword
- ///
- [TestMethod]
- public void NewPasswordTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- AuthenticationPasswordChangeEventArgs target = new AuthenticationPasswordChangeEventArgs(username); // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- target.NewPassword = expected;
- actual = target.NewPassword;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptEventArgsTest.cs
deleted file mode 100644
index 698d1ab23..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptEventArgsTest.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-using System.Collections.Generic;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
-
-
- ///
- ///This is a test class for AuthenticationPromptEventArgsTest and is intended
- ///to contain all AuthenticationPromptEventArgsTest Unit Tests
- ///
- [TestClass]
- public class AuthenticationPromptEventArgsTest : TestBase
- {
- ///
- ///A test for AuthenticationPromptEventArgs Constructor
- ///
- [TestMethod]
- public void AuthenticationPromptEventArgsConstructorTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string instruction = string.Empty; // TODO: Initialize to an appropriate value
- string language = string.Empty; // TODO: Initialize to an appropriate value
- IEnumerable prompts = null; // TODO: Initialize to an appropriate value
- AuthenticationPromptEventArgs target = new AuthenticationPromptEventArgs(username, instruction, language, prompts);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptTest.cs b/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptTest.cs
deleted file mode 100644
index 763f74094..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptTest.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for AuthenticationPromptTest and is intended
- ///to contain all AuthenticationPromptTest Unit Tests
- ///
- [TestClass]
- public class AuthenticationPromptTest : TestBase
- {
- ///
- ///A test for AuthenticationPrompt Constructor
- ///
- [TestMethod]
- public void AuthenticationPromptConstructorTest()
- {
- int id = 0; // TODO: Initialize to an appropriate value
- bool isEchoed = false; // TODO: Initialize to an appropriate value
- string request = string.Empty; // TODO: Initialize to an appropriate value
- AuthenticationPrompt target = new AuthenticationPrompt(id, isEchoed, request);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Response
- ///
- [TestMethod]
- public void ResponseTest()
- {
- int id = 0; // TODO: Initialize to an appropriate value
- bool isEchoed = false; // TODO: Initialize to an appropriate value
- string request = string.Empty; // TODO: Initialize to an appropriate value
- AuthenticationPrompt target = new AuthenticationPrompt(id, isEchoed, request); // TODO: Initialize to an appropriate value
- string expected = string.Empty; // TODO: Initialize to an appropriate value
- string actual;
- target.Response = expected;
- actual = target.Response;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/DerDataTest.cs b/src/Renci.SshNet.Tests/Classes/Common/DerDataTest.cs
deleted file mode 100644
index d0f567909..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/DerDataTest.cs
+++ /dev/null
@@ -1,173 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for DerDataTest and is intended
- ///to contain all DerDataTest Unit Tests
- ///
- [TestClass]
- [Ignore] // placeholder for actual test
- public class DerDataTest : TestBase
- {
- ///
- ///A test for DerData Constructor
- ///
- [TestMethod]
- public void DerDataConstructorTest()
- {
- DerData target = new DerData();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for DerData Constructor
- ///
- [TestMethod]
- public void DerDataConstructorTest1()
- {
- byte[] data = null; // TODO: Initialize to an appropriate value
- DerData target = new DerData(data);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Encode
- ///
- [TestMethod]
- public void EncodeTest()
- {
- DerData target = new DerData(); // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Encode();
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ReadBigInteger
- ///
- [TestMethod]
- public void ReadBigIntegerTest()
- {
- DerData target = new DerData(); // TODO: Initialize to an appropriate value
- BigInteger expected = new BigInteger(); // TODO: Initialize to an appropriate value
- BigInteger actual;
- actual = target.ReadBigInteger();
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ReadInteger
- ///
- [TestMethod]
- public void ReadIntegerTest()
- {
- DerData target = new DerData(); // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.ReadInteger();
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Write
- ///
- [TestMethod]
- public void WriteTest()
- {
- DerData target = new DerData(); // TODO: Initialize to an appropriate value
- bool data = false; // TODO: Initialize to an appropriate value
- target.Write(data);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Write
- ///
- [TestMethod]
- public void WriteTest1()
- {
- DerData target = new DerData(); // TODO: Initialize to an appropriate value
- uint data = 0; // TODO: Initialize to an appropriate value
- target.Write(data);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Write
- ///
- [TestMethod]
- public void WriteTest2()
- {
- DerData target = new DerData(); // TODO: Initialize to an appropriate value
- BigInteger data = new BigInteger(); // TODO: Initialize to an appropriate value
- target.Write(data);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Write
- ///
- [TestMethod]
- public void WriteTest3()
- {
- DerData target = new DerData(); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- target.Write(data);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Write
- ///
- [TestMethod]
- public void WriteTest4()
- {
- DerData target = new DerData(); // TODO: Initialize to an appropriate value
- ObjectIdentifier identifier = new ObjectIdentifier(); // TODO: Initialize to an appropriate value
- target.Write(identifier);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Write
- ///
- [TestMethod]
- public void WriteTest5()
- {
- DerData target = new DerData(); // TODO: Initialize to an appropriate value
- DerData data = null; // TODO: Initialize to an appropriate value
- target.Write(data);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for WriteNull
- ///
- [TestMethod]
- public void WriteNullTest()
- {
- DerData target = new DerData(); // TODO: Initialize to an appropriate value
- target.WriteNull();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for IsEndOfData
- ///
- [TestMethod]
- public void IsEndOfDataTest()
- {
- DerData target = new DerData(); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.IsEndOfData;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/ExceptionEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/ExceptionEventArgsTest.cs
deleted file mode 100644
index ce9542324..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/ExceptionEventArgsTest.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for ExceptionEventArgsTest and is intended
- ///to contain all ExceptionEventArgsTest Unit Tests
- ///
- [TestClass]
- public class ExceptionEventArgsTest : TestBase
- {
- ///
- ///A test for ExceptionEventArgs Constructor
- ///
- [TestMethod]
- public void ExceptionEventArgsConstructorTest()
- {
- Exception exception = null; // TODO: Initialize to an appropriate value
- ExceptionEventArgs target = new ExceptionEventArgs(exception);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/HostKeyEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/HostKeyEventArgsTest.cs
deleted file mode 100644
index 93055c6e0..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/HostKeyEventArgsTest.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Security;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for HostKeyEventArgsTest and is intended
- ///to contain all HostKeyEventArgsTest Unit Tests
- ///
- [TestClass]
- [Ignore] // placeholder for actual test
- public class HostKeyEventArgsTest : TestBase
- {
- ///
- ///A test for HostKeyEventArgs Constructor
- ///
- [TestMethod]
- public void HostKeyEventArgsConstructorTest()
- {
- KeyHostAlgorithm host = null; // TODO: Initialize to an appropriate value
- HostKeyEventArgs target = new HostKeyEventArgs(host);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for CanTrust
- ///
- [TestMethod]
- public void CanTrustTest()
- {
- KeyHostAlgorithm host = null; // TODO: Initialize to an appropriate value
- HostKeyEventArgs target = new HostKeyEventArgs(host); // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.CanTrust = expected;
- actual = target.CanTrust;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/NetConfServerExceptionTest.cs b/src/Renci.SshNet.Tests/Classes/Common/NetConfServerExceptionTest.cs
deleted file mode 100644
index fc3ac4d76..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/NetConfServerExceptionTest.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for NetConfServerExceptionTest and is intended
- ///to contain all NetConfServerExceptionTest Unit Tests
- ///
- [TestClass]
- public class NetConfServerExceptionTest : TestBase
- {
- ///
- ///A test for NetConfServerException Constructor
- ///
- [TestMethod]
- public void NetConfServerExceptionConstructorTest()
- {
- NetConfServerException target = new NetConfServerException();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for NetConfServerException Constructor
- ///
- [TestMethod]
- public void NetConfServerExceptionConstructorTest1()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- NetConfServerException target = new NetConfServerException(message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for NetConfServerException Constructor
- ///
- [TestMethod]
- public void NetConfServerExceptionConstructorTest2()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- Exception innerException = null; // TODO: Initialize to an appropriate value
- NetConfServerException target = new NetConfServerException(message, innerException);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/ObjectIdentifierTest.cs b/src/Renci.SshNet.Tests/Classes/Common/ObjectIdentifierTest.cs
deleted file mode 100644
index 5bfbfc29a..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/ObjectIdentifierTest.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for ObjectIdentifierTest and is intended
- ///to contain all ObjectIdentifierTest Unit Tests
- ///
- [TestClass]
- [Ignore] // placeholder for actual test
- public class ObjectIdentifierTest : TestBase
- {
- ///
- ///A test for ObjectIdentifier Constructor
- ///
- [TestMethod]
- public void ObjectIdentifierConstructorTest()
- {
- ulong[] identifiers = null; // TODO: Initialize to an appropriate value
- ObjectIdentifier target = new ObjectIdentifier(identifiers);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/ProxyExceptionTest.cs b/src/Renci.SshNet.Tests/Classes/Common/ProxyExceptionTest.cs
deleted file mode 100644
index b14d6ccea..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/ProxyExceptionTest.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for ProxyExceptionTest and is intended
- ///to contain all ProxyExceptionTest Unit Tests
- ///
- [TestClass]
- public class ProxyExceptionTest : TestBase
- {
- ///
- ///A test for ProxyException Constructor
- ///
- [TestMethod]
- public void ProxyExceptionConstructorTest()
- {
- ProxyException target = new ProxyException();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ProxyException Constructor
- ///
- [TestMethod]
- public void ProxyExceptionConstructorTest1()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- ProxyException target = new ProxyException(message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ProxyException Constructor
- ///
- [TestMethod]
- public void ProxyExceptionConstructorTest2()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- Exception innerException = null; // TODO: Initialize to an appropriate value
- ProxyException target = new ProxyException(message, innerException);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/ScpDownloadEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/ScpDownloadEventArgsTest.cs
deleted file mode 100644
index bfb16348f..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/ScpDownloadEventArgsTest.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for ScpDownloadEventArgsTest and is intended
- ///to contain all ScpDownloadEventArgsTest Unit Tests
- ///
- [TestClass]
- public class ScpDownloadEventArgsTest : TestBase
- {
- ///
- ///A test for ScpDownloadEventArgs Constructor
- ///
- [TestMethod]
- public void ScpDownloadEventArgsConstructorTest()
- {
- string filename = string.Empty; // TODO: Initialize to an appropriate value
- long size = 0; // TODO: Initialize to an appropriate value
- long downloaded = 0; // TODO: Initialize to an appropriate value
- ScpDownloadEventArgs target = new ScpDownloadEventArgs(filename, size, downloaded);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/ScpExceptionTest.cs b/src/Renci.SshNet.Tests/Classes/Common/ScpExceptionTest.cs
deleted file mode 100644
index 328024b00..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/ScpExceptionTest.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for ScpExceptionTest and is intended
- ///to contain all ScpExceptionTest Unit Tests
- ///
- [TestClass]
- public class ScpExceptionTest : TestBase
- {
- ///
- ///A test for ScpException Constructor
- ///
- [TestMethod]
- public void ScpExceptionConstructorTest()
- {
- ScpException target = new ScpException();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ScpException Constructor
- ///
- [TestMethod]
- public void ScpExceptionConstructorTest1()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- ScpException target = new ScpException(message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ScpException Constructor
- ///
- [TestMethod]
- public void ScpExceptionConstructorTest2()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- Exception innerException = null; // TODO: Initialize to an appropriate value
- ScpException target = new ScpException(message, innerException);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/ScpUploadEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/ScpUploadEventArgsTest.cs
deleted file mode 100644
index 9c5238b93..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/ScpUploadEventArgsTest.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for ScpUploadEventArgsTest and is intended
- ///to contain all ScpUploadEventArgsTest Unit Tests
- ///
- [TestClass]
- public class ScpUploadEventArgsTest : TestBase
- {
- ///
- ///A test for ScpUploadEventArgs Constructor
- ///
- [TestMethod]
- public void ScpUploadEventArgsConstructorTest()
- {
- string filename = string.Empty; // TODO: Initialize to an appropriate value
- long size = 0; // TODO: Initialize to an appropriate value
- long uploaded = 0; // TODO: Initialize to an appropriate value
- ScpUploadEventArgs target = new ScpUploadEventArgs(filename, size, uploaded);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/SemaphoreLightTest.cs b/src/Renci.SshNet.Tests/Classes/Common/SemaphoreLightTest.cs
deleted file mode 100644
index b1d3bfeb0..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/SemaphoreLightTest.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-using System;
-using System.Threading;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- [TestClass]
- public class SemaphoreLightTest : TestBase
- {
- [TestMethod]
- public void SemaphoreLightConstructorTest()
- {
- var initialCount = new Random().Next(1, 10);
- var target = new SemaphoreLight(initialCount);
- Assert.AreEqual(initialCount, target.CurrentCount);
- }
-
- [TestMethod]
- public void Release()
- {
- var initialCount = new Random().Next(1, 10);
- var target = new SemaphoreLight(initialCount);
-
- Assert.AreEqual(initialCount, target.Release());
- Assert.AreEqual(initialCount + 1, target.CurrentCount);
-
- Assert.AreEqual(initialCount + 1, target.Release());
- Assert.AreEqual(initialCount + 2, target.CurrentCount);
- }
-
- ///
- ///A test for Release
- ///
- [TestMethod]
- public void Release_ReleaseCount()
- {
- var initialCount = new Random().Next(1, 10);
- var target = new SemaphoreLight(initialCount);
-
- var releaseCount1 = new Random().Next(1, 10);
- Assert.AreEqual(initialCount, target.Release(releaseCount1));
- Assert.AreEqual(initialCount + releaseCount1, target.CurrentCount);
-
- var releaseCount2 = new Random().Next(1, 10);
- Assert.AreEqual(initialCount + releaseCount1, target.Release(releaseCount2));
- Assert.AreEqual(initialCount + releaseCount1 + releaseCount2, target.CurrentCount);
- }
-
- ///
- ///A test for Wait
- ///
- [TestMethod]
- public void WaitTest()
- {
- const int sleepTime = 200;
- const int initialCount = 2;
- var target = new SemaphoreLight(initialCount);
-
- var start = DateTime.Now;
-
- target.Wait();
- target.Wait();
-
- Assert.IsTrue((DateTime.Now - start).TotalMilliseconds < 50);
-
- var releaseThread = new Thread(
- () =>
- {
- Thread.Sleep(sleepTime);
- target.Release();
- });
- releaseThread.Start();
-
- target.Wait();
-
- var end = DateTime.Now;
- var elapsed = end - start;
-
- Assert.IsTrue(elapsed.TotalMilliseconds > 200);
- Assert.IsTrue(elapsed.TotalMilliseconds < 250);
- }
-
- [TestMethod]
- public void CurrentCountTest()
- {
- var initialCount = new Random().Next(1, 20);
- var target = new SemaphoreLight(initialCount);
-
- Assert.AreEqual(initialCount, target.CurrentCount);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/SftpPathNotFoundExceptionTest.cs b/src/Renci.SshNet.Tests/Classes/Common/SftpPathNotFoundExceptionTest.cs
deleted file mode 100644
index 124e0b535..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/SftpPathNotFoundExceptionTest.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for SftpPathNotFoundExceptionTest and is intended
- ///to contain all SftpPathNotFoundExceptionTest Unit Tests
- ///
- [TestClass]
- public class SftpPathNotFoundExceptionTest : TestBase
- {
- ///
- ///A test for SftpPathNotFoundException Constructor
- ///
- [TestMethod]
- public void SftpPathNotFoundExceptionConstructorTest()
- {
- SftpPathNotFoundException target = new SftpPathNotFoundException();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SftpPathNotFoundException Constructor
- ///
- [TestMethod]
- public void SftpPathNotFoundExceptionConstructorTest1()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- SftpPathNotFoundException target = new SftpPathNotFoundException(message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SftpPathNotFoundException Constructor
- ///
- [TestMethod]
- public void SftpPathNotFoundExceptionConstructorTest2()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- Exception innerException = null; // TODO: Initialize to an appropriate value
- SftpPathNotFoundException target = new SftpPathNotFoundException(message, innerException);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/SftpPermissionDeniedExceptionTest.cs b/src/Renci.SshNet.Tests/Classes/Common/SftpPermissionDeniedExceptionTest.cs
deleted file mode 100644
index 30800de9a..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/SftpPermissionDeniedExceptionTest.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for SftpPermissionDeniedExceptionTest and is intended
- ///to contain all SftpPermissionDeniedExceptionTest Unit Tests
- ///
- [TestClass]
- public class SftpPermissionDeniedExceptionTest : TestBase
- {
- ///
- ///A test for SftpPermissionDeniedException Constructor
- ///
- [TestMethod]
- public void SftpPermissionDeniedExceptionConstructorTest()
- {
- SftpPermissionDeniedException target = new SftpPermissionDeniedException();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SftpPermissionDeniedException Constructor
- ///
- [TestMethod]
- public void SftpPermissionDeniedExceptionConstructorTest1()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- SftpPermissionDeniedException target = new SftpPermissionDeniedException(message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SftpPermissionDeniedException Constructor
- ///
- [TestMethod]
- public void SftpPermissionDeniedExceptionConstructorTest2()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- Exception innerException = null; // TODO: Initialize to an appropriate value
- SftpPermissionDeniedException target = new SftpPermissionDeniedException(message, innerException);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/ShellDataEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/ShellDataEventArgsTest.cs
deleted file mode 100644
index 482529342..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/ShellDataEventArgsTest.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for ShellDataEventArgsTest and is intended
- ///to contain all ShellDataEventArgsTest Unit Tests
- ///
- [TestClass]
- public class ShellDataEventArgsTest
- {
- ///
- ///A test for ShellDataEventArgs Constructor
- ///
- [TestMethod]
- public void ShellDataEventArgsConstructorTest()
- {
- byte[] data = null; // TODO: Initialize to an appropriate value
- ShellDataEventArgs target = new ShellDataEventArgs(data);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ShellDataEventArgs Constructor
- ///
- [TestMethod]
- public void ShellDataEventArgsConstructorTest1()
- {
- string line = string.Empty; // TODO: Initialize to an appropriate value
- ShellDataEventArgs target = new ShellDataEventArgs(line);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/SshAuthenticationExceptionTest.cs b/src/Renci.SshNet.Tests/Classes/Common/SshAuthenticationExceptionTest.cs
deleted file mode 100644
index 95a889580..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/SshAuthenticationExceptionTest.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for SshAuthenticationExceptionTest and is intended
- ///to contain all SshAuthenticationExceptionTest Unit Tests
- ///
- [TestClass]
- public class SshAuthenticationExceptionTest
- {
- ///
- ///A test for SshAuthenticationException Constructor
- ///
- [TestMethod]
- public void SshAuthenticationExceptionConstructorTest()
- {
- SshAuthenticationException target = new SshAuthenticationException();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshAuthenticationException Constructor
- ///
- [TestMethod]
- public void SshAuthenticationExceptionConstructorTest1()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- SshAuthenticationException target = new SshAuthenticationException(message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshAuthenticationException Constructor
- ///
- [TestMethod]
- public void SshAuthenticationExceptionConstructorTest2()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- Exception innerException = null; // TODO: Initialize to an appropriate value
- SshAuthenticationException target = new SshAuthenticationException(message, innerException);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/SshConnectionExceptionTest.cs b/src/Renci.SshNet.Tests/Classes/Common/SshConnectionExceptionTest.cs
deleted file mode 100644
index b960e4f41..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/SshConnectionExceptionTest.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-using System;
-using System.Runtime.Serialization;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Messages.Transport;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for SshConnectionExceptionTest and is intended
- ///to contain all SshConnectionExceptionTest Unit Tests
- ///
- [TestClass]
- public class SshConnectionExceptionTest : TestBase
- {
- ///
- ///A test for SshConnectionException Constructor
- ///
- [TestMethod]
- public void SshConnectionExceptionConstructorTest()
- {
- SshConnectionException target = new SshConnectionException();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshConnectionException Constructor
- ///
- [TestMethod]
- public void SshConnectionExceptionConstructorTest1()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- SshConnectionException target = new SshConnectionException(message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshConnectionException Constructor
- ///
- [TestMethod]
- public void SshConnectionExceptionConstructorTest2()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- DisconnectReason disconnectReasonCode = new DisconnectReason(); // TODO: Initialize to an appropriate value
- SshConnectionException target = new SshConnectionException(message, disconnectReasonCode);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshConnectionException Constructor
- ///
- [TestMethod]
- public void SshConnectionExceptionConstructorTest3()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- DisconnectReason disconnectReasonCode = new DisconnectReason(); // TODO: Initialize to an appropriate value
- Exception inner = null; // TODO: Initialize to an appropriate value
- SshConnectionException target = new SshConnectionException(message, disconnectReasonCode, inner);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for GetObjectData
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GetObjectDataTest()
- {
- SshConnectionException target = new SshConnectionException(); // TODO: Initialize to an appropriate value
- SerializationInfo info = null; // TODO: Initialize to an appropriate value
- StreamingContext context = new StreamingContext(); // TODO: Initialize to an appropriate value
- target.GetObjectData(info, context);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/SshExceptionTest.cs b/src/Renci.SshNet.Tests/Classes/Common/SshExceptionTest.cs
deleted file mode 100644
index 435845086..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/SshExceptionTest.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-using System;
-using System.Runtime.Serialization;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for SshExceptionTest and is intended
- ///to contain all SshExceptionTest Unit Tests
- ///
- [TestClass]
- public class SshExceptionTest : TestBase
- {
- ///
- ///A test for SshException Constructor
- ///
- [TestMethod]
- public void SshExceptionConstructorTest()
- {
- SshException target = new SshException();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshException Constructor
- ///
- [TestMethod]
- public void SshExceptionConstructorTest1()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- SshException target = new SshException(message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshException Constructor
- ///
- [TestMethod]
- public void SshExceptionConstructorTest2()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- Exception inner = null; // TODO: Initialize to an appropriate value
- SshException target = new SshException(message, inner);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for GetObjectData
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GetObjectDataTest()
- {
- SshException target = new SshException(); // TODO: Initialize to an appropriate value
- SerializationInfo info = null; // TODO: Initialize to an appropriate value
- StreamingContext context = new StreamingContext(); // TODO: Initialize to an appropriate value
- target.GetObjectData(info, context);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/SshOperationTimeoutExceptionTest.cs b/src/Renci.SshNet.Tests/Classes/Common/SshOperationTimeoutExceptionTest.cs
deleted file mode 100644
index 9a5f06115..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/SshOperationTimeoutExceptionTest.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for SshOperationTimeoutExceptionTest and is intended
- ///to contain all SshOperationTimeoutExceptionTest Unit Tests
- ///
- [TestClass]
- public class SshOperationTimeoutExceptionTest : TestBase
- {
- ///
- ///A test for SshOperationTimeoutException Constructor
- ///
- [TestMethod]
- public void SshOperationTimeoutExceptionConstructorTest()
- {
- SshOperationTimeoutException target = new SshOperationTimeoutException();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshOperationTimeoutException Constructor
- ///
- [TestMethod]
- public void SshOperationTimeoutExceptionConstructorTest1()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- SshOperationTimeoutException target = new SshOperationTimeoutException(message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshOperationTimeoutException Constructor
- ///
- [TestMethod]
- public void SshOperationTimeoutExceptionConstructorTest2()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- Exception innerException = null; // TODO: Initialize to an appropriate value
- SshOperationTimeoutException target = new SshOperationTimeoutException(message, innerException);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Common/SshPassPhraseNullOrEmptyExceptionTest.cs b/src/Renci.SshNet.Tests/Classes/Common/SshPassPhraseNullOrEmptyExceptionTest.cs
deleted file mode 100644
index 8da8ebc4c..000000000
--- a/src/Renci.SshNet.Tests/Classes/Common/SshPassPhraseNullOrEmptyExceptionTest.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Common
-{
- ///
- ///This is a test class for SshPassPhraseNullOrEmptyExceptionTest and is intended
- ///to contain all SshPassPhraseNullOrEmptyExceptionTest Unit Tests
- ///
- [TestClass]
- public class SshPassPhraseNullOrEmptyExceptionTest : TestBase
- {
- ///
- ///A test for SshPassPhraseNullOrEmptyException Constructor
- ///
- [TestMethod]
- public void SshPassPhraseNullOrEmptyExceptionConstructorTest()
- {
- SshPassPhraseNullOrEmptyException target = new SshPassPhraseNullOrEmptyException();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshPassPhraseNullOrEmptyException Constructor
- ///
- [TestMethod]
- public void SshPassPhraseNullOrEmptyExceptionConstructorTest1()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- SshPassPhraseNullOrEmptyException target = new SshPassPhraseNullOrEmptyException(message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshPassPhraseNullOrEmptyException Constructor
- ///
- [TestMethod]
- public void SshPassPhraseNullOrEmptyExceptionConstructorTest2()
- {
- string message = string.Empty; // TODO: Initialize to an appropriate value
- Exception innerException = null; // TODO: Initialize to an appropriate value
- SshPassPhraseNullOrEmptyException target = new SshPassPhraseNullOrEmptyException(message, innerException);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Compression/CompressorTest.cs b/src/Renci.SshNet.Tests/Classes/Compression/CompressorTest.cs
deleted file mode 100644
index 9a94f6dc6..000000000
--- a/src/Renci.SshNet.Tests/Classes/Compression/CompressorTest.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-using Renci.SshNet.Compression;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Compression
-{
- ///
- ///This is a test class for CompressorTest and is intended
- ///to contain all CompressorTest Unit Tests
- ///
- [TestClass]
- [Ignore] // placeholders only
- public class CompressorTest : TestBase
- {
- internal virtual Compressor CreateCompressor()
- {
- // TODO: Instantiate an appropriate concrete class.
- Compressor target = null;
- return target;
- }
-
- ///
- ///A test for Compress
- ///
- [TestMethod()]
- public void CompressTest()
- {
- Compressor target = CreateCompressor(); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Compress(data);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Decompress
- ///
- [TestMethod()]
- public void DecompressTest()
- {
- Compressor target = CreateCompressor(); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Decompress(data);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod()]
- public void DisposeTest()
- {
- Compressor target = CreateCompressor(); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Init
- ///
- [TestMethod()]
- public void InitTest()
- {
- Compressor target = CreateCompressor(); // TODO: Initialize to an appropriate value
- Session session = null; // TODO: Initialize to an appropriate value
- target.Init(session);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Compression/ZlibOpenSshTest.cs b/src/Renci.SshNet.Tests/Classes/Compression/ZlibOpenSshTest.cs
deleted file mode 100644
index c11e13dcb..000000000
--- a/src/Renci.SshNet.Tests/Classes/Compression/ZlibOpenSshTest.cs
+++ /dev/null
@@ -1,51 +0,0 @@
-using Renci.SshNet.Compression;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Compression
-{
- ///
- ///This is a test class for ZlibOpenSshTest and is intended
- ///to contain all ZlibOpenSshTest Unit Tests
- ///
- [TestClass]
- [Ignore] // placeholders only
- public class ZlibOpenSshTest : TestBase
- {
- ///
- ///A test for ZlibOpenSsh Constructor
- ///
- [TestMethod()]
- public void ZlibOpenSshConstructorTest()
- {
- ZlibOpenSsh target = new ZlibOpenSsh();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Init
- ///
- [TestMethod()]
- public void InitTest()
- {
- ZlibOpenSsh target = new ZlibOpenSsh(); // TODO: Initialize to an appropriate value
- Session session = null; // TODO: Initialize to an appropriate value
- target.Init(session);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Name
- ///
- [TestMethod()]
- public void NameTest()
- {
- ZlibOpenSsh target = new ZlibOpenSsh(); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.Name;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Compression/ZlibStreamTest.cs b/src/Renci.SshNet.Tests/Classes/Compression/ZlibStreamTest.cs
deleted file mode 100644
index dd1c93bf2..000000000
--- a/src/Renci.SshNet.Tests/Classes/Compression/ZlibStreamTest.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-using Renci.SshNet.Compression;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.IO;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Compression
-{
- ///
- ///This is a test class for ZlibStreamTest and is intended
- ///to contain all ZlibStreamTest Unit Tests
- ///
- [TestClass]
- public class ZlibStreamTest : TestBase
- {
- ///
- ///A test for ZlibStream Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ZlibStreamConstructorTest()
- {
- Stream stream = null; // TODO: Initialize to an appropriate value
- CompressionMode mode = new CompressionMode(); // TODO: Initialize to an appropriate value
- ZlibStream target = new ZlibStream(stream, mode);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Write
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void WriteTest()
- {
- Stream stream = null; // TODO: Initialize to an appropriate value
- CompressionMode mode = new CompressionMode(); // TODO: Initialize to an appropriate value
- ZlibStream target = new ZlibStream(stream, mode); // TODO: Initialize to an appropriate value
- byte[] buffer = null; // TODO: Initialize to an appropriate value
- int offset = 0; // TODO: Initialize to an appropriate value
- int count = 0; // TODO: Initialize to an appropriate value
- target.Write(buffer, offset, count);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Compression/ZlibTest.cs b/src/Renci.SshNet.Tests/Classes/Compression/ZlibTest.cs
deleted file mode 100644
index d460b3eb4..000000000
--- a/src/Renci.SshNet.Tests/Classes/Compression/ZlibTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Compression
-{
- ///
- /// Represents "zlib" compression implementation
- ///
- [TestClass]
- public class ZlibTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest.cs
deleted file mode 100644
index 13b2c81b9..000000000
--- a/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest.cs
+++ /dev/null
@@ -1,283 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.Diagnostics;
-using System.Net;
-using System.Threading;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides functionality for local port forwarding
- ///
- [TestClass]
- public partial class ForwardedPortLocalTest : TestBase
- {
- [TestMethod]
- [WorkItem(713)]
- [Owner("Kenneth_aa")]
- [TestCategory("PortForwarding")]
- [TestCategory("integration")]
- [Description("Test if calling Stop on ForwardedPortLocal instance causes wait.")]
- public void Test_PortForwarding_Local_Stop_Hangs_On_Wait()
- {
- using (var client = new SshClient(Resources.HOST, Int32.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD))
- {
- client.Connect();
-
- var port1 = new ForwardedPortLocal("localhost", 8084, "www.google.com", 80);
- client.AddForwardedPort(port1);
- port1.Exception += delegate(object sender, ExceptionEventArgs e)
- {
- Assert.Fail(e.Exception.ToString());
- };
-
- port1.Start();
-
- bool hasTestedTunnel = false;
- System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state)
- {
- try
- {
- var url = "http://www.google.com/";
- Debug.WriteLine("Starting web request to \"" + url + "\"");
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
-
- Assert.IsNotNull(response);
-
- Debug.WriteLine("Http Response status code: " + response.StatusCode.ToString());
-
- response.Close();
-
- hasTestedTunnel = true;
- }
- catch (Exception ex)
- {
- Assert.Fail(ex.ToString());
- }
- });
-
- // Wait for the web request to complete.
- while (!hasTestedTunnel)
- {
- System.Threading.Thread.Sleep(1000);
- }
-
- try
- {
- // Try stop the port forwarding, wait 3 seconds and fail if it is still started.
- System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state)
- {
- Debug.WriteLine("Trying to stop port forward.");
- port1.Stop();
- Debug.WriteLine("Port forwarding stopped.");
- });
-
- System.Threading.Thread.Sleep(3000);
- if (port1.IsStarted)
- {
- Assert.Fail("Port forwarding not stopped.");
- }
- }
- catch (Exception ex)
- {
- Assert.Fail(ex.ToString());
- }
- client.Disconnect();
- Debug.WriteLine("Success.");
- }
- }
-
- [TestMethod]
- public void ConstructorShouldThrowArgumentNullExceptionWhenBoundHostIsNull()
- {
- try
- {
- new ForwardedPortLocal(null, 8080, Resources.HOST, 80);
- Assert.Fail();
- }
- catch (ArgumentNullException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("boundHost", ex.ParamName);
- }
- }
-
- [TestMethod]
- public void ConstructorShouldNotThrowExceptionWhenBoundHostIsEmpty()
- {
- var boundHost = string.Empty;
-
- var forwardedPort = new ForwardedPortLocal(boundHost, 8080, Resources.HOST, 80);
-
- Assert.AreSame(boundHost, forwardedPort.BoundHost);
- }
-
- [TestMethod]
- public void ConstructorShouldNotThrowExceptionWhenBoundHostIsInvalidDnsName()
- {
- const string boundHost = "in_valid_host.";
-
- var forwardedPort = new ForwardedPortLocal(boundHost, 8080, Resources.HOST, 80);
-
- Assert.AreSame(boundHost, forwardedPort.BoundHost);
- }
-
- [TestMethod]
- public void ConstructorShouldThrowArgumentNullExceptionWhenHostIsNull()
- {
- try
- {
- new ForwardedPortLocal(Resources.HOST, 8080, null, 80);
- Assert.Fail();
- }
- catch (ArgumentNullException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("host", ex.ParamName);
- }
- }
-
- [TestMethod]
- public void ConstructorShouldNotThrowExceptionWhenHostIsEmpty()
- {
- var host = string.Empty;
-
- var forwardedPort = new ForwardedPortLocal(Resources.HOST, 8080, string.Empty, 80);
-
- Assert.AreSame(host, forwardedPort.Host);
- }
-
- [TestMethod]
- public void ConstructorShouldNotThrowExceptionWhenHostIsInvalidDnsName()
- {
- const string host = "in_valid_host.";
-
- var forwardedPort = new ForwardedPortLocal(Resources.HOST, 8080, host, 80);
-
- Assert.AreSame(host, forwardedPort.Host);
- }
-
- ///
- ///A test for ForwardedPortRemote Constructor
- ///
- [TestMethod]
- [TestCategory("integration")]
- public void Test_ForwardedPortRemote()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- #region Example SshClient AddForwardedPort Start Stop ForwardedPortLocal
- client.Connect();
- var port = new ForwardedPortLocal(8082, "www.cnn.com", 80);
- client.AddForwardedPort(port);
- port.Exception += delegate(object sender, ExceptionEventArgs e)
- {
- Console.WriteLine(e.Exception.ToString());
- };
- port.Start();
-
- Thread.Sleep(1000 * 60 * 20); // Wait 20 minutes for port to be forwarded
-
- port.Stop();
- #endregion
- }
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
-#if FEATURE_TPL
- [TestMethod]
- [TestCategory("integration")]
- [ExpectedException(typeof(SshConnectionException))]
- public void Test_PortForwarding_Local_Without_Connecting()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- var port1 = new ForwardedPortLocal("localhost", 8084, "www.renci.org", 80);
- client.AddForwardedPort(port1);
- port1.Exception += delegate (object sender, ExceptionEventArgs e)
- {
- Assert.Fail(e.Exception.ToString());
- };
- port1.Start();
-
- System.Threading.Tasks.Parallel.For(0, 100,
-
- //new ParallelOptions
- //{
- // MaxDegreeOfParallelism = 20,
- //},
- (counter) =>
- {
- var start = DateTime.Now;
- var req = HttpWebRequest.Create("http://localhost:8084");
- using (var response = req.GetResponse())
- {
- var data = ReadStream(response.GetResponseStream());
- var end = DateTime.Now;
-
- Debug.WriteLine(string.Format("Request# {2}: Lenght: {0} Time: {1}", data.Length, (end - start), counter));
- }
- }
- );
- }
- }
-
- [TestMethod]
- [TestCategory("integration")]
- public void Test_PortForwarding_Local()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- client.Connect();
- var port1 = new ForwardedPortLocal("localhost", 8084, "www.renci.org", 80);
- client.AddForwardedPort(port1);
- port1.Exception += delegate (object sender, ExceptionEventArgs e)
- {
- Assert.Fail(e.Exception.ToString());
- };
- port1.Start();
-
- System.Threading.Tasks.Parallel.For(0, 100,
-
- //new ParallelOptions
- //{
- // MaxDegreeOfParallelism = 20,
- //},
- (counter) =>
- {
- var start = DateTime.Now;
- var req = HttpWebRequest.Create("http://localhost:8084");
- using (var response = req.GetResponse())
- {
- var data = ReadStream(response.GetResponseStream());
- var end = DateTime.Now;
-
- Debug.WriteLine(string.Format("Request# {2}: Length: {0} Time: {1}", data.Length, (end - start), counter));
- }
- }
- );
- }
- }
-
- private static byte[] ReadStream(System.IO.Stream stream)
- {
- byte[] buffer = new byte[1024];
- using (var ms = new System.IO.MemoryStream())
- {
- while (true)
- {
- int read = stream.Read(buffer, 0, buffer.Length);
- if (read > 0)
- ms.Write(buffer, 0, read);
- else
- return ms.ToArray();
- }
- }
- }
-#endif // FEATURE_TPL
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest.cs
deleted file mode 100644
index 3a99441d1..000000000
--- a/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest.cs
+++ /dev/null
@@ -1,195 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.Net;
-using System.Threading;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides functionality for remote port forwarding
- ///
- [TestClass]
- public partial class ForwardedPortRemoteTest : TestBase
- {
- [TestMethod]
- [Description("Test passing null to AddForwardedPort hosts (remote).")]
- [ExpectedException(typeof(ArgumentNullException))]
- [TestCategory("integration")]
- public void Test_AddForwardedPort_Remote_Hosts_Are_Null()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- client.Connect();
- var port1 = new ForwardedPortRemote((string)null, 8080, (string)null, 80);
- client.AddForwardedPort(port1);
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [Description("Test passing invalid port numbers to AddForwardedPort.")]
- [ExpectedException(typeof(ArgumentOutOfRangeException))]
- [TestCategory("integration")]
- public void Test_AddForwardedPort_Invalid_PortNumber()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- client.Connect();
- var port1 = new ForwardedPortRemote("localhost", IPEndPoint.MaxPort + 1, "www.renci.org", IPEndPoint.MaxPort + 1);
- client.AddForwardedPort(port1);
- client.Disconnect();
- }
- }
-
- ///
- ///A test for ForwardedPortRemote Constructor
- ///
- [TestMethod]
- [TestCategory("integration")]
- public void Test_ForwardedPortRemote()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- #region Example SshClient AddForwardedPort Start Stop ForwardedPortRemote
- client.Connect();
- var port = new ForwardedPortRemote(8082, "www.cnn.com", 80);
- client.AddForwardedPort(port);
- port.Exception += delegate(object sender, ExceptionEventArgs e)
- {
- Console.WriteLine(e.Exception.ToString());
- };
- port.Start();
-
- Thread.Sleep(1000 * 60 * 20); // Wait 20 minutes for port to be forwarded
-
- port.Stop();
- #endregion
- }
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
-
- ///
- ///A test for Stop
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void StopTest()
- {
- uint boundPort = 0; // TODO: Initialize to an appropriate value
- string host = string.Empty; // TODO: Initialize to an appropriate value
- uint port = 0; // TODO: Initialize to an appropriate value
- ForwardedPortRemote target = new ForwardedPortRemote(boundPort, host, port); // TODO: Initialize to an appropriate value
- target.Stop();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- [TestMethod]
- public void Start_NotAddedToClient()
- {
- const int boundPort = 80;
- string host = string.Empty;
- const uint port = 22;
- var target = new ForwardedPortRemote(boundPort, host, port);
-
- try
- {
- target.Start();
- Assert.Fail();
- }
- catch (InvalidOperationException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Forwarded port is not added to a client.", ex.Message);
- }
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void DisposeTest()
- {
- uint boundPort = 0; // TODO: Initialize to an appropriate value
- string host = string.Empty; // TODO: Initialize to an appropriate value
- uint port = 0; // TODO: Initialize to an appropriate value
- ForwardedPortRemote target = new ForwardedPortRemote(boundPort, host, port); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for ForwardedPortRemote Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ForwardedPortRemoteConstructorTest()
- {
- string boundHost = string.Empty; // TODO: Initialize to an appropriate value
- uint boundPort = 0; // TODO: Initialize to an appropriate value
- string host = string.Empty; // TODO: Initialize to an appropriate value
- uint port = 0; // TODO: Initialize to an appropriate value
- ForwardedPortRemote target = new ForwardedPortRemote(boundHost, boundPort, host, port);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ForwardedPortRemote Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ForwardedPortRemoteConstructorTest1()
- {
- uint boundPort = 0; // TODO: Initialize to an appropriate value
- string host = string.Empty; // TODO: Initialize to an appropriate value
- uint port = 0; // TODO: Initialize to an appropriate value
- ForwardedPortRemote target = new ForwardedPortRemote(boundPort, host, port);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
-#if FEATURE_TPL
- [TestMethod]
- [TestCategory("integration")]
- public void Test_PortForwarding_Remote()
- {
- // ******************************************************************
- // ************* Tests are still in not finished ********************
- // ******************************************************************
-
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- client.Connect();
- var port1 = new ForwardedPortRemote(8082, "www.renci.org", 80);
- client.AddForwardedPort(port1);
- port1.Exception += delegate (object sender, ExceptionEventArgs e)
- {
- Assert.Fail(e.Exception.ToString());
- };
- port1.Start();
- var boundport = port1.BoundPort;
-
- System.Threading.Tasks.Parallel.For(0, 5,
-
- //new ParallelOptions
- //{
- // MaxDegreeOfParallelism = 1,
- //},
- (counter) =>
- {
- var cmd = client.CreateCommand(string.Format("wget -O- http://localhost:{0}", boundport));
- var result = cmd.Execute();
- var end = DateTime.Now;
- System.Diagnostics.Debug.WriteLine(string.Format("Length: {0}", result.Length));
- }
- );
- Thread.Sleep(1000 * 100);
- port1.Stop();
- }
- }
-#endif // FEATURE_TPL
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/KeyboardInteractiveAuthenticationMethodTest.cs b/src/Renci.SshNet.Tests/Classes/KeyboardInteractiveAuthenticationMethodTest.cs
deleted file mode 100644
index b85b88a8c..000000000
--- a/src/Renci.SshNet.Tests/Classes/KeyboardInteractiveAuthenticationMethodTest.cs
+++ /dev/null
@@ -1,89 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-using System;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides functionality to perform keyboard interactive authentication.
- ///
- [TestClass]
- public partial class KeyboardInteractiveAuthenticationMethodTest : TestBase
- {
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [Owner("Kenneth_aa")]
- [Description("KeyboardInteractiveAuthenticationMethod: Pass null as username.")]
- [ExpectedException(typeof(ArgumentException))]
- public void Keyboard_Test_Pass_Null()
- {
- new KeyboardInteractiveAuthenticationMethod(null);
- }
-
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [Owner("Kenneth_aa")]
- [Description("KeyboardInteractiveAuthenticationMethod: Pass String.Empty as username.")]
- [ExpectedException(typeof(ArgumentException))]
- public void Keyboard_Test_Pass_Whitespace()
- {
- new KeyboardInteractiveAuthenticationMethod(string.Empty);
- }
-
- ///
- ///A test for Name
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void NameTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- KeyboardInteractiveAuthenticationMethod target = new KeyboardInteractiveAuthenticationMethod(username); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.Name;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DisposeTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- KeyboardInteractiveAuthenticationMethod target = new KeyboardInteractiveAuthenticationMethod(username); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Authenticate
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AuthenticateTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- KeyboardInteractiveAuthenticationMethod target = new KeyboardInteractiveAuthenticationMethod(username); // TODO: Initialize to an appropriate value
- Session session = null; // TODO: Initialize to an appropriate value
- AuthenticationResult expected = new AuthenticationResult(); // TODO: Initialize to an appropriate value
- AuthenticationResult actual;
- actual = target.Authenticate(session);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for KeyboardInteractiveAuthenticationMethod Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyboardInteractiveAuthenticationMethodConstructorTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- KeyboardInteractiveAuthenticationMethod target = new KeyboardInteractiveAuthenticationMethod(username);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/KeyboardInteractiveConnectionInfoTest.cs b/src/Renci.SshNet.Tests/Classes/KeyboardInteractiveConnectionInfoTest.cs
deleted file mode 100644
index 0fc12c462..000000000
--- a/src/Renci.SshNet.Tests/Classes/KeyboardInteractiveConnectionInfoTest.cs
+++ /dev/null
@@ -1,195 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides connection information when keyboard interactive authentication method is used
- ///
- [TestClass]
- public class KeyboardInteractiveConnectionInfoTest : TestBase
- {
- [TestMethod]
- [TestCategory("KeyboardInteractiveConnectionInfo")]
- [TestCategory("integration")]
- public void Test_KeyboardInteractiveConnectionInfo()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
-
- #region Example KeyboardInteractiveConnectionInfo AuthenticationPrompt
- var connectionInfo = new KeyboardInteractiveConnectionInfo(host, username);
- connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
- {
- System.Console.WriteLine(e.Instruction);
-
- foreach (var prompt in e.Prompts)
- {
- Console.WriteLine(prompt.Request);
- prompt.Response = Console.ReadLine();
- }
- };
-
- using (var client = new SftpClient(connectionInfo))
- {
- client.Connect();
- // Do something here
- client.Disconnect();
- }
- #endregion
-
- Assert.AreEqual(connectionInfo.Host, Resources.HOST);
- Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DisposeTest()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, username); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for KeyboardInteractiveConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyboardInteractiveConnectionInfoConstructorTest()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- string proxyPassword = string.Empty; // TODO: Initialize to an appropriate value
- KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, port, username, proxyType, proxyHost, proxyPort, proxyUsername, proxyPassword);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for KeyboardInteractiveConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyboardInteractiveConnectionInfoConstructorTest1()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- string proxyPassword = string.Empty; // TODO: Initialize to an appropriate value
- KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, username, proxyType, proxyHost, proxyPort, proxyUsername, proxyPassword);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for KeyboardInteractiveConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyboardInteractiveConnectionInfoConstructorTest2()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, username, proxyType, proxyHost, proxyPort, proxyUsername);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for KeyboardInteractiveConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyboardInteractiveConnectionInfoConstructorTest3()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, username, proxyType, proxyHost, proxyPort);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for KeyboardInteractiveConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyboardInteractiveConnectionInfoConstructorTest4()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, port, username, proxyType, proxyHost, proxyPort, proxyUsername);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for KeyboardInteractiveConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyboardInteractiveConnectionInfoConstructorTest5()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, port, username, proxyType, proxyHost, proxyPort);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for KeyboardInteractiveConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyboardInteractiveConnectionInfoConstructorTest6()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, port, username);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for KeyboardInteractiveConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyboardInteractiveConnectionInfoConstructorTest7()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, username);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/MessageEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/MessageEventArgsTest.cs
deleted file mode 100644
index 387b5b29e..000000000
--- a/src/Renci.SshNet.Tests/Classes/MessageEventArgsTest.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides data for message events.
- ///
- /// Message type
- [TestClass]
- public class MessageEventArgsTest : TestBase
- {
- ///
- ///A test for MessageEventArgs`1 Constructor
- ///
- public void MessageEventArgsConstructorTestHelper()
- {
- T message = default(T); // TODO: Initialize to an appropriate value
- MessageEventArgs target = new MessageEventArgs(message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void MessageEventArgsConstructorTest()
- {
- MessageEventArgsConstructorTestHelper();
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/BannerMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/BannerMessageTest.cs
deleted file mode 100644
index 0c1021351..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/BannerMessageTest.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Messages.Authentication;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Authentication
-{
- ///
- ///This is a test class for BannerMessageTest and is intended
- ///to contain all BannerMessageTest Unit Tests
- ///
- [TestClass]
- public class BannerMessageTest : TestBase
- {
- ///
- ///A test for BannerMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void BannerMessageConstructorTest()
- {
- BannerMessage target = new BannerMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/FailureMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/FailureMessageTest.cs
deleted file mode 100644
index 9f0169f02..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/FailureMessageTest.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-using Renci.SshNet.Messages.Authentication;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Messages.Authentication
-{
- ///
- ///This is a test class for FailureMessageTest and is intended
- ///to contain all FailureMessageTest Unit Tests
- ///
- [TestClass]
- public class FailureMessageTest : TestBase
- {
- ///
- ///A test for FailureMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void FailureMessageConstructorTest()
- {
- FailureMessage target = new FailureMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for AllowedAuthentications
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void AllowedAuthenticationsTest()
- {
- FailureMessage target = new FailureMessage(); // TODO: Initialize to an appropriate value
- string[] expected = null; // TODO: Initialize to an appropriate value
- string[] actual;
- target.AllowedAuthentications = expected;
- actual = target.AllowedAuthentications;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/InformationRequestMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/InformationRequestMessageTest.cs
deleted file mode 100644
index 31dbd4e6e..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/InformationRequestMessageTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Messages.Authentication
-{
- ///
- /// Represents SSH_MSG_USERAUTH_INFO_REQUEST message.
- ///
- [TestClass]
- public class InformationRequestMessageTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/InformationResponseMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/InformationResponseMessageTest.cs
deleted file mode 100644
index f5d0f0ae3..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/InformationResponseMessageTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Messages.Authentication
-{
- ///
- /// Represents SSH_MSG_USERAUTH_INFO_RESPONSE message.
- ///
- [TestClass]
- public class InformationResponseMessageTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/PasswordChangeRequiredMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/PasswordChangeRequiredMessageTest.cs
deleted file mode 100644
index 3d876373f..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/PasswordChangeRequiredMessageTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Messages.Authentication
-{
- ///
- /// Represents SSH_MSG_USERAUTH_PASSWD_CHANGEREQ message.
- ///
- [TestClass]
- public class PasswordChangeRequiredMessageTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/PublicKeyMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/PublicKeyMessageTest.cs
deleted file mode 100644
index 1ab453989..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/PublicKeyMessageTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Messages.Authentication
-{
- ///
- /// Represents SSH_MSG_USERAUTH_PK_OK message.
- ///
- [TestClass]
- public class PublicKeyMessageTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessageHostTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessageHostTest.cs
deleted file mode 100644
index e50ee295e..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessageHostTest.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Messages.Authentication
-{
- ///
- /// Represents "hostbased" SSH_MSG_USERAUTH_REQUEST message.
- ///
- public class RequestMessageHostTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessageKeyboardInteractiveTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessageKeyboardInteractiveTest.cs
deleted file mode 100644
index b038ed9d9..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessageKeyboardInteractiveTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Messages.Authentication
-{
- ///
- /// Represents "keyboard-interactive" SSH_MSG_USERAUTH_REQUEST message.
- ///
- [TestClass]
- public class RequestMessageKeyboardInteractiveTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessageNoneTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessageNoneTest.cs
deleted file mode 100644
index cfae6875a..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessageNoneTest.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Messages.Authentication
-{
- ///
- /// Represents "none" SSH_MSG_USERAUTH_REQUEST message.
- ///
- public class RequestMessageNoneTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessagePasswordTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessagePasswordTest.cs
deleted file mode 100644
index 47ca635d1..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessagePasswordTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Messages.Authentication
-{
- ///
- /// Represents "password" SSH_MSG_USERAUTH_REQUEST message.
- ///
- [TestClass]
- public class RequestMessagePasswordTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessagePublicKeyTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessagePublicKeyTest.cs
deleted file mode 100644
index f09aa4a4c..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessagePublicKeyTest.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-using Renci.SshNet.Messages.Authentication;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Messages;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Messages.Authentication
-{
- ///
- ///This is a test class for RequestMessagePublicKeyTest and is intended
- ///to contain all RequestMessagePublicKeyTest Unit Tests
- ///
- [TestClass()]
- public class RequestMessagePublicKeyTest : TestBase
- {
- ///
- ///A test for RequestMessagePublicKey Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void RequestMessagePublicKeyConstructorTest()
- {
- ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value
- byte[] keyData = null; // TODO: Initialize to an appropriate value
- RequestMessagePublicKey target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for RequestMessagePublicKey Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void RequestMessagePublicKeyConstructorTest1()
- {
- ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value
- byte[] keyData = null; // TODO: Initialize to an appropriate value
- byte[] signature = null; // TODO: Initialize to an appropriate value
- RequestMessagePublicKey target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData, signature);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for MethodName
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void MethodNameTest()
- {
- ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value
- byte[] keyData = null; // TODO: Initialize to an appropriate value
- RequestMessagePublicKey target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.MethodName;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Signature
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void SignatureTest()
- {
- ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value
- byte[] keyData = null; // TODO: Initialize to an appropriate value
- RequestMessagePublicKey target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData); // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- target.Signature = expected;
- var actual = target.Signature;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/SuccessMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/SuccessMessageTest.cs
deleted file mode 100644
index 24cdbe3c3..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/SuccessMessageTest.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Messages.Authentication;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Authentication
-{
- ///
- ///This is a test class for SuccessMessageTest and is intended
- ///to contain all SuccessMessageTest Unit Tests
- ///
- [TestClass()]
- public class SuccessMessageTest : TestBase
- {
- ///
- ///A test for SuccessMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void SuccessMessageConstructorTest()
- {
- SuccessMessage target = new SuccessMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelCloseMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelCloseMessageTest.cs
deleted file mode 100644
index 9d3ebc3c0..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelCloseMessageTest.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for ChannelCloseMessageTest and is intended
- ///to contain all ChannelCloseMessageTest Unit Tests
- ///
- [TestClass]
- public class ChannelCloseMessageTest : TestBase
- {
- ///
- ///A test for ChannelCloseMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelCloseMessageConstructorTest()
- {
- ChannelCloseMessage target = new ChannelCloseMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ChannelCloseMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelCloseMessageConstructorTest1()
- {
- uint localChannelNumber = 0; // TODO: Initialize to an appropriate value
- ChannelCloseMessage target = new ChannelCloseMessage(localChannelNumber);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelEofMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelEofMessageTest.cs
deleted file mode 100644
index a302fb6e8..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelEofMessageTest.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for ChannelEofMessageTest and is intended
- ///to contain all ChannelEofMessageTest Unit Tests
- ///
- [TestClass]
- public class ChannelEofMessageTest : TestBase
- {
- ///
- ///A test for ChannelEofMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelEofMessageConstructorTest()
- {
- ChannelEofMessage target = new ChannelEofMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ChannelEofMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelEofMessageConstructorTest1()
- {
- uint localChannelNumber = 0; // TODO: Initialize to an appropriate value
- ChannelEofMessage target = new ChannelEofMessage(localChannelNumber);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelExtendedDataMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelExtendedDataMessageTest.cs
deleted file mode 100644
index 469908ea3..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelExtendedDataMessageTest.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for ChannelExtendedDataMessageTest and is intended
- ///to contain all ChannelExtendedDataMessageTest Unit Tests
- ///
- [TestClass]
- public class ChannelExtendedDataMessageTest : TestBase
- {
- ///
- ///A test for ChannelExtendedDataMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelExtendedDataMessageConstructorTest()
- {
- ChannelExtendedDataMessage target = new ChannelExtendedDataMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ChannelExtendedDataMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelExtendedDataMessageConstructorTest1()
- {
- //uint localChannelNumber = 0; // TODO: Initialize to an appropriate value
- //ChannelExtendedDataMessage target = new ChannelExtendedDataMessage(localChannelNumber, null, null);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelFailureMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelFailureMessageTest.cs
deleted file mode 100644
index ef1fe76c4..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelFailureMessageTest.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for ChannelFailureMessageTest and is intended
- ///to contain all ChannelFailureMessageTest Unit Tests
- ///
- [TestClass]
- public class ChannelFailureMessageTest : TestBase
- {
- ///
- ///A test for ChannelFailureMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelFailureMessageConstructorTest()
- {
- ChannelFailureMessage target = new ChannelFailureMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ChannelFailureMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelFailureMessageConstructorTest1()
- {
- uint localChannelNumber = 0; // TODO: Initialize to an appropriate value
- ChannelFailureMessage target = new ChannelFailureMessage(localChannelNumber);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelMessageTest.cs
deleted file mode 100644
index baa4a7fca..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelMessageTest.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for ChannelMessageTest and is intended
- ///to contain all ChannelMessageTest Unit Tests
- ///
- [TestClass]
- [Ignore] // placeholders only
- public class ChannelMessageTest : TestBase
- {
- internal virtual ChannelMessage CreateChannelMessage()
- {
- // TODO: Instantiate an appropriate concrete class.
- ChannelMessage target = null;
- return target;
- }
-
- ///
- ///A test for ToString
- ///
- [TestMethod()]
- public void ToStringTest()
- {
- ChannelMessage target = CreateChannelMessage(); // TODO: Initialize to an appropriate value
- string expected = string.Empty; // TODO: Initialize to an appropriate value
- string actual;
- actual = target.ToString();
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/DirectTcpipChannelInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/DirectTcpipChannelInfoTest.cs
deleted file mode 100644
index 8cda173bd..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/DirectTcpipChannelInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Used to open "direct-tcpip" channel type
- ///
- [TestClass]
- public class DirectTcpipChannelInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/ForwardedTcpipChannelInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/ForwardedTcpipChannelInfoTest.cs
deleted file mode 100644
index df38576a6..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/ForwardedTcpipChannelInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Used to open "forwarded-tcpip" channel type
- ///
- [TestClass]
- public class ForwardedTcpipChannelInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/SessionChannelOpenInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/SessionChannelOpenInfoTest.cs
deleted file mode 100644
index f647ed5ce..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/SessionChannelOpenInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Used to open "session" channel type
- ///
- [TestClass]
- public class SessionChannelOpenInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/X11ChannelOpenInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/X11ChannelOpenInfoTest.cs
deleted file mode 100644
index 44f348292..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/X11ChannelOpenInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Used to open "x11" channel type
- ///
- [TestClass]
- public class X11ChannelOpenInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenConfirmationMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenConfirmationMessageTest.cs
deleted file mode 100644
index ce5abb61a..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenConfirmationMessageTest.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for ChannelOpenConfirmationMessageTest and is intended
- ///to contain all ChannelOpenConfirmationMessageTest Unit Tests
- ///
- [TestClass]
- public class ChannelOpenConfirmationMessageTest : TestBase
- {
- ///
- ///A test for ChannelOpenConfirmationMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelOpenConfirmationMessageConstructorTest()
- {
- ChannelOpenConfirmationMessage target = new ChannelOpenConfirmationMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ChannelOpenConfirmationMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelOpenConfirmationMessageConstructorTest1()
- {
- uint localChannelNumber = 0; // TODO: Initialize to an appropriate value
- uint initialWindowSize = 0; // TODO: Initialize to an appropriate value
- uint maximumPacketSize = 0; // TODO: Initialize to an appropriate value
- uint remoteChannelNumber = 0; // TODO: Initialize to an appropriate value
- ChannelOpenConfirmationMessage target = new ChannelOpenConfirmationMessage(localChannelNumber, initialWindowSize, maximumPacketSize, remoteChannelNumber);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenFailureMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenFailureMessageTest.cs
deleted file mode 100644
index 3992ca491..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenFailureMessageTest.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for ChannelOpenFailureMessageTest and is intended
- ///to contain all ChannelOpenFailureMessageTest Unit Tests
- ///
- [TestClass]
- public class ChannelOpenFailureMessageTest : TestBase
- {
- ///
- ///A test for ChannelOpenFailureMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelOpenFailureMessageConstructorTest()
- {
- ChannelOpenFailureMessage target = new ChannelOpenFailureMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ChannelOpenFailureMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelOpenFailureMessageConstructorTest1()
- {
- uint localChannelNumber = 0; // TODO: Initialize to an appropriate value
- string description = string.Empty; // TODO: Initialize to an appropriate value
- uint reasonCode = 0; // TODO: Initialize to an appropriate value
- ChannelOpenFailureMessage target = new ChannelOpenFailureMessage(localChannelNumber, description, reasonCode);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenInfoTest.cs
deleted file mode 100644
index 845cc8c07..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenInfoTest.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for ChannelOpenInfoTest and is intended
- ///to contain all ChannelOpenInfoTest Unit Tests
- ///
- [TestClass]
- [Ignore] // placeholders only
- public class ChannelOpenInfoTest : TestBase
- {
- internal virtual ChannelOpenInfo CreateChannelOpenInfo()
- {
- // TODO: Instantiate an appropriate concrete class.
- ChannelOpenInfo target = null;
- return target;
- }
-
- ///
- ///A test for ChannelType
- ///
- [TestMethod()]
- public void ChannelTypeTest()
- {
- ChannelOpenInfo target = CreateChannelOpenInfo(); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.ChannelType;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/BreakRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/BreakRequestInfoTest.cs
deleted file mode 100644
index dd8d7b287..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/BreakRequestInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents "break" type channel request information
- ///
- [TestClass]
- public class BreakRequestInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ChannelRequestMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ChannelRequestMessageTest.cs
deleted file mode 100644
index 0c5599975..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ChannelRequestMessageTest.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Messages.Connection;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents SSH_MSG_CHANNEL_REQUEST message.
- ///
- [TestClass]
- [Ignore] // placeholders only
- public class ChannelRequestMessageTest : TestBase
- {
- ///
- ///A test for ChannelRequestMessage Constructor
- ///
- [TestMethod()]
- public void ChannelRequestMessageConstructorTest()
- {
- ChannelRequestMessage target = new ChannelRequestMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ChannelRequestMessage Constructor
- ///
- [TestMethod()]
- public void ChannelRequestMessageConstructorTest1()
- {
- uint localChannelName = 0; // TODO: Initialize to an appropriate value
- RequestInfo info = null; // TODO: Initialize to an appropriate value
- ChannelRequestMessage target = new ChannelRequestMessage(localChannelName, info);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/EndOfWriteRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/EndOfWriteRequestInfoTest.cs
deleted file mode 100644
index 68ffa7af7..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/EndOfWriteRequestInfoTest.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for EndOfWriteRequestInfoTest and is intended
- ///to contain all EndOfWriteRequestInfoTest Unit Tests
- ///
- [TestClass]
- public class EndOfWriteRequestInfoTest : TestBase
- {
- ///
- ///A test for EndOfWriteRequestInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void EndOfWriteRequestInfoConstructorTest()
- {
- EndOfWriteRequestInfo target = new EndOfWriteRequestInfo();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for RequestName
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void RequestNameTest()
- {
- EndOfWriteRequestInfo target = new EndOfWriteRequestInfo(); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.RequestName;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/EnvironmentVariableRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/EnvironmentVariableRequestInfoTest.cs
deleted file mode 100644
index 78899d9d2..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/EnvironmentVariableRequestInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents "env" type channel request information
- ///
- [TestClass]
- public class EnvironmentVariableRequestInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ExecRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ExecRequestInfoTest.cs
deleted file mode 100644
index ed030011b..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ExecRequestInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents "exec" type channel request information
- ///
- [TestClass]
- public class ExecRequestInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ExitSignalRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ExitSignalRequestInfoTest.cs
deleted file mode 100644
index 81c00444e..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ExitSignalRequestInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents "exit-signal" type channel request information
- ///
- [TestClass]
- public class ExitSignalRequestInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ExitStatusRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ExitStatusRequestInfoTest.cs
deleted file mode 100644
index dd17e684d..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ExitStatusRequestInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents "exit-status" type channel request information
- ///
- [TestClass]
- public class ExitStatusRequestInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/KeepAliveRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/KeepAliveRequestInfoTest.cs
deleted file mode 100644
index 515a723a5..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/KeepAliveRequestInfoTest.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for KeepAliveRequestInfoTest and is intended
- ///to contain all KeepAliveRequestInfoTest Unit Tests
- ///
- [TestClass]
- public class KeepAliveRequestInfoTest : TestBase
- {
- ///
- ///A test for KeepAliveRequestInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void KeepAliveRequestInfoConstructorTest()
- {
- KeepAliveRequestInfo target = new KeepAliveRequestInfo();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for RequestName
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void RequestNameTest()
- {
- KeepAliveRequestInfo target = new KeepAliveRequestInfo(); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.RequestName;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ShellRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ShellRequestInfoTest.cs
deleted file mode 100644
index 26ef2e97f..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/ShellRequestInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents "shell" type channel request information
- ///
- [TestClass]
- public class ShellRequestInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/SignalRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/SignalRequestInfoTest.cs
deleted file mode 100644
index 31df73591..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/SignalRequestInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents "signal" type channel request information
- ///
- [TestClass]
- public class SignalRequestInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/SubsystemRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/SubsystemRequestInfoTest.cs
deleted file mode 100644
index 5beaa074f..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/SubsystemRequestInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents "subsystem" type channel request information
- ///
- [TestClass]
- public class SubsystemRequestInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/WindowChangeRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/WindowChangeRequestInfoTest.cs
deleted file mode 100644
index 15cd2d339..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/WindowChangeRequestInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents "window-change" type channel request information
- ///
- [TestClass]
- public class WindowChangeRequestInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/X11ForwardingRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/X11ForwardingRequestInfoTest.cs
deleted file mode 100644
index c5fab8a12..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/X11ForwardingRequestInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents "x11-req" type channel request information
- ///
- [TestClass]
- public class X11ForwardingRequestInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/XonXoffRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/XonXoffRequestInfoTest.cs
deleted file mode 100644
index f6ef5fc56..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/XonXoffRequestInfoTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- /// Represents "xon-xoff" type channel request information
- ///
- [TestClass]
- public class XonXoffRequestInfoTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelSuccessMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelSuccessMessageTest.cs
deleted file mode 100644
index 6bfb5b0c2..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelSuccessMessageTest.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for ChannelSuccessMessageTest and is intended
- ///to contain all ChannelSuccessMessageTest Unit Tests
- ///
- [TestClass]
- public class ChannelSuccessMessageTest : TestBase
- {
- ///
- ///A test for ChannelSuccessMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelSuccessMessageConstructorTest()
- {
- ChannelSuccessMessage target = new ChannelSuccessMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ChannelSuccessMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelSuccessMessageConstructorTest1()
- {
- uint localChannelNumber = 0; // TODO: Initialize to an appropriate value
- ChannelSuccessMessage target = new ChannelSuccessMessage(localChannelNumber);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelWindowAdjustMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelWindowAdjustMessageTest.cs
deleted file mode 100644
index 131cdfda6..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelWindowAdjustMessageTest.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for ChannelWindowAdjustMessageTest and is intended
- ///to contain all ChannelWindowAdjustMessageTest Unit Tests
- ///
- [TestClass]
- public class ChannelWindowAdjustMessageTest : TestBase
- {
- ///
- ///A test for ChannelWindowAdjustMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelWindowAdjustMessageConstructorTest()
- {
- ChannelWindowAdjustMessage target = new ChannelWindowAdjustMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ChannelWindowAdjustMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ChannelWindowAdjustMessageConstructorTest1()
- {
- uint localChannelNumber = 0; // TODO: Initialize to an appropriate value
- uint bytesToAdd = 0; // TODO: Initialize to an appropriate value
- ChannelWindowAdjustMessage target = new ChannelWindowAdjustMessage(localChannelNumber, bytesToAdd);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestFailureMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestFailureMessageTest.cs
deleted file mode 100644
index b482ac0ab..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestFailureMessageTest.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for RequestFailureMessageTest and is intended
- ///to contain all RequestFailureMessageTest Unit Tests
- ///
- [TestClass]
- public class RequestFailureMessageTest : TestBase
- {
- ///
- ///A test for RequestFailureMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void RequestFailureMessageConstructorTest()
- {
- RequestFailureMessage target = new RequestFailureMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestInfoTest.cs
deleted file mode 100644
index fdf6d5348..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestInfoTest.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for RequestInfoTest and is intended
- ///to contain all RequestInfoTest Unit Tests
- ///
- [TestClass]
- [Ignore] // placeholders only
- public class RequestInfoTest : TestBase
- {
- internal virtual RequestInfo CreateRequestInfo()
- {
- // TODO: Instantiate an appropriate concrete class.
- RequestInfo target = null;
- return target;
- }
-
- ///
- ///A test for RequestName
- ///
- [TestMethod()]
- public void RequestNameTest()
- {
- RequestInfo target = CreateRequestInfo(); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.RequestName;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestSuccessMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestSuccessMessageTest.cs
deleted file mode 100644
index 55d7ec6db..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestSuccessMessageTest.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using Renci.SshNet.Messages.Connection;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Connection
-{
- ///
- ///This is a test class for RequestSuccessMessageTest and is intended
- ///to contain all RequestSuccessMessageTest Unit Tests
- ///
- [TestClass]
- public class RequestSuccessMessageTest : TestBase
- {
- ///
- ///A test for RequestSuccessMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void RequestSuccessMessageConstructorTest()
- {
- RequestSuccessMessage target = new RequestSuccessMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for RequestSuccessMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void RequestSuccessMessageConstructorTest1()
- {
- uint boundPort = 0; // TODO: Initialize to an appropriate value
- RequestSuccessMessage target = new RequestSuccessMessage(boundPort);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/MessageAttributeTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/MessageAttributeTest.cs
deleted file mode 100644
index 9c4f93cd0..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/MessageAttributeTest.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-using Renci.SshNet.Messages;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages
-{
- ///
- ///This is a test class for MessageAttributeTest and is intended
- ///to contain all MessageAttributeTest Unit Tests
- ///
- [TestClass()]
- public class MessageAttributeTest : TestBase
- {
- ///
- ///A test for MessageAttribute Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void MessageAttributeConstructorTest()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- byte number = 0; // TODO: Initialize to an appropriate value
- MessageAttribute target = new MessageAttribute(name, number);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Name
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void NameTest()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- byte number = 0; // TODO: Initialize to an appropriate value
- MessageAttribute target = new MessageAttribute(name, number); // TODO: Initialize to an appropriate value
- string expected = string.Empty; // TODO: Initialize to an appropriate value
- target.Name = expected;
- var actual = target.Name;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Number
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void NumberTest()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- byte number = 0; // TODO: Initialize to an appropriate value
- MessageAttribute target = new MessageAttribute(name, number); // TODO: Initialize to an appropriate value
- byte expected = 0; // TODO: Initialize to an appropriate value
- target.Number = expected;
- var actual = target.Number;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/MessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/MessageTest.cs
deleted file mode 100644
index 5ad0d6bfe..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/MessageTest.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using Renci.SshNet.Messages;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages
-{
- ///
- ///This is a test class for MessageTest and is intended
- ///to contain all MessageTest Unit Tests
- ///
- [TestClass]
- [Ignore] // placeholders only
- public class MessageTest : TestBase
- {
- internal virtual Message CreateMessage()
- {
- // TODO: Instantiate an appropriate concrete class.
- Message target = null;
- return target;
- }
-
- ///
- ///A test for GetBytes
- ///
- [TestMethod]
- public void GetBytesTest()
- {
- Message target = CreateMessage(); // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- var actual = target.GetBytes();
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ToString
- ///
- [TestMethod]
- public void ToStringTest()
- {
- Message target = CreateMessage(); // TODO: Initialize to an appropriate value
- string expected = string.Empty; // TODO: Initialize to an appropriate value
- var actual = target.ToString();
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/DebugMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/DebugMessageTest.cs
deleted file mode 100644
index 25f07de37..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/DebugMessageTest.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using Renci.SshNet.Messages.Transport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Transport
-{
- ///
- ///This is a test class for DebugMessageTest and is intended
- ///to contain all DebugMessageTest Unit Tests
- ///
- [TestClass]
- public class DebugMessageTest : TestBase
- {
- ///
- ///A test for DebugMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void DebugMessageConstructorTest()
- {
- DebugMessage target = new DebugMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/DisconnectMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/DisconnectMessageTest.cs
deleted file mode 100644
index 280370364..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/DisconnectMessageTest.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using Renci.SshNet.Messages.Transport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Transport
-{
- ///
- ///This is a test class for DisconnectMessageTest and is intended
- ///to contain all DisconnectMessageTest Unit Tests
- ///
- [TestClass]
- public class DisconnectMessageTest : TestBase
- {
- ///
- ///A test for DisconnectMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void DisconnectMessageConstructorTest()
- {
- DisconnectMessage target = new DisconnectMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for DisconnectMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void DisconnectMessageConstructorTest1()
- {
- DisconnectReason reasonCode = new DisconnectReason(); // TODO: Initialize to an appropriate value
- string message = string.Empty; // TODO: Initialize to an appropriate value
- DisconnectMessage target = new DisconnectMessage(reasonCode, message);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeGroupTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeGroupTest.cs
deleted file mode 100644
index fc49a61d9..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeGroupTest.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using Renci.SshNet.Messages.Transport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Transport
-{
- ///
- ///This is a test class for KeyExchangeDhGroupExchangeGroupTest and is intended
- ///to contain all KeyExchangeDhGroupExchangeGroupTest Unit Tests
- ///
- [TestClass]
- public class KeyExchangeDhGroupExchangeGroupTest : TestBase
- {
- ///
- ///A test for KeyExchangeDhGroupExchangeGroup Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void KeyExchangeDhGroupExchangeGroupConstructorTest()
- {
- KeyExchangeDhGroupExchangeGroup target = new KeyExchangeDhGroupExchangeGroup();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhInitMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhInitMessageTest.cs
deleted file mode 100644
index 01fd55151..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhInitMessageTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Transport
-{
- ///
- /// Represents SSH_MSG_KEXDH_INIT message.
- ///
- [TestClass]
- public class KeyExchangeDhInitMessageTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhReplyMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhReplyMessageTest.cs
deleted file mode 100644
index 961fe4370..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhReplyMessageTest.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using Renci.SshNet.Messages.Transport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Transport
-{
- ///
- ///This is a test class for KeyExchangeDhReplyMessageTest and is intended
- ///to contain all KeyExchangeDhReplyMessageTest Unit Tests
- ///
- [TestClass]
- public class KeyExchangeDhReplyMessageTest : TestBase
- {
- ///
- ///A test for KeyExchangeDhReplyMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void KeyExchangeDhReplyMessageConstructorTest()
- {
- KeyExchangeDhReplyMessage target = new KeyExchangeDhReplyMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/NewKeysMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/NewKeysMessageTest.cs
deleted file mode 100644
index f1ea0398d..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/NewKeysMessageTest.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using Renci.SshNet.Messages.Transport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Transport
-{
- ///
- ///This is a test class for NewKeysMessageTest and is intended
- ///to contain all NewKeysMessageTest Unit Tests
- ///
- [TestClass]
- public class NewKeysMessageTest : TestBase
- {
- ///
- ///A test for NewKeysMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void NewKeysMessageConstructorTest()
- {
- NewKeysMessage target = new NewKeysMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceAcceptMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceAcceptMessageTest.cs
deleted file mode 100644
index 5c8f40912..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceAcceptMessageTest.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using Renci.SshNet.Messages.Transport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Transport
-{
- ///
- ///This is a test class for ServiceAcceptMessageTest and is intended
- ///to contain all ServiceAcceptMessageTest Unit Tests
- ///
- [TestClass]
- public class ServiceAcceptMessageTest
- {
- ///
- ///A test for ServiceAcceptMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ServiceAcceptMessageConstructorTest()
- {
- ServiceAcceptMessage target = new ServiceAcceptMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceRequestMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceRequestMessageTest.cs
deleted file mode 100644
index dc1db6a42..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceRequestMessageTest.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using Renci.SshNet.Messages.Transport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Messages;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Transport
-{
- ///
- ///This is a test class for ServiceRequestMessageTest and is intended
- ///to contain all ServiceRequestMessageTest Unit Tests
- ///
- [TestClass]
- public class ServiceRequestMessageTest
- {
- ///
- ///A test for ServiceRequestMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void ServiceRequestMessageConstructorTest()
- {
- ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value
- ServiceRequestMessage target = new ServiceRequestMessage(serviceName);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/UnimplementedMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/UnimplementedMessageTest.cs
deleted file mode 100644
index 8abdd4ad5..000000000
--- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/UnimplementedMessageTest.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using Renci.SshNet.Messages.Transport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Messages.Transport
-{
- ///
- ///This is a test class for UnimplementedMessageTest and is intended
- ///to contain all UnimplementedMessageTest Unit Tests
- ///
- [TestClass]
- public class UnimplementedMessageTest : TestBase
- {
- ///
- ///A test for UnimplementedMessage Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void UnimplementedMessageConstructorTest()
- {
- UnimplementedMessage target = new UnimplementedMessage();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/NetConfClientTest.cs b/src/Renci.SshNet.Tests/Classes/NetConfClientTest.cs
deleted file mode 100644
index d70fea366..000000000
--- a/src/Renci.SshNet.Tests/Classes/NetConfClientTest.cs
+++ /dev/null
@@ -1,278 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-using System;
-using System.Xml;
-
-namespace Renci.SshNet.Tests.Classes
-{
- [TestClass]
- public class NetConfClientTest : TestBase
- {
- private Random _random;
-
- [TestInitialize]
- public void SetUp()
- {
- _random = new Random();
- }
-
- [TestMethod]
- public void OperationTimeout_Default()
- {
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new NetConfClient(connectionInfo);
-
- var actual = target.OperationTimeout;
-
- Assert.AreEqual(TimeSpan.FromMilliseconds(-1), actual);
- }
-
- [TestMethod]
- public void OperationTimeout_InsideLimits()
- {
- var operationTimeout = TimeSpan.FromMilliseconds(_random.Next(0, int.MaxValue - 1));
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new NetConfClient(connectionInfo)
- {
- OperationTimeout = operationTimeout
- };
-
- var actual = target.OperationTimeout;
-
- Assert.AreEqual(operationTimeout, actual);
- }
-
- [TestMethod]
- public void OperationTimeout_LowerLimit()
- {
- var operationTimeout = TimeSpan.FromMilliseconds(-1);
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new NetConfClient(connectionInfo)
- {
- OperationTimeout = operationTimeout
- };
-
- var actual = target.OperationTimeout;
-
- Assert.AreEqual(operationTimeout, actual);
- }
-
- [TestMethod]
- public void OperationTimeout_UpperLimit()
- {
- var operationTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new NetConfClient(connectionInfo)
- {
- OperationTimeout = operationTimeout
- };
-
- var actual = target.OperationTimeout;
-
- Assert.AreEqual(operationTimeout, actual);
- }
-
- [TestMethod]
- public void OperationTimeout_LessThanLowerLimit()
- {
- var operationTimeout = TimeSpan.FromMilliseconds(-2);
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new NetConfClient(connectionInfo);
-
- try
- {
- target.OperationTimeout = operationTimeout;
- }
- catch (ArgumentOutOfRangeException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("The timeout must represent a value between -1 and Int32.MaxValue, inclusive." + Environment.NewLine + "Parameter name: " + ex.ParamName, ex.Message);
- Assert.AreEqual("value", ex.ParamName);
- }
- }
-
- [TestMethod]
- public void OperationTimeout_GreaterThanLowerLimit()
- {
- var operationTimeout = TimeSpan.FromMilliseconds(int.MaxValue).Add(TimeSpan.FromMilliseconds(1));
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new NetConfClient(connectionInfo);
-
- try
- {
- target.OperationTimeout = operationTimeout;
- }
- catch (ArgumentOutOfRangeException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("The timeout must represent a value between -1 and Int32.MaxValue, inclusive." + Environment.NewLine + "Parameter name: " + ex.ParamName, ex.Message);
- Assert.AreEqual("value", ex.ParamName);
- }
- }
-
- ///
- ///A test for NetConfClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void NetConfClientConstructorTest()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- NetConfClient target = new NetConfClient(host, username, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for NetConfClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void NetConfClientConstructorTest1()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- NetConfClient target = new NetConfClient(host, port, username, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for NetConfClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void NetConfClientConstructorTest2()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- NetConfClient target = new NetConfClient(host, username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for NetConfClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void NetConfClientConstructorTest3()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- NetConfClient target = new NetConfClient(host, port, username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for NetConfClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void NetConfClientConstructorTest4()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- NetConfClient target = new NetConfClient(connectionInfo);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SendReceiveRpc
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SendReceiveRpcTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- NetConfClient target = new NetConfClient(connectionInfo); // TODO: Initialize to an appropriate value
- string xml = string.Empty; // TODO: Initialize to an appropriate value
- XmlDocument expected = null; // TODO: Initialize to an appropriate value
- XmlDocument actual;
- actual = target.SendReceiveRpc(xml);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for SendReceiveRpc
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SendReceiveRpcTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- NetConfClient target = new NetConfClient(connectionInfo); // TODO: Initialize to an appropriate value
- XmlDocument rpc = null; // TODO: Initialize to an appropriate value
- XmlDocument expected = null; // TODO: Initialize to an appropriate value
- XmlDocument actual;
- actual = target.SendReceiveRpc(rpc);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for SendCloseRpc
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SendCloseRpcTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- NetConfClient target = new NetConfClient(connectionInfo); // TODO: Initialize to an appropriate value
- XmlDocument expected = null; // TODO: Initialize to an appropriate value
- XmlDocument actual;
- actual = target.SendCloseRpc();
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ServerCapabilities
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ServerCapabilitiesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- NetConfClient target = new NetConfClient(connectionInfo); // TODO: Initialize to an appropriate value
- XmlDocument actual;
- actual = target.ServerCapabilities;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ClientCapabilities
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ClientCapabilitiesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- NetConfClient target = new NetConfClient(connectionInfo); // TODO: Initialize to an appropriate value
- XmlDocument actual;
- actual = target.ClientCapabilities;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for AutomaticMessageIdHandling
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AutomaticMessageIdHandlingTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- NetConfClient target = new NetConfClient(connectionInfo); // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.AutomaticMessageIdHandling = expected;
- actual = target.AutomaticMessageIdHandling;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Connected.cs b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Connected.cs
deleted file mode 100644
index ba86a7c94..000000000
--- a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Connected.cs
+++ /dev/null
@@ -1,111 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-using Renci.SshNet.NetConf;
-using System;
-
-namespace Renci.SshNet.Tests.Classes
-{
- [TestClass]
- public class NetConfClientTest_Dispose_Connected : NetConfClientTestBase
- {
- private NetConfClient _netConfClient;
- private ConnectionInfo _connectionInfo;
- private int _operationTimeout;
-
- protected override void SetupData()
- {
- _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
- _operationTimeout = new Random().Next(1000, 10000);
- _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object);
- _netConfClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout);
- }
-
- protected override void SetupMocks()
- {
- var sequence = new MockSequence();
-
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSocketFactory())
- .Returns(_socketFactoryMock.Object);
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object))
- .Returns(_sessionMock.Object);
- _sessionMock.InSequence(sequence)
- .Setup(p => p.Connect());
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout))
- .Returns(_netConfSessionMock.Object);
- _netConfSessionMock.InSequence(sequence)
- .Setup(p => p.Connect());
- _sessionMock.InSequence(sequence)
- .Setup(p => p.OnDisconnecting());
- _netConfSessionMock.InSequence(sequence)
- .Setup(p => p.Disconnect());
- _sessionMock.InSequence(sequence)
- .Setup(p => p.Dispose());
- _netConfSessionMock.InSequence(sequence)
- .Setup(p => p.Dispose());
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _netConfClient.Connect();
- }
-
- protected override void Act()
- {
- _netConfClient.Dispose();
- }
-
- [TestMethod]
- public void CreateNetConfSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout), Times.Once);
- }
-
- [TestMethod]
- public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once);
- }
-
- [TestMethod]
- public void CreateSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object),
- Times.Once);
- }
-
- [TestMethod]
- public void DisconnectOnNetConfSessionShouldBeInvokedOnce()
- {
- _netConfSessionMock.Verify(p => p.Disconnect(), Times.Once);
- }
-
- [TestMethod]
- public void DisconnectOnSessionShouldNeverBeInvoked()
- {
- _sessionMock.Verify(p => p.Disconnect(), Times.Never);
- }
-
- [TestMethod]
- public void DisposeOnNetConfSessionShouldBeInvokedOnce()
- {
- _netConfSessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void DisposeOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void OnDisconnectingOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disconnected.cs b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disconnected.cs
deleted file mode 100644
index 8a4fbcd2e..000000000
--- a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disconnected.cs
+++ /dev/null
@@ -1,119 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-using Renci.SshNet.NetConf;
-using System;
-
-namespace Renci.SshNet.Tests.Classes
-{
- [TestClass]
- public class NetConfClientTest_Dispose_Disconnected : NetConfClientTestBase
- {
- private NetConfClient _netConfClient;
- private ConnectionInfo _connectionInfo;
- private int _operationTimeout;
-
- [TestInitialize]
- public void Setup()
- {
- Arrange();
- Act();
- }
-
- [TestCleanup]
- public void Cleanup()
- {
- }
-
- protected override void SetupData()
- {
- _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
- _operationTimeout = new Random().Next(1000, 10000);
- _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object);
- _netConfClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout);
- }
-
- protected override void SetupMocks()
- {
- var sequence = new MockSequence();
-
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSocketFactory())
- .Returns(_socketFactoryMock.Object);
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object))
- .Returns(_sessionMock.Object);
- _sessionMock.InSequence(sequence).Setup(p => p.Connect());
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout))
- .Returns(_netConfSessionMock.Object);
- _netConfSessionMock.InSequence(sequence).Setup(p => p.Connect());
- _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
- _netConfSessionMock.InSequence(sequence).Setup(p => p.Disconnect());
- _sessionMock.InSequence(sequence).Setup(p => p.Dispose());
- _netConfSessionMock.InSequence(sequence).Setup(p => p.Disconnect());
- _netConfSessionMock.InSequence(sequence).Setup(p => p.Dispose());
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _netConfClient.Connect();
- _netConfClient.Disconnect();
- }
-
- protected override void Act()
- {
- _netConfClient.Dispose();
- }
-
- [TestMethod]
- public void CreateNetConfSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout), Times.Once);
- }
-
- [TestMethod]
- public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once);
- }
-
- [TestMethod]
- public void CreateSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object),
- Times.Once);
- }
-
- [TestMethod]
- public void DisconnectOnNetConfSessionShouldBeInvokedTwice()
- {
- _netConfSessionMock.Verify(p => p.Disconnect(), Times.Exactly(2));
- }
-
- [TestMethod]
- public void DisconnectOnSessionShouldNeverBeInvoked()
- {
- _sessionMock.Verify(p => p.Disconnect(), Times.Never);
- }
-
- [TestMethod]
- public void DisposeOnNetConfSessionShouldBeInvokedOnce()
- {
- _netConfSessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void DisposeOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void OnDisconnectingOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disposed.cs b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disposed.cs
deleted file mode 100644
index 9ed692a30..000000000
--- a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disposed.cs
+++ /dev/null
@@ -1,106 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-using Renci.SshNet.NetConf;
-using System;
-
-namespace Renci.SshNet.Tests.Classes
-{
- [TestClass]
- public class NetConfClientTest_Dispose_Disposed : NetConfClientTestBase
- {
- private NetConfClient _netConfClient;
- private ConnectionInfo _connectionInfo;
- private int _operationTimeout;
-
- protected override void SetupData()
- {
- _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
- _operationTimeout = new Random().Next(1000, 10000);
- _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object);
- _netConfClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout);
- }
-
- protected override void SetupMocks()
- {
- var sequence = new MockSequence();
-
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSocketFactory())
- .Returns(_socketFactoryMock.Object);
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object))
- .Returns(_sessionMock.Object);
- _sessionMock.InSequence(sequence).Setup(p => p.Connect());
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout))
- .Returns(_netConfSessionMock.Object);
- _netConfSessionMock.InSequence(sequence).Setup(p => p.Connect());
- _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
- _netConfSessionMock.InSequence(sequence).Setup(p => p.Disconnect());
- _sessionMock.InSequence(sequence).Setup(p => p.Dispose());
- _netConfSessionMock.InSequence(sequence).Setup(p => p.Dispose());
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _netConfClient.Connect();
- _netConfClient.Dispose();
- }
-
- protected override void Act()
- {
- _netConfClient.Dispose();
- }
-
- [TestMethod]
- public void CreateNetConfSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout), Times.Once);
- }
-
- [TestMethod]
- public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once);
- }
-
- [TestMethod]
- public void CreateSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object),
- Times.Once);
- }
-
- [TestMethod]
- public void DisconnectOnNetConfSessionShouldBeInvokedOnce()
- {
- _netConfSessionMock.Verify(p => p.Disconnect(), Times.Once);
- }
-
- [TestMethod]
- public void DisconnectOnSessionShouldNeverBeInvoked()
- {
- _sessionMock.Verify(p => p.Disconnect(), Times.Never);
- }
-
- [TestMethod]
- public void DisposeOnNetConfSessionShouldBeInvokedOnce()
- {
- _netConfSessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void DisposeOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void OnDisconnectingOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/NoneAuthenticationMethodTest.cs b/src/Renci.SshNet.Tests/Classes/NoneAuthenticationMethodTest.cs
deleted file mode 100644
index 3dc69e319..000000000
--- a/src/Renci.SshNet.Tests/Classes/NoneAuthenticationMethodTest.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-using System.Globalization;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-using System;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides functionality for "none" authentication method
- ///
- [TestClass]
- public class NoneAuthenticationMethodTest : TestBase
- {
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [Owner("Kenneth_aa")]
- [Description("NoneAuthenticationMethod: Pass null as username.")]
- [ExpectedException(typeof(ArgumentException))]
- public void None_Test_Pass_Null()
- {
- new NoneAuthenticationMethod(null);
- }
-
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [Owner("Kenneth_aa")]
- [Description("NoneAuthenticationMethod: Pass String.Empty as username.")]
- [ExpectedException(typeof(ArgumentException))]
- public void None_Test_Pass_Whitespace()
- {
- new NoneAuthenticationMethod(string.Empty);
- }
-
- [TestMethod]
- public void Name()
- {
- var username = new Random().Next().ToString(CultureInfo.InvariantCulture);
- var target = new NoneAuthenticationMethod(username);
-
- Assert.AreEqual("none", target.Name);
- }
-
- [TestMethod]
- public void Username()
- {
- var username = new Random().Next().ToString(CultureInfo.InvariantCulture);
- var target = new NoneAuthenticationMethod(username);
-
- Assert.AreSame(username, target.Username);
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DisposeTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- NoneAuthenticationMethod target = new NoneAuthenticationMethod(username); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Authenticate
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AuthenticateTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- NoneAuthenticationMethod target = new NoneAuthenticationMethod(username); // TODO: Initialize to an appropriate value
- Session session = null; // TODO: Initialize to an appropriate value
- AuthenticationResult expected = new AuthenticationResult(); // TODO: Initialize to an appropriate value
- AuthenticationResult actual;
- actual = target.Authenticate(session);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for NoneAuthenticationMethod Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void NoneAuthenticationMethodConstructorTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- NoneAuthenticationMethod target = new NoneAuthenticationMethod(username);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/PasswordAuthenticationMethodTest.cs b/src/Renci.SshNet.Tests/Classes/PasswordAuthenticationMethodTest.cs
deleted file mode 100644
index ec0d3fef8..000000000
--- a/src/Renci.SshNet.Tests/Classes/PasswordAuthenticationMethodTest.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides functionality to perform password authentication.
- ///
- [TestClass]
- public partial class PasswordAuthenticationMethodTest : TestBase
- {
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [Owner("Kenneth_aa")]
- [Description("PasswordAuthenticationMethod: Pass null as username, \"valid\" as password.")]
- [ExpectedException(typeof(ArgumentException))]
- public void Password_Test_Pass_Null_Username()
- {
- new PasswordAuthenticationMethod(null, "valid");
- }
-
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [Owner("Kenneth_aa")]
- [Description("PasswordAuthenticationMethod: Pass \"valid\" as username, null as password.")]
- [ExpectedException(typeof(ArgumentNullException))]
- public void Password_Test_Pass_Null_Password()
- {
- new PasswordAuthenticationMethod("valid", (string)null);
- }
-
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [Owner("Kenneth_aa")]
- [Description("PasswordAuthenticationMethod: Pass \"valid\" as username, \"valid\" as password.")]
- public void Password_Test_Pass_Valid_Username_And_Password()
- {
- new PasswordAuthenticationMethod("valid", "valid");
- }
-
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [Owner("Kenneth_aa")]
- [Description("PasswordAuthenticationMethod: Pass String.Empty as username, \"valid\" as password.")]
- [ExpectedException(typeof(ArgumentException))]
- public void Password_Test_Pass_Whitespace()
- {
- new PasswordAuthenticationMethod(string.Empty, "valid");
- }
-
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [Owner("Kenneth_aa")]
- [Description("PasswordAuthenticationMethod: Pass \"valid\" as username, String.Empty as password.")]
- public void Password_Test_Pass_Valid()
- {
- new PasswordAuthenticationMethod("valid", string.Empty);
- }
-
- [TestMethod]
- [WorkItem(1140)]
- [TestCategory("BaseClient")]
- [TestCategory("integration")]
- [Description("Test whether IsConnected is false after disconnect.")]
- [Owner("Kenneth_aa")]
- public void Test_BaseClient_IsConnected_True_After_Disconnect()
- {
- // 2012-04-29 - Kenneth_aa
- // The problem with this test, is that after SSH Net calls .Disconnect(), the library doesn't wait
- // for the server to confirm disconnect before IsConnected is checked. And now I'm not mentioning
- // anything about Socket's either.
-
- var connectionInfo = new PasswordAuthenticationMethod(Resources.USERNAME, Resources.PASSWORD);
-
- using (SftpClient client = new SftpClient(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD))
- {
- client.Connect();
- Assert.AreEqual(true, client.IsConnected, "IsConnected is not true after Connect() was called.");
-
- client.Disconnect();
-
- Assert.AreEqual(false, client.IsConnected, "IsConnected is true after Disconnect() was called.");
- }
- }
-
- ///
- ///A test for Name
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void NameTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- PasswordAuthenticationMethod target = new PasswordAuthenticationMethod(username, password); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.Name;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DisposeTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- PasswordAuthenticationMethod target = new PasswordAuthenticationMethod(username, password); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Authenticate
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AuthenticateTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- PasswordAuthenticationMethod target = new PasswordAuthenticationMethod(username, password); // TODO: Initialize to an appropriate value
- Session session = null; // TODO: Initialize to an appropriate value
- AuthenticationResult expected = new AuthenticationResult(); // TODO: Initialize to an appropriate value
- AuthenticationResult actual;
- actual = target.Authenticate(session);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for PasswordAuthenticationMethod Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordAuthenticationMethodConstructorTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- PasswordAuthenticationMethod target = new PasswordAuthenticationMethod(username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordAuthenticationMethod Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordAuthenticationMethodConstructorTest1()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- PasswordAuthenticationMethod target = new PasswordAuthenticationMethod(username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/PasswordConnectionInfoTest.cs b/src/Renci.SshNet.Tests/Classes/PasswordConnectionInfoTest.cs
deleted file mode 100644
index 52088160c..000000000
--- a/src/Renci.SshNet.Tests/Classes/PasswordConnectionInfoTest.cs
+++ /dev/null
@@ -1,481 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.Net;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides connection information when password authentication method is used
- ///
- [TestClass]
- public class PasswordConnectionInfoTest : TestBase
- {
- [TestMethod]
- [TestCategory("PasswordConnectionInfo")]
- [TestCategory("integration")]
- public void Test_PasswordConnectionInfo()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
-
- #region Example PasswordConnectionInfo
- var connectionInfo = new PasswordConnectionInfo(host, username, password);
- using (var client = new SftpClient(connectionInfo))
- {
- client.Connect();
- // Do something here
- client.Disconnect();
- }
- #endregion
-
- Assert.AreEqual(connectionInfo.Host, Resources.HOST);
- Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
- }
-
- [TestMethod]
- [TestCategory("PasswordConnectionInfo")]
- [TestCategory("integration")]
- public void Test_PasswordConnectionInfo_PasswordExpired()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
-
- #region Example PasswordConnectionInfo PasswordExpired
- var connectionInfo = new PasswordConnectionInfo("host", "username", "password");
- var encoding = SshData.Ascii;
- connectionInfo.PasswordExpired += delegate(object sender, AuthenticationPasswordChangeEventArgs e)
- {
- e.NewPassword = encoding.GetBytes("123456");
- };
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
-
- client.Disconnect();
- }
- #endregion
-
- Assert.Inconclusive();
- }
- [TestMethod]
- [TestCategory("PasswordConnectionInfo")]
- [TestCategory("integration")]
- public void Test_PasswordConnectionInfo_AuthenticationBanner()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
-
- #region Example PasswordConnectionInfo AuthenticationBanner
- var connectionInfo = new PasswordConnectionInfo(host, username, password);
- connectionInfo.AuthenticationBanner += delegate(object sender, AuthenticationBannerEventArgs e)
- {
- Console.WriteLine(e.BannerMessage);
- };
- using (var client = new SftpClient(connectionInfo))
- {
- client.Connect();
- // Do something here
- client.Disconnect();
- }
- #endregion
-
- Assert.AreEqual(connectionInfo.Host, Resources.HOST);
- Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
- }
-
-
- [WorkItem(703), TestMethod]
- [TestCategory("PasswordConnectionInfo")]
- public void Test_ConnectionInfo_Host_Is_Null()
- {
- try
- {
- new PasswordConnectionInfo(null, Resources.USERNAME, Resources.PASSWORD);
- Assert.Fail();
- }
- catch (ArgumentNullException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("host", ex.ParamName);
- }
-
- }
-
- [WorkItem(703), TestMethod]
- [TestCategory("PasswordConnectionInfo")]
- [ExpectedException(typeof(ArgumentException))]
- public void Test_ConnectionInfo_Username_Is_Null()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, null, Resources.PASSWORD);
- }
-
- [WorkItem(703), TestMethod]
- [TestCategory("PasswordConnectionInfo")]
- [ExpectedException(typeof(ArgumentNullException))]
- public void Test_ConnectionInfo_Password_Is_Null()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, Resources.USERNAME, (string)null);
- }
-
- [TestMethod]
- [TestCategory("PasswordConnectionInfo")]
- [Description("Test passing whitespace to username parameter.")]
- [ExpectedException(typeof(ArgumentException))]
- public void Test_ConnectionInfo_Username_Is_Whitespace()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, " ", Resources.PASSWORD);
- }
-
- [WorkItem(703), TestMethod]
- [TestCategory("PasswordConnectionInfo")]
- [ExpectedException(typeof(ArgumentOutOfRangeException))]
- public void Test_ConnectionInfo_SmallPortNumber()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, IPEndPoint.MinPort - 1, Resources.USERNAME, Resources.PASSWORD);
- }
-
- [WorkItem(703), TestMethod]
- [TestCategory("PasswordConnectionInfo")]
- [ExpectedException(typeof(ArgumentOutOfRangeException))]
- public void Test_ConnectionInfo_BigPortNumber()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, IPEndPoint.MaxPort + 1, Resources.USERNAME, Resources.PASSWORD);
- }
-
- [TestMethod]
- [Owner("Kenneth_aa")]
- [Description("Test connect to remote server via a SOCKS4 proxy server.")]
- [TestCategory("Proxy")]
- [TestCategory("integration")]
- public void Test_Ssh_Connect_Via_Socks4()
- {
- var connInfo = new PasswordConnectionInfo(Resources.HOST, Resources.USERNAME, Resources.PASSWORD, ProxyTypes.Socks4, Resources.PROXY_HOST, int.Parse(Resources.PROXY_PORT));
- using (var client = new SshClient(connInfo))
- {
- client.Connect();
-
- var ret = client.RunCommand("ls -la");
-
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [Owner("Kenneth_aa")]
- [Description("Test connect to remote server via a TCP SOCKS5 proxy server.")]
- [TestCategory("Proxy")]
- [TestCategory("integration")]
- public void Test_Ssh_Connect_Via_TcpSocks5()
- {
- var connInfo = new PasswordConnectionInfo(Resources.HOST, Resources.USERNAME, Resources.PASSWORD, ProxyTypes.Socks5, Resources.PROXY_HOST, int.Parse(Resources.PROXY_PORT));
- using (var client = new SshClient(connInfo))
- {
- client.Connect();
-
- var ret = client.RunCommand("ls -la");
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [Owner("Kenneth_aa")]
- [Description("Test connect to remote server via a HTTP proxy server.")]
- [TestCategory("Proxy")]
- [TestCategory("integration")]
- public void Test_Ssh_Connect_Via_HttpProxy()
- {
- var connInfo = new PasswordConnectionInfo(Resources.HOST, Resources.USERNAME, Resources.PASSWORD, ProxyTypes.Http, Resources.PROXY_HOST, int.Parse(Resources.PROXY_PORT));
- using (var client = new SshClient(connInfo))
- {
- client.Connect();
-
- var ret = client.RunCommand("ls -la");
-
- client.Disconnect();
- }
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DisposeTest()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- string proxyPassword = string.Empty; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, port, username, password, proxyType, proxyHost, proxyPort, proxyUsername, proxyPassword);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest1()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- string proxyPassword = string.Empty; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password, proxyType, proxyHost, proxyPort, proxyUsername, proxyPassword);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest2()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password, proxyType, proxyHost, proxyPort, proxyUsername);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest3()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password, proxyType, proxyHost, proxyPort);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest4()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, port, username, password, proxyType, proxyHost, proxyPort, proxyUsername);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest5()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, port, username, password, proxyType, proxyHost, proxyPort);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest6()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, port, username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest7()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- byte[] password = null; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest8()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- string proxyPassword = string.Empty; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password, proxyType, proxyHost, proxyPort, proxyUsername, proxyPassword);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest9()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password, proxyType, proxyHost, proxyPort, proxyUsername);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest10()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password, proxyType, proxyHost, proxyPort);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest11()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, port, username, password, proxyType, proxyHost, proxyPort, proxyUsername);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest12()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, port, username, password, proxyType, proxyHost, proxyPort);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest13()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, port, username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PasswordConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PasswordConnectionInfoConstructorTest14()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/PrivateKeyAuthenticationMethodTest.cs b/src/Renci.SshNet.Tests/Classes/PrivateKeyAuthenticationMethodTest.cs
deleted file mode 100644
index 6ea7a33ff..000000000
--- a/src/Renci.SshNet.Tests/Classes/PrivateKeyAuthenticationMethodTest.cs
+++ /dev/null
@@ -1,106 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-using System;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides functionality to perform private key authentication.
- ///
- [TestClass]
- public class PrivateKeyAuthenticationMethodTest : TestBase
- {
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [TestCategory("PrivateKeyAuthenticationMethod")]
- [Owner("Kenneth_aa")]
- [Description("PrivateKeyAuthenticationMethod: Pass null as username, null as password.")]
- [ExpectedException(typeof(ArgumentException))]
- public void PrivateKey_Test_Pass_Null()
- {
- new PrivateKeyAuthenticationMethod(null, null);
- }
-
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [TestCategory("PrivateKeyAuthenticationMethod")]
- [Owner("olegkap")]
- [Description("PrivateKeyAuthenticationMethod: Pass valid username, null as password.")]
- [ExpectedException(typeof(ArgumentNullException))]
- public void PrivateKey_Test_Pass_PrivateKey_Null()
- {
- new PrivateKeyAuthenticationMethod("username", null);
- }
-
- [TestMethod]
- [TestCategory("AuthenticationMethod")]
- [TestCategory("PrivateKeyAuthenticationMethod")]
- [Owner("Kenneth_aa")]
- [Description("PrivateKeyAuthenticationMethod: Pass String.Empty as username, null as password.")]
- [ExpectedException(typeof(ArgumentException))]
- public void PrivateKey_Test_Pass_Whitespace()
- {
- new PrivateKeyAuthenticationMethod(string.Empty, null);
- }
-
- ///
- ///A test for Name
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void NameTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.Name;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DisposeTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Authenticate
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AuthenticateTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles); // TODO: Initialize to an appropriate value
- Session session = null; // TODO: Initialize to an appropriate value
- AuthenticationResult expected = new AuthenticationResult(); // TODO: Initialize to an appropriate value
- AuthenticationResult actual;
- actual = target.Authenticate(session);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for PrivateKeyAuthenticationMethod Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PrivateKeyAuthenticationMethodConstructorTest()
- {
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/PrivateKeyConnectionInfoTest.cs b/src/Renci.SshNet.Tests/Classes/PrivateKeyConnectionInfoTest.cs
deleted file mode 100644
index f8c863ba0..000000000
--- a/src/Renci.SshNet.Tests/Classes/PrivateKeyConnectionInfoTest.cs
+++ /dev/null
@@ -1,217 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System.IO;
-using System.Text;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides connection information when private key authentication method is used
- ///
- [TestClass]
- public class PrivateKeyConnectionInfoTest : TestBase
- {
- [TestMethod]
- [TestCategory("PrivateKeyConnectionInfo")]
- [TestCategory("integration")]
- public void Test_PrivateKeyConnectionInfo()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- MemoryStream keyFileStream = new MemoryStream(Encoding.ASCII.GetBytes(Resources.RSA_KEY_WITHOUT_PASS));
-
- #region Example PrivateKeyConnectionInfo PrivateKeyFile
- var connectionInfo = new PrivateKeyConnectionInfo(host, username, new PrivateKeyFile(keyFileStream));
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- #endregion
-
- Assert.AreEqual(connectionInfo.Host, Resources.HOST);
- Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
- }
-
- [TestMethod]
- [TestCategory("PrivateKeyConnectionInfo")]
- [TestCategory("integration")]
- public void Test_PrivateKeyConnectionInfo_MultiplePrivateKey()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- MemoryStream keyFileStream1 = new MemoryStream(Encoding.ASCII.GetBytes(Resources.RSA_KEY_WITHOUT_PASS));
- MemoryStream keyFileStream2 = new MemoryStream(Encoding.ASCII.GetBytes(Resources.RSA_KEY_WITHOUT_PASS));
-
- #region Example PrivateKeyConnectionInfo PrivateKeyFile Multiple
- var connectionInfo = new PrivateKeyConnectionInfo(host, username,
- new PrivateKeyFile(keyFileStream1),
- new PrivateKeyFile(keyFileStream2));
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- #endregion
-
- Assert.AreEqual(connectionInfo.Host, Resources.HOST);
- Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DisposeTest()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, username, keyFiles); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for PrivateKeyConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PrivateKeyConnectionInfoConstructorTest()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- string proxyPassword = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, port, username, proxyType, proxyHost, proxyPort, proxyUsername, proxyPassword, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PrivateKeyConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PrivateKeyConnectionInfoConstructorTest1()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- string proxyPassword = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, username, proxyType, proxyHost, proxyPort, proxyUsername, proxyPassword, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PrivateKeyConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PrivateKeyConnectionInfoConstructorTest2()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, username, proxyType, proxyHost, proxyPort, proxyUsername, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PrivateKeyConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PrivateKeyConnectionInfoConstructorTest3()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, username, proxyType, proxyHost, proxyPort, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PrivateKeyConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PrivateKeyConnectionInfoConstructorTest4()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, port, username, proxyType, proxyHost, proxyPort, proxyUsername, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PrivateKeyConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PrivateKeyConnectionInfoConstructorTest5()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
- string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
- int proxyPort = 0; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, port, username, proxyType, proxyHost, proxyPort, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PrivateKeyConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PrivateKeyConnectionInfoConstructorTest6()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, port, username, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for PrivateKeyConnectionInfo Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PrivateKeyConnectionInfoConstructorTest7()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- PrivateKeyConnectionInfo target = new PrivateKeyConnectionInfo(host, username, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/ScpClientTest.cs b/src/Renci.SshNet.Tests/Classes/ScpClientTest.cs
deleted file mode 100644
index 038d952e0..000000000
--- a/src/Renci.SshNet.Tests/Classes/ScpClientTest.cs
+++ /dev/null
@@ -1,681 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.IO;
-using System.Linq;
-using System.Security.Cryptography;
-using System.Text;
-#if FEATURE_TPL
-using System.Threading.Tasks;
-#endif // FEATURE_TPL
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides SCP client functionality.
- ///
- [TestClass]
- public partial class ScpClientTest : TestBase
- {
- private Random _random;
-
- [TestInitialize]
- public void SetUp()
- {
- _random = new Random();
- }
-
- [TestMethod]
- public void Ctor_ConnectionInfo_Null()
- {
- const ConnectionInfo connectionInfo = null;
-
- try
- {
- new ScpClient(connectionInfo);
- Assert.Fail();
- }
- catch (ArgumentNullException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("connectionInfo", ex.ParamName);
- }
- }
-
- [TestMethod]
- public void Ctor_ConnectionInfo_NotNull()
- {
- var connectionInfo = new ConnectionInfo("HOST", "USER", new PasswordAuthenticationMethod("USER", "PWD"));
-
- var client = new ScpClient(connectionInfo);
- Assert.AreEqual(16 * 1024U, client.BufferSize);
- Assert.AreSame(connectionInfo, client.ConnectionInfo);
- Assert.IsFalse(client.IsConnected);
- Assert.AreEqual(new TimeSpan(0, 0, 0, 0, -1), client.KeepAliveInterval);
- Assert.AreEqual(new TimeSpan(0, 0, 0, 0, -1), client.OperationTimeout);
- Assert.AreSame(RemotePathTransformation.DoubleQuote, client.RemotePathTransformation);
- Assert.IsNull(client.Session);
- }
-
- [TestMethod]
- public void Ctor_HostAndPortAndUsernameAndPassword()
- {
- var host = _random.Next().ToString();
- var port = _random.Next(1, 100);
- var userName = _random.Next().ToString();
- var password = _random.Next().ToString();
-
- var client = new ScpClient(host, port, userName, password);
- Assert.AreEqual(16 * 1024U, client.BufferSize);
- Assert.IsNotNull(client.ConnectionInfo);
- Assert.IsFalse(client.IsConnected);
- Assert.AreEqual(new TimeSpan(0, 0, 0, 0, -1), client.KeepAliveInterval);
- Assert.AreEqual(new TimeSpan(0, 0, 0, 0, -1), client.OperationTimeout);
- Assert.AreSame(RemotePathTransformation.DoubleQuote, client.RemotePathTransformation);
- Assert.IsNull(client.Session);
-
- var passwordConnectionInfo = client.ConnectionInfo as PasswordConnectionInfo;
- Assert.IsNotNull(passwordConnectionInfo);
- Assert.AreEqual(host, passwordConnectionInfo.Host);
- Assert.AreEqual(port, passwordConnectionInfo.Port);
- Assert.AreSame(userName, passwordConnectionInfo.Username);
- Assert.IsNotNull(passwordConnectionInfo.AuthenticationMethods);
- Assert.AreEqual(1, passwordConnectionInfo.AuthenticationMethods.Count);
-
- var passwordAuthentication = passwordConnectionInfo.AuthenticationMethods[0] as PasswordAuthenticationMethod;
- Assert.IsNotNull(passwordAuthentication);
- Assert.AreEqual(userName, passwordAuthentication.Username);
- Assert.IsTrue(Encoding.UTF8.GetBytes(password).IsEqualTo(passwordAuthentication.Password));
- }
-
- [TestMethod]
- public void Ctor_HostAndUsernameAndPassword()
- {
- var host = _random.Next().ToString();
- var userName = _random.Next().ToString();
- var password = _random.Next().ToString();
-
- var client = new ScpClient(host, userName, password);
- Assert.AreEqual(16 * 1024U, client.BufferSize);
- Assert.IsNotNull(client.ConnectionInfo);
- Assert.IsFalse(client.IsConnected);
- Assert.AreEqual(new TimeSpan(0, 0, 0, 0, -1), client.KeepAliveInterval);
- Assert.AreEqual(new TimeSpan(0, 0, 0, 0, -1), client.OperationTimeout);
- Assert.AreSame(RemotePathTransformation.DoubleQuote, client.RemotePathTransformation);
- Assert.IsNull(client.Session);
-
- var passwordConnectionInfo = client.ConnectionInfo as PasswordConnectionInfo;
- Assert.IsNotNull(passwordConnectionInfo);
- Assert.AreEqual(host, passwordConnectionInfo.Host);
- Assert.AreEqual(22, passwordConnectionInfo.Port);
- Assert.AreSame(userName, passwordConnectionInfo.Username);
- Assert.IsNotNull(passwordConnectionInfo.AuthenticationMethods);
- Assert.AreEqual(1, passwordConnectionInfo.AuthenticationMethods.Count);
-
- var passwordAuthentication = passwordConnectionInfo.AuthenticationMethods[0] as PasswordAuthenticationMethod;
- Assert.IsNotNull(passwordAuthentication);
- Assert.AreEqual(userName, passwordAuthentication.Username);
- Assert.IsTrue(Encoding.UTF8.GetBytes(password).IsEqualTo(passwordAuthentication.Password));
- }
-
- [TestMethod]
- public void Ctor_HostAndPortAndUsernameAndPrivateKeys()
- {
- var host = _random.Next().ToString();
- var port = _random.Next(1, 100);
- var userName = _random.Next().ToString();
- var privateKeys = new[] {GetRsaKey(), GetDsaKey()};
-
- var client = new ScpClient(host, port, userName, privateKeys);
- Assert.AreEqual(16 * 1024U, client.BufferSize);
- Assert.IsNotNull(client.ConnectionInfo);
- Assert.IsFalse(client.IsConnected);
- Assert.AreEqual(new TimeSpan(0, 0, 0, 0, -1), client.KeepAliveInterval);
- Assert.AreEqual(new TimeSpan(0, 0, 0, 0, -1), client.OperationTimeout);
- Assert.AreSame(RemotePathTransformation.DoubleQuote, client.RemotePathTransformation);
- Assert.IsNull(client.Session);
-
- var privateKeyConnectionInfo = client.ConnectionInfo as PrivateKeyConnectionInfo;
- Assert.IsNotNull(privateKeyConnectionInfo);
- Assert.AreEqual(host, privateKeyConnectionInfo.Host);
- Assert.AreEqual(port, privateKeyConnectionInfo.Port);
- Assert.AreSame(userName, privateKeyConnectionInfo.Username);
- Assert.IsNotNull(privateKeyConnectionInfo.AuthenticationMethods);
- Assert.AreEqual(1, privateKeyConnectionInfo.AuthenticationMethods.Count);
-
- var privateKeyAuthentication = privateKeyConnectionInfo.AuthenticationMethods[0] as PrivateKeyAuthenticationMethod;
- Assert.IsNotNull(privateKeyAuthentication);
- Assert.AreEqual(userName, privateKeyAuthentication.Username);
- Assert.IsNotNull(privateKeyAuthentication.KeyFiles);
- Assert.AreEqual(privateKeys.Length, privateKeyAuthentication.KeyFiles.Count);
- Assert.IsTrue(privateKeyAuthentication.KeyFiles.Contains(privateKeys[0]));
- Assert.IsTrue(privateKeyAuthentication.KeyFiles.Contains(privateKeys[1]));
- }
-
- [TestMethod]
- public void Ctor_HostAndUsernameAndPrivateKeys()
- {
- var host = _random.Next().ToString();
- var userName = _random.Next().ToString();
- var privateKeys = new[] { GetRsaKey(), GetDsaKey() };
-
- var client = new ScpClient(host, userName, privateKeys);
- Assert.AreEqual(16 * 1024U, client.BufferSize);
- Assert.IsNotNull(client.ConnectionInfo);
- Assert.IsFalse(client.IsConnected);
- Assert.AreEqual(new TimeSpan(0, 0, 0, 0, -1), client.KeepAliveInterval);
- Assert.AreEqual(new TimeSpan(0, 0, 0, 0, -1), client.OperationTimeout);
- Assert.AreSame(RemotePathTransformation.DoubleQuote, client.RemotePathTransformation);
- Assert.IsNull(client.Session);
-
- var privateKeyConnectionInfo = client.ConnectionInfo as PrivateKeyConnectionInfo;
- Assert.IsNotNull(privateKeyConnectionInfo);
- Assert.AreEqual(host, privateKeyConnectionInfo.Host);
- Assert.AreEqual(22, privateKeyConnectionInfo.Port);
- Assert.AreSame(userName, privateKeyConnectionInfo.Username);
- Assert.IsNotNull(privateKeyConnectionInfo.AuthenticationMethods);
- Assert.AreEqual(1, privateKeyConnectionInfo.AuthenticationMethods.Count);
-
- var privateKeyAuthentication = privateKeyConnectionInfo.AuthenticationMethods[0] as PrivateKeyAuthenticationMethod;
- Assert.IsNotNull(privateKeyAuthentication);
- Assert.AreEqual(userName, privateKeyAuthentication.Username);
- Assert.IsNotNull(privateKeyAuthentication.KeyFiles);
- Assert.AreEqual(privateKeys.Length, privateKeyAuthentication.KeyFiles.Count);
- Assert.IsTrue(privateKeyAuthentication.KeyFiles.Contains(privateKeys[0]));
- Assert.IsTrue(privateKeyAuthentication.KeyFiles.Contains(privateKeys[1]));
- }
-
- [TestMethod]
- public void RemotePathTransformation_Value_NotNull()
- {
- var client = new ScpClient("HOST", 22, "USER", "PWD");
-
- Assert.AreSame(RemotePathTransformation.DoubleQuote, client.RemotePathTransformation);
- client.RemotePathTransformation = RemotePathTransformation.ShellQuote;
- Assert.AreSame(RemotePathTransformation.ShellQuote, client.RemotePathTransformation);
- }
-
- [TestMethod]
- public void RemotePathTransformation_Value_Null()
- {
- var client = new ScpClient("HOST", 22, "USER", "PWD")
- {
- RemotePathTransformation = RemotePathTransformation.ShellQuote
- };
-
- try
- {
- client.RemotePathTransformation = null;
- Assert.Fail();
- }
- catch (ArgumentNullException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("value", ex.ParamName);
- }
-
- Assert.AreSame(RemotePathTransformation.ShellQuote, client.RemotePathTransformation);
- }
-
- [TestMethod]
- [TestCategory("Scp")]
- [TestCategory("integration")]
- public void Test_Scp_File_Upload_Download()
- {
- RemoveAllFiles();
-
- using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- scp.Connect();
-
- string uploadedFileName = Path.GetTempFileName();
- string downloadedFileName = Path.GetTempFileName();
-
- this.CreateTestFile(uploadedFileName, 1);
-
- scp.Upload(new FileInfo(uploadedFileName), Path.GetFileName(uploadedFileName));
-
- scp.Download(Path.GetFileName(uploadedFileName), new FileInfo(downloadedFileName));
-
- // Calculate MD5 value
- var uploadedHash = CalculateMD5(uploadedFileName);
- var downloadedHash = CalculateMD5(downloadedFileName);
-
- File.Delete(uploadedFileName);
- File.Delete(downloadedFileName);
-
- scp.Disconnect();
-
- Assert.AreEqual(uploadedHash, downloadedHash);
- }
- }
-
- [TestMethod]
- [TestCategory("Scp")]
- [TestCategory("integration")]
- public void Test_Scp_Stream_Upload_Download()
- {
- RemoveAllFiles();
-
- using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- scp.Connect();
-
- string uploadedFileName = Path.GetTempFileName();
- string downloadedFileName = Path.GetTempFileName();
-
- this.CreateTestFile(uploadedFileName, 1);
-
- // Calculate has value
- using (var stream = File.OpenRead(uploadedFileName))
- {
- scp.Upload(stream, Path.GetFileName(uploadedFileName));
- }
-
- using (var stream = File.OpenWrite(downloadedFileName))
- {
- scp.Download(Path.GetFileName(uploadedFileName), stream);
- }
-
- // Calculate MD5 value
- var uploadedHash = CalculateMD5(uploadedFileName);
- var downloadedHash = CalculateMD5(downloadedFileName);
-
- File.Delete(uploadedFileName);
- File.Delete(downloadedFileName);
-
- scp.Disconnect();
-
- Assert.AreEqual(uploadedHash, downloadedHash);
- }
- }
-
- [TestMethod]
- [TestCategory("Scp")]
- [TestCategory("integration")]
- public void Test_Scp_10MB_File_Upload_Download()
- {
- RemoveAllFiles();
-
- using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- scp.Connect();
-
- string uploadedFileName = Path.GetTempFileName();
- string downloadedFileName = Path.GetTempFileName();
-
- this.CreateTestFile(uploadedFileName, 10);
-
- scp.Upload(new FileInfo(uploadedFileName), Path.GetFileName(uploadedFileName));
-
- scp.Download(Path.GetFileName(uploadedFileName), new FileInfo(downloadedFileName));
-
- // Calculate MD5 value
- var uploadedHash = CalculateMD5(uploadedFileName);
- var downloadedHash = CalculateMD5(downloadedFileName);
-
- File.Delete(uploadedFileName);
- File.Delete(downloadedFileName);
-
- scp.Disconnect();
-
- Assert.AreEqual(uploadedHash, downloadedHash);
- }
- }
-
- [TestMethod]
- [TestCategory("Scp")]
- [TestCategory("integration")]
- public void Test_Scp_10MB_Stream_Upload_Download()
- {
- RemoveAllFiles();
-
- using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- scp.Connect();
-
- string uploadedFileName = Path.GetTempFileName();
- string downloadedFileName = Path.GetTempFileName();
-
- this.CreateTestFile(uploadedFileName, 10);
-
- // Calculate has value
- using (var stream = File.OpenRead(uploadedFileName))
- {
- scp.Upload(stream, Path.GetFileName(uploadedFileName));
- }
-
- using (var stream = File.OpenWrite(downloadedFileName))
- {
- scp.Download(Path.GetFileName(uploadedFileName), stream);
- }
-
- // Calculate MD5 value
- var uploadedHash = CalculateMD5(uploadedFileName);
- var downloadedHash = CalculateMD5(downloadedFileName);
-
- File.Delete(uploadedFileName);
- File.Delete(downloadedFileName);
-
- scp.Disconnect();
-
- Assert.AreEqual(uploadedHash, downloadedHash);
- }
- }
-
- [TestMethod]
- [TestCategory("Scp")]
- [TestCategory("integration")]
- public void Test_Scp_Directory_Upload_Download()
- {
- RemoveAllFiles();
-
- using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- scp.Connect();
-
- var uploadDirectory =
- Directory.CreateDirectory(string.Format("{0}\\{1}", Path.GetTempPath(), Path.GetRandomFileName()));
- for (int i = 0; i < 3; i++)
- {
- var subfolder =
- Directory.CreateDirectory(string.Format(@"{0}\folder_{1}", uploadDirectory.FullName, i));
- for (int j = 0; j < 5; j++)
- {
- this.CreateTestFile(string.Format(@"{0}\file_{1}", subfolder.FullName, j), 1);
- }
- this.CreateTestFile(string.Format(@"{0}\file_{1}", uploadDirectory.FullName, i), 1);
- }
-
- scp.Upload(uploadDirectory, "uploaded_dir");
-
- var downloadDirectory =
- Directory.CreateDirectory(string.Format("{0}\\{1}", Path.GetTempPath(), Path.GetRandomFileName()));
-
- scp.Download("uploaded_dir", downloadDirectory);
-
- var uploadedFiles = uploadDirectory.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
- var downloadFiles = downloadDirectory.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
-
- var result = from f1 in uploadedFiles
- from f2 in downloadFiles
- where
- f1.FullName.Substring(uploadDirectory.FullName.Length) ==
- f2.FullName.Substring(downloadDirectory.FullName.Length)
- && CalculateMD5(f1.FullName) == CalculateMD5(f2.FullName)
- select f1;
-
- var counter = result.Count();
-
- scp.Disconnect();
-
- Assert.IsTrue(counter == uploadedFiles.Length && uploadedFiles.Length == downloadFiles.Length);
- }
- }
-
- ///
- ///A test for OperationTimeout
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OperationTimeoutTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value
- TimeSpan expected = new TimeSpan(); // TODO: Initialize to an appropriate value
- TimeSpan actual;
- target.OperationTimeout = expected;
- actual = target.OperationTimeout;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for BufferSize
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void BufferSizeTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value
- uint expected = 0; // TODO: Initialize to an appropriate value
- uint actual;
- target.BufferSize = expected;
- actual = target.BufferSize;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Upload
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void UploadTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value
- DirectoryInfo directoryInfo = null; // TODO: Initialize to an appropriate value
- string filename = string.Empty; // TODO: Initialize to an appropriate value
- target.Upload(directoryInfo, filename);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Upload
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void UploadTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value
- FileInfo fileInfo = null; // TODO: Initialize to an appropriate value
- string filename = string.Empty; // TODO: Initialize to an appropriate value
- target.Upload(fileInfo, filename);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Upload
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void UploadTest2()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value
- Stream source = null; // TODO: Initialize to an appropriate value
- string filename = string.Empty; // TODO: Initialize to an appropriate value
- target.Upload(source, filename);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Download
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DownloadTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string directoryName = string.Empty; // TODO: Initialize to an appropriate value
- DirectoryInfo directoryInfo = null; // TODO: Initialize to an appropriate value
- target.Download(directoryName, directoryInfo);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Download
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DownloadTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string filename = string.Empty; // TODO: Initialize to an appropriate value
- FileInfo fileInfo = null; // TODO: Initialize to an appropriate value
- target.Download(filename, fileInfo);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Download
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DownloadTest2()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string filename = string.Empty; // TODO: Initialize to an appropriate value
- Stream destination = null; // TODO: Initialize to an appropriate value
- target.Download(filename, destination);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
-#if FEATURE_TPL
- [TestMethod]
- [TestCategory("Scp")]
- [TestCategory("integration")]
- public void Test_Scp_File_20_Parallel_Upload_Download()
- {
- using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- scp.Connect();
-
- var uploadFilenames = new string[20];
- for (int i = 0; i < uploadFilenames.Length; i++)
- {
- uploadFilenames[i] = Path.GetTempFileName();
- this.CreateTestFile(uploadFilenames[i], 1);
- }
-
- Parallel.ForEach(uploadFilenames,
- (filename) =>
- {
- scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
- });
-
- Parallel.ForEach(uploadFilenames,
- (filename) =>
- {
- scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename)));
- });
-
- var result = from file in uploadFilenames
- where
- CalculateMD5(file) == CalculateMD5(string.Format("{0}.down", file))
- select file;
-
- scp.Disconnect();
-
- Assert.IsTrue(result.Count() == uploadFilenames.Length);
- }
- }
-
- [TestMethod]
- [TestCategory("Scp")]
- [TestCategory("integration")]
- public void Test_Scp_File_Upload_Download_Events()
- {
- using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- scp.Connect();
-
- var uploadFilenames = new string[10];
-
- for (int i = 0; i < uploadFilenames.Length; i++)
- {
- uploadFilenames[i] = Path.GetTempFileName();
- this.CreateTestFile(uploadFilenames[i], 1);
- }
-
- var uploadedFiles = uploadFilenames.ToDictionary((filename) => Path.GetFileName(filename), (filename) => 0L);
- var downloadedFiles = uploadFilenames.ToDictionary((filename) => string.Format("{0}.down", Path.GetFileName(filename)), (filename) => 0L);
-
- scp.Uploading += delegate (object sender, ScpUploadEventArgs e)
- {
- uploadedFiles[e.Filename] = e.Uploaded;
- };
-
- scp.Downloading += delegate (object sender, ScpDownloadEventArgs e)
- {
- downloadedFiles[string.Format("{0}.down", e.Filename)] = e.Downloaded;
- };
-
- Parallel.ForEach(uploadFilenames,
- (filename) =>
- {
- scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
- });
-
- Parallel.ForEach(uploadFilenames,
- (filename) =>
- {
- scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename)));
- });
-
- var result = from uf in uploadedFiles
- from df in downloadedFiles
- where
- string.Format("{0}.down", uf.Key) == df.Key
- && uf.Value == df.Value
- select uf;
-
- scp.Disconnect();
-
- Assert.IsTrue(result.Count() == uploadFilenames.Length && uploadFilenames.Length == uploadedFiles.Count && uploadedFiles.Count == downloadedFiles.Count);
- }
- }
-#endif // FEATURE_TPL
-
- protected static string CalculateMD5(string fileName)
- {
- using (var file = new FileStream(fileName, FileMode.Open))
- {
- var md5 = new MD5CryptoServiceProvider();
- byte[] retVal = md5.ComputeHash(file);
- file.Close();
-
- var sb = new StringBuilder();
- for (var i = 0; i < retVal.Length; i++)
- {
- sb.Append(i.ToString("x2"));
- }
- return sb.ToString();
- }
- }
-
- private static void RemoveAllFiles()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- client.Connect();
- client.RunCommand("rm -rf *");
- client.Disconnect();
- }
- }
-
- private PrivateKeyFile GetRsaKey()
- {
- using (var stream = GetData("Key.RSA.txt"))
- {
- return new PrivateKeyFile(stream);
- }
- }
-
- private PrivateKeyFile GetDsaKey()
- {
- using (var stream = GetData("Key.SSH2.DSA.txt"))
- {
- return new PrivateKeyFile(stream);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/AlgorithmTest.cs b/src/Renci.SshNet.Tests/Classes/Security/AlgorithmTest.cs
deleted file mode 100644
index 00c9d5d24..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/AlgorithmTest.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security
-{
- ///
- ///This is a test class for AlgorithmTest and is intended
- ///to contain all AlgorithmTest Unit Tests
- ///
- [TestClass()]
- public class AlgorithmTest : TestBase
- {
- internal virtual Algorithm CreateAlgorithm()
- {
- // TODO: Instantiate an appropriate concrete class.
- Algorithm target = null;
- return target;
- }
-
- ///
- ///A test for Name
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void NameTest()
- {
- Algorithm target = CreateAlgorithm(); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.Name;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/CertificateHostAlgorithmTest.cs b/src/Renci.SshNet.Tests/Classes/Security/CertificateHostAlgorithmTest.cs
deleted file mode 100644
index 31beb9f27..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/CertificateHostAlgorithmTest.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security
-{
- ///
- ///This is a test class for CertificateHostAlgorithmTest and is intended
- ///to contain all CertificateHostAlgorithmTest Unit Tests
- ///
- [TestClass()]
- public class CertificateHostAlgorithmTest : TestBase
- {
- ///
- ///A test for CertificateHostAlgorithm Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void CertificateHostAlgorithmConstructorTest()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- CertificateHostAlgorithm target = new CertificateHostAlgorithm(name);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Sign
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SignTest()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- CertificateHostAlgorithm target = new CertificateHostAlgorithm(name); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Sign(data);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for VerifySignature
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void VerifySignatureTest()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- CertificateHostAlgorithm target = new CertificateHostAlgorithm(name); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] signature = null; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.VerifySignature(data, signature);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Data
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DataTest()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- CertificateHostAlgorithm target = new CertificateHostAlgorithm(name); // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Data;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/CipherDigitalSignatureTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/CipherDigitalSignatureTest.cs
deleted file mode 100644
index 2bdce8e15..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/CipherDigitalSignatureTest.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography
-{
- ///
- ///This is a test class for CipherDigitalSignatureTest and is intended
- ///to contain all CipherDigitalSignatureTest Unit Tests
- ///
- [TestClass()]
- public class CipherDigitalSignatureTest : TestBase
- {
- internal virtual CipherDigitalSignature CreateCipherDigitalSignature()
- {
- // TODO: Instantiate an appropriate concrete class.
- CipherDigitalSignature target = null;
- return target;
- }
-
- ///
- ///A test for Sign
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SignTest()
- {
- CipherDigitalSignature target = CreateCipherDigitalSignature(); // TODO: Initialize to an appropriate value
- byte[] input = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Sign(input);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Verify
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void VerifyTest()
- {
- CipherDigitalSignature target = CreateCipherDigitalSignature(); // TODO: Initialize to an appropriate value
- byte[] input = null; // TODO: Initialize to an appropriate value
- byte[] signature = null; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.Verify(input, signature);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/CipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/CipherTest.cs
deleted file mode 100644
index 8af4f653c..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/CipherTest.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography
-{
- ///
- ///This is a test class for CipherTest and is intended
- ///to contain all CipherTest Unit Tests
- ///
- [TestClass()]
- public class CipherTest : TestBase
- {
- internal virtual Cipher CreateCipher()
- {
- // TODO: Instantiate an appropriate concrete class.
- Cipher target = null;
- return target;
- }
-
- ///
- ///A test for Decrypt
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptTest()
- {
- Cipher target = CreateCipher(); // TODO: Initialize to an appropriate value
- byte[] input = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Decrypt(input);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Encrypt
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptTest()
- {
- Cipher target = CreateCipher(); // TODO: Initialize to an appropriate value
- byte[] input = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Encrypt(input);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/AesCipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/AesCipherTest.cs
deleted file mode 100644
index ef6b69197..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/AesCipherTest.cs
+++ /dev/null
@@ -1,266 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Security.Cryptography.Ciphers;
-using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers
-{
- ///
- ///
- ///
- [TestClass]
- public class AesCipherTest : TestBase
- {
- [TestMethod]
- public void Encrypt_Input_128_CBC()
- {
- var input = new byte[] { 0x00, 0x00, 0x00, 0x2c, 0x1a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0x30, 0x9e, 0xe0, 0x9c, 0x12, 0xee, 0x3a, 0x30, 0x03, 0x52, 0x1c, 0x1a, 0xe7, 0x3e, 0x0b, 0x9a, 0xcf, 0x9a, 0x57, 0x42, 0x0b, 0x4f, 0x4a, 0x15, 0xa0, 0xf5 };
- var key = new byte[] { 0xe4, 0x94, 0xf9, 0xb1, 0x00, 0x4f, 0x16, 0x2a, 0x80, 0x11, 0xea, 0x73, 0x0d, 0xb9, 0xbf, 0x64 };
- var iv = new byte[] { 0x74, 0x8b, 0x4f, 0xe6, 0xc1, 0x29, 0xb3, 0x54, 0xec, 0x77, 0x92, 0xf3, 0x15, 0xa0, 0x41, 0xa8 };
- var expected = new byte[] { 0x19, 0x7f, 0x80, 0xd8, 0xc9, 0x89, 0xc4, 0xa7, 0xc6, 0xc6, 0x3f, 0x9f, 0x1e, 0x00, 0x1f, 0x72, 0xa7, 0x5e, 0xde, 0x40, 0x88, 0xa2, 0x72, 0xf2, 0xed, 0x3f, 0x81, 0x45, 0xb6, 0xbd, 0x45, 0x87, 0x15, 0xa5, 0x10, 0x92, 0x4a, 0x37, 0x9e, 0xa9, 0x80, 0x1c, 0x14, 0x83, 0xa3, 0x39, 0x45, 0x28 };
- var testCipher = new AesCipher(key, new CbcCipherMode(iv), null);
-
- var actual = testCipher.Encrypt(input);
-
- Assert.IsTrue(actual.IsEqualTo(expected));
- }
-
- [TestMethod]
- public void Encrypt_InputAndOffsetAndLength_128_CBC()
- {
- // 2 dummy bytes before and 3 after the input from test case above
- var input = new byte[] { 0x05, 0x07, 0x00, 0x00, 0x00, 0x2c, 0x1a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0x30, 0x9e, 0xe0, 0x9c, 0x12, 0xee, 0x3a, 0x30, 0x03, 0x52, 0x1c, 0x1a, 0xe7, 0x3e, 0x0b, 0x9a, 0xcf, 0x9a, 0x57, 0x42, 0x0b, 0x4f, 0x4a, 0x15, 0xa0, 0xf5, 0x0f, 0x0d, 0x03 };
- var key = new byte[] { 0xe4, 0x94, 0xf9, 0xb1, 0x00, 0x4f, 0x16, 0x2a, 0x80, 0x11, 0xea, 0x73, 0x0d, 0xb9, 0xbf, 0x64 };
- var iv = new byte[] { 0x74, 0x8b, 0x4f, 0xe6, 0xc1, 0x29, 0xb3, 0x54, 0xec, 0x77, 0x92, 0xf3, 0x15, 0xa0, 0x41, 0xa8 };
- var expected = new byte[] { 0x19, 0x7f, 0x80, 0xd8, 0xc9, 0x89, 0xc4, 0xa7, 0xc6, 0xc6, 0x3f, 0x9f, 0x1e, 0x00, 0x1f, 0x72, 0xa7, 0x5e, 0xde, 0x40, 0x88, 0xa2, 0x72, 0xf2, 0xed, 0x3f, 0x81, 0x45, 0xb6, 0xbd, 0x45, 0x87, 0x15, 0xa5, 0x10, 0x92, 0x4a, 0x37, 0x9e, 0xa9, 0x80, 0x1c, 0x14, 0x83, 0xa3, 0x39, 0x45, 0x28 };
- var testCipher = new AesCipher(key, new CbcCipherMode(iv), null);
-
- var actual = testCipher.Encrypt(input, 2, input.Length - 5);
-
- Assert.IsTrue(actual.IsEqualTo(expected));
- }
-
- [TestMethod]
- public void Encrypt_Input_128_CTR()
- {
- var input = new byte[] { 0x00, 0x00, 0x00, 0x2c, 0x1a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0xb0, 0x74, 0x21, 0x87, 0x16, 0xb9, 0x69, 0x48, 0x33, 0xce, 0xb3, 0xe7, 0xdc, 0x3f, 0x50, 0xdc, 0xcc, 0xd5, 0x27, 0xb7, 0xfe, 0x7a, 0x78, 0x22, 0xae, 0xc8 };
- var key = new byte[] { 0x17, 0x78, 0x56, 0xe1, 0x3e, 0xbd, 0x3e, 0x50, 0x1d, 0x79, 0x3f, 0x0f, 0x55, 0x37, 0x45, 0x54 };
- var iv = new byte[] { 0xe6, 0x65, 0x36, 0x0d, 0xdd, 0xd7, 0x50, 0xc3, 0x48, 0xdb, 0x48, 0x07, 0xa1, 0x30, 0xd2, 0x38 };
- var expected = new byte[] { 0xca, 0xfb, 0x1c, 0x49, 0xbf, 0x82, 0x2a, 0xbb, 0x1c, 0x52, 0xc7, 0x86, 0x22, 0x8a, 0xe5, 0xa4, 0xf3, 0xda, 0x4e, 0x1c, 0x3a, 0x87, 0x41, 0x1c, 0xd2, 0x6e, 0x76, 0xdc, 0xc2, 0xe9, 0xc2, 0x0e, 0xf5, 0xc7, 0xbd, 0x12, 0x85, 0xfa, 0x0e, 0xda, 0xee, 0x50, 0xd7, 0xfd, 0x81, 0x34, 0x25, 0x6d };
- var testCipher = new AesCipher(key, new CtrCipherMode(iv), null);
-
- var actual = testCipher.Encrypt(input);
-
- Assert.IsTrue(actual.IsEqualTo(expected));
- }
-
- [TestMethod]
- public void Decrypt_Input_128_CTR()
- {
- var key = new byte[] { 0x17, 0x78, 0x56, 0xe1, 0x3e, 0xbd, 0x3e, 0x50, 0x1d, 0x79, 0x3f, 0x0f, 0x55, 0x37, 0x45, 0x54 };
- var iv = new byte[] { 0xe6, 0x65, 0x36, 0x0d, 0xdd, 0xd7, 0x50, 0xc3, 0x48, 0xdb, 0x48, 0x07, 0xa1, 0x30, 0xd2, 0x38 };
- var input = new byte[] { 0xca, 0xfb, 0x1c, 0x49, 0xbf, 0x82, 0x2a, 0xbb, 0x1c, 0x52, 0xc7, 0x86, 0x22, 0x8a, 0xe5, 0xa4, 0xf3, 0xda, 0x4e, 0x1c, 0x3a, 0x87, 0x41, 0x1c, 0xd2, 0x6e, 0x76, 0xdc, 0xc2, 0xe9, 0xc2, 0x0e, 0xf5, 0xc7, 0xbd, 0x12, 0x85, 0xfa, 0x0e, 0xda, 0xee, 0x50, 0xd7, 0xfd, 0x81, 0x34, 0x25, 0x6d };
- var expected = new byte[] { 0x00, 0x00, 0x00, 0x2c, 0x1a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0xb0, 0x74, 0x21, 0x87, 0x16, 0xb9, 0x69, 0x48, 0x33, 0xce, 0xb3, 0xe7, 0xdc, 0x3f, 0x50, 0xdc, 0xcc, 0xd5, 0x27, 0xb7, 0xfe, 0x7a, 0x78, 0x22, 0xae, 0xc8 };
- var testCipher = new AesCipher(key, new CtrCipherMode(iv), null);
-
- var actual = testCipher.Decrypt(input);
-
- Assert.IsTrue(expected.IsEqualTo(actual));
- }
-
- [TestMethod]
- public void Decrypt_InputAndOffsetAndLength_128_CTR()
- {
- var key = new byte[] { 0x17, 0x78, 0x56, 0xe1, 0x3e, 0xbd, 0x3e, 0x50, 0x1d, 0x79, 0x3f, 0x0f, 0x55, 0x37, 0x45, 0x54 };
- var iv = new byte[] { 0xe6, 0x65, 0x36, 0x0d, 0xdd, 0xd7, 0x50, 0xc3, 0x48, 0xdb, 0x48, 0x07, 0xa1, 0x30, 0xd2, 0x38 };
- var input = new byte[] { 0x0a, 0xca, 0xfb, 0x1c, 0x49, 0xbf, 0x82, 0x2a, 0xbb, 0x1c, 0x52, 0xc7, 0x86, 0x22, 0x8a, 0xe5, 0xa4, 0xf3, 0xda, 0x4e, 0x1c, 0x3a, 0x87, 0x41, 0x1c, 0xd2, 0x6e, 0x76, 0xdc, 0xc2, 0xe9, 0xc2, 0x0e, 0xf5, 0xc7, 0xbd, 0x12, 0x85, 0xfa, 0x0e, 0xda, 0xee, 0x50, 0xd7, 0xfd, 0x81, 0x34, 0x25, 0x6d, 0x0a, 0x05 };
- var expected = new byte[] { 0x00, 0x00, 0x00, 0x2c, 0x1a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0xb0, 0x74, 0x21, 0x87, 0x16, 0xb9, 0x69, 0x48, 0x33, 0xce, 0xb3, 0xe7, 0xdc, 0x3f, 0x50, 0xdc, 0xcc, 0xd5, 0x27, 0xb7, 0xfe, 0x7a, 0x78, 0x22, 0xae, 0xc8 };
- var testCipher = new AesCipher(key, new CtrCipherMode(iv), null);
-
- var actual = testCipher.Decrypt(input, 1, input.Length - 3);
-
- Assert.IsTrue(expected.IsEqualTo(actual));
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_AEes128CBC_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("aes128-cbc", new CipherInfo(128, (key, iv) => { return new AesCipher(key, new CbcCipherMode(iv), null); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_Aes192CBC_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("aes192-cbc", new CipherInfo(192, (key, iv) => { return new AesCipher(key, new CbcCipherMode(iv), null); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_Aes256CBC_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("aes256-cbc", new CipherInfo(256, (key, iv) => { return new AesCipher(key, new CbcCipherMode(iv), null); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_Aes128CTR_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("aes128-ctr", new CipherInfo(128, (key, iv) => { return new AesCipher(key, new CtrCipherMode(iv), null); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_Aes192CTR_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("aes192-ctr", new CipherInfo(192, (key, iv) => { return new AesCipher(key, new CtrCipherMode(iv), null); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_Aes256CTR_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("aes256-ctr", new CipherInfo(256, (key, iv) => { return new AesCipher(key, new CtrCipherMode(iv), null); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_Arcfour_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("arcfour", new CipherInfo(128, (key, iv) => { return new Arc4Cipher(key, false); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- AesCipher target = new AesCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for AesCipher Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AesCipherConstructorTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- AesCipher target = new AesCipher(key, mode, padding);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- AesCipher target = new AesCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Arc4CipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Arc4CipherTest.cs
deleted file mode 100644
index f83aa7aa5..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Arc4CipherTest.cs
+++ /dev/null
@@ -1,195 +0,0 @@
-using System.Text;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Security.Cryptography.Ciphers;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers
-{
- ///
- /// Implements ARCH4 cipher algorithm
- ///
- [TestClass]
- public class Arc4CipherTest : TestBase
- {
- ///
- ///A test for Arc4Cipher Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void Arc4CipherConstructorTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- Arc4Cipher target = new Arc4Cipher(key, true);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- [TestMethod]
- public void Decrypt_DischargeFirstBytes_False1()
- {
- const string key = "Key";
- const string expectedPlainText = "Plaintext";
- var encoding = Encoding.ASCII;
- var cipher = new Arc4Cipher(encoding.GetBytes(key), false);
- var cipherText = new byte[] { 0xBB, 0xF3, 0x16, 0xE8, 0xD9, 0x40, 0xAF, 0x0A, 0xD3 };
-
- var actualPlainText = cipher.Decrypt(cipherText);
-
- Assert.AreEqual(expectedPlainText, encoding.GetString(actualPlainText));
- }
-
- [TestMethod]
- public void Decrypt_DischargeFirstBytes_False2()
- {
- const string key = "Wiki";
- const string expectedPlainText = "pedia";
- var encoding = Encoding.ASCII;
- var cipher = new Arc4Cipher(encoding.GetBytes(key), false);
- var cipherText = new byte[] { 0x10, 0X21, 0xBF, 0x04, 0x20 };
-
- var actualPlainText = cipher.Decrypt(cipherText);
-
- Assert.AreEqual(expectedPlainText, encoding.GetString(actualPlainText));
- }
-
- [TestMethod]
- public void Decrypt_InputAndOffsetAndLength()
- {
- const string key = "Key";
- const string expectedPlainText = "Plaintext";
- var encoding = Encoding.ASCII;
- var cipher = new Arc4Cipher(encoding.GetBytes(key), false);
- var cipherText = new byte[] { 0x0A, 0x0f, 0xBB, 0xF3, 0x16, 0xE8, 0xD9, 0x40, 0xAF, 0x0A, 0xD3, 0x0d, 0x05 };
-
- var actualPlainText = cipher.Decrypt(cipherText, 2, cipherText.Length - 4);
-
- Assert.AreEqual(expectedPlainText, encoding.GetString(actualPlainText));
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- Arc4Cipher target = new Arc4Cipher(key, true); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- [TestMethod]
- public void Encrypt_DischargeFirstBytes_False1()
- {
- const string key = "Key";
- const string plainText = "Plaintext";
- var encoding = Encoding.ASCII;
- var cipher = new Arc4Cipher(encoding.GetBytes(key), false);
- var expectedCipherText = new byte[] { 0xBB, 0xF3, 0x16, 0xE8, 0xD9, 0x40, 0xAF, 0x0A, 0xD3 };
-
- var actualCipherText = cipher.Encrypt(encoding.GetBytes(plainText));
-
- Assert.IsNotNull(actualCipherText);
- Assert.IsTrue(expectedCipherText.IsEqualTo(actualCipherText));
- }
-
- [TestMethod]
- public void Encrypt_DischargeFirstBytes_False2()
- {
- const string key = "Wiki";
- const string plainText = "pedia";
- var encoding = Encoding.ASCII;
- var cipher = new Arc4Cipher(encoding.GetBytes(key), false);
- var expectedCipherText = new byte[] { 0x10, 0X21, 0xBF, 0x04, 0x20 };
-
- var actualCipherText = cipher.Encrypt(encoding.GetBytes(plainText));
-
- Assert.IsNotNull(actualCipherText);
- Assert.IsTrue(expectedCipherText.IsEqualTo(actualCipherText));
- }
-
- [TestMethod]
- public void Encrypt_InputAndOffsetAndLength()
- {
- const string key = "Wiki";
- const string plainText = "NOpediaNO";
- var encoding = Encoding.ASCII;
- var cipher = new Arc4Cipher(encoding.GetBytes(key), false);
- var plainTextBytes = encoding.GetBytes(plainText);
- var expectedCipherText = new byte[] { 0x10, 0X21, 0xBF, 0x04, 0x20 };
-
- var actualCipherText = cipher.Encrypt(plainTextBytes, 2, plainTextBytes.Length - 4);
-
- Assert.IsNotNull(actualCipherText);
- Assert.IsTrue(expectedCipherText.IsEqualTo(actualCipherText));
-
- Assert.IsTrue(plainTextBytes.IsEqualTo(encoding.GetBytes(plainText)));
- }
-
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- Arc4Cipher target = new Arc4Cipher(key, true); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_Arcfour128_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("arcfour128", new CipherInfo(128, (key, iv) => { return new Arc4Cipher(key, true); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_Arcfour256_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("arcfour256", new CipherInfo(256, (key, iv) => { return new Arc4Cipher(key, true); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/BlowfishCipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/BlowfishCipherTest.cs
deleted file mode 100644
index 1fd7b7d11..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/BlowfishCipherTest.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography.Ciphers;
-using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System.Linq;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers
-{
- ///
- ///
- ///
- [TestClass]
- public class BlowfishCipherTest : TestBase
- {
- [TestMethod]
- public void Test_Cipher_Blowfish_128_CBC()
- {
- var input = new byte[] { 0x00, 0x00, 0x00, 0x2c, 0x1a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0x30, 0x9e, 0xe0, 0x9c, 0x12, 0xee, 0x3a, 0x30, 0x03, 0x52, 0x1c, 0x1a, 0xe7, 0x3e, 0x0b, 0x9a, 0xcf, 0x9a, 0x57, 0x42, 0x0b, 0x4f, 0x4a, 0x15, 0xa0, 0xf5 };
- var key = new byte[] { 0xe4, 0x94, 0xf9, 0xb1, 0x00, 0x4f, 0x16, 0x2a, 0x80, 0x11, 0xea, 0x73, 0x0d, 0xb9, 0xbf, 0x64 };
- var iv = new byte[] { 0x74, 0x8b, 0x4f, 0xe6, 0xc1, 0x29, 0xb3, 0x54, 0xec, 0x77, 0x92, 0xf3, 0x15, 0xa0, 0x41, 0xa8 };
- var output = new byte[] { 0x50, 0x49, 0xe0, 0xce, 0x98, 0x93, 0x8b, 0xec, 0x82, 0x7d, 0x14, 0x1b, 0x3e, 0xdc, 0xca, 0x63, 0xef, 0x36, 0x20, 0x67, 0x58, 0x63, 0x1f, 0x9c, 0xd2, 0x12, 0x6b, 0xca, 0xea, 0xd0, 0x78, 0x8b, 0x61, 0x50, 0x4f, 0xc4, 0x5b, 0x32, 0x91, 0xd6, 0x65, 0xcb, 0x74, 0xe5, 0x6e, 0xf5, 0xde, 0x14 };
- var testCipher = new Renci.SshNet.Security.Cryptography.Ciphers.BlowfishCipher(key, new Renci.SshNet.Security.Cryptography.Ciphers.Modes.CbcCipherMode(iv), null);
- var r = testCipher.Encrypt(input);
-
- if (!r.SequenceEqual(output))
- Assert.Fail("Invalid encryption");
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_BlowfishCBC_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("blowfish-cbc", new CipherInfo(128, (key, iv) => { return new BlowfishCipher(key, new CbcCipherMode(iv), null); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- ///
- ///A test for BlowfishCipher Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void BlowfishCipherConstructorTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- BlowfishCipher target = new BlowfishCipher(key, mode, padding);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- BlowfishCipher target = new BlowfishCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- BlowfishCipher target = new BlowfishCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/CastCipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/CastCipherTest.cs
deleted file mode 100644
index c077a3098..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/CastCipherTest.cs
+++ /dev/null
@@ -1,118 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography.Ciphers;
-using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System.Linq;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers
-{
- ///
- /// Implements CAST cipher algorithm
- ///
- [TestClass]
- public class CastCipherTest : TestBase
- {
- [TestMethod]
- public void Encrypt_128_CBC()
- {
- var input = new byte[] { 0x00, 0x00, 0x00, 0x2c, 0x1a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0x30, 0x9e, 0xe0, 0x9c, 0x12, 0xee, 0x3a, 0x30, 0x03, 0x52, 0x1c, 0x1a, 0xe7, 0x3e, 0x0b, 0x9a, 0xcf, 0x9a, 0x57, 0x42, 0x0b, 0x4f, 0x4a, 0x15, 0xa0, 0xf5 };
- var key = new byte[] { 0xe4, 0x94, 0xf9, 0xb1, 0x00, 0x4f, 0x16, 0x2a, 0x80, 0x11, 0xea, 0x73, 0x0d, 0xb9, 0xbf, 0x64 };
- var iv = new byte[] { 0x74, 0x8b, 0x4f, 0xe6, 0xc1, 0x29, 0xb3, 0x54, 0xec, 0x77, 0x92, 0xf3, 0x15, 0xa0, 0x41, 0xa8 };
- var output = new byte[] { 0x32, 0xef, 0xbd, 0xac, 0xb6, 0xfd, 0x1f, 0xae, 0x1b, 0x13, 0x5f, 0x31, 0x6d, 0x38, 0xcd, 0xb0, 0xe3, 0xca, 0xe1, 0xbc, 0xf8, 0xa7, 0xc2, 0x31, 0x62, 0x14, 0x3a, 0x9a, 0xda, 0xe3, 0xf8, 0xc8, 0x70, 0x87, 0x53, 0x21, 0x5d, 0xb7, 0x94, 0xb7, 0xe8, 0xc6, 0x9d, 0x46, 0x0c, 0x6d, 0x64, 0x6d };
- var testCipher = new CastCipher(key, new CbcCipherMode(iv), null);
- var r = testCipher.Encrypt(input);
-
- Assert.IsTrue(r.SequenceEqual(output));
- }
-
- [TestMethod]
- public void Decrypt_128_CBC()
- {
- var input = new byte[] { 0x00, 0x00, 0x00, 0x2c, 0x1a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0x30, 0x9e, 0xe0, 0x9c, 0x12, 0xee, 0x3a, 0x30, 0x03, 0x52, 0x1c, 0x1a, 0xe7, 0x3e, 0x0b, 0x9a, 0xcf, 0x9a, 0x57, 0x42, 0x0b, 0x4f, 0x4a, 0x15, 0xa0, 0xf5 };
- var key = new byte[] { 0xe4, 0x94, 0xf9, 0xb1, 0x00, 0x4f, 0x16, 0x2a, 0x80, 0x11, 0xea, 0x73, 0x0d, 0xb9, 0xbf, 0x64 };
- var iv = new byte[] { 0x74, 0x8b, 0x4f, 0xe6, 0xc1, 0x29, 0xb3, 0x54, 0xec, 0x77, 0x92, 0xf3, 0x15, 0xa0, 0x41, 0xa8 };
- var output = new byte[] { 0x32, 0xef, 0xbd, 0xac, 0xb6, 0xfd, 0x1f, 0xae, 0x1b, 0x13, 0x5f, 0x31, 0x6d, 0x38, 0xcd, 0xb0, 0xe3, 0xca, 0xe1, 0xbc, 0xf8, 0xa7, 0xc2, 0x31, 0x62, 0x14, 0x3a, 0x9a, 0xda, 0xe3, 0xf8, 0xc8, 0x70, 0x87, 0x53, 0x21, 0x5d, 0xb7, 0x94, 0xb7, 0xe8, 0xc6, 0x9d, 0x46, 0x0c, 0x6d, 0x64, 0x6d };
- var testCipher = new CastCipher(key, new CbcCipherMode(iv), null);
- var r = testCipher.Decrypt(output);
-
- Assert.IsTrue(r.SequenceEqual(input));
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_Cast128CBC_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("cast128-cbc", new CipherInfo(128, (key, iv) => { return new CastCipher(key, new CbcCipherMode(iv), null); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
- ///
- ///A test for CastCipher Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CastCipherConstructorTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- CastCipher target = new CastCipher(key, mode, padding);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- CastCipher target = new CastCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- CastCipher target = new CastCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/CipherModeTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/CipherModeTest.cs
deleted file mode 100644
index d3b4c0adb..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/CipherModeTest.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography.Ciphers;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers
-{
- ///
- ///This is a test class for CipherModeTest and is intended
- ///to contain all CipherModeTest Unit Tests
- ///
- [TestClass()]
- public class CipherModeTest : TestBase
- {
- internal virtual CipherMode CreateCipherMode()
- {
- // TODO: Instantiate an appropriate concrete class.
- CipherMode target = null;
- return target;
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- CipherMode target = CreateCipherMode(); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- CipherMode target = CreateCipherMode(); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/CipherPaddingTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/CipherPaddingTest.cs
deleted file mode 100644
index c923584a0..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/CipherPaddingTest.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography.Ciphers;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers
-{
- ///
- ///This is a test class for CipherPaddingTest and is intended
- ///to contain all CipherPaddingTest Unit Tests
- ///
- [TestClass()]
- public class CipherPaddingTest : TestBase
- {
- internal virtual CipherPadding CreateCipherPadding()
- {
- // TODO: Instantiate an appropriate concrete class.
- CipherPadding target = null;
- return target;
- }
-
- ///
- ///A test for Pad
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PadTest()
- {
- CipherPadding target = CreateCipherPadding(); // TODO: Initialize to an appropriate value
- int blockSize = 0; // TODO: Initialize to an appropriate value
- byte[] input = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Pad(blockSize, input);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/CbcCipherModeTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/CbcCipherModeTest.cs
deleted file mode 100644
index c43191c28..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/CbcCipherModeTest.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers.Modes
-{
- ///
- ///This is a test class for CbcCipherModeTest and is intended
- ///to contain all CbcCipherModeTest Unit Tests
- ///
- [TestClass()]
- public class CbcCipherModeTest : TestBase
- {
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- CbcCipherMode target = new CbcCipherMode(iv); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- CbcCipherMode target = new CbcCipherMode(iv); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CbcCipherMode Constructor
- ///
- [TestMethod()]
- public void CbcCipherModeConstructorTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- CbcCipherMode target = new CbcCipherMode(iv);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/CfbCipherModeTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/CfbCipherModeTest.cs
deleted file mode 100644
index f7dd046d6..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/CfbCipherModeTest.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers.Modes
-{
- ///
- ///This is a test class for CfbCipherModeTest and is intended
- ///to contain all CfbCipherModeTest Unit Tests
- ///
- [TestClass()]
- public class CfbCipherModeTest : TestBase
- {
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- CfbCipherMode target = new CfbCipherMode(iv); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- CfbCipherMode target = new CfbCipherMode(iv); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CfbCipherMode Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CfbCipherModeConstructorTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- CfbCipherMode target = new CfbCipherMode(iv);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/CtrCipherModeTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/CtrCipherModeTest.cs
deleted file mode 100644
index 23e0391e2..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/CtrCipherModeTest.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers.Modes
-{
- ///
- ///This is a test class for CtrCipherModeTest and is intended
- ///to contain all CtrCipherModeTest Unit Tests
- ///
- [TestClass()]
- public class CtrCipherModeTest : TestBase
- {
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- CtrCipherMode target = new CtrCipherMode(iv); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- CtrCipherMode target = new CtrCipherMode(iv); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CtrCipherMode Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CtrCipherModeConstructorTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- CtrCipherMode target = new CtrCipherMode(iv);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/OfbCipherModeTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/OfbCipherModeTest.cs
deleted file mode 100644
index d4719e256..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/Modes/OfbCipherModeTest.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers.Modes
-{
- ///
- ///This is a test class for OfbCipherModeTest and is intended
- ///to contain all OfbCipherModeTest Unit Tests
- ///
- [TestClass()]
- public class OfbCipherModeTest : TestBase
- {
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- OfbCipherMode target = new OfbCipherMode(iv); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- OfbCipherMode target = new OfbCipherMode(iv); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OfbCipherMode Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OfbCipherModeConstructorTest()
- {
- byte[] iv = null; // TODO: Initialize to an appropriate value
- OfbCipherMode target = new OfbCipherMode(iv);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/RsaCipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/RsaCipherTest.cs
deleted file mode 100644
index 2de87cdde..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/RsaCipherTest.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security;
-using Renci.SshNet.Security.Cryptography.Ciphers;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers
-{
- ///
- /// Implements RSA cipher algorithm.
- ///
- [TestClass]
- public class RsaCipherTest : TestBase
- {
- ///
- ///A test for RsaCipher Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void RsaCipherConstructorTest()
- {
- RsaKey key = null; // TODO: Initialize to an appropriate value
- RsaCipher target = new RsaCipher(key);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Decrypt
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptTest()
- {
- RsaKey key = null; // TODO: Initialize to an appropriate value
- RsaCipher target = new RsaCipher(key); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Decrypt(data);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Encrypt
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptTest()
- {
- RsaKey key = null; // TODO: Initialize to an appropriate value
- RsaCipher target = new RsaCipher(key); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Encrypt(data);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/SerpentCipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/SerpentCipherTest.cs
deleted file mode 100644
index f604f5dc9..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/SerpentCipherTest.cs
+++ /dev/null
@@ -1,73 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography.Ciphers;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers
-{
- ///
- /// Implements Serpent cipher algorithm.
- ///
- [TestClass]
- public class SerpentCipherTest : TestBase
- {
- ///
- ///A test for SerpentCipher Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SerpentCipherConstructorTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- SerpentCipher target = new SerpentCipher(key, mode, padding);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- SerpentCipher target = new SerpentCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- SerpentCipher target = new SerpentCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/TripleDesCipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/TripleDesCipherTest.cs
deleted file mode 100644
index f791c9df5..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/TripleDesCipherTest.cs
+++ /dev/null
@@ -1,106 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography.Ciphers;
-using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System.Linq;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers
-{
- ///
- /// Implements 3DES cipher algorithm.
- ///
- [TestClass]
- public class TripleDesCipherTest : TestBase
- {
- [TestMethod]
- public void Test_Cipher_3DES_CBC()
- {
- var input = new byte[] { 0x00, 0x00, 0x00, 0x1c, 0x0a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0x72, 0x4e, 0x06, 0x08, 0x28, 0x2d, 0xaa, 0xe2, 0xb3, 0xd9 };
- var key = new byte[] { 0x78, 0xf6, 0xc6, 0xbb, 0x57, 0x03, 0x69, 0xca, 0xba, 0x31, 0x18, 0x2f, 0x2f, 0x4c, 0x35, 0x34, 0x64, 0x06, 0x85, 0x30, 0xbe, 0x78, 0x60, 0xb3 };
- var iv = new byte[] { 0xc0, 0x75, 0xf2, 0x26, 0x0a, 0x2a, 0x42, 0x96 };
- var output = new byte[] { 0x28, 0x77, 0x2f, 0x07, 0x3e, 0xc2, 0x27, 0xa6, 0xdb, 0x36, 0x4d, 0xc6, 0x7a, 0x26, 0x7a, 0x38, 0xe6, 0x54, 0x0b, 0xab, 0x07, 0x87, 0xf0, 0xa4, 0x73, 0x1f, 0xde, 0xe6, 0x81, 0x1d, 0x4b, 0x4b };
- var testCipher = new TripleDesCipher(key, new CbcCipherMode(iv), null);
- var r = testCipher.Encrypt(input);
-
- if (!r.SequenceEqual(output))
- Assert.Fail("Invalid encryption");
- }
-
- [TestMethod]
- [Owner("olegkap")]
- [TestCategory("Cipher")]
- [TestCategory("integration")]
- public void Test_Cipher_TripleDESCBC_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.Encryptions.Clear();
- connectionInfo.Encryptions.Add("3des-cbc", new CipherInfo(192, (key, iv) => { return new TripleDesCipher(key, new CbcCipherMode(iv), null); }));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
- ///
- ///A test for TripleDesCipher Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void TripleDesCipherConstructorTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- TripleDesCipher target = new TripleDesCipher(key, mode, padding);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- TripleDesCipher target = new TripleDesCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- TripleDesCipher target = new TripleDesCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/TwofishCipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/TwofishCipherTest.cs
deleted file mode 100644
index e0693e971..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/TwofishCipherTest.cs
+++ /dev/null
@@ -1,73 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography.Ciphers;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers
-{
- ///
- /// Implements Twofish cipher algorithm
- ///
- [TestClass]
- public class TwofishCipherTest : TestBase
- {
- ///
- ///A test for TwofishCipher Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void TwofishCipherConstructorTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- TwofishCipher target = new TwofishCipher(key, mode, padding);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- TwofishCipher target = new TwofishCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- byte[] key = null; // TODO: Initialize to an appropriate value
- CipherMode mode = null; // TODO: Initialize to an appropriate value
- CipherPadding padding = null; // TODO: Initialize to an appropriate value
- TwofishCipher target = new TwofishCipher(key, mode, padding); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DigitalSignatureTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DigitalSignatureTest.cs
deleted file mode 100644
index efe45c9ca..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DigitalSignatureTest.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security.Cryptography;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography
-{
- ///
- ///This is a test class for DigitalSignatureTest and is intended
- ///to contain all DigitalSignatureTest Unit Tests
- ///
- [TestClass()]
- public class DigitalSignatureTest : TestBase
- {
- internal virtual DigitalSignature CreateDigitalSignature()
- {
- // TODO: Instantiate an appropriate concrete class.
- DigitalSignature target = null;
- return target;
- }
-
- ///
- ///A test for Sign
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SignTest()
- {
- DigitalSignature target = CreateDigitalSignature(); // TODO: Initialize to an appropriate value
- byte[] input = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Sign(input);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Verify
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void VerifyTest()
- {
- DigitalSignature target = CreateDigitalSignature(); // TODO: Initialize to an appropriate value
- byte[] input = null; // TODO: Initialize to an appropriate value
- byte[] signature = null; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.Verify(input, signature);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DsaDigitalSignatureTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DsaDigitalSignatureTest.cs
deleted file mode 100644
index 0d3423c95..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DsaDigitalSignatureTest.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security;
-using Renci.SshNet.Security.Cryptography;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography
-{
- ///
- /// Implements DSA digital signature algorithm.
- ///
- [TestClass]
- public class DsaDigitalSignatureTest : TestBase
- {
- ///
- ///A test for DsaDigitalSignature Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DsaDigitalSignatureConstructorTest()
- {
- DsaKey key = null; // TODO: Initialize to an appropriate value
- DsaDigitalSignature target = new DsaDigitalSignature(key);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DisposeTest()
- {
- DsaKey key = null; // TODO: Initialize to an appropriate value
- DsaDigitalSignature target = new DsaDigitalSignature(key); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Sign
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SignTest()
- {
- DsaKey key = null; // TODO: Initialize to an appropriate value
- DsaDigitalSignature target = new DsaDigitalSignature(key); // TODO: Initialize to an appropriate value
- byte[] input = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Sign(input);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Verify
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void VerifyTest()
- {
- DsaKey key = null; // TODO: Initialize to an appropriate value
- DsaDigitalSignature target = new DsaDigitalSignature(key); // TODO: Initialize to an appropriate value
- byte[] input = null; // TODO: Initialize to an appropriate value
- byte[] signature = null; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.Verify(input, signature);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DsaKeyTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DsaKeyTest.cs
deleted file mode 100644
index 57fe73f5d..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DsaKeyTest.cs
+++ /dev/null
@@ -1,160 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Security;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography
-{
- ///
- ///This is a test class for DsaKeyTest and is intended
- ///to contain all DsaKeyTest Unit Tests
- ///
- [TestClass]
- public class DsaKeyTest : TestBase
- {
- ///
- ///A test for DsaKey Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DsaKeyConstructorTest()
- {
- DsaKey target = new DsaKey();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for DsaKey Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DsaKeyConstructorTest1()
- {
- byte[] data = null; // TODO: Initialize to an appropriate value
- DsaKey target = new DsaKey(data);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for DsaKey Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DsaKeyConstructorTest2()
- {
- BigInteger p = new BigInteger(); // TODO: Initialize to an appropriate value
- BigInteger q = new BigInteger(); // TODO: Initialize to an appropriate value
- BigInteger g = new BigInteger(); // TODO: Initialize to an appropriate value
- BigInteger y = new BigInteger(); // TODO: Initialize to an appropriate value
- BigInteger x = new BigInteger(); // TODO: Initialize to an appropriate value
- DsaKey target = new DsaKey(p, q, g, y, x);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DisposeTest()
- {
- DsaKey target = new DsaKey(); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for G
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GTest()
- {
- DsaKey target = new DsaKey(); // TODO: Initialize to an appropriate value
- BigInteger actual;
- actual = target.G;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for KeyLength
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyLengthTest()
- {
- DsaKey target = new DsaKey(); // TODO: Initialize to an appropriate value
- int actual;
- actual = target.KeyLength;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for P
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PTest()
- {
- DsaKey target = new DsaKey(); // TODO: Initialize to an appropriate value
- BigInteger actual;
- actual = target.P;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Public
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PublicTest()
- {
- DsaKey target = new DsaKey(); // TODO: Initialize to an appropriate value
- BigInteger[] expected = null; // TODO: Initialize to an appropriate value
- BigInteger[] actual;
- target.Public = expected;
- actual = target.Public;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Q
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void QTest()
- {
- DsaKey target = new DsaKey(); // TODO: Initialize to an appropriate value
- BigInteger actual;
- actual = target.Q;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for X
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void XTest()
- {
- DsaKey target = new DsaKey(); // TODO: Initialize to an appropriate value
- BigInteger actual;
- actual = target.X;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Y
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void YTest()
- {
- DsaKey target = new DsaKey(); // TODO: Initialize to an appropriate value
- BigInteger actual;
- actual = target.Y;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/HMacTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/HMacTest.cs
deleted file mode 100644
index 13d8f1dda..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/HMacTest.cs
+++ /dev/null
@@ -1,135 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using Renci.SshNet.Abstractions;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography
-{
- ///
- /// Provides HMAC algorithm implementation.
- ///
- ///
- [TestClass]
- public class HMacTest : TestBase
- {
- [TestMethod]
- [TestCategory("integration")]
- public void Test_HMac_MD5_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.HmacAlgorithms.Clear();
- connectionInfo.HmacAlgorithms.Add("hmac-md5", new HashInfo(16 * 8, CryptoAbstraction.CreateHMACMD5));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("integration")]
- public void Test_HMac_Sha1_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.HmacAlgorithms.Clear();
- connectionInfo.HmacAlgorithms.Add("hmac-sha1", new HashInfo(20 * 8, CryptoAbstraction.CreateHMACSHA1));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("integration")]
- public void Test_HMac_MD5_96_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.HmacAlgorithms.Clear();
- connectionInfo.HmacAlgorithms.Add("hmac-md5", new HashInfo(16 * 8, key => CryptoAbstraction.CreateHMACMD5(key, 96)));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("integration")]
- public void Test_HMac_Sha1_96_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.HmacAlgorithms.Clear();
- connectionInfo.HmacAlgorithms.Add("hmac-sha1", new HashInfo(20 * 8, key => CryptoAbstraction.CreateHMACSHA1(key, 96)));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("integration")]
- public void Test_HMac_Sha256_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.HmacAlgorithms.Clear();
- connectionInfo.HmacAlgorithms.Add("hmac-sha2-256", new HashInfo(32 * 8, CryptoAbstraction.CreateHMACSHA256));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("integration")]
- public void Test_HMac_Sha256_96_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.HmacAlgorithms.Clear();
- connectionInfo.HmacAlgorithms.Add("hmac-sha2-256-96", new HashInfo(32 * 8, (key) => CryptoAbstraction.CreateHMACSHA256(key, 96)));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("integration")]
- public void Test_HMac_RIPEMD160_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.HmacAlgorithms.Clear();
- connectionInfo.HmacAlgorithms.Add("hmac-ripemd160", new HashInfo(160, CryptoAbstraction.CreateHMACRIPEMD160));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("integration")]
- public void Test_HMac_RIPEMD160_OPENSSH_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.HmacAlgorithms.Clear();
- connectionInfo.HmacAlgorithms.Add("hmac-ripemd160@openssh.com", new HashInfo(160, CryptoAbstraction.CreateHMACRIPEMD160));
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/RsaDigitalSignatureTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/RsaDigitalSignatureTest.cs
deleted file mode 100644
index 93a76bbee..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/RsaDigitalSignatureTest.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security;
-using Renci.SshNet.Security.Cryptography;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security.Cryptography
-{
- ///
- /// Implements RSA digital signature algorithm.
- ///
- [TestClass]
- public class RsaDigitalSignatureTest : TestBase
- {
-
- ///
- ///A test for RsaDigitalSignature Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void RsaDigitalSignatureConstructorTest()
- {
- RsaKey rsaKey = null; // TODO: Initialize to an appropriate value
- RsaDigitalSignature target = new RsaDigitalSignature(rsaKey);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Dispose
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DisposeTest()
- {
- RsaKey rsaKey = null; // TODO: Initialize to an appropriate value
- RsaDigitalSignature target = new RsaDigitalSignature(rsaKey); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/RsaKeyTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/RsaKeyTest.cs
deleted file mode 100644
index 89323337a..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/RsaKeyTest.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security
-{
- ///
- /// Contains RSA private and public key
- ///
- [TestClass]
- public class RsaKeyTest : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/SymmetricCipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/SymmetricCipherTest.cs
deleted file mode 100644
index 8dce88815..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/SymmetricCipherTest.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-using Renci.SshNet.Security.Cryptography;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests
-{
- ///
- ///This is a test class for SymmetricCipherTest and is intended
- ///to contain all SymmetricCipherTest Unit Tests
- ///
- [TestClass()]
- public class SymmetricCipherTest : TestBase
- {
- internal virtual SymmetricCipher CreateSymmetricCipher()
- {
- // TODO: Instantiate an appropriate concrete class.
- SymmetricCipher target = null;
- return target;
- }
-
- ///
- ///A test for DecryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DecryptBlockTest()
- {
- SymmetricCipher target = CreateSymmetricCipher(); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for EncryptBlock
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EncryptBlockTest()
- {
- SymmetricCipher target = CreateSymmetricCipher(); // TODO: Initialize to an appropriate value
- byte[] inputBuffer = null; // TODO: Initialize to an appropriate value
- int inputOffset = 0; // TODO: Initialize to an appropriate value
- int inputCount = 0; // TODO: Initialize to an appropriate value
- byte[] outputBuffer = null; // TODO: Initialize to an appropriate value
- int outputOffset = 0; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/HostAlgorithmTest.cs b/src/Renci.SshNet.Tests/Classes/Security/HostAlgorithmTest.cs
deleted file mode 100644
index a9547a54b..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/HostAlgorithmTest.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security
-{
- ///
- ///This is a test class for HostAlgorithmTest and is intended
- ///to contain all HostAlgorithmTest Unit Tests
- ///
- [TestClass()]
- public class HostAlgorithmTest : TestBase
- {
- internal virtual HostAlgorithm CreateHostAlgorithm()
- {
- // TODO: Instantiate an appropriate concrete class.
- HostAlgorithm target = null;
- return target;
- }
-
- ///
- ///A test for Sign
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SignTest()
- {
- HostAlgorithm target = CreateHostAlgorithm(); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Sign(data);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for VerifySignature
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void VerifySignatureTest()
- {
- HostAlgorithm target = CreateHostAlgorithm(); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] signature = null; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.VerifySignature(data, signature);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Data
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DataTest()
- {
- HostAlgorithm target = CreateHostAlgorithm(); // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Data;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroupExchangeSha1Test.cs b/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroupExchangeSha1Test.cs
deleted file mode 100644
index 980733e09..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroupExchangeSha1Test.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security
-{
- ///
- /// Represents "diffie-hellman-group-exchange-sha1" algorithm implementation.
- ///
- [TestClass]
- public class KeyExchangeDiffieHellmanGroupExchangeSha1Test : TestBase
- {
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroupExchangeSha256Test.cs b/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroupExchangeSha256Test.cs
deleted file mode 100644
index 5a0baf353..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroupExchangeSha256Test.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Messages.Transport;
-using Renci.SshNet.Security;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security
-{
- ///
- ///This is a test class for KeyExchangeDiffieHellmanGroupExchangeSha256Test and is intended
- ///to contain all KeyExchangeDiffieHellmanGroupExchangeSha256Test Unit Tests
- ///
- [TestClass]
- public class KeyExchangeDiffieHellmanGroupExchangeSha256Test : TestBase
- {
- ///
- ///A test for KeyExchangeDiffieHellmanGroupExchangeSha256 Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyExchangeDiffieHellmanGroupExchangeSha256ConstructorTest()
- {
- KeyExchangeDiffieHellmanGroupExchangeSha256 target = new KeyExchangeDiffieHellmanGroupExchangeSha256();
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Finish
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void FinishTest()
- {
- KeyExchangeDiffieHellmanGroupExchangeSha256 target = new KeyExchangeDiffieHellmanGroupExchangeSha256(); // TODO: Initialize to an appropriate value
- target.Finish();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Start
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void StartTest()
- {
- KeyExchangeDiffieHellmanGroupExchangeSha256 target = new KeyExchangeDiffieHellmanGroupExchangeSha256(); // TODO: Initialize to an appropriate value
- Session session = null; // TODO: Initialize to an appropriate value
- KeyExchangeInitMessage message = null; // TODO: Initialize to an appropriate value
- target.Start(session, message);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Name
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void NameTest()
- {
- KeyExchangeDiffieHellmanGroupExchangeSha256 target = new KeyExchangeDiffieHellmanGroupExchangeSha256(); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.Name;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroupSha1Test.cs b/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroupSha1Test.cs
deleted file mode 100644
index 40d6b3b80..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroupSha1Test.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Messages.Transport;
-using Renci.SshNet.Security;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security
-{
- ///
- ///This is a test class for KeyExchangeDiffieHellmanGroupSha1Test and is intended
- ///to contain all KeyExchangeDiffieHellmanGroupSha1Test Unit Tests
- ///
- [TestClass()]
- public class KeyExchangeDiffieHellmanGroupSha1Test : TestBase
- {
- internal virtual KeyExchangeDiffieHellmanGroupSha1 CreateKeyExchangeDiffieHellmanGroupSha1()
- {
- // TODO: Instantiate an appropriate concrete class.
- KeyExchangeDiffieHellmanGroupSha1 target = null;
- return target;
- }
-
- ///
- ///A test for Finish
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void FinishTest()
- {
- KeyExchangeDiffieHellmanGroupSha1 target = CreateKeyExchangeDiffieHellmanGroupSha1(); // TODO: Initialize to an appropriate value
- target.Finish();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Start
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void StartTest()
- {
- KeyExchangeDiffieHellmanGroupSha1 target = CreateKeyExchangeDiffieHellmanGroupSha1(); // TODO: Initialize to an appropriate value
- Session session = null; // TODO: Initialize to an appropriate value
- KeyExchangeInitMessage message = null; // TODO: Initialize to an appropriate value
- target.Start(session, message);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for GroupPrime
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GroupPrimeTest()
- {
- KeyExchangeDiffieHellmanGroupSha1 target = CreateKeyExchangeDiffieHellmanGroupSha1(); // TODO: Initialize to an appropriate value
- BigInteger actual;
- actual = target.GroupPrime;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanTest.cs b/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanTest.cs
deleted file mode 100644
index 98b738588..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanTest.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Messages.Transport;
-using Renci.SshNet.Security;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security
-{
- ///
- ///This is a test class for KeyExchangeDiffieHellmanTest and is intended
- ///to contain all KeyExchangeDiffieHellmanTest Unit Tests
- ///
- [TestClass()]
- public class KeyExchangeDiffieHellmanTest : TestBase
- {
- internal virtual KeyExchangeDiffieHellman CreateKeyExchangeDiffieHellman()
- {
- // TODO: Instantiate an appropriate concrete class.
- KeyExchangeDiffieHellman target = null;
- return target;
- }
-
- ///
- ///A test for Start
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void StartTest()
- {
- KeyExchangeDiffieHellman target = CreateKeyExchangeDiffieHellman(); // TODO: Initialize to an appropriate value
- Session session = null; // TODO: Initialize to an appropriate value
- KeyExchangeInitMessage message = null; // TODO: Initialize to an appropriate value
- target.Start(session, message);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeTest.cs b/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeTest.cs
deleted file mode 100644
index 839394e6e..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeTest.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-using Renci.SshNet.Security;
-using Renci.SshNet.Tests.Common;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-
-namespace Renci.SshNet.Tests
-{
- ///
- ///This is a test class for KeyExchangeTest and is intended
- ///to contain all KeyExchangeTest Unit Tests
- ///
- [TestClass()]
- public class KeyExchangeTest : TestBase
- {
-
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Security/KeyHostAlgorithmTest.cs b/src/Renci.SshNet.Tests/Classes/Security/KeyHostAlgorithmTest.cs
deleted file mode 100644
index 9bd5d10c3..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/KeyHostAlgorithmTest.cs
+++ /dev/null
@@ -1,123 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Security;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-
-namespace Renci.SshNet.Tests.Classes.Security
-{
- ///
- /// Implements key support for host algorithm.
- ///
- [TestClass]
- public class KeyHostAlgorithmTest : TestBase
- {
- [TestMethod]
- [TestCategory("integration")]
- public void Test_HostKey_SshRsa_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.HostKeyAlgorithms.Clear();
- connectionInfo.HostKeyAlgorithms.Add("ssh-rsa", (data) => { return new KeyHostAlgorithm("ssh-rsa", new RsaKey(), data); });
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("integration")]
- public void Test_HostKey_SshDss_Connection()
- {
- var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
- connectionInfo.HostKeyAlgorithms.Clear();
- connectionInfo.HostKeyAlgorithms.Add("ssh-dss", (data) => { return new KeyHostAlgorithm("ssh-dss", new DsaKey(), data); });
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- ///
- ///A test for KeyHostAlgorithm Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyHostAlgorithmConstructorTest()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- Key key = null; // TODO: Initialize to an appropriate value
- KeyHostAlgorithm target = new KeyHostAlgorithm(name, key);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for KeyHostAlgorithm Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyHostAlgorithmConstructorTest1()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- Key key = null; // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- KeyHostAlgorithm target = new KeyHostAlgorithm(name, key, data);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for Sign
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SignTest()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- Key key = null; // TODO: Initialize to an appropriate value
- KeyHostAlgorithm target = new KeyHostAlgorithm(name, key); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Sign(data);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for VerifySignature
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void VerifySignatureTest()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- Key key = null; // TODO: Initialize to an appropriate value
- KeyHostAlgorithm target = new KeyHostAlgorithm(name, key); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] signature = null; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.VerifySignature(data, signature);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Data
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DataTest()
- {
- string name = string.Empty; // TODO: Initialize to an appropriate value
- Key key = null; // TODO: Initialize to an appropriate value
- KeyHostAlgorithm target = new KeyHostAlgorithm(name, key); // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Data;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Security/KeyTest.cs b/src/Renci.SshNet.Tests/Classes/Security/KeyTest.cs
deleted file mode 100644
index bbbbacff1..000000000
--- a/src/Renci.SshNet.Tests/Classes/Security/KeyTest.cs
+++ /dev/null
@@ -1,84 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Security;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Security
-{
- ///
- ///This is a test class for KeyTest and is intended
- ///to contain all KeyTest Unit Tests
- ///
- [TestClass()]
- public class KeyTest : TestBase
- {
- internal virtual Key CreateKey()
- {
- // TODO: Instantiate an appropriate concrete class.
- Key target = null;
- return target;
- }
-
- ///
- ///A test for Sign
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SignTest()
- {
- Key target = CreateKey(); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.Sign(data);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for VerifySignature
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void VerifySignatureTest()
- {
- Key target = CreateKey(); // TODO: Initialize to an appropriate value
- byte[] data = null; // TODO: Initialize to an appropriate value
- byte[] signature = null; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.VerifySignature(data, signature);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for KeyLength
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void KeyLengthTest()
- {
- Key target = CreateKey(); // TODO: Initialize to an appropriate value
- int actual;
- actual = target.KeyLength;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Public
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void PublicTest()
- {
- Key target = CreateKey(); // TODO: Initialize to an appropriate value
- BigInteger[] expected = null; // TODO: Initialize to an appropriate value
- BigInteger[] actual;
- target.Public = expected;
- actual = target.Public;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest.HttpProxy.cs b/src/Renci.SshNet.Tests/Classes/SessionTest.HttpProxy.cs
deleted file mode 100644
index 03ce2491c..000000000
--- a/src/Renci.SshNet.Tests/Classes/SessionTest.HttpProxy.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System;
-using System.Net;
-using System.Linq;
-using System.Text;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Connection;
-
-namespace Renci.SshNet.Tests.Classes
-{
- public partial class SessionTest
- {
- private static ConnectionInfo CreateConnectionInfoWithHttpProxy(IPEndPoint proxyEndPoint, IPEndPoint serverEndPoint, string proxyUserName)
- {
- return new ConnectionInfo(
- serverEndPoint.Address.ToString(),
- serverEndPoint.Port,
- "eric",
- ProxyTypes.Http,
- proxyEndPoint.Address.ToString(),
- proxyEndPoint.Port,
- proxyUserName,
- "proxypwd",
- new NoneAuthenticationMethod("eric"));
- }
-
- private static string CreateProxyAuthorizationHeader(ConnectionInfo connectionInfo)
- {
- return string.Format("Proxy-Authorization: Basic {0}",
- Convert.ToBase64String(
- Encoding.ASCII.GetBytes(string.Format("{0}:{1}", connectionInfo.ProxyUsername,
- connectionInfo.ProxyPassword))));
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileAttributesTest.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileAttributesTest.cs
deleted file mode 100644
index db54be81b..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileAttributesTest.cs
+++ /dev/null
@@ -1,238 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Sftp;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- ///
- ///This is a test class for SftpFileAttributesTest and is intended
- ///to contain all SftpFileAttributesTest Unit Tests
- ///
- [TestClass]
- [Ignore] // placeholders only
- public class SftpFileAttributesTest : TestBase
- {
- ///
- ///A test for SetPermissions
- ///
- [TestMethod()]
- public void SetPermissionsTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- short mode = 0; // TODO: Initialize to an appropriate value
- target.SetPermissions(mode);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for GroupCanExecute
- ///
- [TestMethod()]
- public void GroupCanExecuteTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.GroupCanExecute = expected;
- actual = target.GroupCanExecute;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for GroupCanRead
- ///
- [TestMethod()]
- public void GroupCanReadTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.GroupCanRead = expected;
- actual = target.GroupCanRead;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for GroupCanWrite
- ///
- [TestMethod()]
- public void GroupCanWriteTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.GroupCanWrite = expected;
- actual = target.GroupCanWrite;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for GroupId
- ///
- [TestMethod()]
- public void GroupIdTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- target.GroupId = expected;
- actual = target.GroupId;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for LastAccessTime
- ///
- [TestMethod()]
- public void LastAccessTimeTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- DateTime expected = new DateTime(); // TODO: Initialize to an appropriate value
- DateTime actual;
- target.LastAccessTime = expected;
- actual = target.LastAccessTime;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for LastWriteTime
- ///
- [TestMethod()]
- public void LastWriteTimeTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- DateTime expected = new DateTime(); // TODO: Initialize to an appropriate value
- DateTime actual;
- target.LastWriteTime = expected;
- actual = target.LastWriteTime;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OthersCanExecute
- ///
- [TestMethod()]
- public void OthersCanExecuteTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OthersCanExecute = expected;
- actual = target.OthersCanExecute;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OthersCanRead
- ///
- [TestMethod()]
- public void OthersCanReadTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OthersCanRead = expected;
- actual = target.OthersCanRead;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OthersCanWrite
- ///
- [TestMethod()]
- public void OthersCanWriteTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OthersCanWrite = expected;
- actual = target.OthersCanWrite;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OwnerCanExecute
- ///
- [TestMethod()]
- public void OwnerCanExecuteTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OwnerCanExecute = expected;
- actual = target.OwnerCanExecute;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OwnerCanRead
- ///
- [TestMethod()]
- public void OwnerCanReadTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OwnerCanRead = expected;
- actual = target.OwnerCanRead;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OwnerCanWrite
- ///
- [TestMethod()]
- public void OwnerCanWriteTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OwnerCanWrite = expected;
- actual = target.OwnerCanWrite;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Size
- ///
- [TestMethod()]
- public void SizeTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- long expected = 0; // TODO: Initialize to an appropriate value
- long actual;
- target.Size = expected;
- actual = target.Size;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for UserId
- ///
- [TestMethod()]
- public void UserIdTest()
- {
- SftpFileAttributes target = SftpFileAttributes.Empty; // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- target.UserId = expected;
- actual = target.UserId;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsNotOpen.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsNotOpen.cs
deleted file mode 100644
index 7c2d87ce8..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsNotOpen.cs
+++ /dev/null
@@ -1,138 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-#if !FEATURE_EVENTWAITHANDLE_DISPOSE
-using Renci.SshNet.Common;
-#endif // !FEATURE_EVENTWAITHANDLE_DISPOSE
-using Renci.SshNet.Sftp;
-using System;
-using System.Threading;
-using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- [TestClass]
- public class SftpFileReaderTest_Dispose_SftpSessionIsNotOpen : SftpFileReaderTestBase
- {
- private const int ChunkLength = 32 * 1024;
-
- private MockSequence _seq;
- private byte[] _handle;
- private int _fileSize;
- private WaitHandle[] _waitHandleArray;
- private int _operationTimeout;
- private SftpFileReader _reader;
- private AsyncCallback _readAsyncCallback;
- private ManualResetEvent _beginReadInvoked;
- private EventWaitHandle _disposeCompleted;
-
- [TestCleanup]
- public void TearDown()
- {
- if (_beginReadInvoked != null)
- {
- _beginReadInvoked.Dispose();
- }
-
- if (_disposeCompleted != null)
- {
- _disposeCompleted.Dispose();
- }
- }
-
- protected override void SetupData()
- {
- var random = new Random();
-
- _handle = CreateByteArray(random, 5);
- _fileSize = 5000;
- _waitHandleArray = new WaitHandle[2];
- _operationTimeout = random.Next(10000, 20000);
- _beginReadInvoked = new ManualResetEvent(false);
- _disposeCompleted = new ManualResetEvent(false);
- _readAsyncCallback = null;
- }
-
- protected override void SetupMocks()
- {
- _seq = new MockSequence();
-
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull()))
- .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) =>
- {
- _waitHandleArray[0] = disposingWaitHandle;
- _waitHandleArray[1] = semaphoreAvailableWaitHandle;
- return _waitHandleArray;
- });
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.OperationTimeout)
- .Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback(() =>
- {
- // harden test by making sure that we've invoked BeginRead before Dispose is invoked
- _beginReadInvoked.Set();
- })
- .Returns((handle, offset, length, callback, state) =>
- {
- _readAsyncCallback = callback;
- return null;
- })
- .Callback(() =>
- {
- // wait until Dispose has been invoked on reader to allow us to harden test, and
- // verify whether Dispose will prevent us from entering the read-ahead loop again
- _waitHandleArray[0].WaitOne();
- });
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.IsOpen)
- .Returns(false);
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _reader = new SftpFileReader(_handle, SftpSessionMock.Object, ChunkLength, 1, _fileSize);
- }
-
- protected override void Act()
- {
- Assert.IsTrue(_beginReadInvoked.WaitOne(5000));
- _reader.Dispose();
- }
-
- [TestMethod]
- public void ReadAfterDisposeShouldThrowObjectDisposedException()
- {
- try
- {
- _reader.Read();
- Assert.Fail();
- }
- catch (ObjectDisposedException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual(typeof(SftpFileReader).FullName, ex.ObjectName);
- }
- }
-
- [TestMethod]
- public void InvokeOfReadAheadCallbackShouldCompleteImmediately()
- {
- Assert.IsNotNull(_readAsyncCallback);
-
- _readAsyncCallback(new SftpReadAsyncResult(null, null));
- }
-
- [TestMethod]
- public void BeginCloseOnSftpSessionShouldNeverHaveBeenInvoked()
- {
- SftpSessionMock.Verify(p => p.BeginClose(_handle, null, null), Times.Never);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_BeginCloseThrowsException.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_BeginCloseThrowsException.cs
deleted file mode 100644
index 015aba53e..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_BeginCloseThrowsException.cs
+++ /dev/null
@@ -1,141 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-#if !FEATURE_EVENTWAITHANDLE_DISPOSE
-using Renci.SshNet.Common;
-#endif // !FEATURE_EVENTWAITHANDLE_DISPOSE
-using Renci.SshNet.Sftp;
-using System;
-using System.Threading;
-using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- [TestClass]
- public class SftpFileReaderTest_Dispose_SftpSessionIsOpen_BeginCloseThrowsException : SftpFileReaderTestBase
- {
- private const int ChunkLength = 32 * 1024;
-
- private MockSequence _seq;
- private byte[] _handle;
- private int _fileSize;
- private WaitHandle[] _waitHandleArray;
- private int _operationTimeout;
- private SftpFileReader _reader;
- private AsyncCallback _readAsyncCallback;
- private ManualResetEvent _beginReadInvoked;
- private EventWaitHandle _disposeCompleted;
-
- [TestCleanup]
- public void TearDown()
- {
- if (_beginReadInvoked != null)
- {
- _beginReadInvoked.Dispose();
- }
-
- if (_disposeCompleted != null)
- {
- _disposeCompleted.Dispose();
- }
- }
-
- protected override void SetupData()
- {
- var random = new Random();
-
- _handle = CreateByteArray(random, 5);
- _fileSize = 5000;
- _waitHandleArray = new WaitHandle[2];
- _operationTimeout = random.Next(10000, 20000);
- _beginReadInvoked = new ManualResetEvent(false);
- _disposeCompleted = new ManualResetEvent(false);
- _readAsyncCallback = null;
- }
-
- protected override void SetupMocks()
- {
- _seq = new MockSequence();
-
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull()))
- .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) =>
- {
- _waitHandleArray[0] = disposingWaitHandle;
- _waitHandleArray[1] = semaphoreAvailableWaitHandle;
- return _waitHandleArray;
- });
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.OperationTimeout)
- .Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback(() =>
- {
- // harden test by making sure that we've invoked BeginRead before Dispose is invoked
- _beginReadInvoked.Set();
- })
- .Returns((handle, offset, length, callback, state) =>
- {
- _readAsyncCallback = callback;
- return null;
- })
- .Callback(() =>
- {
- // wait until Dispose has been invoked on reader to allow us to harden test, and
- // verify whether Dispose will prevent us from entering the read-ahead loop again
- _waitHandleArray[0].WaitOne();
- });
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.IsOpen)
- .Returns(true);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginClose(_handle, null, null))
- .Throws(new SshException());
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _reader = new SftpFileReader(_handle, SftpSessionMock.Object, ChunkLength, 1, _fileSize);
- }
-
- protected override void Act()
- {
- Assert.IsTrue(_beginReadInvoked.WaitOne(5000));
- _reader.Dispose();
- }
-
- [TestMethod]
- public void ReadAfterDisposeShouldThrowObjectDisposedException()
- {
- try
- {
- _reader.Read();
- Assert.Fail();
- }
- catch (ObjectDisposedException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual(typeof(SftpFileReader).FullName, ex.ObjectName);
- }
- }
-
- [TestMethod]
- public void InvokeOfReadAheadCallbackShouldCompleteImmediately()
- {
- Assert.IsNotNull(_readAsyncCallback);
-
- _readAsyncCallback(new SftpReadAsyncResult(null, null));
- }
-
- [TestMethod]
- public void BeginCloseOnSftpSessionShouldHaveBeenInvokedOnce()
- {
- SftpSessionMock.Verify(p => p.BeginClose(_handle, null, null), Times.Once);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_EndCloseThrowsException.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_EndCloseThrowsException.cs
deleted file mode 100644
index 4a175648e..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_EndCloseThrowsException.cs
+++ /dev/null
@@ -1,146 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-#if !FEATURE_EVENTWAITHANDLE_DISPOSE
-using Renci.SshNet.Common;
-#endif // !FEATURE_EVENTWAITHANDLE_DISPOSE
-using Renci.SshNet.Sftp;
-using System;
-using System.Threading;
-using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- [TestClass]
- public class SftpFileReaderTest_Dispose_SftpSessionIsOpen_EndCloseThrowsException : SftpFileReaderTestBase
- {
- private const int ChunkLength = 32 * 1024;
-
- private MockSequence _seq;
- private byte[] _handle;
- private int _fileSize;
- private WaitHandle[] _waitHandleArray;
- private int _operationTimeout;
- private SftpCloseAsyncResult _closeAsyncResult;
- private SftpFileReader _reader;
- private AsyncCallback _readAsyncCallback;
- private ManualResetEvent _beginReadInvoked;
- private EventWaitHandle _disposeCompleted;
-
- [TestCleanup]
- public void TearDown()
- {
- if (_beginReadInvoked != null)
- {
- _beginReadInvoked.Dispose();
- }
-
- if (_disposeCompleted != null)
- {
- _disposeCompleted.Dispose();
- }
- }
-
- protected override void SetupData()
- {
- var random = new Random();
-
- _handle = CreateByteArray(random, 5);
- _fileSize = 5000;
- _waitHandleArray = new WaitHandle[2];
- _operationTimeout = random.Next(10000, 20000);
- _closeAsyncResult = new SftpCloseAsyncResult(null, null);
- _beginReadInvoked = new ManualResetEvent(false);
- _disposeCompleted = new ManualResetEvent(false);
- _readAsyncCallback = null;
- }
-
- protected override void SetupMocks()
- {
- _seq = new MockSequence();
-
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull()))
- .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) =>
- {
- _waitHandleArray[0] = disposingWaitHandle;
- _waitHandleArray[1] = semaphoreAvailableWaitHandle;
- return _waitHandleArray;
- });
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.OperationTimeout)
- .Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback(() =>
- {
- // harden test by making sure that we've invoked BeginRead before Dispose is invoked
- _beginReadInvoked.Set();
- })
- .Returns((handle, offset, length, callback, state) =>
- {
- _readAsyncCallback = callback;
- return null;
- })
- .Callback(() =>
- {
- // wait until Dispose has been invoked on reader to allow us to harden test, and
- // verify whether Dispose will prevent us from entering the read-ahead loop again
- _waitHandleArray[0].WaitOne();
- });
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.IsOpen)
- .Returns(true);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginClose(_handle, null, null))
- .Returns(_closeAsyncResult);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.EndClose(_closeAsyncResult))
- .Throws(new SshException());
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _reader = new SftpFileReader(_handle, SftpSessionMock.Object, ChunkLength, 1, _fileSize);
- }
-
- protected override void Act()
- {
- Assert.IsTrue(_beginReadInvoked.WaitOne(5000));
- _reader.Dispose();
- }
-
- [TestMethod]
- public void ReadAfterDisposeShouldThrowObjectDisposedException()
- {
- try
- {
- _reader.Read();
- Assert.Fail();
- }
- catch (ObjectDisposedException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual(typeof(SftpFileReader).FullName, ex.ObjectName);
- }
- }
-
- [TestMethod]
- public void InvokeOfReadAheadCallbackShouldCompleteImmediately()
- {
- Assert.IsNotNull(_readAsyncCallback);
-
- _readAsyncCallback(new SftpReadAsyncResult(null, null));
- }
-
- [TestMethod]
- public void EndCloseOnSftpSessionShouldHaveBeenInvokedOnce()
- {
- SftpSessionMock.Verify(p => p.EndClose(_closeAsyncResult), Times.Once);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsNotReached.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsNotReached.cs
deleted file mode 100644
index 8c38a000f..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsNotReached.cs
+++ /dev/null
@@ -1,302 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-using Renci.SshNet.Common;
-using Renci.SshNet.Sftp;
-using System;
-using System.Diagnostics;
-using System.Threading;
-using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- [TestClass]
- public class SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsNotReached : SftpFileReaderTestBase
- {
- private const int ChunkLength = 32 * 1024;
-
- private MockSequence _seq;
- private byte[] _handle;
- private int _fileSize;
- private WaitHandle[] _waitHandleArray;
- private int _operationTimeout;
- private SftpCloseAsyncResult _closeAsyncResult;
- private byte[] _chunk1;
- private byte[] _chunk2;
- private byte[] _chunk2CatchUp1;
- private byte[] _chunk2CatchUp2;
- private byte[] _chunk3;
- private byte[] _chunk4;
- private byte[] _chunk5;
- private SftpFileReader _reader;
- private byte[] _actualChunk1;
- private byte[] _actualChunk2;
- private byte[] _actualChunk3;
- private ManualResetEvent _chunk1BeginRead;
- private ManualResetEvent _chunk2BeginRead;
- private ManualResetEvent _chunk3BeginRead;
- private ManualResetEvent _chunk4BeginRead;
- private ManualResetEvent _chunk5BeginRead;
- private ManualResetEvent _waitBeforeChunk6;
- private ManualResetEvent _chunk6BeginRead;
- private byte[] _actualChunk4;
- private byte[] _actualChunk2CatchUp1;
- private byte[] _actualChunk2CatchUp2;
- private byte[] _chunk6;
- private byte[] _actualChunk5;
- private byte[] _actualChunk6;
-
- protected override void SetupData()
- {
- var random = new Random();
-
- _handle = CreateByteArray(random, 3);
- _chunk1 = CreateByteArray(random, ChunkLength);
- _chunk2 = CreateByteArray(random, ChunkLength - 17);
- _chunk2CatchUp1 = CreateByteArray(random, 10);
- _chunk2CatchUp2 = CreateByteArray(random, 7);
- _chunk3 = CreateByteArray(random, ChunkLength);
- _chunk4 = CreateByteArray(random, ChunkLength);
- _chunk5 = CreateByteArray(random, ChunkLength);
- _chunk6 = new byte[0];
- _chunk1BeginRead = new ManualResetEvent(false);
- _chunk2BeginRead = new ManualResetEvent(false);
- _chunk3BeginRead = new ManualResetEvent(false);
- _chunk4BeginRead = new ManualResetEvent(false);
- _chunk5BeginRead = new ManualResetEvent(false);
- _waitBeforeChunk6 = new ManualResetEvent(false);
- _chunk6BeginRead = new ManualResetEvent(false);
- _fileSize = _chunk1.Length + _chunk2.Length + _chunk2CatchUp1.Length + _chunk2CatchUp2.Length + _chunk3.Length + _chunk4.Length + _chunk5.Length;
- _waitHandleArray = new WaitHandle[2];
- _operationTimeout = random.Next(10000, 20000);
- _closeAsyncResult = new SftpCloseAsyncResult(null, null);
- }
-
- protected override void SetupMocks()
- {
- _seq = new MockSequence();
-
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull()))
- .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) =>
- {
- _waitHandleArray[0] = disposingWaitHandle;
- _waitHandleArray[1] = semaphoreAvailableWaitHandle;
- return _waitHandleArray;
- });
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback((handle, offset, length, callback, state) =>
- {
- _chunk1BeginRead.Set();
- var asyncResult = new SftpReadAsyncResult(callback, state);
- asyncResult.SetAsCompleted(_chunk1, false);
- })
- .Returns((SftpReadAsyncResult)null);
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback((handle, offset, length, callback, state) =>
- {
- _chunk2BeginRead.Set();
- var asyncResult = new SftpReadAsyncResult(callback, state);
- asyncResult.SetAsCompleted(_chunk2, false);
- })
- .Returns((SftpReadAsyncResult)null);
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, 2 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback((handle, offset, length, callback, state) =>
- {
- _chunk3BeginRead.Set();
- var asyncResult = new SftpReadAsyncResult(callback, state);
- asyncResult.SetAsCompleted(_chunk3, false);
- })
- .Returns((SftpReadAsyncResult)null);
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, 3 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback((handle, offset, length, callback, state) =>
- {
- _chunk4BeginRead.Set();
- var asyncResult = new SftpReadAsyncResult(callback, state);
- asyncResult.SetAsCompleted(_chunk4, false);
- })
- .Returns((SftpReadAsyncResult)null);
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, 4 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback((handle, offset, length, callback, state) =>
- {
- _chunk5BeginRead.Set();
- var asyncResult = new SftpReadAsyncResult(callback, state);
- asyncResult.SetAsCompleted(_chunk5, false);
- })
- .Returns((SftpReadAsyncResult)null);
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Callback(() => _waitBeforeChunk6.Set())
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.RequestRead(_handle, 2 * ChunkLength - 17, 17))
- .Returns(_chunk2CatchUp1);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.RequestRead(_handle, 2 * ChunkLength - 7, 7))
- .Returns(_chunk2CatchUp2);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, 5 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback((handle, offset, length, callback, state) =>
- {
- _chunk6BeginRead.Set();
- var asyncResult = new SftpReadAsyncResult(callback, state);
- asyncResult.SetAsCompleted(_chunk6, false);
- })
- .Returns((SftpReadAsyncResult)null);
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _reader = new SftpFileReader(_handle, SftpSessionMock.Object, ChunkLength, 3, _fileSize);
- }
-
- protected override void Act()
- {
- // reader is configured to read-ahead max. 3 chunks, so chunk4 should not have been read
- Assert.IsFalse(_chunk4BeginRead.WaitOne(0));
- // consume chunk 1
- _actualChunk1 = _reader.Read();
- // consuming chunk1 allows chunk4 to be read-ahead
- Assert.IsTrue(_chunk4BeginRead.WaitOne(200));
- // verify that chunk5 has not yet been read-ahead
- Assert.IsFalse(_chunk5BeginRead.WaitOne(0));
- // consume chunk 2
- _actualChunk2 = _reader.Read();
- // consuming chunk2 allows chunk5 to be read-ahead
- Assert.IsTrue(_chunk5BeginRead.WaitOne(200));
- // pauze until the read-ahead has started waiting a semaphore to become available
- Assert.IsTrue(_waitBeforeChunk6.WaitOne(200));
- // consume remaining parts of chunk 2
- _actualChunk2CatchUp1 = _reader.Read();
- _actualChunk2CatchUp2 = _reader.Read();
- // verify that chunk6 has not yet been read-ahead
- Assert.IsFalse(_chunk6BeginRead.WaitOne(0));
- // consume chunk 3
- _actualChunk3 = _reader.Read();
- // consuming chunk3 allows chunk6 to be read-ahead
- Assert.IsTrue(_chunk6BeginRead.WaitOne(200));
- // consume chunk 4
- _actualChunk4 = _reader.Read();
- // consume chunk 5
- _actualChunk5 = _reader.Read();
- // consume chunk 6
- _actualChunk6 = _reader.Read();
- }
-
- [TestMethod]
- public void FirstReadShouldReturnChunk1()
- {
- Assert.IsNotNull(_actualChunk1);
- Assert.AreSame(_chunk1, _actualChunk1);
- }
-
- [TestMethod]
- public void SecondReadShouldReturnChunk2()
- {
- Assert.IsNotNull(_actualChunk2);
- Assert.AreSame(_chunk2, _actualChunk2);
- }
-
- [TestMethod]
- public void ThirdReadShouldReturnChunk2CatchUp1()
- {
- Assert.IsNotNull(_actualChunk2CatchUp1);
- Assert.AreSame(_chunk2CatchUp1, _actualChunk2CatchUp1);
- }
-
- [TestMethod]
- public void FourthReadShouldReturnChunk2CatchUp2()
- {
- Assert.IsNotNull(_actualChunk2CatchUp2);
- Assert.AreSame(_chunk2CatchUp2, _actualChunk2CatchUp2);
- }
-
- [TestMethod]
- public void FifthReadShouldReturnChunk3()
- {
- Assert.IsNotNull(_actualChunk3);
- Assert.AreSame(_chunk3, _actualChunk3);
- }
-
- [TestMethod]
- public void SixthReadShouldReturnChunk4()
- {
- Assert.IsNotNull(_actualChunk4);
- Assert.AreSame(_chunk4, _actualChunk4);
- }
-
- [TestMethod]
- public void SeventhReadShouldReturnChunk5()
- {
- Assert.IsNotNull(_actualChunk5);
- Assert.AreSame(_chunk5, _actualChunk5);
- }
-
- [TestMethod]
- public void EightReadShouldReturnChunk6()
- {
- Assert.IsNotNull(_actualChunk6);
- Assert.AreSame(_chunk6, _actualChunk6);
- }
-
- [TestMethod]
- public void ReadAfterEndOfFileShouldThrowSshException()
- {
- try
- {
- _reader.Read();
- Assert.Fail();
- }
- catch (SshException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Attempting to read beyond the end of the file.", ex.Message);
- }
- }
-
- [TestMethod]
- public void DisposeShouldCloseHandleAndCompleteImmediately()
- {
- SftpSessionMock.InSequence(_seq).Setup(p => p.IsOpen).Returns(true);
- SftpSessionMock.InSequence(_seq).Setup(p => p.BeginClose(_handle, null, null)).Returns(_closeAsyncResult);
- SftpSessionMock.InSequence(_seq).Setup(p => p.EndClose(_closeAsyncResult));
-
- var stopwatch = Stopwatch.StartNew();
- _reader.Dispose();
- stopwatch.Stop();
-
- Assert.IsTrue(stopwatch.ElapsedMilliseconds < 200, "Dispose took too long to complete: " + stopwatch.ElapsedMilliseconds);
-
- SftpSessionMock.Verify(p => p.IsOpen, Times.Once);
- SftpSessionMock.Verify(p => p.BeginClose(_handle, null, null), Times.Once);
- SftpSessionMock.Verify(p => p.EndClose(_closeAsyncResult), Times.Once);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsReached.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsReached.cs
deleted file mode 100644
index 2b5cc0f2e..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsReached.cs
+++ /dev/null
@@ -1,192 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-using Renci.SshNet.Common;
-using Renci.SshNet.Sftp;
-using System;
-using System.Diagnostics;
-using System.Threading;
-using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- [TestClass]
- public class SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsReached : SftpFileReaderTestBase
- {
- private const int ChunkLength = 32 * 1024;
-
- private MockSequence _seq;
- private byte[] _handle;
- private int _fileSize;
- private WaitHandle[] _waitHandleArray;
- private int _operationTimeout;
- private SftpCloseAsyncResult _closeAsyncResult;
- private byte[] _chunk1;
- private byte[] _chunk2;
- private byte[] _chunk2CatchUp;
- private byte[] _chunk3;
- private SftpFileReader _reader;
- private byte[] _actualChunk1;
- private byte[] _actualChunk2;
- private byte[] _actualChunk2CatchUp;
- private byte[] _actualChunk3;
- private ManualResetEvent _chunk1BeginRead;
- private ManualResetEvent _chunk2BeginRead;
- private ManualResetEvent _chunk3BeginRead;
-
- protected override void SetupData()
- {
- var random = new Random();
-
- _handle = CreateByteArray(random, 3);
- _chunk1 = CreateByteArray(random, ChunkLength);
- _chunk2 = CreateByteArray(random, ChunkLength - 10);
- _chunk2CatchUp = CreateByteArray(random, 10);
- _chunk3 = new byte[0];
- _chunk1BeginRead = new ManualResetEvent(false);
- _chunk2BeginRead = new ManualResetEvent(false);
- _chunk3BeginRead = new ManualResetEvent(false);
- _fileSize = _chunk1.Length + _chunk2.Length + _chunk2CatchUp.Length + _chunk3.Length;
- _waitHandleArray = new WaitHandle[2];
- _operationTimeout = random.Next(10000, 20000);
- _closeAsyncResult = new SftpCloseAsyncResult(null, null);
- }
-
- protected override void SetupMocks()
- {
- _seq = new MockSequence();
-
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull()))
- .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) =>
- {
- _waitHandleArray[0] = disposingWaitHandle;
- _waitHandleArray[1] = semaphoreAvailableWaitHandle;
- return _waitHandleArray;
- });
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback((handle, offset, length, callback, state) =>
- {
- _chunk1BeginRead.Set();
- var asyncResult = new SftpReadAsyncResult(callback, state);
- asyncResult.SetAsCompleted(_chunk1, false);
- })
- .Returns((SftpReadAsyncResult)null);
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback((handle, offset, length, callback, state) =>
- {
- _chunk2BeginRead.Set();
- var asyncResult = new SftpReadAsyncResult(callback, state);
- asyncResult.SetAsCompleted(_chunk2, false);
- })
- .Returns((SftpReadAsyncResult)null);
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, 2 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback((handle, offset, length, callback, state) =>
- {
- _chunk3BeginRead.Set();
- var asyncResult = new SftpReadAsyncResult(callback, state);
- asyncResult.SetAsCompleted(_chunk3, false);
- })
- .Returns((SftpReadAsyncResult)null);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.RequestRead(_handle, 2 * ChunkLength - 10, 10))
- .Returns(_chunk2CatchUp);
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _reader = new SftpFileReader(_handle, SftpSessionMock.Object, ChunkLength, 5, _fileSize);
- }
-
- protected override void Act()
- {
- // consume chunk 1
- _actualChunk1 = _reader.Read();
- // consume chunk 2
- _actualChunk2 = _reader.Read();
- // wait until chunk3 has been read-ahead
- Assert.IsTrue(_chunk3BeginRead.WaitOne(200));
- // consume remaining parts of chunk 2
- _actualChunk2CatchUp = _reader.Read();
- // consume chunk 3
- _actualChunk3 = _reader.Read();
- }
-
- [TestMethod]
- public void FirstReadShouldReturnChunk1()
- {
- Assert.IsNotNull(_actualChunk1);
- Assert.AreSame(_chunk1, _actualChunk1);
- }
-
- [TestMethod]
- public void SecondReadShouldReturnChunk2()
- {
- Assert.IsNotNull(_actualChunk2);
- Assert.AreSame(_chunk2, _actualChunk2);
- }
-
- [TestMethod]
- public void ThirdReadShouldReturnChunk2CatchUp()
- {
- Assert.IsNotNull(_actualChunk2CatchUp);
- Assert.AreSame(_chunk2CatchUp, _actualChunk2CatchUp);
- }
-
- [TestMethod]
- public void FourthReadShouldReturnChunk3()
- {
- Assert.IsNotNull(_actualChunk3);
- Assert.AreSame(_chunk3, _actualChunk3);
- }
-
- [TestMethod]
- public void ReadAfterEndOfFileShouldThrowSshException()
- {
- try
- {
- _reader.Read();
- Assert.Fail();
- }
- catch (SshException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Attempting to read beyond the end of the file.", ex.Message);
- }
- }
-
- [TestMethod]
- public void DisposeShouldCloseHandleAndCompleteImmediately()
- {
- SftpSessionMock.InSequence(_seq).Setup(p => p.IsOpen).Returns(true);
- SftpSessionMock.InSequence(_seq).Setup(p => p.BeginClose(_handle, null, null)).Returns(_closeAsyncResult);
- SftpSessionMock.InSequence(_seq).Setup(p => p.EndClose(_closeAsyncResult));
-
- var stopwatch = Stopwatch.StartNew();
- _reader.Dispose();
- stopwatch.Stop();
-
- Assert.IsTrue(stopwatch.ElapsedMilliseconds < 200, "Dispose took too long to complete: " + stopwatch.ElapsedMilliseconds);
-
- SftpSessionMock.Verify(p => p.IsOpen, Times.Once);
- SftpSessionMock.Verify(p => p.BeginClose(_handle, null, null), Times.Once);
- SftpSessionMock.Verify(p => p.EndClose(_closeAsyncResult), Times.Once);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadAheadEndInvokeException_PreventsFurtherReadAheads.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadAheadEndInvokeException_PreventsFurtherReadAheads.cs
deleted file mode 100644
index 0e4e65eaf..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadAheadEndInvokeException_PreventsFurtherReadAheads.cs
+++ /dev/null
@@ -1,176 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-using Renci.SshNet.Abstractions;
-using Renci.SshNet.Common;
-using Renci.SshNet.Sftp;
-using System;
-using System.Diagnostics;
-using System.Threading;
-using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- [TestClass]
- public class SftpFileReaderTest_ReadAheadEndInvokeException_PreventsFurtherReadAheads : SftpFileReaderTestBase
- {
- private const int ChunkLength = 32 * 1024;
-
- private MockSequence _seq;
- private byte[] _handle;
- private int _fileSize;
- private WaitHandle[] _waitHandleArray;
- private int _operationTimeout;
- private SftpCloseAsyncResult _closeAsyncResult;
- private byte[] _chunk1;
- private byte[] _chunk3;
- private SftpFileReader _reader;
- private ManualResetEvent _readAheadChunk2;
- private ManualResetEvent _readChunk2;
- private SshException _exception;
- private SshException _actualException;
-
- protected override void SetupData()
- {
- var random = new Random();
-
- _handle = CreateByteArray(random, 5);
- _chunk1 = CreateByteArray(random, ChunkLength);
- _chunk3 = CreateByteArray(random, ChunkLength);
- _fileSize = 3 * _chunk1.Length;
- _waitHandleArray = new WaitHandle[2];
- _operationTimeout = random.Next(10000, 20000);
- _closeAsyncResult = new SftpCloseAsyncResult(null, null);
-
- _readAheadChunk2 = new ManualResetEvent(false);
- _readChunk2 = new ManualResetEvent(false);
-
- _exception = new SshException();
- }
-
- protected override void SetupMocks()
- {
- _seq = new MockSequence();
-
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull()))
- .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) =>
- {
- _waitHandleArray[0] = disposingWaitHandle;
- _waitHandleArray[1] = semaphoreAvailableWaitHandle;
- return _waitHandleArray;
- });
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback((handle, offset, length, callback, state) =>
- {
- var asyncResult = new SftpReadAsyncResult(callback, state);
- asyncResult.SetAsCompleted(_chunk1, false);
- })
- .Returns((SftpReadAsyncResult)null);
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.BeginRead(_handle, ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny()))
- .Callback((handle, offset, length, callback, state) =>
- {
- ThreadAbstraction.ExecuteThread(() =>
- {
- // signal that we're in the read-ahead for chunk2
- _readAheadChunk2.Set();
- // wait for client to start reading this chunk
- _readChunk2.WaitOne(TimeSpan.FromSeconds(5));
- // sleep a short time to make sure the client is in the blocking wait
- Thread.Sleep(500);
- // complete async read of chunk2 with exception
- var asyncResult = new SftpReadAsyncResult(callback, state);
- asyncResult.SetAsCompleted(_exception, false);
- });
- })
- .Returns((SftpReadAsyncResult)null);
- SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
- SftpSessionMock.InSequence(_seq)
- .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
- .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- // use a max. read-ahead of 1 to allow us to verify that the next read-ahead is not done
- // when a read-ahead has failed
- _reader = new SftpFileReader(_handle, SftpSessionMock.Object, ChunkLength, 1, _fileSize);
- }
-
- protected override void Act()
- {
- _reader.Read();
-
- // wait until SftpFileReader has starting reading ahead chunk 2
- Assert.IsTrue(_readAheadChunk2.WaitOne(TimeSpan.FromSeconds(5)));
- // signal that we are about to read chunk 2
- _readChunk2.Set();
-
- try
- {
- _reader.Read();
- Assert.Fail();
- }
- catch (SshException ex)
- {
- _actualException = ex;
- }
- }
-
- [TestMethod]
- public void ReadOfSecondChunkShouldThrowExceptionThatOccurredInReadAhead()
- {
- Assert.IsNotNull(_actualException);
- Assert.AreSame(_exception, _actualException);
- }
-
- [TestMethod]
- public void ReadAfterReadAheadExceptionShouldRethrowExceptionThatOccurredInReadAhead()
- {
- try
- {
- _reader.Read();
- Assert.Fail();
- }
- catch (SshException ex)
- {
- Assert.AreSame(_exception, ex);
- }
- }
-
- [TestMethod]
- public void DisposeShouldCloseHandleAndCompleteImmediately()
- {
- SftpSessionMock.InSequence(_seq).Setup(p => p.IsOpen).Returns(true);
- SftpSessionMock.InSequence(_seq).Setup(p => p.BeginClose(_handle, null, null)).Returns(_closeAsyncResult);
- SftpSessionMock.InSequence(_seq).Setup(p => p.EndClose(_closeAsyncResult));
-
- var stopwatch = Stopwatch.StartNew();
- _reader.Dispose();
- stopwatch.Stop();
-
- Assert.IsTrue(stopwatch.ElapsedMilliseconds < 200, "Dispose took too long to complete: " + stopwatch.ElapsedMilliseconds);
-
- SftpSessionMock.Verify(p => p.IsOpen, Times.Once);
- SftpSessionMock.Verify(p => p.BeginClose(_handle, null, null), Times.Once);
- SftpSessionMock.Verify(p => p.EndClose(_closeAsyncResult), Times.Once);
- }
-
- [TestMethod]
- public void ExceptionInReadAheadShouldPreventFurtherReadAheads()
- {
- SftpSessionMock.Verify(p => p.BeginRead(_handle, 2 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny()), Times.Never);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackBeginReadException.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackBeginReadException.cs
deleted file mode 100644
index f00a0273a..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackBeginReadException.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- class SftpFileReaderTest_ReadBackBeginReadException
- {
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackEndInvokeException.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackEndInvokeException.cs
deleted file mode 100644
index 19c816fc8..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackEndInvokeException.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- class SftpFileReaderTest_ReadBackEndInvokeException
- {
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Finalize_SessionOpen.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Finalize_SessionOpen.cs
deleted file mode 100644
index 41312f668..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Finalize_SessionOpen.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-using System;
-using System.Globalization;
-using System.IO;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-using Renci.SshNet.Sftp;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- [TestClass]
- public class SftpFileStreamTest_Finalize_SessionOpen : SftpFileStreamTestBase
- {
- private SftpFileStream _target;
- private string _path;
- private byte[] _handle;
- private uint _bufferSize;
- private uint _readBufferSize;
- private uint _writeBufferSize;
-
- protected override void SetupData()
- {
- base.SetupData();
-
- var random = new Random();
- _path = random.Next().ToString(CultureInfo.InvariantCulture);
- _handle = GenerateRandom(7, random);
- _bufferSize = (uint) random.Next(1, 1000);
- _readBufferSize = (uint) random.Next(0, 1000);
- _writeBufferSize = (uint) random.Next(0, 1000);
- }
-
- protected override void SetupMocks()
- {
- SftpSessionMock.InSequence(MockSequence)
- .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.CreateNewOrOpen, false))
- .Returns(_handle);
- SftpSessionMock.InSequence(MockSequence)
- .Setup(p => p.CalculateOptimalReadLength(_bufferSize))
- .Returns(_readBufferSize);
- SftpSessionMock.InSequence(MockSequence)
- .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle))
- .Returns(_writeBufferSize);
- SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true);
- SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestClose(_handle));
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _target = new SftpFileStream(SftpSessionMock.Object,
- _path,
- FileMode.OpenOrCreate,
- FileAccess.ReadWrite,
- (int) _bufferSize);
- _target = null;
- }
-
- protected override void Act()
- {
- GC.Collect();
- GC.WaitForPendingFinalizers();
- }
-
- [TestMethod]
- public void IsOpenOnSftpSessionShouldNeverBeInvoked()
- {
- SftpSessionMock.Verify(p => p.IsOpen, Times.Never);
- }
-
- [TestMethod]
- public void RequestCloseOnSftpSessionShouldNeverBeInvoked()
- {
- SftpSessionMock.Verify(p => p.RequestClose(_handle), Times.Never);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileSystemInformationTest.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileSystemInformationTest.cs
deleted file mode 100644
index 22262af79..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileSystemInformationTest.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Sftp;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- ///
- ///This is a test class for SftpFileSytemInformationTest and is intended
- ///to contain all SftpFileSytemInformationTest Unit Tests
- ///
- [TestClass]
- public class SftpFileSystemInformationTest : TestBase
- {
- ///
- ///A test for IsReadOnly
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void IsReadOnlyTest()
- {
- ulong bsize = 0; // TODO: Initialize to an appropriate value
- ulong frsize = 0; // TODO: Initialize to an appropriate value
- ulong blocks = 0; // TODO: Initialize to an appropriate value
- ulong bfree = 0; // TODO: Initialize to an appropriate value
- ulong bavail = 0; // TODO: Initialize to an appropriate value
- ulong files = 0; // TODO: Initialize to an appropriate value
- ulong ffree = 0; // TODO: Initialize to an appropriate value
- ulong favail = 0; // TODO: Initialize to an appropriate value
- ulong sid = 0; // TODO: Initialize to an appropriate value
- ulong flag = 0; // TODO: Initialize to an appropriate value
- ulong namemax = 0; // TODO: Initialize to an appropriate value
- SftpFileSytemInformation target = new SftpFileSytemInformation(bsize, frsize, blocks, bfree, bavail, files, ffree, favail, sid, flag, namemax); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.IsReadOnly;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for SupportsSetUid
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void SupportsSetUidTest()
- {
- ulong bsize = 0; // TODO: Initialize to an appropriate value
- ulong frsize = 0; // TODO: Initialize to an appropriate value
- ulong blocks = 0; // TODO: Initialize to an appropriate value
- ulong bfree = 0; // TODO: Initialize to an appropriate value
- ulong bavail = 0; // TODO: Initialize to an appropriate value
- ulong files = 0; // TODO: Initialize to an appropriate value
- ulong ffree = 0; // TODO: Initialize to an appropriate value
- ulong favail = 0; // TODO: Initialize to an appropriate value
- ulong sid = 0; // TODO: Initialize to an appropriate value
- ulong flag = 0; // TODO: Initialize to an appropriate value
- ulong namemax = 0; // TODO: Initialize to an appropriate value
- SftpFileSytemInformation target = new SftpFileSytemInformation(bsize, frsize, blocks, bfree, bavail, files, ffree, favail, sid, flag, namemax); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.SupportsSetUid;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileTest.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileTest.cs
deleted file mode 100644
index d1716a957..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileTest.cs
+++ /dev/null
@@ -1,626 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Sftp;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.IO;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- ///
- /// Represents SFTP file information
- ///
- [TestClass]
- public class SftpFileTest : TestBase
- {
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
- public void Test_Get_Root_Directory()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.Connect();
- var directory = sftp.Get("/");
-
- Assert.AreEqual("/", directory.FullName);
- Assert.IsTrue(directory.IsDirectory);
- Assert.IsFalse(directory.IsRegularFile);
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
- [ExpectedException(typeof(SftpPathNotFoundException))]
- public void Test_Get_Invalid_Directory()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.Connect();
-
- sftp.Get("/xyz");
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
- public void Test_Get_File()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.Connect();
-
- sftp.UploadFile(new MemoryStream(), "abc.txt");
-
- var file = sftp.Get("abc.txt");
-
- Assert.AreEqual("/home/tester/abc.txt", file.FullName);
- Assert.IsTrue(file.IsRegularFile);
- Assert.IsFalse(file.IsDirectory);
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
- [Description("Test passing null to Get.")]
- [ExpectedException(typeof(ArgumentNullException))]
- public void Test_Get_File_Null()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.Connect();
-
- var file = sftp.Get(null);
-
- sftp.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
- public void Test_Get_International_File()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.Connect();
-
- sftp.UploadFile(new MemoryStream(), "test-üöä-");
-
- var file = sftp.Get("test-üöä-");
-
- Assert.AreEqual("/home/tester/test-üöä-", file.FullName);
- Assert.IsTrue(file.IsRegularFile);
- Assert.IsFalse(file.IsDirectory);
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
- public void Test_Sftp_SftpFile_MoveTo()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.Connect();
-
- string uploadedFileName = Path.GetTempFileName();
- string remoteFileName = Path.GetRandomFileName();
- string newFileName = Path.GetRandomFileName();
-
- this.CreateTestFile(uploadedFileName, 1);
-
- using (var file = File.OpenRead(uploadedFileName))
- {
- sftp.UploadFile(file, remoteFileName);
- }
-
- var sftpFile = sftp.Get(remoteFileName);
-
- sftpFile.MoveTo(newFileName);
-
- Assert.AreEqual(newFileName, sftpFile.Name);
-
- sftp.Disconnect();
- }
- }
-
- ///
- ///A test for Delete
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DeleteTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- target.Delete();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for MoveTo
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void MoveToTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- string destFileName = string.Empty; // TODO: Initialize to an appropriate value
- target.MoveTo(destFileName);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for SetPermissions
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SetPermissionsTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- short mode = 0; // TODO: Initialize to an appropriate value
- target.SetPermissions(mode);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for ToString
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ToStringTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- string expected = string.Empty; // TODO: Initialize to an appropriate value
- string actual;
- actual = target.ToString();
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for UpdateStatus
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void UpdateStatusTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- target.UpdateStatus();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for GroupCanExecute
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GroupCanExecuteTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.GroupCanExecute = expected;
- actual = target.GroupCanExecute;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for GroupCanRead
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GroupCanReadTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.GroupCanRead = expected;
- actual = target.GroupCanRead;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for GroupCanWrite
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GroupCanWriteTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.GroupCanWrite = expected;
- actual = target.GroupCanWrite;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for GroupId
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GroupIdTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- target.GroupId = expected;
- actual = target.GroupId;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for IsBlockDevice
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void IsBlockDeviceTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.IsBlockDevice;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for IsCharacterDevice
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void IsCharacterDeviceTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.IsCharacterDevice;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for IsDirectory
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void IsDirectoryTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.IsDirectory;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for IsNamedPipe
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void IsNamedPipeTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.IsNamedPipe;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for IsRegularFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void IsRegularFileTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.IsRegularFile;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for IsSocket
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void IsSocketTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.IsSocket;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for IsSymbolicLink
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void IsSymbolicLinkTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.IsSymbolicLink;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for LastAccessTime
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void LastAccessTimeTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- DateTime expected = new DateTime(); // TODO: Initialize to an appropriate value
- DateTime actual;
- target.LastAccessTime = expected;
- actual = target.LastAccessTime;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for LastAccessTimeUtc
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void LastAccessTimeUtcTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- DateTime expected = new DateTime(); // TODO: Initialize to an appropriate value
- DateTime actual;
- target.LastAccessTimeUtc = expected;
- actual = target.LastAccessTimeUtc;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for LastWriteTime
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void LastWriteTimeTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- DateTime expected = new DateTime(); // TODO: Initialize to an appropriate value
- DateTime actual;
- target.LastWriteTime = expected;
- actual = target.LastWriteTime;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for LastWriteTimeUtc
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void LastWriteTimeUtcTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- DateTime expected = new DateTime(); // TODO: Initialize to an appropriate value
- DateTime actual;
- target.LastWriteTimeUtc = expected;
- actual = target.LastWriteTimeUtc;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Length
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void LengthTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- long actual;
- actual = target.Length;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OthersCanExecute
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OthersCanExecuteTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OthersCanExecute = expected;
- actual = target.OthersCanExecute;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OthersCanRead
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OthersCanReadTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OthersCanRead = expected;
- actual = target.OthersCanRead;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OthersCanWrite
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OthersCanWriteTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OthersCanWrite = expected;
- actual = target.OthersCanWrite;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OwnerCanExecute
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OwnerCanExecuteTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OwnerCanExecute = expected;
- actual = target.OwnerCanExecute;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OwnerCanRead
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OwnerCanReadTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OwnerCanRead = expected;
- actual = target.OwnerCanRead;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OwnerCanWrite
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OwnerCanWriteTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- target.OwnerCanWrite = expected;
- actual = target.OwnerCanWrite;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for UserId
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void UserIdTest()
- {
- SftpSession sftpSession = null; // TODO: Initialize to an appropriate value
- string fullName = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes attributes = null; // TODO: Initialize to an appropriate value
- SftpFile target = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
- int expected = 0; // TODO: Initialize to an appropriate value
- int actual;
- target.UserId = expected;
- actual = target.UserId;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpListDirectoryAsyncResultTest.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpListDirectoryAsyncResultTest.cs
deleted file mode 100644
index 8195330a9..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpListDirectoryAsyncResultTest.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using Renci.SshNet.Sftp;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests
-{
- ///
- ///This is a test class for SftpListDirectoryAsyncResultTest and is intended
- ///to contain all SftpListDirectoryAsyncResultTest Unit Tests
- ///
- [TestClass]
- public class SftpListDirectoryAsyncResultTest : TestBase
- {
- ///
- ///A test for SftpListDirectoryAsyncResult Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void SftpListDirectoryAsyncResultConstructorTest()
- {
- AsyncCallback asyncCallback = null; // TODO: Initialize to an appropriate value
- object state = null; // TODO: Initialize to an appropriate value
- SftpListDirectoryAsyncResult target = new SftpListDirectoryAsyncResult(asyncCallback, state);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpSynchronizeDirectoriesAsyncResultTest.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpSynchronizeDirectoriesAsyncResultTest.cs
deleted file mode 100644
index a2230ea05..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpSynchronizeDirectoriesAsyncResultTest.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Sftp;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- ///
- ///This is a test class for SftpSynchronizeDirectoriesAsyncResultTest and is intended
- ///to contain all SftpSynchronizeDirectoriesAsyncResultTest Unit Tests
- ///
- [TestClass]
- public class SftpSynchronizeDirectoriesAsyncResultTest : TestBase
- {
- ///
- ///A test for SftpSynchronizeDirectoriesAsyncResult Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void SftpSynchronizeDirectoriesAsyncResultConstructorTest()
- {
- AsyncCallback asyncCallback = null; // TODO: Initialize to an appropriate value
- object state = null; // TODO: Initialize to an appropriate value
- SftpSynchronizeDirectoriesAsyncResult target = new SftpSynchronizeDirectoriesAsyncResult(asyncCallback, state);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpUploadAsyncResultTest.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpUploadAsyncResultTest.cs
deleted file mode 100644
index 20cd7dc89..000000000
--- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpUploadAsyncResultTest.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Sftp;
-using Renci.SshNet.Tests.Common;
-
-namespace Renci.SshNet.Tests.Classes.Sftp
-{
- ///
- ///This is a test class for SftpUploadAsyncResultTest and is intended
- ///to contain all SftpUploadAsyncResultTest Unit Tests
- ///
- [TestClass]
- public class SftpUploadAsyncResultTest : TestBase
- {
- ///
- ///A test for SftpUploadAsyncResult Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder
- public void SftpUploadAsyncResultConstructorTest()
- {
- AsyncCallback asyncCallback = null; // TODO: Initialize to an appropriate value
- object state = null; // TODO: Initialize to an appropriate value
- SftpUploadAsyncResult target = new SftpUploadAsyncResult(asyncCallback, state);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.CreateDirectory.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest.CreateDirectory.cs
deleted file mode 100644
index 2c6284a6a..000000000
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.CreateDirectory.cs
+++ /dev/null
@@ -1,104 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
- ///
- public partial class SftpClientTest
- {
- [TestMethod]
- [TestCategory("Sftp")]
- [ExpectedException(typeof(SshConnectionException))]
- public void Test_Sftp_CreateDirectory_Without_Connecting()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.CreateDirectory("test");
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
- public void Test_Sftp_CreateDirectory_In_Current_Location()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.Connect();
-
- sftp.CreateDirectory("test");
-
- sftp.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
- [ExpectedException(typeof(SftpPermissionDeniedException))]
- public void Test_Sftp_CreateDirectory_In_Forbidden_Directory()
- {
- if (Resources.USERNAME == "root")
- Assert.Fail("Must not run this test as root!");
-
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.Connect();
-
- sftp.CreateDirectory("/sbin/test");
-
- sftp.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
- [ExpectedException(typeof(SftpPathNotFoundException))]
- public void Test_Sftp_CreateDirectory_Invalid_Path()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.Connect();
-
- sftp.CreateDirectory("/abcdefg/abcefg");
-
- sftp.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
- [ExpectedException(typeof(SshException))]
- public void Test_Sftp_CreateDirectory_Already_Exists()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.Connect();
-
- sftp.CreateDirectory("test");
-
- sftp.CreateDirectory("test");
-
- sftp.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [Description("Test passing null to CreateDirectory.")]
- [ExpectedException(typeof(ArgumentException))]
- public void Test_Sftp_CreateDirectory_Null()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.CreateDirectory(null);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest.cs
deleted file mode 100644
index f562f66bb..000000000
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.cs
+++ /dev/null
@@ -1,1414 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Sftp;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Security.Cryptography;
-using System.Text;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
- ///
- [TestClass]
- public partial class SftpClientTest : TestBase
- {
- private Random _random;
-
- [TestInitialize]
- public void SetUp()
- {
- _random = new Random();
- }
-
- [TestMethod]
- public void OperationTimeout_Default()
- {
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new SftpClient(connectionInfo);
-
- var actual = target.OperationTimeout;
-
- Assert.AreEqual(TimeSpan.FromMilliseconds(-1), actual);
- }
-
- [TestMethod]
- public void OperationTimeout_InsideLimits()
- {
- var operationTimeout = TimeSpan.FromMilliseconds(_random.Next(0, int.MaxValue - 1));
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new SftpClient(connectionInfo)
- {
- OperationTimeout = operationTimeout
- };
-
- var actual = target.OperationTimeout;
-
- Assert.AreEqual(operationTimeout, actual);
- }
-
- [TestMethod]
- public void OperationTimeout_LowerLimit()
- {
- var operationTimeout = TimeSpan.FromMilliseconds(-1);
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new SftpClient(connectionInfo)
- {
- OperationTimeout = operationTimeout
- };
-
- var actual = target.OperationTimeout;
-
- Assert.AreEqual(operationTimeout, actual);
- }
-
- [TestMethod]
- public void OperationTimeout_UpperLimit()
- {
- var operationTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new SftpClient(connectionInfo)
- {
- OperationTimeout = operationTimeout
- };
-
- var actual = target.OperationTimeout;
-
- Assert.AreEqual(operationTimeout, actual);
- }
-
- [TestMethod]
- public void OperationTimeout_LessThanLowerLimit()
- {
- var operationTimeout = TimeSpan.FromMilliseconds(-2);
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new SftpClient(connectionInfo);
-
- try
- {
- target.OperationTimeout = operationTimeout;
- }
- catch (ArgumentOutOfRangeException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("The timeout must represent a value between -1 and Int32.MaxValue, inclusive." + Environment.NewLine + "Parameter name: " + ex.ParamName, ex.Message);
- Assert.AreEqual("value", ex.ParamName);
- }
- }
-
- [TestMethod]
- public void OperationTimeout_GreaterThanLowerLimit()
- {
- var operationTimeout = TimeSpan.FromMilliseconds(int.MaxValue).Add(TimeSpan.FromMilliseconds(1));
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new SftpClient(connectionInfo);
-
- try
- {
- target.OperationTimeout = operationTimeout;
- }
- catch (ArgumentOutOfRangeException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("The timeout must represent a value between -1 and Int32.MaxValue, inclusive." + Environment.NewLine + "Parameter name: " + ex.ParamName, ex.Message);
- Assert.AreEqual("value", ex.ParamName);
- }
- }
-
- [TestMethod]
- public void OperationTimeout_Disposed()
- {
- var connectionInfo = new PasswordConnectionInfo("host", 22, "admin", "pwd");
- var target = new SftpClient(connectionInfo);
- target.Dispose();
-
- // getter
- try
- {
- var actual = target.OperationTimeout;
- Assert.Fail("Should have failed, but returned: " + actual);
- }
- catch (ObjectDisposedException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual(typeof(SftpClient).FullName, ex.ObjectName);
- }
-
- // setter
- try
- {
- target.OperationTimeout = TimeSpan.FromMilliseconds(5);
- Assert.Fail();
- }
- catch (ObjectDisposedException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual(typeof(SftpClient).FullName, ex.ObjectName);
- }
- }
-
- ///
- ///A test for SftpClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SftpClientConstructorTest()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(host, username, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SftpClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SftpClientConstructorTest1()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(host, port, username, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SftpClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SftpClientConstructorTest2()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(host, username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SftpClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SftpClientConstructorTest3()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(host, port, username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SftpClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SftpClientConstructorTest4()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for ChangePermissions
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ChangePermissionsTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- short mode = 0; // TODO: Initialize to an appropriate value
- target.ChangePermissions(path, mode);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for ChangeDirectory
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ChangeDirectoryTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- target.ChangeDirectory(path);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for BeginUploadFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void BeginUploadFileTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- Stream input = null; // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- AsyncCallback asyncCallback = null; // TODO: Initialize to an appropriate value
- object state = null; // TODO: Initialize to an appropriate value
- Action uploadCallback = null; // TODO: Initialize to an appropriate value
- IAsyncResult expected = null; // TODO: Initialize to an appropriate value
- IAsyncResult actual;
- actual = target.BeginUploadFile(input, path, asyncCallback, state, uploadCallback);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for BeginUploadFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void BeginUploadFileTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- Stream input = null; // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- bool canOverride = false; // TODO: Initialize to an appropriate value
- AsyncCallback asyncCallback = null; // TODO: Initialize to an appropriate value
- object state = null; // TODO: Initialize to an appropriate value
- Action uploadCallback = null; // TODO: Initialize to an appropriate value
- IAsyncResult expected = null; // TODO: Initialize to an appropriate value
- IAsyncResult actual;
- actual = target.BeginUploadFile(input, path, canOverride, asyncCallback, state, uploadCallback);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for BeginSynchronizeDirectories
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void BeginSynchronizeDirectoriesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string sourcePath = string.Empty; // TODO: Initialize to an appropriate value
- string destinationPath = string.Empty; // TODO: Initialize to an appropriate value
- string searchPattern = string.Empty; // TODO: Initialize to an appropriate value
- AsyncCallback asyncCallback = null; // TODO: Initialize to an appropriate value
- object state = null; // TODO: Initialize to an appropriate value
- IAsyncResult expected = null; // TODO: Initialize to an appropriate value
- IAsyncResult actual;
- actual = target.BeginSynchronizeDirectories(sourcePath, destinationPath, searchPattern, asyncCallback, state);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for BeginListDirectory
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void BeginListDirectoryTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- AsyncCallback asyncCallback = null; // TODO: Initialize to an appropriate value
- object state = null; // TODO: Initialize to an appropriate value
- Action listCallback = null; // TODO: Initialize to an appropriate value
- IAsyncResult expected = null; // TODO: Initialize to an appropriate value
- IAsyncResult actual;
- actual = target.BeginListDirectory(path, asyncCallback, state, listCallback);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for BeginDownloadFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void BeginDownloadFileTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- Stream output = null; // TODO: Initialize to an appropriate value
- AsyncCallback asyncCallback = null; // TODO: Initialize to an appropriate value
- object state = null; // TODO: Initialize to an appropriate value
- Action downloadCallback = null; // TODO: Initialize to an appropriate value
- IAsyncResult expected = null; // TODO: Initialize to an appropriate value
- IAsyncResult actual;
- actual = target.BeginDownloadFile(path, output, asyncCallback, state, downloadCallback);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for AppendText
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AppendTextTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- StreamWriter expected = null; // TODO: Initialize to an appropriate value
- StreamWriter actual;
- actual = target.AppendText(path, encoding);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for AppendText
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AppendTextTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- StreamWriter expected = null; // TODO: Initialize to an appropriate value
- StreamWriter actual;
- actual = target.AppendText(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for AppendAllText
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AppendAllTextTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- string contents = string.Empty; // TODO: Initialize to an appropriate value
- target.AppendAllText(path, contents);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for AppendAllText
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AppendAllTextTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- string contents = string.Empty; // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- target.AppendAllText(path, contents, encoding);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for AppendAllLines
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AppendAllLinesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- IEnumerable contents = null; // TODO: Initialize to an appropriate value
- target.AppendAllLines(path, contents);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for AppendAllLines
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AppendAllLinesTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- IEnumerable contents = null; // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- target.AppendAllLines(path, contents, encoding);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for CreateText
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateTextTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- StreamWriter expected = null; // TODO: Initialize to an appropriate value
- StreamWriter actual;
- actual = target.CreateText(path, encoding);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CreateText
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateTextTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- StreamWriter expected = null; // TODO: Initialize to an appropriate value
- StreamWriter actual;
- actual = target.CreateText(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CreateDirectory
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateDirectoryTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- target.CreateDirectory(path);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Create
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- int bufferSize = 0; // TODO: Initialize to an appropriate value
- SftpFileStream expected = null; // TODO: Initialize to an appropriate value
- SftpFileStream actual;
- actual = target.Create(path, bufferSize);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Create
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileStream expected = null; // TODO: Initialize to an appropriate value
- SftpFileStream actual;
- actual = target.Create(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for EndSynchronizeDirectories
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EndSynchronizeDirectoriesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- IAsyncResult asyncResult = null; // TODO: Initialize to an appropriate value
- IEnumerable expected = null; // TODO: Initialize to an appropriate value
- IEnumerable actual;
- actual = target.EndSynchronizeDirectories(asyncResult);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for EndListDirectory
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EndListDirectoryTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- IAsyncResult asyncResult = null; // TODO: Initialize to an appropriate value
- IEnumerable expected = null; // TODO: Initialize to an appropriate value
- IEnumerable actual;
- actual = target.EndListDirectory(asyncResult);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for EndDownloadFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EndDownloadFileTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- IAsyncResult asyncResult = null; // TODO: Initialize to an appropriate value
- target.EndDownloadFile(asyncResult);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for DownloadFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DownloadFileTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- Stream output = null; // TODO: Initialize to an appropriate value
- Action downloadCallback = null; // TODO: Initialize to an appropriate value
- target.DownloadFile(path, output, downloadCallback);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for DeleteFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DeleteFileTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- target.DeleteFile(path);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for DeleteDirectory
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DeleteDirectoryTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- target.DeleteDirectory(path);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Delete
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void DeleteTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- target.Delete(path);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for GetLastAccessTimeUtc
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GetLastAccessTimeUtcTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- DateTime expected = new DateTime(); // TODO: Initialize to an appropriate value
- DateTime actual;
- actual = target.GetLastAccessTimeUtc(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for GetLastAccessTime
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GetLastAccessTimeTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- DateTime expected = new DateTime(); // TODO: Initialize to an appropriate value
- DateTime actual;
- actual = target.GetLastAccessTime(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for GetAttributes
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GetAttributesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes expected = null; // TODO: Initialize to an appropriate value
- SftpFileAttributes actual;
- actual = target.GetAttributes(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Get
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GetTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- SftpFile expected = null; // TODO: Initialize to an appropriate value
- SftpFile actual;
- actual = target.Get(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Exists
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ExistsTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- bool expected = false; // TODO: Initialize to an appropriate value
- bool actual;
- actual = target.Exists(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for EndUploadFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void EndUploadFileTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- IAsyncResult asyncResult = null; // TODO: Initialize to an appropriate value
- target.EndUploadFile(asyncResult);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for GetLastWriteTimeUtc
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GetLastWriteTimeUtcTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- DateTime expected = new DateTime(); // TODO: Initialize to an appropriate value
- DateTime actual;
- actual = target.GetLastWriteTimeUtc(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for GetLastWriteTime
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GetLastWriteTimeTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- DateTime expected = new DateTime(); // TODO: Initialize to an appropriate value
- DateTime actual;
- actual = target.GetLastWriteTime(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for GetStatus
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void GetStatusTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileSytemInformation expected = null; // TODO: Initialize to an appropriate value
- SftpFileSytemInformation actual;
- actual = target.GetStatus(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ListDirectory
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ListDirectoryTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- Action listCallback = null; // TODO: Initialize to an appropriate value
- IEnumerable expected = null; // TODO: Initialize to an appropriate value
- IEnumerable actual;
- actual = target.ListDirectory(path, listCallback);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Open
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OpenTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- FileMode mode = new FileMode(); // TODO: Initialize to an appropriate value
- SftpFileStream expected = null; // TODO: Initialize to an appropriate value
- SftpFileStream actual;
- actual = target.Open(path, mode);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Open
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OpenTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- FileMode mode = new FileMode(); // TODO: Initialize to an appropriate value
- FileAccess access = new FileAccess(); // TODO: Initialize to an appropriate value
- SftpFileStream expected = null; // TODO: Initialize to an appropriate value
- SftpFileStream actual;
- actual = target.Open(path, mode, access);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OpenRead
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OpenReadTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileStream expected = null; // TODO: Initialize to an appropriate value
- SftpFileStream actual;
- actual = target.OpenRead(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OpenText
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OpenTextTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- StreamReader expected = null; // TODO: Initialize to an appropriate value
- StreamReader actual;
- actual = target.OpenText(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OpenWrite
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OpenWriteTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileStream expected = null; // TODO: Initialize to an appropriate value
- SftpFileStream actual;
- actual = target.OpenWrite(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ReadAllBytes
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ReadAllBytesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- byte[] expected = null; // TODO: Initialize to an appropriate value
- byte[] actual;
- actual = target.ReadAllBytes(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ReadAllLines
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ReadAllLinesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- string[] expected = null; // TODO: Initialize to an appropriate value
- string[] actual;
- actual = target.ReadAllLines(path, encoding);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ReadAllLines
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ReadAllLinesTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- string[] expected = null; // TODO: Initialize to an appropriate value
- string[] actual;
- actual = target.ReadAllLines(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ReadAllText
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ReadAllTextTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- string expected = string.Empty; // TODO: Initialize to an appropriate value
- string actual;
- actual = target.ReadAllText(path, encoding);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ReadAllText
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ReadAllTextTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- string expected = string.Empty; // TODO: Initialize to an appropriate value
- string actual;
- actual = target.ReadAllText(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ReadLines
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ReadLinesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- IEnumerable expected = null; // TODO: Initialize to an appropriate value
- IEnumerable actual;
- actual = target.ReadLines(path);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ReadLines
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ReadLinesTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- IEnumerable expected = null; // TODO: Initialize to an appropriate value
- IEnumerable actual;
- actual = target.ReadLines(path, encoding);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for RenameFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void RenameFileTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string oldPath = string.Empty; // TODO: Initialize to an appropriate value
- string newPath = string.Empty; // TODO: Initialize to an appropriate value
- target.RenameFile(oldPath, newPath);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for RenameFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void RenameFileTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string oldPath = string.Empty; // TODO: Initialize to an appropriate value
- string newPath = string.Empty; // TODO: Initialize to an appropriate value
- bool isPosix = false; // TODO: Initialize to an appropriate value
- target.RenameFile(oldPath, newPath, isPosix);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for SetAttributes
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SetAttributesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- SftpFileAttributes fileAttributes = null; // TODO: Initialize to an appropriate value
- target.SetAttributes(path, fileAttributes);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for SetLastAccessTime
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SetLastAccessTimeTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- DateTime lastAccessTime = new DateTime(); // TODO: Initialize to an appropriate value
-#pragma warning disable CS0618 // Type or member is obsolete
- target.SetLastAccessTime(path, lastAccessTime);
-#pragma warning restore CS0618 // Type or member is obsolete
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for SetLastAccessTimeUtc
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SetLastAccessTimeUtcTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- DateTime lastAccessTimeUtc = new DateTime(); // TODO: Initialize to an appropriate value
-#pragma warning disable CS0618 // Type or member is obsolete
- target.SetLastAccessTimeUtc(path, lastAccessTimeUtc);
-#pragma warning restore CS0618 // Type or member is obsolete
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for SetLastWriteTime
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SetLastWriteTimeTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- DateTime lastWriteTime = new DateTime(); // TODO: Initialize to an appropriate value
-#pragma warning disable CS0618 // Type or member is obsolete
- target.SetLastWriteTime(path, lastWriteTime);
-#pragma warning restore CS0618 // Type or member is obsolete
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for SetLastWriteTimeUtc
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SetLastWriteTimeUtcTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- DateTime lastWriteTimeUtc = new DateTime(); // TODO: Initialize to an appropriate value
-#pragma warning disable CS0618 // Type or member is obsolete
- target.SetLastWriteTimeUtc(path, lastWriteTimeUtc);
-#pragma warning restore CS0618 // Type or member is obsolete
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for SymbolicLink
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SymbolicLinkTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- string linkPath = string.Empty; // TODO: Initialize to an appropriate value
- target.SymbolicLink(path, linkPath);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for SynchronizeDirectories
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SynchronizeDirectoriesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string sourcePath = string.Empty; // TODO: Initialize to an appropriate value
- string destinationPath = string.Empty; // TODO: Initialize to an appropriate value
- string searchPattern = string.Empty; // TODO: Initialize to an appropriate value
- IEnumerable expected = null; // TODO: Initialize to an appropriate value
- IEnumerable actual;
- actual = target.SynchronizeDirectories(sourcePath, destinationPath, searchPattern);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for UploadFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void UploadFileTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- Stream input = null; // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- Action uploadCallback = null; // TODO: Initialize to an appropriate value
- target.UploadFile(input, path, uploadCallback);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for UploadFile
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void UploadFileTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- Stream input = null; // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- bool canOverride = false; // TODO: Initialize to an appropriate value
- Action uploadCallback = null; // TODO: Initialize to an appropriate value
- target.UploadFile(input, path, canOverride, uploadCallback);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for WriteAllBytes
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void WriteAllBytesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- byte[] bytes = null; // TODO: Initialize to an appropriate value
- target.WriteAllBytes(path, bytes);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for WriteAllLines
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void WriteAllLinesTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- IEnumerable contents = null; // TODO: Initialize to an appropriate value
- target.WriteAllLines(path, contents);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for WriteAllLines
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void WriteAllLinesTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- string[] contents = null; // TODO: Initialize to an appropriate value
- target.WriteAllLines(path, contents);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for WriteAllLines
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void WriteAllLinesTest2()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- IEnumerable contents = null; // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- target.WriteAllLines(path, contents, encoding);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for WriteAllLines
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void WriteAllLinesTest3()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- string[] contents = null; // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- target.WriteAllLines(path, contents, encoding);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for WriteAllText
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void WriteAllTextTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- string contents = string.Empty; // TODO: Initialize to an appropriate value
- target.WriteAllText(path, contents);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for WriteAllText
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void WriteAllTextTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string path = string.Empty; // TODO: Initialize to an appropriate value
- string contents = string.Empty; // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- target.WriteAllText(path, contents, encoding);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for BufferSize
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void BufferSizeTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- uint expected = 0; // TODO: Initialize to an appropriate value
- uint actual;
- target.BufferSize = expected;
- actual = target.BufferSize;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for OperationTimeout
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void OperationTimeoutTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- TimeSpan expected = new TimeSpan(); // TODO: Initialize to an appropriate value
- TimeSpan actual;
- target.OperationTimeout = expected;
- actual = target.OperationTimeout;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for WorkingDirectory
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void WorkingDirectoryTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.WorkingDirectory;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- protected static string CalculateMD5(string fileName)
- {
- using (FileStream file = new FileStream(fileName, FileMode.Open))
- {
- MD5 md5 = new MD5CryptoServiceProvider();
- byte[] retVal = md5.ComputeHash(file);
- file.Close();
-
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < retVal.Length; i++)
- {
- sb.Append(retVal[i].ToString("x2"));
- }
- return sb.ToString();
- }
- }
-
- private static void RemoveAllFiles()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- client.Connect();
- client.RunCommand("rm -rf *");
- client.Disconnect();
- }
- }
-
- ///
- /// Helper class to help with upload and download testing
- ///
- private class TestInfo
- {
- public string RemoteFileName { get; set; }
-
- public string UploadedFileName { get; set; }
-
- public string DownloadedFileName { get; set; }
-
- //public ulong UploadedBytes { get; set; }
-
- //public ulong DownloadedBytes { get; set; }
-
- public FileStream UploadedFile { get; set; }
-
- public FileStream DownloadedFile { get; set; }
-
- public string UploadedHash { get; set; }
-
- public string DownloadedHash { get; set; }
-
- public SftpUploadAsyncResult UploadResult { get; set; }
-
- public SftpDownloadAsyncResult DownloadResult { get; set; }
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTestBase.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTestBase.cs
deleted file mode 100644
index 11657962c..000000000
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTestBase.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-using Moq;
-using Renci.SshNet.Sftp;
-
-namespace Renci.SshNet.Tests.Classes
-{
- public abstract class SftpClientTestBase : BaseClientTestBase
- {
- internal Mock _sftpResponseFactoryMock { get; private set; }
- internal Mock _sftpSessionMock { get; private set; }
-
- protected override void CreateMocks()
- {
- base.CreateMocks();
-
- _sftpResponseFactoryMock = new Mock(MockBehavior.Strict);
- _sftpSessionMock = new Mock(MockBehavior.Strict);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Connected.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Connected.cs
deleted file mode 100644
index 239c84931..000000000
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Connected.cs
+++ /dev/null
@@ -1,115 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-using Renci.SshNet.Sftp;
-
-namespace Renci.SshNet.Tests.Classes
-{
- [TestClass]
- public class SftpClientTest_Dispose_Connected : SftpClientTestBase
- {
- private SftpClient _sftpClient;
- private ConnectionInfo _connectionInfo;
- private int _operationTimeout;
-
- protected override void SetupData()
- {
- _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
- _operationTimeout = new Random().Next(1000, 10000);
- _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object);
- _sftpClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout);
- }
-
- protected override void SetupMocks()
- {
- var sequence = new MockSequence();
-
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSocketFactory())
- .Returns(_socketFactoryMock.Object);
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object))
- .Returns(_sessionMock.Object);
- _sessionMock.InSequence(sequence).Setup(p => p.Connect());
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSftpResponseFactory())
- .Returns(_sftpResponseFactoryMock.Object);
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object))
- .Returns(_sftpSessionMock.Object);
- _sftpSessionMock.InSequence(sequence).Setup(p => p.Connect());
- _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
- _sftpSessionMock.InSequence(sequence).Setup(p => p.Dispose());
- _sessionMock.InSequence(sequence).Setup(p => p.Dispose());
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _sftpClient.Connect();
- }
-
- protected override void Act()
- {
- _sftpClient.Dispose();
- }
-
- [TestMethod]
- public void CreateSftpMessageFactoryOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSftpResponseFactory(), Times.Once);
- }
-
- [TestMethod]
- public void CreateSftpSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(
- p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object),
- Times.Once);
- }
-
- [TestMethod]
- public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once);
- }
-
- [TestMethod]
- public void CreateSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object),
- Times.Once);
- }
-
- [TestMethod]
- public void DisconnectOnNetConfSessionShouldNeverBeInvoked()
- {
- _sftpSessionMock.Verify(p => p.Disconnect(), Times.Never);
- }
-
- [TestMethod]
- public void DisconnectOnSessionShouldNeverBeInvoked()
- {
- _sessionMock.Verify(p => p.Disconnect(), Times.Never);
- }
-
- [TestMethod]
- public void DisposeOnNetConfSessionShouldBeInvokedOnce()
- {
- _sftpSessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void DisposeOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void OnDisconnectingOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disconnected.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disconnected.cs
deleted file mode 100644
index 192c5e957..000000000
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disconnected.cs
+++ /dev/null
@@ -1,117 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-using Renci.SshNet.Sftp;
-
-namespace Renci.SshNet.Tests.Classes
-{
- [TestClass]
- public class SftpClientTest_Dispose_Disconnected : SftpClientTestBase
- {
- private SftpClient _sftpClient;
- private ConnectionInfo _connectionInfo;
-
- private int _operationTimeout;
-
- protected override void SetupData()
- {
- _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
- _operationTimeout = new Random().Next(1000, 10000);
- _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object);
- _sftpClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout);
- }
-
- protected override void SetupMocks()
- {
- var sequence = new MockSequence();
-
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSocketFactory())
- .Returns(_socketFactoryMock.Object);
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object))
- .Returns(_sessionMock.Object);
- _sessionMock.InSequence(sequence).Setup(p => p.Connect());
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSftpResponseFactory())
- .Returns(_sftpResponseFactoryMock.Object);
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object))
- .Returns(_sftpSessionMock.Object);
- _sftpSessionMock.InSequence(sequence).Setup(p => p.Connect());
- _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
- _sftpSessionMock.InSequence(sequence).Setup(p => p.Dispose());
- _sessionMock.InSequence(sequence).Setup(p => p.Dispose());
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _sftpClient.Connect();
- _sftpClient.Disconnect();
- }
-
- protected override void Act()
- {
- _sftpClient.Dispose();
- }
-
- [TestMethod]
- public void CreateSftpMessageFactoryOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSftpResponseFactory(), Times.Once);
- }
-
- [TestMethod]
- public void CreateSftpSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(
- p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object),
- Times.Once);
- }
-
- [TestMethod]
- public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once);
- }
-
- [TestMethod]
- public void CreateSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object),
- Times.Once);
- }
-
- [TestMethod]
- public void DisconnectOnNetConfSessionShouldNeverBeInvoked()
- {
- _sftpSessionMock.Verify(p => p.Disconnect(), Times.Never);
- }
-
- [TestMethod]
- public void DisconnectOnSessionShouldNeverBeInvoked()
- {
- _sessionMock.Verify(p => p.Disconnect(), Times.Never);
- }
-
- [TestMethod]
- public void DisposeOnNetConfSessionShouldBeInvokedOnce()
- {
- _sftpSessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void DisposeOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void OnDisconnectingOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disposed.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disposed.cs
deleted file mode 100644
index 11e00ad03..000000000
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disposed.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-using Renci.SshNet.Sftp;
-
-namespace Renci.SshNet.Tests.Classes
-{
- [TestClass]
- public class SftpClientTest_Dispose_Disposed : SftpClientTestBase
- {
- private SftpClient _sftpClient;
- private ConnectionInfo _connectionInfo;
- private int _operationTimeout;
-
- protected override void SetupData()
- {
- _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
- _operationTimeout = new Random().Next(1000, 10000);
- _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object);
- _sftpClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout);
- }
-
- protected override void SetupMocks()
- {
- var sequence = new MockSequence();
-
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSocketFactory())
- .Returns(_socketFactoryMock.Object);
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object))
- .Returns(_sessionMock.Object);
- _sessionMock.InSequence(sequence).Setup(p => p.Connect());
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSftpResponseFactory())
- .Returns(_sftpResponseFactoryMock.Object);
- _serviceFactoryMock.InSequence(sequence)
- .Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object))
- .Returns(_sftpSessionMock.Object);
- _sftpSessionMock.InSequence(sequence).Setup(p => p.Connect());
- _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
- _sftpSessionMock.InSequence(sequence).Setup(p => p.Dispose());
- _sessionMock.InSequence(sequence).Setup(p => p.Dispose());
- }
-
- protected override void Arrange()
- {
- base.Arrange();
-
- _sftpClient.Connect();
- _sftpClient.Dispose();
- }
-
- protected override void Act()
- {
- _sftpClient.Dispose();
- }
-
- [TestMethod]
- public void CreateSftpMessageFactoryOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSftpResponseFactory(), Times.Once);
- }
-
- [TestMethod]
- public void CreateSftpSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(
- p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object),
- Times.Once);
- }
-
- [TestMethod]
- public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once);
- }
-
- [TestMethod]
- public void CreateSessionOnServiceFactoryShouldBeInvokedOnce()
- {
- _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object),
- Times.Once);
- }
-
- [TestMethod]
- public void DisconnectOnNetConfSessionShouldNeverBeInvoked()
- {
- _sftpSessionMock.Verify(p => p.Disconnect(), Times.Never);
- }
-
- [TestMethod]
- public void DisconnectOnSessionShouldNeverBeInvoked()
- {
- _sessionMock.Verify(p => p.Disconnect(), Times.Never);
- }
-
- [TestMethod]
- public void DisposeOnNetConfSessionShouldBeInvokedOnce()
- {
- _sftpSessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void DisposeOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.Dispose(), Times.Once);
- }
-
- [TestMethod]
- public void OnDisconnectingOnSessionShouldBeInvokedOnce()
- {
- _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once);
- }
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/ShellTestTest.cs b/src/Renci.SshNet.Tests/Classes/ShellTestTest.cs
deleted file mode 100644
index c7eceb1e6..000000000
--- a/src/Renci.SshNet.Tests/Classes/ShellTestTest.cs
+++ /dev/null
@@ -1,82 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-using System.Collections.Generic;
-using System.IO;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Represents instance of the SSH shell object
- ///
- [TestClass]
- [Ignore] // class contains just for unit tests
- public partial class ShellTestTest : TestBase
- {
- ///
- ///A test for Dispose
- ///
- [TestMethod()]
- public void DisposeTest()
- {
- Session session = null; // TODO: Initialize to an appropriate value
- Stream input = null; // TODO: Initialize to an appropriate value
- Stream output = null; // TODO: Initialize to an appropriate value
- Stream extendedOutput = null; // TODO: Initialize to an appropriate value
- string terminalName = string.Empty; // TODO: Initialize to an appropriate value
- uint columns = 0; // TODO: Initialize to an appropriate value
- uint rows = 0; // TODO: Initialize to an appropriate value
- uint width = 0; // TODO: Initialize to an appropriate value
- uint height = 0; // TODO: Initialize to an appropriate value
- IDictionary terminalModes = null; // TODO: Initialize to an appropriate value
- int bufferSize = 0; // TODO: Initialize to an appropriate value
- Shell target = new Shell(session, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize); // TODO: Initialize to an appropriate value
- target.Dispose();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Start
- ///
- [TestMethod()]
- public void StartTest()
- {
- Session session = null; // TODO: Initialize to an appropriate value
- Stream input = null; // TODO: Initialize to an appropriate value
- Stream output = null; // TODO: Initialize to an appropriate value
- Stream extendedOutput = null; // TODO: Initialize to an appropriate value
- string terminalName = string.Empty; // TODO: Initialize to an appropriate value
- uint columns = 0; // TODO: Initialize to an appropriate value
- uint rows = 0; // TODO: Initialize to an appropriate value
- uint width = 0; // TODO: Initialize to an appropriate value
- uint height = 0; // TODO: Initialize to an appropriate value
- IDictionary terminalModes = null; // TODO: Initialize to an appropriate value
- int bufferSize = 0; // TODO: Initialize to an appropriate value
- Shell target = new Shell(session, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize); // TODO: Initialize to an appropriate value
- target.Start();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for Stop
- ///
- [TestMethod()]
- public void StopTest()
- {
- Session session = null; // TODO: Initialize to an appropriate value
- Stream input = null; // TODO: Initialize to an appropriate value
- Stream output = null; // TODO: Initialize to an appropriate value
- Stream extendedOutput = null; // TODO: Initialize to an appropriate value
- string terminalName = string.Empty; // TODO: Initialize to an appropriate value
- uint columns = 0; // TODO: Initialize to an appropriate value
- uint rows = 0; // TODO: Initialize to an appropriate value
- uint width = 0; // TODO: Initialize to an appropriate value
- uint height = 0; // TODO: Initialize to an appropriate value
- IDictionary terminalModes = null; // TODO: Initialize to an appropriate value
- int bufferSize = 0; // TODO: Initialize to an appropriate value
- Shell target = new Shell(session, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize); // TODO: Initialize to an appropriate value
- target.Stop();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/SshClientTest.cs b/src/Renci.SshNet.Tests/Classes/SshClientTest.cs
deleted file mode 100644
index 78f1db6c4..000000000
--- a/src/Renci.SshNet.Tests/Classes/SshClientTest.cs
+++ /dev/null
@@ -1,945 +0,0 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Text;
-using System.Linq;
-
-namespace Renci.SshNet.Tests.Classes
-{
- ///
- /// Provides client connection to SSH server.
- ///
- [TestClass]
- public class SshClientTest : TestBase
- {
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- public void Test_Connect_Using_Correct_Password()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
-
- #region Example SshClient(host, username) Connect
- using (var client = new SshClient(host, username, password))
- {
- client.Connect();
- // Do something here
- client.Disconnect();
- }
- #endregion
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- public void Test_Connect_Handle_HostKeyReceived()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
- var hostKeyValidated = false;
-
- #region Example SshClient Connect HostKeyReceived
- using (var client = new SshClient(host, username, password))
- {
- client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
- {
- hostKeyValidated = true;
-
- if (e.FingerPrint.SequenceEqual(new byte[] { 0x00, 0x01, 0x02, 0x03 }))
- {
- e.CanTrust = true;
- }
- else
- {
- e.CanTrust = false;
- }
- };
- client.Connect();
- // Do something here
- client.Disconnect();
- }
- #endregion
-
- Assert.IsTrue(hostKeyValidated);
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- public void Test_Connect_Timeout()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
-
- #region Example SshClient Connect Timeout
- var connectionInfo = new PasswordConnectionInfo(host, username, password);
-
- connectionInfo.Timeout = TimeSpan.FromSeconds(30);
-
- using (var client = new SshClient(connectionInfo))
- {
- client.Connect();
- // Do something here
- client.Disconnect();
- }
- #endregion
- Assert.Inconclusive();
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- public void Test_Connect_Handle_ErrorOccurred()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
- var exceptionOccured = false;
-
- #region Example SshClient Connect ErrorOccurred
- using (var client = new SshClient(host, username, password))
- {
- client.ErrorOccurred += delegate(object sender, ExceptionEventArgs e)
- {
- Console.WriteLine("Error occured: " + e.Exception);
- exceptionOccured = true;
- };
-
- client.Connect();
- // Do something here
- client.Disconnect();
- }
- #endregion
- Assert.IsTrue(exceptionOccured);
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- [ExpectedException(typeof(SshAuthenticationException))]
- public void Test_Connect_Using_Invalid_Password()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- public void Test_Connect_Using_Rsa_Key_Without_PassPhrase()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- MemoryStream keyFileStream = new MemoryStream(Encoding.ASCII.GetBytes(Resources.RSA_KEY_WITHOUT_PASS));
-
- #region Example SshClient(host, username) Connect PrivateKeyFile
- using (var client = new SshClient(host, username, new PrivateKeyFile(keyFileStream)))
- {
- client.Connect();
- client.Disconnect();
- }
- #endregion
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- public void Test_Connect_Using_RsaKey_With_PassPhrase()
- {
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var passphrase = Resources.PASSWORD;
- MemoryStream keyFileStream = new MemoryStream(Encoding.ASCII.GetBytes(Resources.RSA_KEY_WITH_PASS));
-
- #region Example SshClient(host, username) Connect PrivateKeyFile PassPhrase
- using (var client = new SshClient(host, username, new PrivateKeyFile(keyFileStream, passphrase)))
- {
- client.Connect();
- client.Disconnect();
- }
- #endregion
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- [ExpectedException(typeof(SshPassPhraseNullOrEmptyException))]
- public void Test_Connect_Using_Key_With_Empty_PassPhrase()
- {
- MemoryStream keyFileStream = new MemoryStream(Encoding.ASCII.GetBytes(Resources.RSA_KEY_WITH_PASS));
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, new PrivateKeyFile(keyFileStream, null)))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- public void Test_Connect_Using_DsaKey_Without_PassPhrase()
- {
- MemoryStream keyFileStream = new MemoryStream(Encoding.ASCII.GetBytes(Resources.DSA_KEY_WITHOUT_PASS));
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, new PrivateKeyFile(keyFileStream)))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- public void Test_Connect_Using_DsaKey_With_PassPhrase()
- {
- MemoryStream keyFileStream = new MemoryStream(Encoding.ASCII.GetBytes(Resources.DSA_KEY_WITH_PASS));
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, new PrivateKeyFile(keyFileStream, Resources.PASSWORD)))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- [ExpectedException(typeof(SshAuthenticationException))]
- public void Test_Connect_Using_Invalid_PrivateKey()
- {
- MemoryStream keyFileStream = new MemoryStream(Encoding.ASCII.GetBytes(Resources.INVALID_KEY));
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, new PrivateKeyFile(keyFileStream)))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- public void Test_Connect_Using_Multiple_PrivateKeys()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME,
- new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(Resources.INVALID_KEY))),
- new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(Resources.DSA_KEY_WITH_PASS)), Resources.PASSWORD),
- new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(Resources.RSA_KEY_WITH_PASS)), Resources.PASSWORD),
- new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(Resources.RSA_KEY_WITHOUT_PASS))),
- new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(Resources.DSA_KEY_WITHOUT_PASS)))
- ))
- {
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- [TestCategory("Authentication")]
- [TestCategory("integration")]
- public void Test_Connect_Then_Reconnect()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- client.Connect();
- client.Disconnect();
- client.Connect();
- client.Disconnect();
- }
- }
-
- [TestMethod]
- public void CreateShellStream1_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- const string terminalName = "vt100";
- const uint columns = 80;
- const uint rows = 25;
- const uint width = 640;
- const uint height = 480;
- const int bufferSize = 4096;
-
- try
- {
- client.CreateShellStream(terminalName, columns, rows, width, height, bufferSize);
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
- [TestMethod]
- public void CreateShellStream2_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- const string terminalName = "vt100";
- const uint columns = 80;
- const uint rows = 25;
- const uint width = 640;
- const uint height = 480;
- var terminalModes = new Dictionary();
- const int bufferSize = 4096;
-
- try
- {
- client.CreateShellStream(terminalName, columns, rows, width, height, bufferSize, terminalModes);
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
- ///
- ///A test for CreateShellStream
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateShellStreamTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- string terminalName = string.Empty; // TODO: Initialize to an appropriate value
- uint columns = 0; // TODO: Initialize to an appropriate value
- uint rows = 0; // TODO: Initialize to an appropriate value
- uint width = 0; // TODO: Initialize to an appropriate value
- uint height = 0; // TODO: Initialize to an appropriate value
- int bufferSize = 0; // TODO: Initialize to an appropriate value
- IDictionary terminalModeValues = null; // TODO: Initialize to an appropriate value
- ShellStream expected = null; // TODO: Initialize to an appropriate value
- ShellStream actual;
- actual = target.CreateShellStream(terminalName, columns, rows, width, height, bufferSize, terminalModeValues);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CreateShellStream
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateShellStreamTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- string terminalName = string.Empty; // TODO: Initialize to an appropriate value
- uint columns = 0; // TODO: Initialize to an appropriate value
- uint rows = 0; // TODO: Initialize to an appropriate value
- uint width = 0; // TODO: Initialize to an appropriate value
- uint height = 0; // TODO: Initialize to an appropriate value
- int bufferSize = 0; // TODO: Initialize to an appropriate value
- ShellStream expected = null; // TODO: Initialize to an appropriate value
- ShellStream actual;
- actual = target.CreateShellStream(terminalName, columns, rows, width, height, bufferSize);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- [TestMethod]
- public void CreateShell1_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- var encoding = Encoding.UTF8;
- const string input = "INPUT";
- var output = new MemoryStream();
- var extendedOutput = new MemoryStream();
-
-
- try
- {
- client.CreateShell(encoding, input, output, extendedOutput);
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
- [TestMethod]
- public void CreateShell2_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- var encoding = Encoding.UTF8;
- const string input = "INPUT";
- var output = new MemoryStream();
- var extendedOutput = new MemoryStream();
- const string terminalName = "vt100";
- const uint columns = 80;
- const uint rows = 25;
- const uint width = 640;
- const uint height = 480;
- var terminalModes = new Dictionary();
-
- try
- {
- client.CreateShell(
- encoding,
- input,
- output,
- extendedOutput,
- terminalName,
- columns,
- rows,
- width,
- height,
- terminalModes);
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
- [TestMethod]
- public void CreateShell3_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- var encoding = Encoding.UTF8;
- const string input = "INPUT";
- var output = new MemoryStream();
- var extendedOutput = new MemoryStream();
- const string terminalName = "vt100";
- const uint columns = 80;
- const uint rows = 25;
- const uint width = 640;
- const uint height = 480;
- var terminalModes = new Dictionary();
- const int bufferSize = 4096;
-
- try
- {
-
- client.CreateShell(
- encoding,
- input,
- output,
- extendedOutput,
- terminalName,
- columns,
- rows,
- width,
- height,
- terminalModes,
- bufferSize);
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
- [TestMethod]
- public void CreateShell4_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- var input = new MemoryStream();
- var output = new MemoryStream();
- var extendedOutput = new MemoryStream();
-
- try
- {
-
- client.CreateShell(input, output, extendedOutput);
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
- [TestMethod]
- public void CreateShell5_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- var input = new MemoryStream();
- var output = new MemoryStream();
- var extendedOutput = new MemoryStream();
- const string terminalName = "vt100";
- const uint columns = 80;
- const uint rows = 25;
- const uint width = 640;
- const uint height = 480;
- var terminalModes = new Dictionary();
-
- try
- {
- client.CreateShell(
- input,
- output,
- extendedOutput,
- terminalName,
- columns,
- rows,
- width,
- height,
- terminalModes);
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
- [TestMethod]
- public void CreateShell6_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- var input = new MemoryStream();
- var output = new MemoryStream();
- var extendedOutput = new MemoryStream();
- const string terminalName = "vt100";
- const uint columns = 80;
- const uint rows = 25;
- const uint width = 640;
- const uint height = 480;
- var terminalModes = new Dictionary();
- const int bufferSize = 4096;
-
- try
- {
-
- client.CreateShell(
- input,
- output,
- extendedOutput,
- terminalName,
- columns,
- rows,
- width,
- height,
- terminalModes,
- bufferSize);
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
- ///
- ///A test for CreateShell
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateShellTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- string input = string.Empty; // TODO: Initialize to an appropriate value
- Stream output = null; // TODO: Initialize to an appropriate value
- Stream extendedOutput = null; // TODO: Initialize to an appropriate value
- Shell expected = null; // TODO: Initialize to an appropriate value
- Shell actual;
- actual = target.CreateShell(encoding, input, output, extendedOutput);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CreateShell
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateShellTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- string input = string.Empty; // TODO: Initialize to an appropriate value
- Stream output = null; // TODO: Initialize to an appropriate value
- Stream extendedOutput = null; // TODO: Initialize to an appropriate value
- string terminalName = string.Empty; // TODO: Initialize to an appropriate value
- uint columns = 0; // TODO: Initialize to an appropriate value
- uint rows = 0; // TODO: Initialize to an appropriate value
- uint width = 0; // TODO: Initialize to an appropriate value
- uint height = 0; // TODO: Initialize to an appropriate value
- IDictionary terminalModes = null; // TODO: Initialize to an appropriate value
- Shell expected = null; // TODO: Initialize to an appropriate value
- Shell actual;
- actual = target.CreateShell(encoding, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CreateShell
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateShellTest2()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- string input = string.Empty; // TODO: Initialize to an appropriate value
- Stream output = null; // TODO: Initialize to an appropriate value
- Stream extendedOutput = null; // TODO: Initialize to an appropriate value
- string terminalName = string.Empty; // TODO: Initialize to an appropriate value
- uint columns = 0; // TODO: Initialize to an appropriate value
- uint rows = 0; // TODO: Initialize to an appropriate value
- uint width = 0; // TODO: Initialize to an appropriate value
- uint height = 0; // TODO: Initialize to an appropriate value
- IDictionary terminalModes = null; // TODO: Initialize to an appropriate value
- int bufferSize = 0; // TODO: Initialize to an appropriate value
- Shell expected = null; // TODO: Initialize to an appropriate value
- Shell actual;
- actual = target.CreateShell(encoding, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CreateShell
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateShellTest3()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- Stream input = null; // TODO: Initialize to an appropriate value
- Stream output = null; // TODO: Initialize to an appropriate value
- Stream extendedOutput = null; // TODO: Initialize to an appropriate value
- Shell expected = null; // TODO: Initialize to an appropriate value
- Shell actual;
- actual = target.CreateShell(input, output, extendedOutput);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CreateShell
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateShellTest4()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- Stream input = null; // TODO: Initialize to an appropriate value
- Stream output = null; // TODO: Initialize to an appropriate value
- Stream extendedOutput = null; // TODO: Initialize to an appropriate value
- string terminalName = string.Empty; // TODO: Initialize to an appropriate value
- uint columns = 0; // TODO: Initialize to an appropriate value
- uint rows = 0; // TODO: Initialize to an appropriate value
- uint width = 0; // TODO: Initialize to an appropriate value
- uint height = 0; // TODO: Initialize to an appropriate value
- IDictionary terminalModes = null; // TODO: Initialize to an appropriate value
- Shell expected = null; // TODO: Initialize to an appropriate value
- Shell actual;
- actual = target.CreateShell(input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CreateShell
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateShellTest5()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- Stream input = null; // TODO: Initialize to an appropriate value
- Stream output = null; // TODO: Initialize to an appropriate value
- Stream extendedOutput = null; // TODO: Initialize to an appropriate value
- string terminalName = string.Empty; // TODO: Initialize to an appropriate value
- uint columns = 0; // TODO: Initialize to an appropriate value
- uint rows = 0; // TODO: Initialize to an appropriate value
- uint width = 0; // TODO: Initialize to an appropriate value
- uint height = 0; // TODO: Initialize to an appropriate value
- IDictionary terminalModes = null; // TODO: Initialize to an appropriate value
- int bufferSize = 0; // TODO: Initialize to an appropriate value
- Shell expected = null; // TODO: Initialize to an appropriate value
- Shell actual;
- actual = target.CreateShell(input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- [TestMethod]
- public void CreateCommand_CommandText_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- try
- {
- client.CreateCommand("ls");
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
- [TestMethod]
- public void CreateCommand_CommandTextAndEncoding_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- try
- {
- client.CreateCommand("ls", Encoding.UTF8);
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
- ///
- ///A test for CreateCommand
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateCommandTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- string commandText = string.Empty; // TODO: Initialize to an appropriate value
- Encoding encoding = null; // TODO: Initialize to an appropriate value
- SshCommand expected = null; // TODO: Initialize to an appropriate value
- SshCommand actual;
- actual = target.CreateCommand(commandText, encoding);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CreateCommand
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CreateCommandTest1()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- string commandText = string.Empty; // TODO: Initialize to an appropriate value
- SshCommand expected = null; // TODO: Initialize to an appropriate value
- SshCommand actual;
- actual = target.CreateCommand(commandText);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
-
- [TestMethod]
- public void AddForwardedPort_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- var port = new ForwardedPortLocal(50, "host", 8080);
-
- try
- {
- client.AddForwardedPort(port);
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
-
- ///
- ///A test for AddForwardedPort
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void AddForwardedPortTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- ForwardedPort port = null; // TODO: Initialize to an appropriate value
- target.AddForwardedPort(port);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- ///
- ///A test for SshClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SshClientConstructorTest()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(host, username, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SshClientConstructorTest1()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(host, port, username, keyFiles);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SshClientConstructorTest2()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(host, username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SshClientConstructorTest3()
- {
- string host = string.Empty; // TODO: Initialize to an appropriate value
- int port = 0; // TODO: Initialize to an appropriate value
- string username = string.Empty; // TODO: Initialize to an appropriate value
- string password = string.Empty; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(host, port, username, password);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for SshClient Constructor
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void SshClientConstructorTest4()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo);
- Assert.Inconclusive("TODO: Implement code to verify target");
- }
-
- ///
- ///A test for RemoveForwardedPort
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void RemoveForwardedPortTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- ForwardedPort port = null; // TODO: Initialize to an appropriate value
- target.RemoveForwardedPort(port);
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
- [TestMethod]
- public void RunCommand_CommandText_NeverConnected()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
- {
- try
- {
- client.RunCommand("ls");
- Assert.Fail();
- }
- catch (SshConnectionException ex)
- {
- Assert.IsNull(ex.InnerException);
- Assert.AreEqual("Client not connected.", ex.Message);
- }
- }
- }
-
- ///
- ///A test for RunCommand
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void RunCommandTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- string commandText = string.Empty; // TODO: Initialize to an appropriate value
- SshCommand expected = null; // TODO: Initialize to an appropriate value
- SshCommand actual;
- actual = target.RunCommand(commandText);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for ForwardedPorts
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ForwardedPortsTest()
- {
- ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
- SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
- IEnumerable actual;
- actual = target.ForwardedPorts;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_NeverConnected.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_NeverConnected.cs
deleted file mode 100644
index d784c7aed..000000000
--- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_NeverConnected.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Renci.SshNet.Tests.Classes
-{
- class SubsystemSession_Connect_NeverConnected
- {
- }
-}
diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_SendData_Disconnected.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_SendData_Disconnected.cs
deleted file mode 100644
index 6d60a61b2..000000000
--- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_SendData_Disconnected.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Renci.SshNet.Tests.Classes
-{
- class SubsystemSession_SendData_Disconnected
- {
- }
-}
diff --git a/src/Renci.SshNet.Tests/Data/Key.OPENSSH.ED25519.Encrypted.txt b/src/Renci.SshNet.Tests/Data/Key.OPENSSH.ED25519.Encrypted.txt
deleted file mode 100644
index 50b4d9689..000000000
--- a/src/Renci.SshNet.Tests/Data/Key.OPENSSH.ED25519.Encrypted.txt
+++ /dev/null
@@ -1,9 +0,0 @@
------BEGIN OPENSSH PRIVATE KEY-----
-b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jYmMAAAAGYmNyeXB0AAAAGAAAABBg
-HWh+J0IG6OfYxD74SoT9AAAAEAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIGFd
-yflleGqSPOhgSYZf7ZQFlG0zEL9VDGC69UbtaaByAAAAoDLm8u8wFwlqjzZRfVxj
-wzGTYFJFtfkHRqfFBE4xKgknHNRbCT1OQb7rgE7nZbUXIlb1NCTZLbXti9AYNZpz
-ycvPD4Dc6lB03b8pNHoFVSkrCwxrWB5bKtIM4OZNcDK1lZDBEWE2aZXf9puRHbu3
-ccrK/F5GjRi2pUa8qnfqThN1mNPZwFTx4oSKeRaUMdeHBrNwDtaxq32A6Q4KHoYO
-KPM=
------END OPENSSH PRIVATE KEY-----
diff --git a/src/Renci.SshNet.Tests/Renci.SshNet.Tests.csproj b/src/Renci.SshNet.Tests/Renci.SshNet.Tests.csproj
deleted file mode 100644
index d7ee81e9a..000000000
--- a/src/Renci.SshNet.Tests/Renci.SshNet.Tests.csproj
+++ /dev/null
@@ -1,121 +0,0 @@
-
-
- true
- ..\Renci.SshNet.snk
-
-
-
- net35;net40;netcoreapp2.1;netcoreapp2.2
-
-
- net35;net40;netcoreapp2.1;netcoreapp2.2;netcoreapp3.0
-
-
-
-
-
-
- FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_TPL
-
-
- FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_TPL
-
-
- FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_TPL
-
-
- FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_TPL
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- $(MSBuildProgramFiles32)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
- $(MSTestV1UnitTestFrameworkAssemblyCandidate)
-
- $(MSBuildProgramFiles32)\Microsoft Visual Studio\2017\Professional\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
- $(MSTestV1UnitTestFrameworkAssemblyCandidate)
-
- $(MSBuildProgramFiles32)\Microsoft Visual Studio\2017\Community\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
- $(MSTestV1UnitTestFrameworkAssemblyCandidate)
-
-
-
-
- $(MSBuildProgramFiles32)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
- $(MSTestV1UnitTestFrameworkAssemblyCandidate)
-
- $(MSBuildProgramFiles32)\Microsoft Visual Studio\2019\Professional\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
- $(MSTestV1UnitTestFrameworkAssemblyCandidate)
-
- $(MSBuildProgramFiles32)\Microsoft Visual Studio\2019\Community\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
- $(MSTestV1UnitTestFrameworkAssemblyCandidate)
-
- $(MSBuildProgramFiles32)\Microsoft Visual Studio\2019\Preview\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
- $(MSTestV1UnitTestFrameworkAssemblyCandidate)
-
-
-
-
- $(MSTestV1UnitTestFrameworkAssembly)
-
-
-
-
-
- $(MSTestV1UnitTestFrameworkAssembly)
-
-
-
-
-
-
-
- 2.1.0
-
-
-
-
-
-
-
- 2.1.0
-
-
-
-
-
-
-
- 2.1.0
-
-
-
-
-
-
-
diff --git a/src/Renci.SshNet.UAP10/Properties/AssemblyInfo.cs b/src/Renci.SshNet.UAP10/Properties/AssemblyInfo.cs
deleted file mode 100644
index f71ba6793..000000000
--- a/src/Renci.SshNet.UAP10/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-
-[assembly: AssemblyTitle("SSH.NET UAP 10.0")]
-[assembly: InternalsVisibleTo("Renci.SshNet.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f9194e1eb66b7e2575aaee115ee1d27bc100920e7150e43992d6f668f9737de8b9c7ae892b62b8a36dd1d57929ff1541665d101dc476d6e02390846efae7e5186eec409710fdb596e3f83740afef0d4443055937649bc5a773175b61c57615dac0f0fd10f52b52fedf76c17474cc567b3f7a79de95dde842509fb39aaf69c6c2")]
-[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
-
-// https://github.com/dotnet/corefx/issues/7274
-//[assembly: Guid("4EE4F2DC-208D-42B2-B286-5E5DEC1DD766")]
\ No newline at end of file
diff --git a/src/Renci.SshNet.UAP10/Properties/Renci.SshNet.UAP10.rd.xml b/src/Renci.SshNet.UAP10/Properties/Renci.SshNet.UAP10.rd.xml
deleted file mode 100644
index ba5e1b0ac..000000000
--- a/src/Renci.SshNet.UAP10/Properties/Renci.SshNet.UAP10.rd.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
-
-
-
-
-
-
diff --git a/src/Renci.SshNet.UAP10/Renci.SshNet.UAP10.csproj b/src/Renci.SshNet.UAP10/Renci.SshNet.UAP10.csproj
deleted file mode 100644
index d0eb423a2..000000000
--- a/src/Renci.SshNet.UAP10/Renci.SshNet.UAP10.csproj
+++ /dev/null
@@ -1,1523 +0,0 @@
-
-
-
-
- Debug
- AnyCPU
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}
- Library
- Properties
- Renci.SshNet
- Renci.SshNet
- en-US
- UAP
- 10.0.10240.0
- 10.0.10240.0
- 14
- 512
- {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
-
-
- AnyCPU
- true
- full
- false
- bin\Debug\
- TRACE;DEBUG;FEATURE_STRINGBUILDER_CLEAR;FEATURE_HASHALGORITHM_DISPOSE;FEATURE_DATAGRAMSOCKET;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_TAP;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_TAP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_TRYGETBUFFER;FEATURE_REFLECTION_TYPEINFO;FEATURE_ENCODING_ASCII
- prompt
- 4
- bin\Debug\Renci.SshNet.xml
- true
-
-
- AnyCPU
- pdbonly
- true
- bin\Release\
- TRACE;FEATURE_STRINGBUILDER_CLEAR;FEATURE_HASHALGORITHM_DISPOSE;FEATURE_DATAGRAMSOCKET;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_TAP;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_TAP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_TRYGETBUFFER;FEATURE_REFLECTION_TYPEINFO;FEATURE_ENCODING_ASCII
- prompt
- 4
- bin\Release\Renci.SshNet.xml
- true
-
-
- x86
- true
- bin\x86\Debug\
- TRACE;DEBUG;FEATURE_DATAGRAMSOCKET;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_TAP;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_TAP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_TRYGETBUFFER;FEATURE_REFLECTION_TYPEINFO;FEATURE_ENCODING_ASCII
- ;2008
- full
- x86
- false
- prompt
-
-
- x86
- bin\x86\Release\
- TRACE;FEATURE_DATAGRAMSOCKET;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_TAP;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_TAP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_TRYGETBUFFER;FEATURE_REFLECTION_TYPEINFO;FEATURE_ENCODING_ASCII
- true
- ;2008
- pdbonly
- x86
- false
- prompt
-
-
- ARM
- true
- bin\ARM\Debug\
- TRACE;DEBUG;FEATURE_DATAGRAMSOCKET;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_TAP;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_TAP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_TRYGETBUFFER;FEATURE_REFLECTION_TYPEINFO;FEATURE_ENCODING_ASCII
- ;2008
- full
- ARM
- false
- prompt
-
-
- ARM
- bin\ARM\Release\
- TRACE;FEATURE_DATAGRAMSOCKET;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_TAP;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_TAP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_TRYGETBUFFER;FEATURE_REFLECTION_TYPEINFO;FEATURE_ENCODING_ASCII
- true
- ;2008
- pdbonly
- ARM
- false
- prompt
-
-
- x64
- true
- bin\x64\Debug\
- TRACE;DEBUG;FEATURE_DATAGRAMSOCKET;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_TAP;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_TAP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_TRYGETBUFFER;FEATURE_REFLECTION_TYPEINFO;FEATURE_ENCODING_ASCII
- ;2008
- full
- x64
- false
- prompt
-
-
- x64
- bin\x64\Release\
- TRACE;FEATURE_DATAGRAMSOCKET;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_TAP;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_TAP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_TRYGETBUFFER;FEATURE_REFLECTION_TYPEINFO;FEATURE_ENCODING_ASCII
- true
- ;2008
- pdbonly
- x64
- false
- prompt
-
-
-
-
-
-
-
- Abstractions\CryptoAbstraction.cs
-
-
- Abstractions\DiagnosticAbstraction.cs
-
-
- Abstractions\DnsAbstraction.cs
-
-
- Abstractions\FileSystemAbstraction.cs
-
-
- Abstractions\ReflectionAbstraction.cs
-
-
- Abstractions\SocketAbstraction.cs
-
-
- Abstractions\ThreadAbstraction.cs
-
-
- AuthenticationMethod.cs
-
-
- AuthenticationResult.cs
-
-
- BaseClient.cs
-
-
- Channels\Channel.cs
-
-
- Channels\ChannelDirectTcpip.cs
-
-
- Channels\ChannelForwardedTcpip.cs
-
-
- Channels\ChannelSession.cs
-
-
- Channels\ChannelTypes.cs
-
-
- Channels\ClientChannel.cs
-
-
- Channels\IChannel.cs
-
-
- Channels\IChannelDirectTcpip.cs
-
-
- Channels\IChannelForwardedTcpip.cs
-
-
- Channels\IChannelSession.cs
-
-
- Channels\ServerChannel.cs
-
-
- CipherInfo.cs
-
-
- ClientAuthentication.cs
-
-
- CommandAsyncResult.cs
-
-
- Common\Array.cs
-
-
- Common\ASCIIEncoding.cs
-
-
- Common\AsyncResult.cs
-
-
- Common\AuthenticationBannerEventArgs.cs
-
-
- Common\AuthenticationEventArgs.cs
-
-
- Common\AuthenticationPasswordChangeEventArgs.cs
-
-
- Common\AuthenticationPrompt.cs
-
-
- Common\AuthenticationPromptEventArgs.cs
-
-
- Common\BigInteger.cs
-
-
- Common\ChannelDataEventArgs.cs
-
-
- Common\ChannelEventArgs.cs
-
-
- Common\ChannelExtendedDataEventArgs.cs
-
-
- Common\ChannelOpenConfirmedEventArgs.cs
-
-
- Common\ChannelOpenFailedEventArgs.cs
-
-
- Common\ChannelRequestEventArgs.cs
-
-
- Common\CountdownEvent.cs
-
-
- Common\DerData.cs
-
-
- Common\ExceptionEventArgs.cs
-
-
- Common\Extensions.cs
-
-
- Common\HostKeyEventArgs.cs
-
-
- Common\NetConfServerException.cs
-
-
- Common\ObjectIdentifier.cs
-
-
- Common\Pack.cs
-
-
- Common\PacketDump.cs
-
-
- Common\PipeStream.cs
-
-
- Common\PortForwardEventArgs.cs
-
-
- Common\PosixPath.cs
-
-
- Common\ProxyException.cs
-
-
- Common\ScpDownloadEventArgs.cs
-
-
- Common\ScpException.cs
-
-
- Common\ScpUploadEventArgs.cs
-
-
- Common\SemaphoreLight.cs
-
-
- Common\SftpPathNotFoundException.cs
-
-
- Common\SftpPermissionDeniedException.cs
-
-
- Common\ShellDataEventArgs.cs
-
-
- Common\SshAuthenticationException.cs
-
-
- Common\SshConnectionException.cs
-
-
- Common\SshData.cs
-
-
- Common\SshDataStream.cs
-
-
- Common\SshException.cs
-
-
- Common\SshOperationTimeoutException.cs
-
-
- Common\SshPassPhraseNullOrEmptyException.cs
-
-
- Common\TerminalModes.cs
-
-
- Compression\CompressionMode.cs
-
-
- Compression\Compressor.cs
-
-
- Compression\Zlib.cs
-
-
- Compression\ZlibOpenSsh.cs
-
-
- Compression\ZlibStream.cs
-
-
- ConnectionInfo.cs
-
-
- Connection\ConnectorBase.cs
-
-
- Connection\DirectConnector.cs
-
-
- Connection\HttpConnector.cs
-
-
- Connection\IConnector.cs
-
-
- Connection\IProtocolVersionExchange.cs
-
-
- Connection\ISocketFactory.cs
-
-
- Connection\ProtocolVersionExchange.cs
-
-
- Connection\SocketFactory.cs
-
-
- Connection\Socks4Connector.cs
-
-
- Connection\Socks5Connector.cs
-
-
- Connection\SshIdentification.cs
-
-
- ExpectAction.cs
-
-
- ExpectAsyncResult.cs
-
-
- ForwardedPort.cs
-
-
- ForwardedPortDynamic.cs
-
-
- ForwardedPortDynamic.NET.cs
-
-
- ForwardedPortLocal.cs
-
-
- ForwardedPortLocal.NET.cs
-
-
- ForwardedPortRemote.cs
-
-
- ForwardedPortStatus.cs
-
-
- HashInfo.cs
-
-
- IAuthenticationMethod.cs
-
-
- IClientAuthentication.cs
-
-
- IConnectionInfo.cs
-
-
- IForwardedPort.cs
-
-
- IRemotePathTransformation.cs
-
-
- IServiceFactory.cs
-
-
- IServiceFactory.NET.cs
-
-
- ISession.cs
-
-
- ISftpClient.cs
-
-
- ISubsystemSession.cs
-
-
- KeyboardInteractiveAuthenticationMethod.cs
-
-
- KeyboardInteractiveConnectionInfo.cs
-
-
- MessageEventArgs.cs
-
-
- Messages\Authentication\BannerMessage.cs
-
-
- Messages\Authentication\FailureMessage.cs
-
-
- Messages\Authentication\InformationRequestMessage.cs
-
-
- Messages\Authentication\InformationResponseMessage.cs
-
-
- Messages\Authentication\PasswordChangeRequiredMessage.cs
-
-
- Messages\Authentication\PublicKeyMessage.cs
-
-
- Messages\Authentication\RequestMessage.cs
-
-
- Messages\Authentication\RequestMessageHost.cs
-
-
- Messages\Authentication\RequestMessageKeyboardInteractive.cs
-
-
- Messages\Authentication\RequestMessageNone.cs
-
-
- Messages\Authentication\RequestMessagePassword.cs
-
-
- Messages\Authentication\RequestMessagePublicKey.cs
-
-
- Messages\Authentication\SuccessMessage.cs
-
-
- Messages\Connection\CancelTcpIpForwardGlobalRequestMessage.cs
-
-
- Messages\Connection\ChannelCloseMessage.cs
-
-
- Messages\Connection\ChannelDataMessage.cs
-
-
- Messages\Connection\ChannelEofMessage.cs
-
-
- Messages\Connection\ChannelExtendedDataMessage.cs
-
-
- Messages\Connection\ChannelFailureMessage.cs
-
-
- Messages\Connection\ChannelMessage.cs
-
-
- Messages\Connection\ChannelOpenConfirmationMessage.cs
-
-
- Messages\Connection\ChannelOpenFailureMessage.cs
-
-
- Messages\Connection\ChannelOpenFailureReasons.cs
-
-
- Messages\Connection\ChannelOpen\ChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelOpen\ChannelOpenMessage.cs
-
-
- Messages\Connection\ChannelOpen\DirectTcpipChannelInfo.cs
-
-
- Messages\Connection\ChannelOpen\ForwardedTcpipChannelInfo.cs
-
-
- Messages\Connection\ChannelOpen\SessionChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelOpen\X11ChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelRequest\BreakRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ChannelRequestMessage.cs
-
-
- Messages\Connection\ChannelRequest\EndOfWriteRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\EnvironmentVariableRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExecRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExitSignalRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExitStatusRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\KeepAliveRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\PseudoTerminalInfo.cs
-
-
- Messages\Connection\ChannelRequest\RequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ShellRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\SignalRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\SubsystemRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\WindowChangeRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\X11ForwardingRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\XonXoffRequestInfo.cs
-
-
- Messages\Connection\ChannelSuccessMessage.cs
-
-
- Messages\Connection\ChannelWindowAdjustMessage.cs
-
-
- Messages\Connection\GlobalRequestMessage.cs
-
-
- Messages\Connection\GlobalRequestName.cs
-
-
- Messages\Connection\RequestFailureMessage.cs
-
-
- Messages\Connection\RequestSuccessMessage.cs
-
-
- Messages\Connection\TcpIpForwardGlobalRequestMessage.cs
-
-
- Messages\Message.cs
-
-
- Messages\MessageAttribute.cs
-
-
- Messages\ServiceName.cs
-
-
- Messages\Transport\DebugMessage.cs
-
-
- Messages\Transport\DisconnectMessage.cs
-
-
- Messages\Transport\DisconnectReason.cs
-
-
- Messages\Transport\IgnoreMessage.cs
-
-
- Messages\Transport\IKeyExchangedAllowed.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeGroup.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeInit.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeReply.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeRequest.cs
-
-
- Messages\Transport\KeyExchangeDhInitMessage.cs
-
-
- Messages\Transport\KeyExchangeDhReplyMessage.cs
-
-
- Messages\Transport\KeyExchangeEcdhInitMessage.cs
-
-
- Messages\Transport\KeyExchangeEcdhReplyMessage.cs
-
-
- Messages\Transport\KeyExchangeInitMessage.cs
-
-
- Messages\Transport\NewKeysMessage.cs
-
-
- Messages\Transport\ServiceAcceptMessage.cs
-
-
- Messages\Transport\ServiceRequestMessage.cs
-
-
- Messages\Transport\UnimplementedMessage.cs
-
-
- NetConfClient.cs
-
-
- Netconf\INetConfSession.cs
-
-
- Netconf\NetConfSession.cs
-
-
- NoneAuthenticationMethod.cs
-
-
- PasswordAuthenticationMethod.cs
-
-
- PasswordConnectionInfo.cs
-
-
- PrivateKeyAuthenticationMethod.cs
-
-
- PrivateKeyConnectionInfo.cs
-
-
- PrivateKeyFile.cs
-
-
- Properties\CommonAssemblyInfo.cs
-
-
- ProxyTypes.cs
-
-
- RemotePathDoubleQuoteTransformation.cs
-
-
- RemotePathNoneTransformation.cs
-
-
- RemotePathShellQuoteTransformation.cs
-
-
- RemotePathTransformation.cs
-
-
- ScpClient.cs
-
-
- ScpClient.NET.cs
-
-
- Security\Algorithm.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\sec\SECNamedCurves.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9Curve.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECParameters.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECParametersHolder.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECPoint.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\agreement\ECDHCBasicAgreement.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\AsymmetricCipherKeyPair.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\AsymmetricKeyParameter.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\digests\GeneralDigest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\digests\Sha256Digest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\generators\ECKeyPairGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\IAsymmetricCipherKeyPairGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\IDigest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\KeyGenerationParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECDomainParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECKeyGenerationParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECPrivateKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECPublicKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\CryptoApiRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\DigestRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\IRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\util\Pack.cs
-
-
- Security\Cryptography\BouncyCastle\math\BigInteger.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\SimpleBigDecimal.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\Tnaf.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\ZTauElement.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECAlgorithms.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECCurve.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECFieldElement.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECLookupTable.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECPoint.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECPointMap.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\endo\ECEndomorphism.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\endo\GlvEndomorphism.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\LongArray.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\AbstractECMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\ECMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointCombMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\GlvMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\IPreCompCallback.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\PreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\ValidityPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafL2RMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WTauNafMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WTauNafPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\FiniteFields.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\GenericPolynomialExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\GF2Polynomial.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IFiniteField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IPolynomial.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IPolynomialExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\PrimeField.cs
-
-
- Security\Cryptography\BouncyCastle\math\raw\Mod.cs
-
-
- Security\Cryptography\BouncyCastle\math\raw\Nat.cs
-
-
- Security\Cryptography\BouncyCastle\security\DigestUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\security\SecureRandom.cs
-
-
- Security\Cryptography\BouncyCastle\security\SecurityUtilityException.cs
-
-
- Security\Cryptography\BouncyCastle\util\Arrays.cs
-
-
- Security\Cryptography\BouncyCastle\util\BigIntegers.cs
-
-
- Security\Cryptography\BouncyCastle\util\encoders\Hex.cs
-
-
- Security\Cryptography\BouncyCastle\util\encoders\HexEncoder.cs
-
-
- Security\Cryptography\BouncyCastle\util\IMemoable.cs
-
-
- Security\Cryptography\BouncyCastle\util\Integers.cs
-
-
- Security\Cryptography\BouncyCastle\util\MemoableResetException.cs
-
-
- Security\Cryptography\BouncyCastle\util\Times.cs
-
-
- Security\CertificateHostAlgorithm.cs
-
-
- Security\Cryptography\Chaos.NaCl\CryptoBytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Ed25519.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Array16.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Array8.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\ByteIntegerConverter.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\base.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\base2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\d.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\d2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_1.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_cmov.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_cswap.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_frombytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_invert.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_isnegative.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_isnonzero.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_mul.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_mul121666.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_neg.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_pow22523.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sq.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sq2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\FieldElement.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_double_scalarmult.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_frombytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_madd.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_msub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p1p1_to_p2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p1p1_to_p3.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p2_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p2_dbl.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_dbl.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_to_cached.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_to_p2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_precomp_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_scalarmult_base.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_sub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\GroupElement.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\keypair.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\open.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\scalarmult.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_clamp.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_mul_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_reduce.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sign.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sqrtm1.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\InternalAssert.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Poly1305Donna.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Salsa\Salsa20.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Salsa\SalsaCore.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Sha512Internal.cs
-
-
- Security\Cryptography\Chaos.NaCl\MontgomeryCurve25519.cs
-
-
- Security\Cryptography\Chaos.NaCl\Sha512.cs
-
-
- Security\Cryptography\AsymmetricCipher.cs
-
-
- Security\Cryptography\Bcrypt.cs
-
-
- Security\Cryptography\BlockCipher.cs
-
-
- Security\Cryptography\Cipher.cs
-
-
- Security\Cryptography\CipherDigitalSignature.cs
-
-
- Security\Cryptography\Ciphers\AesCipher.cs
-
-
- Security\Cryptography\Ciphers\Arc4Cipher.cs
-
-
- Security\Cryptography\Ciphers\BlowfishCipher.cs
-
-
- Security\Cryptography\Ciphers\CastCipher.cs
-
-
- Security\Cryptography\Ciphers\CipherMode.cs
-
-
- Security\Cryptography\Ciphers\CipherPadding.cs
-
-
- Security\Cryptography\Ciphers\DesCipher.cs
-
-
- Security\Cryptography\Ciphers\Modes\CbcCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\CfbCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\CtrCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\OfbCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Paddings\PKCS5Padding.cs
-
-
- Security\Cryptography\Ciphers\Paddings\PKCS7Padding.cs
-
-
- Security\Cryptography\Ciphers\RsaCipher.cs
-
-
- Security\Cryptography\Ciphers\SerpentCipher.cs
-
-
- Security\Cryptography\Ciphers\TripleDesCipher.cs
-
-
- Security\Cryptography\Ciphers\TwofishCipher.cs
-
-
- Security\Cryptography\DigitalSignature.cs
-
-
- Security\Cryptography\DsaDigitalSignature.cs
-
-
- Security\Cryptography\DsaKey.cs
-
-
- Security\Cryptography\ED25519DigitalSignature.cs
-
-
- Security\Cryptography\ED25519Key.cs
-
-
- Security\Cryptography\HMACMD5.cs
-
-
- Security\Cryptography\HMACSHA1.cs
-
-
- Security\Cryptography\HMACSHA256.cs
-
-
- Security\Cryptography\HMACSHA384.cs
-
-
- Security\Cryptography\HMACSHA512.cs
-
-
- Security\Cryptography\Key.cs
-
-
- Security\Cryptography\EcdsaDigitalSignature.cs
-
-
- Security\Cryptography\EcdsaKey.cs
-
-
- Security\Cryptography\RsaDigitalSignature.cs
-
-
- Security\Cryptography\RsaKey.cs
-
-
- Security\Cryptography\StreamCipher.cs
-
-
- Security\Cryptography\SymmetricCipher.cs
-
-
- Security\GroupExchangeHashData.cs
-
-
- Security\HostAlgorithm.cs
-
-
- Security\IKeyExchange.cs
-
-
- Security\KeyExchange.cs
-
-
- Security\KeyExchangeDiffieHellman.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup14Sha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup14Sha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup16Sha512.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup1Sha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeSha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeSha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeShaBase.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha512.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupShaBase.cs
-
-
- Security\KeyExchangeEC.cs
-
-
- Security\KeyExchangeECCurve25519.cs
-
-
- Security\KeyExchangeECDH.cs
-
-
- Security\KeyExchangeECDH256.cs
-
-
- Security\KeyExchangeECDH384.cs
-
-
- Security\KeyExchangeECDH521.cs
-
-
- Security\KeyExchangeHash.cs
-
-
- Security\KeyHostAlgorithm.cs
-
-
- ServiceFactory.cs
-
-
- ServiceFactory.NET.cs
-
-
- Session.cs
-
-
- SftpClient.cs
-
-
- Sftp\Flags.cs
-
-
- Sftp\ISftpFileReader.cs
-
-
- Sftp\ISftpResponseFactory.cs
-
-
- Sftp\ISftpSession.cs
-
-
- Sftp\Requests\ExtendedRequests\FStatVfsRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\HardLinkRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\PosixRenameRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\StatVfsRequest.cs
-
-
- Sftp\Requests\SftpBlockRequest.cs
-
-
- Sftp\Requests\SftpCloseRequest.cs
-
-
- Sftp\Requests\SftpExtendedRequest.cs
-
-
- Sftp\Requests\SftpFSetStatRequest.cs
-
-
- Sftp\Requests\SftpFStatRequest.cs
-
-
- Sftp\Requests\SftpInitRequest.cs
-
-
- Sftp\Requests\SftpLinkRequest.cs
-
-
- Sftp\Requests\SftpLStatRequest.cs
-
-
- Sftp\Requests\SftpMkDirRequest.cs
-
-
- Sftp\Requests\SftpOpenDirRequest.cs
-
-
- Sftp\Requests\SftpOpenRequest.cs
-
-
- Sftp\Requests\SftpReadDirRequest.cs
-
-
- Sftp\Requests\SftpReadLinkRequest.cs
-
-
- Sftp\Requests\SftpReadRequest.cs
-
-
- Sftp\Requests\SftpRealPathRequest.cs
-
-
- Sftp\Requests\SftpRemoveRequest.cs
-
-
- Sftp\Requests\SftpRenameRequest.cs
-
-
- Sftp\Requests\SftpRequest.cs
-
-
- Sftp\Requests\SftpRmDirRequest.cs
-
-
- Sftp\Requests\SftpSetStatRequest.cs
-
-
- Sftp\Requests\SftpStatRequest.cs
-
-
- Sftp\Requests\SftpSymLinkRequest.cs
-
-
- Sftp\Requests\SftpUnblockRequest.cs
-
-
- Sftp\Requests\SftpWriteRequest.cs
-
-
- Sftp\Responses\ExtendedReplies\ExtendedReplyInfo.cs
-
-
- Sftp\Responses\ExtendedReplies\StatVfsReplyInfo.cs
-
-
- Sftp\Responses\SftpAttrsResponse.cs
-
-
- Sftp\Responses\SftpDataResponse.cs
-
-
- Sftp\Responses\SftpExtendedReplyResponse.cs
-
-
- Sftp\Responses\SftpHandleResponse.cs
-
-
- Sftp\Responses\SftpNameResponse.cs
-
-
- Sftp\Responses\SftpResponse.cs
-
-
- Sftp\Responses\SftpStatusResponse.cs
-
-
- Sftp\Responses\SftpVersionResponse.cs
-
-
- Sftp\SftpCloseAsyncResult.cs
-
-
- Sftp\SftpDownloadAsyncResult.cs
-
-
- Sftp\SftpFile.cs
-
-
- Sftp\SftpFileAttributes.cs
-
-
- Sftp\SftpFileReader.cs
-
-
- Sftp\SftpFileStream.cs
-
-
- Sftp\SftpFileSystemInformation.cs
-
-
- Sftp\SftpListDirectoryAsyncResult.cs
-
-
- Sftp\SftpMessage.cs
-
-
- Sftp\SftpMessageTypes.cs
-
-
- Sftp\SftpOpenAsyncResult.cs
-
-
- Sftp\SftpReadAsyncResult.cs
-
-
- Sftp\SftpRealPathAsyncResult.cs
-
-
- Sftp\SftpResponseFactory.cs
-
-
- Sftp\SftpSession.cs
-
-
- Sftp\SFtpStatAsyncResult.cs
-
-
- Sftp\SftpSynchronizeDirectoriesAsyncResult.cs
-
-
- Sftp\SftpUploadAsyncResult.cs
-
-
- Sftp\StatusCodes.cs
-
-
- Shell.cs
-
-
- ShellStream.cs
-
-
- SshClient.cs
-
-
- SshCommand.cs
-
-
- SshMessageFactory.cs
-
-
- SubsystemSession.cs
-
-
-
-
-
- 14.0
-
-
-
-
\ No newline at end of file
diff --git a/src/Renci.SshNet.UAP10/project.json b/src/Renci.SshNet.UAP10/project.json
deleted file mode 100644
index 6916d5e63..000000000
--- a/src/Renci.SshNet.UAP10/project.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "dependencies": {
- "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.0",
- "SshNet.Security.Cryptography": "1.2.0",
- "System.Xml.XPath.XmlDocument": "4.0.1"
- },
- "frameworks": {
- "uap10.0": {}
- },
- "runtimes": {
- "win10-arm": {},
- "win10-arm-aot": {},
- "win10-x86": {},
- "win10-x86-aot": {},
- "win10-x64": {},
- "win10-x64-aot": {}
- }
-}
\ No newline at end of file
diff --git a/src/Renci.SshNet.VS2012.sln b/src/Renci.SshNet.VS2012.sln
deleted file mode 100644
index a80b19085..000000000
--- a/src/Renci.SshNet.VS2012.sln
+++ /dev/null
@@ -1,108 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 2012
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Renci.SshNet.Silverlight", "Renci.SshNet.Silverlight\Renci.SshNet.Silverlight.csproj", "{77C294BB-1DC2-49DC-BE16-963F8F22794D}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Renci.SshNet.WindowsPhone", "Renci.SshNet.WindowsPhone\Renci.SshNet.WindowsPhone.csproj", "{3AD3EDF0-702E-4A91-8735-DCE4659AA54C}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Renci.SshNet.Silverlight5", "Renci.SshNet.Silverlight5\Renci.SshNet.Silverlight5.csproj", "{E367F791-C1EC-4181-912A-2943CAC6B3BC}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Renci.SshNet.WindowsPhone8", "Renci.SshNet.WindowsPhone8\Renci.SshNet.WindowsPhone8.csproj", "{4A6CA785-1C8A-47FE-98C0-30C675A9328B}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}"
- ProjectSection(SolutionItems) = preProject
- ..\build\build.proj = ..\build\build.proj
- EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "nuget", "nuget", "{94EE3919-19FA-4D9B-8DA9-249050B15232}"
- ProjectSection(SolutionItems) = preProject
- ..\build\nuget\SSH.NET.nuspec = ..\build\nuget\SSH.NET.nuspec
- EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sandcastle", "sandcastle", "{A6C3FFD3-16A5-44D3-8C1F-3613D6DD17D1}"
- ProjectSection(SolutionItems) = preProject
- ..\build\sandcastle\SSH.NET.shfbproj = ..\build\sandcastle\SSH.NET.shfbproj
- EndProjectSection
-EndProject
-Global
- GlobalSection(TestCaseManagementSettings) = postSolution
- CategoryFile = Renci.SshNet1.vsmdi
- EndGlobalSection
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Debug|ARM = Debug|ARM
- Debug|Mixed Platforms = Debug|Mixed Platforms
- Debug|x64 = Debug|x64
- Debug|x86 = Debug|x86
- Release|Any CPU = Release|Any CPU
- Release|ARM = Release|ARM
- Release|Mixed Platforms = Release|Mixed Platforms
- Release|x64 = Release|x64
- Release|x86 = Release|x86
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Debug|ARM.ActiveCfg = Debug|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Debug|x64.ActiveCfg = Debug|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Debug|x86.ActiveCfg = Debug|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Release|Any CPU.Build.0 = Release|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Release|ARM.ActiveCfg = Release|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Release|x64.ActiveCfg = Release|Any CPU
- {77C294BB-1DC2-49DC-BE16-963F8F22794D}.Release|x86.ActiveCfg = Release|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Debug|ARM.ActiveCfg = Debug|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Debug|x64.ActiveCfg = Debug|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Debug|x86.ActiveCfg = Debug|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Release|Any CPU.Build.0 = Release|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Release|ARM.ActiveCfg = Release|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Release|x64.ActiveCfg = Release|Any CPU
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}.Release|x86.ActiveCfg = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|ARM.ActiveCfg = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|x64.ActiveCfg = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|x86.ActiveCfg = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|Any CPU.Build.0 = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|ARM.ActiveCfg = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|x64.ActiveCfg = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|x86.ActiveCfg = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|ARM.ActiveCfg = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|x64.ActiveCfg = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|x86.ActiveCfg = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|Any CPU.Build.0 = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|ARM.ActiveCfg = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|x64.ActiveCfg = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|x86.ActiveCfg = Release|Any CPU
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(NestedProjects) = preSolution
- {94EE3919-19FA-4D9B-8DA9-249050B15232} = {2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}
- {A6C3FFD3-16A5-44D3-8C1F-3613D6DD17D1} = {2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}
- EndGlobalSection
-EndGlobal
diff --git a/src/Renci.SshNet.VS2015.sln b/src/Renci.SshNet.VS2015.sln
deleted file mode 100644
index 81fa71554..000000000
--- a/src/Renci.SshNet.VS2015.sln
+++ /dev/null
@@ -1,130 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 14
-VisualStudioVersion = 14.0.25420.1
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}"
- ProjectSection(SolutionItems) = preProject
- ..\build\build.proj = ..\build\build.proj
- EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "nuget", "nuget", "{94EE3919-19FA-4D9B-8DA9-249050B15232}"
- ProjectSection(SolutionItems) = preProject
- ..\build\nuget\SSH.NET.nuspec = ..\build\nuget\SSH.NET.nuspec
- EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sandcastle", "sandcastle", "{A6C3FFD3-16A5-44D3-8C1F-3613D6DD17D1}"
- ProjectSection(SolutionItems) = preProject
- ..\build\sandcastle\SSH.NET.shfbproj = ..\build\sandcastle\SSH.NET.shfbproj
- EndProjectSection
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Renci.SshNet.Silverlight5", "Renci.SshNet.Silverlight5\Renci.SshNet.Silverlight5.csproj", "{E367F791-C1EC-4181-912A-2943CAC6B3BC}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Renci.SshNet.WindowsPhone8", "Renci.SshNet.WindowsPhone8\Renci.SshNet.WindowsPhone8.csproj", "{4A6CA785-1C8A-47FE-98C0-30C675A9328B}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Renci.SshNet.UAP10", "Renci.SshNet.UAP10\Renci.SshNet.UAP10.csproj", "{EC212E04-A372-4B95-B45B-C0D4A739EF80}"
-EndProject
-Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Renci.SshNet.Shared.Tests", "..\test\Renci.SshNet.Shared.Tests\Renci.SshNet.Shared.Tests.shproj", "{FAE3948F-A438-458E-8E0E-7F6E39A5DD8A}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Renci.SshNet.WindowsPhone8.Tests", "..\test\Renci.SshNet.WindowsPhone8.Tests\Renci.SshNet.WindowsPhone8.Tests.csproj", "{26F0D644-B3EF-47DF-8040-E9E4B2E63884}"
-EndProject
-Global
- GlobalSection(SharedMSBuildProjectFiles) = preSolution
- ..\test\Renci.SshNet.Shared.Tests\Renci.SshNet.Shared.Tests.projitems*{26f0d644-b3ef-47df-8040-e9e4b2e63884}*SharedItemsImports = 4
- ..\test\Renci.SshNet.Shared.Tests\Renci.SshNet.Shared.Tests.projitems*{fae3948f-a438-458e-8e0e-7f6e39a5dd8a}*SharedItemsImports = 13
- EndGlobalSection
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Debug|ARM = Debug|ARM
- Debug|Mixed Platforms = Debug|Mixed Platforms
- Debug|x64 = Debug|x64
- Debug|x86 = Debug|x86
- Release|Any CPU = Release|Any CPU
- Release|ARM = Release|ARM
- Release|Mixed Platforms = Release|Mixed Platforms
- Release|x64 = Release|x64
- Release|x86 = Release|x86
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|ARM.ActiveCfg = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|x64.ActiveCfg = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Debug|x86.ActiveCfg = Debug|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|Any CPU.Build.0 = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|ARM.ActiveCfg = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|x64.ActiveCfg = Release|Any CPU
- {E367F791-C1EC-4181-912A-2943CAC6B3BC}.Release|x86.ActiveCfg = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|ARM.ActiveCfg = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|x64.ActiveCfg = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Debug|x86.ActiveCfg = Debug|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|Any CPU.Build.0 = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|ARM.ActiveCfg = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|x64.ActiveCfg = Release|Any CPU
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}.Release|x86.ActiveCfg = Release|Any CPU
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Debug|ARM.ActiveCfg = Debug|ARM
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Debug|ARM.Build.0 = Debug|ARM
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Debug|Mixed Platforms.Build.0 = Debug|x86
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Debug|x64.ActiveCfg = Debug|x64
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Debug|x64.Build.0 = Debug|x64
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Debug|x86.ActiveCfg = Debug|x86
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Debug|x86.Build.0 = Debug|x86
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Release|Any CPU.Build.0 = Release|Any CPU
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Release|ARM.ActiveCfg = Release|ARM
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Release|ARM.Build.0 = Release|ARM
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Release|x64.ActiveCfg = Release|x64
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Release|x64.Build.0 = Release|x64
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Release|x86.ActiveCfg = Release|x86
- {EC212E04-A372-4B95-B45B-C0D4A739EF80}.Release|x86.Build.0 = Release|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Debug|Any CPU.ActiveCfg = Debug|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Debug|ARM.ActiveCfg = Debug|ARM
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Debug|ARM.Build.0 = Debug|ARM
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Debug|ARM.Deploy.0 = Debug|ARM
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Debug|Mixed Platforms.Build.0 = Debug|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Debug|Mixed Platforms.Deploy.0 = Debug|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Debug|x64.ActiveCfg = Debug|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Debug|x86.ActiveCfg = Debug|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Debug|x86.Build.0 = Debug|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Debug|x86.Deploy.0 = Debug|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Release|Any CPU.ActiveCfg = Release|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Release|ARM.ActiveCfg = Release|ARM
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Release|ARM.Build.0 = Release|ARM
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Release|ARM.Deploy.0 = Release|ARM
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Release|Mixed Platforms.ActiveCfg = Release|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Release|Mixed Platforms.Build.0 = Release|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Release|Mixed Platforms.Deploy.0 = Release|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Release|x64.ActiveCfg = Release|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Release|x86.ActiveCfg = Release|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Release|x86.Build.0 = Release|x86
- {26F0D644-B3EF-47DF-8040-E9E4B2E63884}.Release|x86.Deploy.0 = Release|x86
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(NestedProjects) = preSolution
- {94EE3919-19FA-4D9B-8DA9-249050B15232} = {2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}
- {A6C3FFD3-16A5-44D3-8C1F-3613D6DD17D1} = {2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}
- EndGlobalSection
- GlobalSection(TestCaseManagementSettings) = postSolution
- CategoryFile = Renci.SshNet1.vsmdi
- EndGlobalSection
-EndGlobal
diff --git a/src/Renci.SshNet.VS2015.sln.DotSettings b/src/Renci.SshNet.VS2015.sln.DotSettings
deleted file mode 100644
index 15b1b217e..000000000
--- a/src/Renci.SshNet.VS2015.sln.DotSettings
+++ /dev/null
@@ -1,22 +0,0 @@
-
- DO_NOT_SHOW
- DO_NOT_SHOW
- DO_NOT_SHOW
- DO_NOT_SHOW
- DO_NOT_SHOW
- SUGGESTION
- WARNING
- DO_NOT_SHOW
- DO_NOT_SHOW
- DO_NOT_SHOW
- True
- True
- True
- NEXT_LINE_SHIFTED_2
- CHOP_IF_LONG
- HMACMD
- HMACSHA
- True
- True
- True
- integration,LongRunning
\ No newline at end of file
diff --git a/src/Renci.SshNet.VS2017.sln b/src/Renci.SshNet.VS2017.sln
deleted file mode 100644
index 9f1ce5e37..000000000
--- a/src/Renci.SshNet.VS2017.sln
+++ /dev/null
@@ -1,82 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 15
-VisualStudioVersion = 15.0.26014.0
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}"
- ProjectSection(SolutionItems) = preProject
- ..\build\build.cmd = ..\build\build.cmd
- ..\build\build.proj = ..\build\build.proj
- EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "nuget", "nuget", "{94EE3919-19FA-4D9B-8DA9-249050B15232}"
- ProjectSection(SolutionItems) = preProject
- ..\build\nuget\SSH.NET.nuspec = ..\build\nuget\SSH.NET.nuspec
- EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sandcastle", "sandcastle", "{A6C3FFD3-16A5-44D3-8C1F-3613D6DD17D1}"
- ProjectSection(SolutionItems) = preProject
- ..\build\sandcastle\SSH.NET.shfbproj = ..\build\sandcastle\SSH.NET.shfbproj
- EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Renci.SshNet", "Renci.SshNet\Renci.SshNet.csproj", "{2F5F8C90-0BD1-424F-997C-7BC6280919D1}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Renci.SshNet.Tests", "Renci.SshNet.Tests\Renci.SshNet.Tests.csproj", "{C45379B9-17B1-4E89-BC2E-6D41726413E8}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Debug|ARM = Debug|ARM
- Debug|Mixed Platforms = Debug|Mixed Platforms
- Debug|x64 = Debug|x64
- Debug|x86 = Debug|x86
- Release|Any CPU = Release|Any CPU
- Release|ARM = Release|ARM
- Release|Mixed Platforms = Release|Mixed Platforms
- Release|x64 = Release|x64
- Release|x86 = Release|x86
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|ARM.ActiveCfg = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|x64.ActiveCfg = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|x86.ActiveCfg = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Any CPU.Build.0 = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|ARM.ActiveCfg = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|x64.ActiveCfg = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|x86.ActiveCfg = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|ARM.ActiveCfg = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|x64.ActiveCfg = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|x86.ActiveCfg = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|Any CPU.Build.0 = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|ARM.ActiveCfg = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|x64.ActiveCfg = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|x86.ActiveCfg = Release|Any CPU
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(NestedProjects) = preSolution
- {94EE3919-19FA-4D9B-8DA9-249050B15232} = {2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}
- {A6C3FFD3-16A5-44D3-8C1F-3613D6DD17D1} = {2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}
- EndGlobalSection
- GlobalSection(ExtensibilityGlobals) = postSolution
- SolutionGuid = {C3D130B3-A070-4B12-A10F-E3E44D6ACEE2}
- EndGlobalSection
- GlobalSection(TestCaseManagementSettings) = postSolution
- CategoryFile = Renci.SshNet1.vsmdi
- EndGlobalSection
-EndGlobal
diff --git a/src/Renci.SshNet.VS2019.sln b/src/Renci.SshNet.VS2019.sln
deleted file mode 100644
index bc1f6f6d3..000000000
--- a/src/Renci.SshNet.VS2019.sln
+++ /dev/null
@@ -1,82 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio Version 16
-VisualStudioVersion = 16.0.29521.150
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}"
- ProjectSection(SolutionItems) = preProject
- ..\build\build.cmd = ..\build\build.cmd
- ..\build\build.proj = ..\build\build.proj
- EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "nuget", "nuget", "{94EE3919-19FA-4D9B-8DA9-249050B15232}"
- ProjectSection(SolutionItems) = preProject
- ..\build\nuget\SSH.NET.nuspec = ..\build\nuget\SSH.NET.nuspec
- EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sandcastle", "sandcastle", "{A6C3FFD3-16A5-44D3-8C1F-3613D6DD17D1}"
- ProjectSection(SolutionItems) = preProject
- ..\build\sandcastle\SSH.NET.shfbproj = ..\build\sandcastle\SSH.NET.shfbproj
- EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Renci.SshNet", "Renci.SshNet\Renci.SshNet.csproj", "{2F5F8C90-0BD1-424F-997C-7BC6280919D1}"
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Renci.SshNet.Tests", "Renci.SshNet.Tests\Renci.SshNet.Tests.csproj", "{C45379B9-17B1-4E89-BC2E-6D41726413E8}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Debug|ARM = Debug|ARM
- Debug|Mixed Platforms = Debug|Mixed Platforms
- Debug|x64 = Debug|x64
- Debug|x86 = Debug|x86
- Release|Any CPU = Release|Any CPU
- Release|ARM = Release|ARM
- Release|Mixed Platforms = Release|Mixed Platforms
- Release|x64 = Release|x64
- Release|x86 = Release|x86
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|ARM.ActiveCfg = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|x64.ActiveCfg = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Debug|x86.ActiveCfg = Debug|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Any CPU.Build.0 = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|ARM.ActiveCfg = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|x64.ActiveCfg = Release|Any CPU
- {2F5F8C90-0BD1-424F-997C-7BC6280919D1}.Release|x86.ActiveCfg = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|ARM.ActiveCfg = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|x64.ActiveCfg = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Debug|x86.ActiveCfg = Debug|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|Any CPU.Build.0 = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|ARM.ActiveCfg = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|x64.ActiveCfg = Release|Any CPU
- {C45379B9-17B1-4E89-BC2E-6D41726413E8}.Release|x86.ActiveCfg = Release|Any CPU
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(NestedProjects) = preSolution
- {94EE3919-19FA-4D9B-8DA9-249050B15232} = {2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}
- {A6C3FFD3-16A5-44D3-8C1F-3613D6DD17D1} = {2D6CAE62-D053-476F-9BDD-2B1F27FA9C5D}
- EndGlobalSection
- GlobalSection(ExtensibilityGlobals) = postSolution
- SolutionGuid = {BAD6019D-4AF7-4E15-99A0-8036E16FC0E5}
- EndGlobalSection
- GlobalSection(TestCaseManagementSettings) = postSolution
- CategoryFile = Renci.SshNet1.vsmdi
- EndGlobalSection
-EndGlobal
diff --git a/src/Renci.SshNet.WindowsPhone/Properties/AssemblyInfo.cs b/src/Renci.SshNet.WindowsPhone/Properties/AssemblyInfo.cs
deleted file mode 100644
index f61fb1340..000000000
--- a/src/Renci.SshNet.WindowsPhone/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,5 +0,0 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-[assembly: AssemblyTitle("SSH.NET Windows Phone 7.1")]
-[assembly: Guid("b044a9d9-fe40-4d7e-b198-c142ab9721f0")]
diff --git a/src/Renci.SshNet.WindowsPhone/Renci.SshNet.WindowsPhone.csproj b/src/Renci.SshNet.WindowsPhone/Renci.SshNet.WindowsPhone.csproj
deleted file mode 100644
index 317dbc845..000000000
--- a/src/Renci.SshNet.WindowsPhone/Renci.SshNet.WindowsPhone.csproj
+++ /dev/null
@@ -1,1432 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 10.0.20506
- 2.0
- {3AD3EDF0-702E-4A91-8735-DCE4659AA54C}
- {C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}
- Library
- Properties
- Renci.SshNet
- Renci.SshNet
- v4.0
- $(TargetFrameworkVersion)
- WindowsPhone71
- Silverlight
- false
- true
- true
-
-
- true
- full
- false
- Bin\Debug
- TRACE;DEBUG;FEATURE_DEVICEINFORMATION_APM;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_REGEX_COMPILE;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_DEVICEINFORMATION_APM;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_HASH_SHA1;FEATURE_HASH_SHA256;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256
- true
- true
- prompt
- 4
- Bin\Debug\Renci.SshNet.xml
-
-
- none
- true
- Bin\Release
- TRACE;FEATURE_DEVICEINFORMATION_APM;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_REGEX_COMPILE;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_DEVICEINFORMATION_APM;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_HASH_SHA1;FEATURE_HASH_SHA256;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256
- true
- true
- prompt
- 4
- Bin\Release\Renci.SshNet.xml
- 1591
-
-
-
-
- False
- ..\..\packages\SshNet.Security.Cryptography.1.2.0\lib\wp71\SshNet.Security.Cryptography.dll
-
-
-
-
-
-
- Abstractions\CryptoAbstraction.cs
-
-
- Abstractions\DiagnosticAbstraction.cs
-
-
- Abstractions\DnsAbstraction.cs
-
-
- Abstractions\FileSystemAbstraction.cs
-
-
- Abstractions\ReflectionAbstraction.cs
-
-
- Abstractions\SocketAbstraction.cs
-
-
- Abstractions\ThreadAbstraction.cs
-
-
- AuthenticationMethod.cs
-
-
- AuthenticationResult.cs
-
-
- BaseClient.cs
-
-
- Channels\Channel.cs
-
-
- Channels\ChannelDirectTcpip.cs
-
-
- Channels\ChannelForwardedTcpip.cs
-
-
- Channels\ChannelSession.cs
-
-
- Channels\ChannelTypes.cs
-
-
- Channels\ClientChannel.cs
-
-
- Channels\IChannel.cs
-
-
- Channels\IChannelDirectTcpip.cs
-
-
- Channels\IChannelForwardedTcpip.cs
-
-
- Channels\IChannelSession.cs
-
-
- Channels\ServerChannel.cs
-
-
- CipherInfo.cs
-
-
- ClientAuthentication.cs
-
-
- CommandAsyncResult.cs
-
-
- Common\Array.cs
-
-
- Common\ASCIIEncoding.cs
-
-
- Common\AsyncResult.cs
-
-
- Common\AuthenticationBannerEventArgs.cs
-
-
- Common\AuthenticationEventArgs.cs
-
-
- Common\AuthenticationPasswordChangeEventArgs.cs
-
-
- Common\AuthenticationPrompt.cs
-
-
- Common\AuthenticationPromptEventArgs.cs
-
-
- Common\BigInteger.cs
-
-
- Common\ChannelDataEventArgs.cs
-
-
- Common\ChannelEventArgs.cs
-
-
- Common\ChannelExtendedDataEventArgs.cs
-
-
- Common\ChannelOpenConfirmedEventArgs.cs
-
-
- Common\ChannelOpenFailedEventArgs.cs
-
-
- Common\ChannelRequestEventArgs.cs
-
-
- Common\CountdownEvent.cs
-
-
- Common\DerData.cs
-
-
- Common\ExceptionEventArgs.cs
-
-
- Common\Extensions.cs
-
-
- Common\HostKeyEventArgs.cs
-
-
- Common\ObjectIdentifier.cs
-
-
- Common\Pack.cs
-
-
- Common\PacketDump.cs
-
-
- Common\PipeStream.cs
-
-
- Common\PortForwardEventArgs.cs
-
-
- Common\PosixPath.cs
-
-
- Common\ProxyException.cs
-
-
- Common\ScpDownloadEventArgs.cs
-
-
- Common\ScpException.cs
-
-
- Common\ScpUploadEventArgs.cs
-
-
- Common\SemaphoreLight.cs
-
-
- Common\SftpPathNotFoundException.cs
-
-
- Common\SftpPermissionDeniedException.cs
-
-
- Common\ShellDataEventArgs.cs
-
-
- Common\SshAuthenticationException.cs
-
-
- Common\SshConnectionException.cs
-
-
- Common\SshData.cs
-
-
- Common\SshDataStream.cs
-
-
- Common\SshException.cs
-
-
- Common\SshOperationTimeoutException.cs
-
-
- Common\SshPassPhraseNullOrEmptyException.cs
-
-
- Common\TerminalModes.cs
-
-
- Compression\CompressionMode.cs
-
-
- Compression\Compressor.cs
-
-
- Compression\Zlib.cs
-
-
- Compression\ZlibOpenSsh.cs
-
-
- Compression\ZlibStream.cs
-
-
- ConnectionInfo.cs
-
-
- Connection\ConnectorBase.cs
-
-
- Connection\DirectConnector.cs
-
-
- Connection\HttpConnector.cs
-
-
- Connection\IConnector.cs
-
-
- Connection\IProtocolVersionExchange.cs
-
-
- Connection\ISocketFactory.cs
-
-
- Connection\ProtocolVersionExchange.cs
-
-
- Connection\SocketFactory.cs
-
-
- Connection\Socks4Connector.cs
-
-
- Connection\Socks5Connector.cs
-
-
- Connection\SshIdentification.cs
-
-
- ExpectAction.cs
-
-
- ExpectAsyncResult.cs
-
-
- ForwardedPort.cs
-
-
- ForwardedPortDynamic.cs
-
-
- ForwardedPortLocal.cs
-
-
- ForwardedPortRemote.cs
-
-
- ForwardedPortStatus.cs
-
-
- HashInfo.cs
-
-
- IAuthenticationMethod.cs
-
-
- IClientAuthentication.cs
-
-
- IConnectionInfo.cs
-
-
- IForwardedPort.cs
-
-
- IRemotePathTransformation.cs
-
-
- IServiceFactory.cs
-
-
- ISession.cs
-
-
- ISubsystemSession.cs
-
-
- KeyboardInteractiveAuthenticationMethod.cs
-
-
- KeyboardInteractiveConnectionInfo.cs
-
-
- MessageEventArgs.cs
-
-
- Messages\Authentication\BannerMessage.cs
-
-
- Messages\Authentication\FailureMessage.cs
-
-
- Messages\Authentication\InformationRequestMessage.cs
-
-
- Messages\Authentication\InformationResponseMessage.cs
-
-
- Messages\Authentication\PasswordChangeRequiredMessage.cs
-
-
- Messages\Authentication\PublicKeyMessage.cs
-
-
- Messages\Authentication\RequestMessage.cs
-
-
- Messages\Authentication\RequestMessageHost.cs
-
-
- Messages\Authentication\RequestMessageKeyboardInteractive.cs
-
-
- Messages\Authentication\RequestMessageNone.cs
-
-
- Messages\Authentication\RequestMessagePassword.cs
-
-
- Messages\Authentication\RequestMessagePublicKey.cs
-
-
- Messages\Authentication\SuccessMessage.cs
-
-
- Messages\Connection\CancelTcpIpForwardGlobalRequestMessage.cs
-
-
- Messages\Connection\ChannelCloseMessage.cs
-
-
- Messages\Connection\ChannelDataMessage.cs
-
-
- Messages\Connection\ChannelEofMessage.cs
-
-
- Messages\Connection\ChannelExtendedDataMessage.cs
-
-
- Messages\Connection\ChannelFailureMessage.cs
-
-
- Messages\Connection\ChannelMessage.cs
-
-
- Messages\Connection\ChannelOpenConfirmationMessage.cs
-
-
- Messages\Connection\ChannelOpenFailureMessage.cs
-
-
- Messages\Connection\ChannelOpenFailureReasons.cs
-
-
- Messages\Connection\ChannelOpen\ChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelOpen\ChannelOpenMessage.cs
-
-
- Messages\Connection\ChannelOpen\DirectTcpipChannelInfo.cs
-
-
- Messages\Connection\ChannelOpen\ForwardedTcpipChannelInfo.cs
-
-
- Messages\Connection\ChannelOpen\SessionChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelOpen\X11ChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelRequest\BreakRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ChannelRequestMessage.cs
-
-
- Messages\Connection\ChannelRequest\EndOfWriteRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\EnvironmentVariableRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExecRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExitSignalRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExitStatusRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\KeepAliveRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\PseudoTerminalInfo.cs
-
-
- Messages\Connection\ChannelRequest\RequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ShellRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\SignalRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\SubsystemRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\WindowChangeRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\X11ForwardingRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\XonXoffRequestInfo.cs
-
-
- Messages\Connection\ChannelSuccessMessage.cs
-
-
- Messages\Connection\ChannelWindowAdjustMessage.cs
-
-
- Messages\Connection\GlobalRequestMessage.cs
-
-
- Messages\Connection\GlobalRequestName.cs
-
-
- Messages\Connection\RequestFailureMessage.cs
-
-
- Messages\Connection\RequestSuccessMessage.cs
-
-
- Messages\Connection\TcpIpForwardGlobalRequestMessage.cs
-
-
- Messages\Message.cs
-
-
- Messages\MessageAttribute.cs
-
-
- Messages\ServiceName.cs
-
-
- Messages\Transport\DebugMessage.cs
-
-
- Messages\Transport\DisconnectMessage.cs
-
-
- Messages\Transport\DisconnectReason.cs
-
-
- Messages\Transport\IgnoreMessage.cs
-
-
- Messages\Transport\IKeyExchangedAllowed.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeGroup.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeInit.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeReply.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeRequest.cs
-
-
- Messages\Transport\KeyExchangeDhInitMessage.cs
-
-
- Messages\Transport\KeyExchangeDhReplyMessage.cs
-
-
- Messages\Transport\KeyExchangeEcdhInitMessage.cs
-
-
- Messages\Transport\KeyExchangeEcdhReplyMessage.cs
-
-
- Messages\Transport\KeyExchangeInitMessage.cs
-
-
- Messages\Transport\NewKeysMessage.cs
-
-
- Messages\Transport\ServiceAcceptMessage.cs
-
-
- Messages\Transport\ServiceRequestMessage.cs
-
-
- Messages\Transport\UnimplementedMessage.cs
-
-
- NoneAuthenticationMethod.cs
-
-
- PasswordAuthenticationMethod.cs
-
-
- PasswordConnectionInfo.cs
-
-
- PrivateKeyAuthenticationMethod.cs
-
-
- PrivateKeyConnectionInfo.cs
-
-
- PrivateKeyFile.cs
-
-
- ProxyTypes.cs
-
-
- RemotePathDoubleQuoteTransformation.cs
-
-
- RemotePathNoneTransformation.cs
-
-
- RemotePathShellQuoteTransformation.cs
-
-
- RemotePathTransformation.cs
-
-
- ScpClient.cs
-
-
- Security\Algorithm.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\sec\SECNamedCurves.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9Curve.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECParameters.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECParametersHolder.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECPoint.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\agreement\ECDHCBasicAgreement.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\AsymmetricCipherKeyPair.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\AsymmetricKeyParameter.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\digests\GeneralDigest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\digests\Sha256Digest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\generators\ECKeyPairGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\IAsymmetricCipherKeyPairGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\IDigest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\KeyGenerationParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECDomainParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECKeyGenerationParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECPrivateKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECPublicKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\CryptoApiRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\DigestRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\IRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\util\Pack.cs
-
-
- Security\Cryptography\BouncyCastle\math\BigInteger.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\SimpleBigDecimal.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\Tnaf.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\ZTauElement.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECAlgorithms.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECCurve.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECFieldElement.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECLookupTable.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECPoint.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECPointMap.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\endo\ECEndomorphism.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\endo\GlvEndomorphism.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\LongArray.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\AbstractECMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\ECMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointCombMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\GlvMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\IPreCompCallback.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\PreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\ValidityPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafL2RMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WTauNafMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WTauNafPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\FiniteFields.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\GenericPolynomialExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\GF2Polynomial.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IFiniteField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IPolynomial.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IPolynomialExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\PrimeField.cs
-
-
- Security\Cryptography\BouncyCastle\math\raw\Mod.cs
-
-
- Security\Cryptography\BouncyCastle\math\raw\Nat.cs
-
-
- Security\Cryptography\BouncyCastle\security\DigestUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\security\SecureRandom.cs
-
-
- Security\Cryptography\BouncyCastle\security\SecurityUtilityException.cs
-
-
- Security\Cryptography\BouncyCastle\util\Arrays.cs
-
-
- Security\Cryptography\BouncyCastle\util\BigIntegers.cs
-
-
- Security\Cryptography\BouncyCastle\util\encoders\Hex.cs
-
-
- Security\Cryptography\BouncyCastle\util\encoders\HexEncoder.cs
-
-
- Security\Cryptography\BouncyCastle\util\IMemoable.cs
-
-
- Security\Cryptography\BouncyCastle\util\Integers.cs
-
-
- Security\Cryptography\BouncyCastle\util\MemoableResetException.cs
-
-
- Security\Cryptography\BouncyCastle\util\Times.cs
-
-
- Security\CertificateHostAlgorithm.cs
-
-
- Security\Cryptography\Chaos.NaCl\CryptoBytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Ed25519.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Array16.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Array8.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\ByteIntegerConverter.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\base.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\base2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\d.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\d2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_1.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_cmov.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_cswap.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_frombytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_invert.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_isnegative.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_isnonzero.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_mul.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_mul121666.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_neg.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_pow22523.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sq.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sq2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\FieldElement.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_double_scalarmult.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_frombytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_madd.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_msub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p1p1_to_p2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p1p1_to_p3.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p2_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p2_dbl.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_dbl.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_to_cached.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_to_p2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_precomp_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_scalarmult_base.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_sub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\GroupElement.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\keypair.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\open.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\scalarmult.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_clamp.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_mul_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_reduce.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sign.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sqrtm1.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\InternalAssert.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Poly1305Donna.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Salsa\Salsa20.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Salsa\SalsaCore.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Sha512Internal.cs
-
-
- Security\Cryptography\Chaos.NaCl\MontgomeryCurve25519.cs
-
-
- Security\Cryptography\Chaos.NaCl\Sha512.cs
-
-
- Security\Cryptography\AsymmetricCipher.cs
-
-
- Security\Cryptography\Bcrypt.cs
-
-
- Security\Cryptography\BlockCipher.cs
-
-
- Security\Cryptography\Cipher.cs
-
-
- Security\Cryptography\CipherDigitalSignature.cs
-
-
- Security\Cryptography\Ciphers\AesCipher.cs
-
-
- Security\Cryptography\Ciphers\Arc4Cipher.cs
-
-
- Security\Cryptography\Ciphers\BlowfishCipher.cs
-
-
- Security\Cryptography\Ciphers\CastCipher.cs
-
-
- Security\Cryptography\Ciphers\CipherMode.cs
-
-
- Security\Cryptography\Ciphers\CipherPadding.cs
-
-
- Security\Cryptography\Ciphers\DesCipher.cs
-
-
- Security\Cryptography\Ciphers\Modes\CbcCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\CfbCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\CtrCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\OfbCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Paddings\PKCS7Padding.cs
-
-
- Security\Cryptography\Ciphers\RsaCipher.cs
-
-
- Security\Cryptography\Ciphers\SerpentCipher.cs
-
-
- Security\Cryptography\Ciphers\TripleDesCipher.cs
-
-
- Security\Cryptography\Ciphers\TwofishCipher.cs
-
-
- Security\Cryptography\DigitalSignature.cs
-
-
- Security\Cryptography\DsaDigitalSignature.cs
-
-
- Security\Cryptography\DsaKey.cs
-
-
- Security\Cryptography\ED25519DigitalSignature.cs
-
-
- Security\Cryptography\ED25519Key.cs
-
-
- Security\Cryptography\HMACMD5.cs
-
-
- Security\Cryptography\HMACSHA1.cs
-
-
- Security\Cryptography\HMACSHA256.cs
-
-
- Security\Cryptography\HMACSHA384.cs
-
-
- Security\Cryptography\HMACSHA512.cs
-
-
- Security\Cryptography\Key.cs
-
-
- Security\Cryptography\RsaDigitalSignature.cs
-
-
- Security\Cryptography\RsaKey.cs
-
-
- Security\Cryptography\StreamCipher.cs
-
-
- Security\Cryptography\SymmetricCipher.cs
-
-
- Security\GroupExchangeHashData.cs
-
-
- Security\HostAlgorithm.cs
-
-
- Security\IKeyExchange.cs
-
-
- Security\KeyExchange.cs
-
-
- Security\KeyExchangeDiffieHellman.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup14Sha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup14Sha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup16Sha512.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup1Sha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeSha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeSha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeShaBase.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha512.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupShaBase.cs
-
-
- Security\KeyExchangeEC.cs
-
-
- Security\KeyExchangeECCurve25519.cs
-
-
- Security\KeyExchangeECDH.cs
-
-
- Security\KeyExchangeECDH256.cs
-
-
- Security\KeyExchangeECDH384.cs
-
-
- Security\KeyExchangeECDH521.cs
-
-
- Security\KeyExchangeHash.cs
-
-
- Security\KeyHostAlgorithm.cs
-
-
- ServiceFactory.cs
-
-
- Session.cs
-
-
- SftpClient.cs
-
-
- ISftpClient.cs
-
-
- Sftp\Flags.cs
-
-
- Sftp\ISftpFileReader.cs
-
-
- Sftp\ISftpResponseFactory.cs
-
-
- Sftp\ISftpSession.cs
-
-
- Sftp\Requests\ExtendedRequests\FStatVfsRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\HardLinkRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\PosixRenameRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\StatVfsRequest.cs
-
-
- Sftp\Requests\SftpBlockRequest.cs
-
-
- Sftp\Requests\SftpCloseRequest.cs
-
-
- Sftp\Requests\SftpExtendedRequest.cs
-
-
- Sftp\Requests\SftpFSetStatRequest.cs
-
-
- Sftp\Requests\SftpFStatRequest.cs
-
-
- Sftp\Requests\SftpInitRequest.cs
-
-
- Sftp\Requests\SftpLinkRequest.cs
-
-
- Sftp\Requests\SftpLStatRequest.cs
-
-
- Sftp\Requests\SftpMkDirRequest.cs
-
-
- Sftp\Requests\SftpOpenDirRequest.cs
-
-
- Sftp\Requests\SftpOpenRequest.cs
-
-
- Sftp\Requests\SftpReadDirRequest.cs
-
-
- Sftp\Requests\SftpReadLinkRequest.cs
-
-
- Sftp\Requests\SftpReadRequest.cs
-
-
- Sftp\Requests\SftpRealPathRequest.cs
-
-
- Sftp\Requests\SftpRemoveRequest.cs
-
-
- Sftp\Requests\SftpRenameRequest.cs
-
-
- Sftp\Requests\SftpRequest.cs
-
-
- Sftp\Requests\SftpRmDirRequest.cs
-
-
- Sftp\Requests\SftpSetStatRequest.cs
-
-
- Sftp\Requests\SftpStatRequest.cs
-
-
- Sftp\Requests\SftpSymLinkRequest.cs
-
-
- Sftp\Requests\SftpUnblockRequest.cs
-
-
- Sftp\Requests\SftpWriteRequest.cs
-
-
- Sftp\Responses\ExtendedReplies\ExtendedReplyInfo.cs
-
-
- Sftp\Responses\ExtendedReplies\StatVfsReplyInfo.cs
-
-
- Sftp\Responses\SftpAttrsResponse.cs
-
-
- Sftp\Responses\SftpDataResponse.cs
-
-
- Sftp\Responses\SftpExtendedReplyResponse.cs
-
-
- Sftp\Responses\SftpHandleResponse.cs
-
-
- Sftp\Responses\SftpNameResponse.cs
-
-
- Sftp\Responses\SftpResponse.cs
-
-
- Sftp\Responses\SftpStatusResponse.cs
-
-
- Sftp\Responses\SftpVersionResponse.cs
-
-
- Sftp\SftpCloseAsyncResult.cs
-
-
- Sftp\SftpDownloadAsyncResult.cs
-
-
- Sftp\SftpFile.cs
-
-
- Sftp\SftpFileAttributes.cs
-
-
- Sftp\SftpFileReader.cs
-
-
- Sftp\SftpFileStream.cs
-
-
- Sftp\SftpFileSystemInformation.cs
-
-
- Sftp\SftpListDirectoryAsyncResult.cs
-
-
- Sftp\SftpMessage.cs
-
-
- Sftp\SftpMessageTypes.cs
-
-
- Sftp\SftpOpenAsyncResult.cs
-
-
- Sftp\SftpReadAsyncResult.cs
-
-
- Sftp\SftpRealPathAsyncResult.cs
-
-
- Sftp\SftpResponseFactory.cs
-
-
- Sftp\SftpSession.cs
-
-
- Sftp\SFtpStatAsyncResult.cs
-
-
- Sftp\SftpSynchronizeDirectoriesAsyncResult.cs
-
-
- Sftp\SftpUploadAsyncResult.cs
-
-
- Sftp\StatusCodes.cs
-
-
- Shell.cs
-
-
- ShellStream.cs
-
-
- SshClient.cs
-
-
- SshCommand.cs
-
-
- SshMessageFactory.cs
-
-
- SubsystemSession.cs
-
-
-
- Properties\CommonAssemblyInfo.cs
-
-
-
-
- Designer
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Renci.SshNet.WindowsPhone/packages.config b/src/Renci.SshNet.WindowsPhone/packages.config
deleted file mode 100644
index a9e0cd0e6..000000000
--- a/src/Renci.SshNet.WindowsPhone/packages.config
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/src/Renci.SshNet.WindowsPhone8/Properties/AssemblyInfo.cs b/src/Renci.SshNet.WindowsPhone8/Properties/AssemblyInfo.cs
deleted file mode 100644
index 3db5746c8..000000000
--- a/src/Renci.SshNet.WindowsPhone8/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-[assembly: AssemblyTitle("SSH.NET Windows Phone 8.0")]
-[assembly: Guid("b044a9d9-fe40-4d7e-b198-c142ab9721f0")]
-
-[assembly: InternalsVisibleTo("Renci.SshNet.Tests")]
\ No newline at end of file
diff --git a/src/Renci.SshNet.WindowsPhone8/Renci.SshNet.WindowsPhone8.csproj b/src/Renci.SshNet.WindowsPhone8/Renci.SshNet.WindowsPhone8.csproj
deleted file mode 100644
index f34c1d8e8..000000000
--- a/src/Renci.SshNet.WindowsPhone8/Renci.SshNet.WindowsPhone8.csproj
+++ /dev/null
@@ -1,1493 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 10.0.20506
- 2.0
- {4A6CA785-1C8A-47FE-98C0-30C675A9328B}
- {C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}
- Library
- Properties
- Renci.SshNet
- Renci.SshNet
- v8.0
- WindowsPhone
- false
- true
- true
- 11.0
-
-
- true
- full
- false
- Bin\Debug
- TRACE;DEBUG;FEATURE_REGEX_COMPILE;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_STREAM_TAP;FEATURE_DEVICEINFORMATION_APM;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_HASH_SHA1_MANAGED;FEATURE_HASH_SHA256_MANAGED;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256
- true
- true
- prompt
- 4
- false
- Bin\Debug\Renci.SshNet.xml
- true
-
-
- none
- true
- Bin\Release
- TRACE;FEATURE_REGEX_COMPILE;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_STREAM_TAP;FEATURE_DEVICEINFORMATION_APM;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_HASH_SHA1_MANAGED;FEATURE_HASH_SHA256_MANAGED;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256
- true
- true
- prompt
- 4
- false
- Bin\Release\Renci.SshNet.xml
-
-
- true
-
-
- true
- Bin\x86\Debug
- TRACE;DEBUG;FEATURE_REGEX_COMPILE;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_STREAM_TAP;FEATURE_DEVICEINFORMATION_APM;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_HASH_SHA1_MANAGED;FEATURE_HASH_SHA256_MANAGED;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256
- true
- full
-
-
- prompt
- MinimumRecommendedRules.ruleset
- false
-
-
- Bin\x86\Release
- TRACE;FEATURE_REGEX_COMPILE;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_STREAM_TAP;FEATURE_DEVICEINFORMATION_APM;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_HASH_SHA1_MANAGED;FEATURE_HASH_SHA256_MANAGED;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256
- true
- true
- pdbonly
-
-
- prompt
- MinimumRecommendedRules.ruleset
-
-
- true
- Bin\ARM\Debug
- TRACE;DEBUG;FEATURE_REGEX_COMPILE;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_STREAM_TAP;FEATURE_DEVICEINFORMATION_APM;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_HASH_SHA1_MANAGED;FEATURE_HASH_SHA256_MANAGED;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256
- true
- full
-
-
- prompt
- MinimumRecommendedRules.ruleset
- false
-
-
- Bin\ARM\Release
- TRACE;FEATURE_REGEX_COMPILE;FEATURE_RNG_CSP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_STREAM_TAP;FEATURE_DEVICEINFORMATION_APM;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_HASH_SHA1_MANAGED;FEATURE_HASH_SHA256_MANAGED;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256
- true
- true
- pdbonly
-
-
- prompt
- MinimumRecommendedRules.ruleset
-
-
-
- Abstractions\CryptoAbstraction.cs
-
-
- Abstractions\DiagnosticAbstraction.cs
-
-
- Abstractions\DnsAbstraction.cs
-
-
- Abstractions\FileSystemAbstraction.cs
-
-
- Abstractions\ReflectionAbstraction.cs
-
-
- Abstractions\SocketAbstraction.cs
-
-
- Abstractions\ThreadAbstraction.cs
-
-
- AuthenticationMethod.cs
-
-
- AuthenticationResult.cs
-
-
- BaseClient.cs
-
-
- Channels\Channel.cs
-
-
- Channels\ChannelDirectTcpip.cs
-
-
- Channels\ChannelForwardedTcpip.cs
-
-
- Channels\ChannelSession.cs
-
-
- Channels\ChannelTypes.cs
-
-
- Channels\ClientChannel.cs
-
-
- Channels\IChannel.cs
-
-
- Channels\IChannelDirectTcpip.cs
-
-
- Channels\IChannelForwardedTcpip.cs
-
-
- Channels\IChannelSession.cs
-
-
- Channels\ServerChannel.cs
-
-
- CipherInfo.cs
-
-
- ClientAuthentication.cs
-
-
- CommandAsyncResult.cs
-
-
- Common\Array.cs
-
-
- Common\ASCIIEncoding.cs
-
-
- Common\AsyncResult.cs
-
-
- Common\AuthenticationBannerEventArgs.cs
-
-
- Common\AuthenticationEventArgs.cs
-
-
- Common\AuthenticationPasswordChangeEventArgs.cs
-
-
- Common\AuthenticationPrompt.cs
-
-
- Common\AuthenticationPromptEventArgs.cs
-
-
- Common\BigInteger.cs
-
-
- Common\ChannelDataEventArgs.cs
-
-
- Common\ChannelEventArgs.cs
-
-
- Common\ChannelExtendedDataEventArgs.cs
-
-
- Common\ChannelOpenConfirmedEventArgs.cs
-
-
- Common\ChannelOpenFailedEventArgs.cs
-
-
- Common\ChannelRequestEventArgs.cs
-
-
- Common\CountdownEvent.cs
-
-
- Common\DerData.cs
-
-
- Common\ExceptionEventArgs.cs
-
-
- Common\Extensions.cs
-
-
- Common\HostKeyEventArgs.cs
-
-
- Common\ObjectIdentifier.cs
-
-
- Common\Pack.cs
-
-
- Common\PacketDump.cs
-
-
- Common\PipeStream.cs
-
-
- Common\PortForwardEventArgs.cs
-
-
- Common\PosixPath.cs
-
-
- Common\ProxyException.cs
-
-
- Common\ScpDownloadEventArgs.cs
-
-
- Common\ScpException.cs
-
-
- Common\ScpUploadEventArgs.cs
-
-
- Common\SemaphoreLight.cs
-
-
- Common\SftpPathNotFoundException.cs
-
-
- Common\SftpPermissionDeniedException.cs
-
-
- Common\ShellDataEventArgs.cs
-
-
- Common\SshAuthenticationException.cs
-
-
- Common\SshConnectionException.cs
-
-
- Common\SshData.cs
-
-
- Common\SshDataStream.cs
-
-
- Common\SshException.cs
-
-
- Common\SshOperationTimeoutException.cs
-
-
- Common\SshPassPhraseNullOrEmptyException.cs
-
-
- Common\TerminalModes.cs
-
-
- Compression\CompressionMode.cs
-
-
- Compression\Compressor.cs
-
-
- Compression\Zlib.cs
-
-
- Compression\ZlibOpenSsh.cs
-
-
- Compression\ZlibStream.cs
-
-
- ConnectionInfo.cs
-
-
- Connection\ConnectorBase.cs
-
-
- Connection\DirectConnector.cs
-
-
- Connection\HttpConnector.cs
-
-
- Connection\IConnector.cs
-
-
- Connection\IProtocolVersionExchange.cs
-
-
- Connection\ISocketFactory.cs
-
-
- Connection\ProtocolVersionExchange.cs
-
-
- Connection\SocketFactory.cs
-
-
- Connection\Socks4Connector.cs
-
-
- Connection\Socks5Connector.cs
-
-
- Connection\SshIdentification.cs
-
-
- ExpectAction.cs
-
-
- ExpectAsyncResult.cs
-
-
- ForwardedPort.cs
-
-
- ForwardedPortDynamic.cs
-
-
- ForwardedPortDynamic.NET.cs
-
-
- ForwardedPortLocal.cs
-
-
- ForwardedPortLocal.NET.cs
-
-
- ForwardedPortRemote.cs
-
-
- ForwardedPortStatus.cs
-
-
- HashInfo.cs
-
-
- IAuthenticationMethod.cs
-
-
- IClientAuthentication.cs
-
-
- IConnectionInfo.cs
-
-
- IForwardedPort.cs
-
-
- IRemotePathTransformation.cs
-
-
- IServiceFactory.cs
-
-
- ISession.cs
-
-
- ISftpClient.cs
-
-
- ISubsystemSession.cs
-
-
- KeyboardInteractiveAuthenticationMethod.cs
-
-
- KeyboardInteractiveConnectionInfo.cs
-
-
- MessageEventArgs.cs
-
-
- Messages\Authentication\BannerMessage.cs
-
-
- Messages\Authentication\FailureMessage.cs
-
-
- Messages\Authentication\InformationRequestMessage.cs
-
-
- Messages\Authentication\InformationResponseMessage.cs
-
-
- Messages\Authentication\PasswordChangeRequiredMessage.cs
-
-
- Messages\Authentication\PublicKeyMessage.cs
-
-
- Messages\Authentication\RequestMessage.cs
-
-
- Messages\Authentication\RequestMessageHost.cs
-
-
- Messages\Authentication\RequestMessageKeyboardInteractive.cs
-
-
- Messages\Authentication\RequestMessageNone.cs
-
-
- Messages\Authentication\RequestMessagePassword.cs
-
-
- Messages\Authentication\RequestMessagePublicKey.cs
-
-
- Messages\Authentication\SuccessMessage.cs
-
-
- Messages\Connection\CancelTcpIpForwardGlobalRequestMessage.cs
-
-
- Messages\Connection\ChannelCloseMessage.cs
-
-
- Messages\Connection\ChannelDataMessage.cs
-
-
- Messages\Connection\ChannelEofMessage.cs
-
-
- Messages\Connection\ChannelExtendedDataMessage.cs
-
-
- Messages\Connection\ChannelFailureMessage.cs
-
-
- Messages\Connection\ChannelMessage.cs
-
-
- Messages\Connection\ChannelOpenConfirmationMessage.cs
-
-
- Messages\Connection\ChannelOpenFailureMessage.cs
-
-
- Messages\Connection\ChannelOpenFailureReasons.cs
-
-
- Messages\Connection\ChannelOpen\ChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelOpen\ChannelOpenMessage.cs
-
-
- Messages\Connection\ChannelOpen\DirectTcpipChannelInfo.cs
-
-
- Messages\Connection\ChannelOpen\ForwardedTcpipChannelInfo.cs
-
-
- Messages\Connection\ChannelOpen\SessionChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelOpen\X11ChannelOpenInfo.cs
-
-
- Messages\Connection\ChannelRequest\BreakRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ChannelRequestMessage.cs
-
-
- Messages\Connection\ChannelRequest\EndOfWriteRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\EnvironmentVariableRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExecRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExitSignalRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ExitStatusRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\KeepAliveRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\PseudoTerminalInfo.cs
-
-
- Messages\Connection\ChannelRequest\RequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\ShellRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\SignalRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\SubsystemRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\WindowChangeRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\X11ForwardingRequestInfo.cs
-
-
- Messages\Connection\ChannelRequest\XonXoffRequestInfo.cs
-
-
- Messages\Connection\ChannelSuccessMessage.cs
-
-
- Messages\Connection\ChannelWindowAdjustMessage.cs
-
-
- Messages\Connection\GlobalRequestMessage.cs
-
-
- Messages\Connection\GlobalRequestName.cs
-
-
- Messages\Connection\RequestFailureMessage.cs
-
-
- Messages\Connection\RequestSuccessMessage.cs
-
-
- Messages\Connection\TcpIpForwardGlobalRequestMessage.cs
-
-
- Messages\Message.cs
-
-
- Messages\MessageAttribute.cs
-
-
- Messages\ServiceName.cs
-
-
- Messages\Transport\DebugMessage.cs
-
-
- Messages\Transport\DisconnectMessage.cs
-
-
- Messages\Transport\DisconnectReason.cs
-
-
- Messages\Transport\IgnoreMessage.cs
-
-
- Messages\Transport\IKeyExchangedAllowed.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeGroup.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeInit.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeReply.cs
-
-
- Messages\Transport\KeyExchangeDhGroupExchangeRequest.cs
-
-
- Messages\Transport\KeyExchangeDhInitMessage.cs
-
-
- Messages\Transport\KeyExchangeDhReplyMessage.cs
-
-
- Messages\Transport\KeyExchangeEcdhInitMessage.cs
-
-
- Messages\Transport\KeyExchangeEcdhReplyMessage.cs
-
-
- Messages\Transport\KeyExchangeInitMessage.cs
-
-
- Messages\Transport\NewKeysMessage.cs
-
-
- Messages\Transport\ServiceAcceptMessage.cs
-
-
- Messages\Transport\ServiceRequestMessage.cs
-
-
- Messages\Transport\UnimplementedMessage.cs
-
-
- NoneAuthenticationMethod.cs
-
-
- PasswordAuthenticationMethod.cs
-
-
- PasswordConnectionInfo.cs
-
-
- PrivateKeyAuthenticationMethod.cs
-
-
- PrivateKeyConnectionInfo.cs
-
-
- PrivateKeyFile.cs
-
-
- ProxyTypes.cs
-
-
- RemotePathDoubleQuoteTransformation.cs
-
-
- RemotePathNoneTransformation.cs
-
-
- RemotePathShellQuoteTransformation.cs
-
-
- RemotePathTransformation.cs
-
-
- ScpClient.cs
-
-
- Security\Algorithm.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\sec\SECNamedCurves.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9Curve.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECParameters.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECParametersHolder.cs
-
-
- Security\Cryptography\BouncyCastle\asn1\x9\X9ECPoint.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\agreement\ECDHCBasicAgreement.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\AsymmetricCipherKeyPair.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\AsymmetricKeyParameter.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\digests\GeneralDigest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\digests\Sha256Digest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\generators\ECKeyPairGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\IAsymmetricCipherKeyPairGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\IDigest.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\KeyGenerationParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECDomainParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECKeyGenerationParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECPrivateKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\parameters\ECPublicKeyParameters.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\CryptoApiRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\DigestRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\prng\IRandomGenerator.cs
-
-
- Security\Cryptography\BouncyCastle\crypto\util\Pack.cs
-
-
- Security\Cryptography\BouncyCastle\math\BigInteger.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\SimpleBigDecimal.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\Tnaf.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\abc\ZTauElement.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECAlgorithms.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECCurve.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECFieldElement.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECLookupTable.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECPoint.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\ECPointMap.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\endo\ECEndomorphism.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\endo\GlvEndomorphism.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\LongArray.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\AbstractECMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\ECMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointCombMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\FixedPointUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\GlvMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\IPreCompCallback.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\PreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\ValidityPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafL2RMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WNafUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WTauNafMultiplier.cs
-
-
- Security\Cryptography\BouncyCastle\math\ec\multiplier\WTauNafPreCompInfo.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\FiniteFields.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\GenericPolynomialExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\GF2Polynomial.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IFiniteField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IPolynomial.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\IPolynomialExtensionField.cs
-
-
- Security\Cryptography\BouncyCastle\math\field\PrimeField.cs
-
-
- Security\Cryptography\BouncyCastle\math\raw\Mod.cs
-
-
- Security\Cryptography\BouncyCastle\math\raw\Nat.cs
-
-
- Security\Cryptography\BouncyCastle\security\DigestUtilities.cs
-
-
- Security\Cryptography\BouncyCastle\security\SecureRandom.cs
-
-
- Security\Cryptography\BouncyCastle\security\SecurityUtilityException.cs
-
-
- Security\Cryptography\BouncyCastle\util\Arrays.cs
-
-
- Security\Cryptography\BouncyCastle\util\BigIntegers.cs
-
-
- Security\Cryptography\BouncyCastle\util\encoders\Hex.cs
-
-
- Security\Cryptography\BouncyCastle\util\encoders\HexEncoder.cs
-
-
- Security\Cryptography\BouncyCastle\util\IMemoable.cs
-
-
- Security\Cryptography\BouncyCastle\util\Integers.cs
-
-
- Security\Cryptography\BouncyCastle\util\MemoableResetException.cs
-
-
- Security\Cryptography\BouncyCastle\util\Times.cs
-
-
- Security\CertificateHostAlgorithm.cs
-
-
- Security\Cryptography\Chaos.NaCl\CryptoBytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Ed25519.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Array16.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Array8.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\ByteIntegerConverter.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\base.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\base2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\d.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\d2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_1.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_cmov.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_cswap.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_frombytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_invert.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_isnegative.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_isnonzero.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_mul.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_mul121666.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_neg.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_pow22523.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sq.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sq2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_sub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\fe_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\FieldElement.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_double_scalarmult.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_frombytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_madd.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_msub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p1p1_to_p2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p1p1_to_p3.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p2_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p2_dbl.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_dbl.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_to_cached.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_p3_to_p2.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_precomp_0.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_scalarmult_base.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_sub.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\ge_tobytes.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\GroupElement.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\keypair.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\open.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\scalarmult.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_clamp.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_mul_add.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sc_reduce.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sign.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Ed25519Ref10\sqrtm1.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\InternalAssert.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Poly1305Donna.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Salsa\Salsa20.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Salsa\SalsaCore.cs
-
-
- Security\Cryptography\Chaos.NaCl\Internal\Sha512Internal.cs
-
-
- Security\Cryptography\Chaos.NaCl\MontgomeryCurve25519.cs
-
-
- Security\Cryptography\Chaos.NaCl\Sha512.cs
-
-
- Security\Cryptography\AsymmetricCipher.cs
-
-
- Security\Cryptography\Bcrypt.cs
-
-
- Security\Cryptography\BlockCipher.cs
-
-
- Security\Cryptography\Cipher.cs
-
-
- Security\Cryptography\CipherDigitalSignature.cs
-
-
- Security\Cryptography\Ciphers\AesCipher.cs
-
-
- Security\Cryptography\Ciphers\Arc4Cipher.cs
-
-
- Security\Cryptography\Ciphers\BlowfishCipher.cs
-
-
- Security\Cryptography\Ciphers\CastCipher.cs
-
-
- Security\Cryptography\Ciphers\CipherMode.cs
-
-
- Security\Cryptography\Ciphers\CipherPadding.cs
-
-
- Security\Cryptography\Ciphers\DesCipher.cs
-
-
- Security\Cryptography\Ciphers\Modes\CbcCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\CfbCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\CtrCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Modes\OfbCipherMode.cs
-
-
- Security\Cryptography\Ciphers\Paddings\PKCS7Padding.cs
-
-
- Security\Cryptography\Ciphers\RsaCipher.cs
-
-
- Security\Cryptography\Ciphers\SerpentCipher.cs
-
-
- Security\Cryptography\Ciphers\TripleDesCipher.cs
-
-
- Security\Cryptography\Ciphers\TwofishCipher.cs
-
-
- Security\Cryptography\DigitalSignature.cs
-
-
- Security\Cryptography\DsaDigitalSignature.cs
-
-
- Security\Cryptography\DsaKey.cs
-
-
- Security\Cryptography\ED25519DigitalSignature.cs
-
-
- Security\Cryptography\ED25519Key.cs
-
-
- Security\Cryptography\HMACMD5.cs
-
-
- Security\Cryptography\HMACSHA1.cs
-
-
- Security\Cryptography\HMACSHA256.cs
-
-
- Security\Cryptography\HMACSHA384.cs
-
-
- Security\Cryptography\HMACSHA512.cs
-
-
- Security\Cryptography\Key.cs
-
-
- Security\Cryptography\EcdsaDigitalSignature.cs
-
-
- Security\Cryptography\EcdsaKey.cs
-
-
- Security\Cryptography\RsaDigitalSignature.cs
-
-
- Security\Cryptography\RsaKey.cs
-
-
- Security\Cryptography\StreamCipher.cs
-
-
- Security\Cryptography\SymmetricCipher.cs
-
-
- Security\GroupExchangeHashData.cs
-
-
- Security\HostAlgorithm.cs
-
-
- Security\IKeyExchange.cs
-
-
- Security\KeyExchange.cs
-
-
- Security\KeyExchangeDiffieHellman.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup14Sha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup14Sha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup16Sha512.cs
-
-
- Security\KeyExchangeDiffieHellmanGroup1Sha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeSha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeSha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupExchangeShaBase.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha1.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha256.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupSha512.cs
-
-
- Security\KeyExchangeDiffieHellmanGroupShaBase.cs
-
-
- Security\KeyExchangeEC.cs
-
-
- Security\KeyExchangeECCurve25519.cs
-
-
- Security\KeyExchangeECDH.cs
-
-
- Security\KeyExchangeECDH256.cs
-
-
- Security\KeyExchangeECDH384.cs
-
-
- Security\KeyExchangeECDH521.cs
-
-
- Security\KeyExchangeHash.cs
-
-
- Security\KeyHostAlgorithm.cs
-
-
- ServiceFactory.cs
-
-
- Session.cs
-
-
- SftpClient.cs
-
-
- Sftp\Flags.cs
-
-
- Sftp\ISftpFileReader.cs
-
-
- Sftp\ISftpResponseFactory.cs
-
-
- Sftp\ISftpSession.cs
-
-
- Sftp\Requests\ExtendedRequests\FStatVfsRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\HardLinkRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\PosixRenameRequest.cs
-
-
- Sftp\Requests\ExtendedRequests\StatVfsRequest.cs
-
-
- Sftp\Requests\SftpBlockRequest.cs
-
-
- Sftp\Requests\SftpCloseRequest.cs
-
-
- Sftp\Requests\SftpExtendedRequest.cs
-
-
- Sftp\Requests\SftpFSetStatRequest.cs
-
-
- Sftp\Requests\SftpFStatRequest.cs
-
-
- Sftp\Requests\SftpInitRequest.cs
-
-
- Sftp\Requests\SftpLinkRequest.cs
-
-
- Sftp\Requests\SftpLStatRequest.cs
-
-
- Sftp\Requests\SftpMkDirRequest.cs
-
-
- Sftp\Requests\SftpOpenDirRequest.cs
-
-
- Sftp\Requests\SftpOpenRequest.cs
-
-
- Sftp\Requests\SftpReadDirRequest.cs
-
-
- Sftp\Requests\SftpReadLinkRequest.cs
-
-
- Sftp\Requests\SftpReadRequest.cs
-
-
- Sftp\Requests\SftpRealPathRequest.cs
-
-
- Sftp\Requests\SftpRemoveRequest.cs
-
-
- Sftp\Requests\SftpRenameRequest.cs
-
-
- Sftp\Requests\SftpRequest.cs
-
-
- Sftp\Requests\SftpRmDirRequest.cs
-
-
- Sftp\Requests\SftpSetStatRequest.cs
-
-
- Sftp\Requests\SftpStatRequest.cs
-
-
- Sftp\Requests\SftpSymLinkRequest.cs
-
-
- Sftp\Requests\SftpUnblockRequest.cs
-
-
- Sftp\Requests\SftpWriteRequest.cs
-
-
- Sftp\Responses\ExtendedReplies\ExtendedReplyInfo.cs
-
-
- Sftp\Responses\ExtendedReplies\StatVfsReplyInfo.cs
-
-
- Sftp\Responses\SftpAttrsResponse.cs
-
-
- Sftp\Responses\SftpDataResponse.cs
-
-
- Sftp\Responses\SftpExtendedReplyResponse.cs
-
-
- Sftp\Responses\SftpHandleResponse.cs
-
-
- Sftp\Responses\SftpNameResponse.cs
-
-
- Sftp\Responses\SftpResponse.cs
-
-
- Sftp\Responses\SftpStatusResponse.cs
-
-
- Sftp\Responses\SftpVersionResponse.cs
-
-
- Sftp\SftpCloseAsyncResult.cs
-
-
- Sftp\SftpDownloadAsyncResult.cs
-
-
- Sftp\SftpFile.cs
-
-
- Sftp\SftpFileAttributes.cs
-
-
- Sftp\SftpFileReader.cs
-
-
- Sftp\SftpFileStream.cs
-
-
- Sftp\SftpFileSystemInformation.cs
-
-
- Sftp\SftpListDirectoryAsyncResult.cs
-
-
- Sftp\SftpMessage.cs
-
-
- Sftp\SftpMessageTypes.cs
-
-
- Sftp\SftpOpenAsyncResult.cs
-
-
- Sftp\SftpReadAsyncResult.cs
-
-
- Sftp\SftpRealPathAsyncResult.cs
-
-
- Sftp\SftpResponseFactory.cs
-
-
- Sftp\SftpSession.cs
-
-
- Sftp\SFtpStatAsyncResult.cs
-
-
- Sftp\SftpSynchronizeDirectoriesAsyncResult.cs
-
-
- Sftp\SftpUploadAsyncResult.cs
-
-
- Sftp\StatusCodes.cs
-
-
- Shell.cs
-
-
- ShellStream.cs
-
-
- SshClient.cs
-
-
- SshCommand.cs
-
-
- SshMessageFactory.cs
-
-
- SubsystemSession.cs
-
-
-
- Properties\CommonAssemblyInfo.cs
-
-
-
-
-
-
-
- ..\..\packages\SshNet.Security.Cryptography.1.2.0\lib\wp8\SshNet.Security.Cryptography.dll
- True
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Renci.SshNet.WindowsPhone8/packages.config b/src/Renci.SshNet.WindowsPhone8/packages.config
deleted file mode 100644
index a571ea4f4..000000000
--- a/src/Renci.SshNet.WindowsPhone8/packages.config
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/src/Renci.SshNet/.editorconfig b/src/Renci.SshNet/.editorconfig
new file mode 100644
index 000000000..c5f4bdf61
--- /dev/null
+++ b/src/Renci.SshNet/.editorconfig
@@ -0,0 +1,161 @@
+[*.cs]
+
+#### Sonar rules ####
+
+# S1264: A "while" loop should be used instead of a "for" loop
+# https://rules.sonarsource.com/csharp/RSPEC-1264
+dotnet_diagnostic.S1264.severity = none
+
+# S1450: Private fields only used as local variables in methods should become local variables
+# https://rules.sonarsource.com/csharp/RSPEC-1450
+#
+# TODO: Re-enable when the following issue is resolved:
+# https://github.com/SonarSource/sonar-dotnet/issues/8239
+dotnet_diagnostic.S1450.severity = none
+
+# S2372: Exceptions should not be thrown from property getters
+# https://rules.sonarsource.com/csharp/RSPEC-2372/
+dotnet_diagnostic.S2372.severity = none
+
+# S2583: Conditionally executed code should be reachable
+# https://rules.sonarsource.com/csharp/RSPEC-2583/
+#
+# TODO: Re-enable when the following issue is resolved:
+# https://github.com/SonarSource/sonar-dotnet/issues/8264
+dotnet_diagnostic.S2583.severity = none
+
+# S2589: Boolean expressions should not be gratuitous
+# https://rules.sonarsource.com/csharp/RSPEC-2589/
+#
+# TODO: Re-enable when the following issue is resolved:
+# https://github.com/SonarSource/sonar-dotnet/issues/8262
+dotnet_diagnostic.S2589.severity = none
+
+dotnet_diagnostic.S2372.severity = none
+
+#### SYSLIB diagnostics ####
+
+# SYSLIB1045: Use 'GeneratedRegexAttribute' to generate the regular expression implementation at compile-time
+#
+# TODO: Remove this when https://github.com/sshnet/SSH.NET/issues/1131 is implemented.
+dotnet_diagnostic.SYSLIB1045.severity = none
+
+#### StyleCop Analyzers rules ####
+
+# SA1123: Do not place regions within elements
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1123.md
+dotnet_diagnostic.SA1123.severity = none
+
+# SA1124: Do not use regions
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1124.md
+dotnet_diagnostic.SA1124.severity = none
+
+# SA1202: Elements must be ordered by access
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1202.md
+dotnet_diagnostic.SA1202.severity = none
+
+# SA1204: Static elements must appear before instance elements
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1204.md
+dotnet_diagnostic.SA1204.severity = none
+
+# SA1310: Field names must not contain underscore
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1310.md
+#dotnet_diagnostic.SA1310.severity = none
+
+# SA1312: Variable names should begin with lower-case letter
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1312.md
+dotnet_diagnostic.SA1312.severity = none
+
+# SA1636: File header copyright text should match
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1636.md
+dotnet_diagnostic.SA1636.severity = none
+
+# SA1643: Destructor summary documentation must begin with standard text
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1643.md
+dotnet_diagnostic.SA1643.severity = none
+
+#### Meziantou.Analyzer rules ####
+
+# MA0001: StringComparison is missing
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0001.md
+dotnet_diagnostic.MA0001.severity = none
+
+# MA0011: IFormatProvider is missing
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0011.md
+#
+# TODO: Remove exclusion when issues are fixed
+dotnet_diagnostic.MA0011.severity = none
+
+# MA0015: Specify the parameter name in ArgumentException
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0015.md
+#
+# TODO: Remove exclusion when issues are fixed
+dotnet_diagnostic.MA0015.severity = none
+
+# MA0050: Validate arguments correctly in iterator methods
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0050.md
+#
+# TODO: Re-enable when https://github.com/meziantou/Meziantou.Analyzer/issues/617 is fixed
+dotnet_diagnostic.MA0050.severity = none
+
+# MA0053: Make class sealed
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0053.md
+MA0053.public_class_should_be_sealed = false
+
+# MA0055: Do not use finalizer
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0055.md
+#
+# TODO: Remove exclusion when issues are fixed
+dotnet_diagnostic.MA0055.severity = none
+
+# MA0110: Use the Regex source generator
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0110.md
+dotnet_diagnostic.MA0110.severity = none
+
+#### .NET Compiler Platform analysers rules ####
+
+# CA1030: Use events where appropriate
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1030
+dotnet_diagnostic.CA1030.severity = none
+
+# CA1031: Do not catch general exception types
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1031
+dotnet_diagnostic.CA1031.severity = none
+
+# CA1062: Validate arguments of public methods
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1062
+#
+# TODO: Remove exclusion when issues are fixed
+dotnet_diagnostic.CA1062.severity = none
+
+# CA1307: Specify StringComparison for clarity
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1307
+dotnet_diagnostic.CA1307.severity = none
+
+# CA1716: Identifiers should not match keywords
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1716
+dotnet_diagnostic.CA1716.severity = none
+
+# CA1822: Mark members as static
+# https://learn.microsoft.com/en-US/dotnet/fundamentals/code-analysis/quality-rules/ca1822
+dotnet_code_quality.CA1822.api_surface = private,internal
+
+# CA2213: Disposable fields should be disposed
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2213
+dotnet_diagnostic.CA2213.severity = none
+
+# CA3075: Insecure DTD Processing
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca3075
+dotnet_diagnostic.CA3075.severity = none
+
+# IDE0004: Types that own disposable fields should be disposable
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0004
+dotnet_diagnostic.IDE0004.severity = none
+
+# IDE0048: Add parentheses for clarity
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0047
+dotnet_diagnostic.IDE0048.severity = none
+
+# IDE0305: Collection initialization can be simplified
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0305
+dotnet_diagnostic.IDE0305.severity = none
diff --git a/src/Renci.SshNet/Abstractions/CryptoAbstraction.cs b/src/Renci.SshNet/Abstractions/CryptoAbstraction.cs
index ff9e50a52..ca187833f 100644
--- a/src/Renci.SshNet/Abstractions/CryptoAbstraction.cs
+++ b/src/Renci.SshNet/Abstractions/CryptoAbstraction.cs
@@ -5,12 +5,10 @@ namespace Renci.SshNet.Abstractions
{
internal static class CryptoAbstraction
{
-#if FEATURE_RNG_CREATE || FEATURE_RNG_CSP
private static readonly System.Security.Cryptography.RandomNumberGenerator Randomizer = CreateRandomNumberGenerator();
-#endif
///
- /// Generates a array of the specified length, and fills it with a
+ /// Generates a array of the specified length, and fills it with a
/// cryptographically strong random sequence of values.
///
/// The length of the array generate.
@@ -25,117 +23,56 @@ public static byte[] GenerateRandom(int length)
/// Fills an array of bytes with a cryptographically strong random sequence of values.
///
/// The array to fill with cryptographically strong random bytes.
- /// is null.
+ /// is .
///
/// The length of the byte array determines how many random bytes are produced.
///
public static void GenerateRandom(byte[] data)
{
-#if FEATURE_RNG_CREATE || FEATURE_RNG_CSP
Randomizer.GetBytes(data);
-#else
- if(data == null)
- throw new ArgumentNullException("data");
-
- var buffer = Windows.Security.Cryptography.CryptographicBuffer.GenerateRandom((uint) data.Length);
- System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.CopyTo(buffer, data);
-#endif
}
-#if FEATURE_RNG_CREATE || FEATURE_RNG_CSP
public static System.Security.Cryptography.RandomNumberGenerator CreateRandomNumberGenerator()
{
-#if FEATURE_RNG_CREATE
return System.Security.Cryptography.RandomNumberGenerator.Create();
-#elif FEATURE_RNG_CSP
- return new System.Security.Cryptography.RNGCryptoServiceProvider();
-#else
-#error Creation of RandomNumberGenerator is not implemented.
-#endif
}
-#endif // FEATURE_RNG_CREATE || FEATURE_RNG_CSP
-#if FEATURE_HASH_MD5
public static System.Security.Cryptography.MD5 CreateMD5()
{
+#pragma warning disable CA5351 // Do not use broken cryptographic algorithms
return System.Security.Cryptography.MD5.Create();
+#pragma warning restore CA5351 // Do not use broken cryptographic algorithms
}
-#else
- public static global::SshNet.Security.Cryptography.MD5 CreateMD5()
- {
- return new global::SshNet.Security.Cryptography.MD5();
- }
-#endif // FEATURE_HASH_MD5
-#if FEATURE_HASH_SHA1_CREATE || FEATURE_HASH_SHA1_MANAGED
public static System.Security.Cryptography.SHA1 CreateSHA1()
{
-#if FEATURE_HASH_SHA1_CREATE
+#pragma warning disable CA5350 // Do not use weak cryptographic algorithms
return System.Security.Cryptography.SHA1.Create();
-#elif FEATURE_HASH_SHA1_MANAGED
- return new System.Security.Cryptography.SHA1Managed();
-#endif
+#pragma warning restore CA5350 // Do not use weak cryptographic algorithms
}
-#else
- public static global::SshNet.Security.Cryptography.SHA1 CreateSHA1()
- {
- return new global::SshNet.Security.Cryptography.SHA1();
- }
-#endif
-#if FEATURE_HASH_SHA256_CREATE || FEATURE_HASH_SHA256_MANAGED
public static System.Security.Cryptography.SHA256 CreateSHA256()
{
-#if FEATURE_HASH_SHA256_CREATE
return System.Security.Cryptography.SHA256.Create();
-#elif FEATURE_HASH_SHA256_MANAGED
- return new System.Security.Cryptography.SHA256Managed();
-#endif
}
-#else
- public static global::SshNet.Security.Cryptography.SHA256 CreateSHA256()
- {
- return new global::SshNet.Security.Cryptography.SHA256();
- }
-#endif
-#if FEATURE_HASH_SHA384_CREATE || FEATURE_HASH_SHA384_MANAGED
public static System.Security.Cryptography.SHA384 CreateSHA384()
{
-#if FEATURE_HASH_SHA384_CREATE
return System.Security.Cryptography.SHA384.Create();
-#elif FEATURE_HASH_SHA384_MANAGED
- return new System.Security.Cryptography.SHA384Managed();
-#endif
- }
-#else
- public static global::SshNet.Security.Cryptography.SHA384 CreateSHA384()
- {
- return new global::SshNet.Security.Cryptography.SHA384();
}
-#endif
-#if FEATURE_HASH_SHA512_CREATE || FEATURE_HASH_SHA512_MANAGED
public static System.Security.Cryptography.SHA512 CreateSHA512()
{
-#if FEATURE_HASH_SHA512_CREATE
return System.Security.Cryptography.SHA512.Create();
-#elif FEATURE_HASH_SHA512_MANAGED
- return new System.Security.Cryptography.SHA512Managed();
-#endif
}
-#else
- public static global::SshNet.Security.Cryptography.SHA512 CreateSHA512()
- {
- return new global::SshNet.Security.Cryptography.SHA512();
- }
-#endif
#if FEATURE_HASH_RIPEMD160_CREATE || FEATURE_HASH_RIPEMD160_MANAGED
public static System.Security.Cryptography.RIPEMD160 CreateRIPEMD160()
{
#if FEATURE_HASH_RIPEMD160_CREATE
+#pragma warning disable CA5350 // Do not use weak cryptographic algorithms
return System.Security.Cryptography.RIPEMD160.Create();
+#pragma warning restore CA5350 // Do not use weak cryptographic algorithms
#else
return new System.Security.Cryptography.RIPEMD160Managed();
#endif
@@ -147,51 +84,34 @@ public static System.Security.Cryptography.RIPEMD160 CreateRIPEMD160()
}
#endif // FEATURE_HASH_RIPEMD160
-#if FEATURE_HMAC_MD5
public static System.Security.Cryptography.HMACMD5 CreateHMACMD5(byte[] key)
{
+#pragma warning disable CA5351 // Do not use broken cryptographic algorithms
return new System.Security.Cryptography.HMACMD5(key);
+#pragma warning restore CA5351 // Do not use broken cryptographic algorithms
}
public static HMACMD5 CreateHMACMD5(byte[] key, int hashSize)
{
+#pragma warning disable CA5351 // Do not use broken cryptographic algorithms
return new HMACMD5(key, hashSize);
+#pragma warning restore CA5351 // Do not use broken cryptographic algorithms
}
-#else
- public static global::SshNet.Security.Cryptography.HMACMD5 CreateHMACMD5(byte[] key)
- {
- return new global::SshNet.Security.Cryptography.HMACMD5(key);
- }
-
- public static global::SshNet.Security.Cryptography.HMACMD5 CreateHMACMD5(byte[] key, int hashSize)
- {
- return new global::SshNet.Security.Cryptography.HMACMD5(key, hashSize);
- }
-#endif // FEATURE_HMAC_MD5
-#if FEATURE_HMAC_SHA1
public static System.Security.Cryptography.HMACSHA1 CreateHMACSHA1(byte[] key)
{
+#pragma warning disable CA5350 // Do not use weak cryptographic algorithms
return new System.Security.Cryptography.HMACSHA1(key);
+#pragma warning restore CA5350 // Do not use weak cryptographic algorithms
}
public static HMACSHA1 CreateHMACSHA1(byte[] key, int hashSize)
{
+#pragma warning disable CA5350 // Do not use weak cryptographic algorithms
return new HMACSHA1(key, hashSize);
- }
-#else
- public static global::SshNet.Security.Cryptography.HMACSHA1 CreateHMACSHA1(byte[] key)
- {
- return new global::SshNet.Security.Cryptography.HMACSHA1(key);
+#pragma warning restore CA5350 // Do not use weak cryptographic algorithms
}
- public static global::SshNet.Security.Cryptography.HMACSHA1 CreateHMACSHA1(byte[] key, int hashSize)
- {
- return new global::SshNet.Security.Cryptography.HMACSHA1(key, hashSize);
- }
-#endif // FEATURE_HMAC_SHA1
-
-#if FEATURE_HMAC_SHA256
public static System.Security.Cryptography.HMACSHA256 CreateHMACSHA256(byte[] key)
{
return new System.Security.Cryptography.HMACSHA256(key);
@@ -201,19 +121,7 @@ public static HMACSHA256 CreateHMACSHA256(byte[] key, int hashSize)
{
return new HMACSHA256(key, hashSize);
}
-#else
- public static global::SshNet.Security.Cryptography.HMACSHA256 CreateHMACSHA256(byte[] key)
- {
- return new global::SshNet.Security.Cryptography.HMACSHA256(key);
- }
- public static global::SshNet.Security.Cryptography.HMACSHA256 CreateHMACSHA256(byte[] key, int hashSize)
- {
- return new global::SshNet.Security.Cryptography.HMACSHA256(key, hashSize);
- }
-#endif // FEATURE_HMAC_SHA256
-
-#if FEATURE_HMAC_SHA384
public static System.Security.Cryptography.HMACSHA384 CreateHMACSHA384(byte[] key)
{
return new System.Security.Cryptography.HMACSHA384(key);
@@ -223,19 +131,7 @@ public static HMACSHA384 CreateHMACSHA384(byte[] key, int hashSize)
{
return new HMACSHA384(key, hashSize);
}
-#else
- public static global::SshNet.Security.Cryptography.HMACSHA384 CreateHMACSHA384(byte[] key)
- {
- return new global::SshNet.Security.Cryptography.HMACSHA384(key);
- }
-
- public static global::SshNet.Security.Cryptography.HMACSHA384 CreateHMACSHA384(byte[] key, int hashSize)
- {
- return new global::SshNet.Security.Cryptography.HMACSHA384(key, hashSize);
- }
-#endif // FEATURE_HMAC_SHA384
-#if FEATURE_HMAC_SHA512
public static System.Security.Cryptography.HMACSHA512 CreateHMACSHA512(byte[] key)
{
return new System.Security.Cryptography.HMACSHA512(key);
@@ -245,22 +141,13 @@ public static HMACSHA512 CreateHMACSHA512(byte[] key, int hashSize)
{
return new HMACSHA512(key, hashSize);
}
-#else
- public static global::SshNet.Security.Cryptography.HMACSHA512 CreateHMACSHA512(byte[] key)
- {
- return new global::SshNet.Security.Cryptography.HMACSHA512(key);
- }
-
- public static global::SshNet.Security.Cryptography.HMACSHA512 CreateHMACSHA512(byte[] key, int hashSize)
- {
- return new global::SshNet.Security.Cryptography.HMACSHA512(key, hashSize);
- }
-#endif // FEATURE_HMAC_SHA512
#if FEATURE_HMAC_RIPEMD160
public static System.Security.Cryptography.HMACRIPEMD160 CreateHMACRIPEMD160(byte[] key)
{
+#pragma warning disable CA5350 // Do not use weak cryptographic algorithms
return new System.Security.Cryptography.HMACRIPEMD160(key);
+#pragma warning restore CA5350 // Do not use weak cryptographic algorithms
}
#else
public static global::SshNet.Security.Cryptography.HMACRIPEMD160 CreateHMACRIPEMD160(byte[] key)
diff --git a/src/Renci.SshNet/Abstractions/DiagnosticAbstraction.cs b/src/Renci.SshNet/Abstractions/DiagnosticAbstraction.cs
index 6fc1308ee..bc1248dc0 100644
--- a/src/Renci.SshNet/Abstractions/DiagnosticAbstraction.cs
+++ b/src/Renci.SshNet/Abstractions/DiagnosticAbstraction.cs
@@ -1,35 +1,69 @@
-using System.Diagnostics;
-#if FEATURE_DIAGNOSTICS_TRACESOURCE
-using System.Threading;
-#endif // FEATURE_DIAGNOSTICS_TRACESOURCE
+using System.ComponentModel;
+using System.Diagnostics;
namespace Renci.SshNet.Abstractions
{
- internal static class DiagnosticAbstraction
+ ///
+ /// Provides access to the internals of SSH.NET.
+ ///
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public static class DiagnosticAbstraction
{
-#if FEATURE_DIAGNOSTICS_TRACESOURCE
-
- private static readonly SourceSwitch SourceSwitch = new SourceSwitch("SshNetSwitch");
-
- public static bool IsEnabled(TraceEventType traceEventType)
- {
- return SourceSwitch.ShouldTrace(traceEventType);
- }
-
- private static readonly TraceSource Loggging =
-#if DEBUG
- new TraceSource("SshNet.Logging", SourceLevels.All);
-#else
- new TraceSource("SshNet.Logging");
-#endif // DEBUG
-#endif // FEATURE_DIAGNOSTICS_TRACESOURCE
+ ///
+ /// The instance used by SSH.NET.
+ ///
+ ///
+ ///
+ /// Currently, the library only traces events when compiled in Debug mode.
+ ///
+ ///
+ /// Configuration on .NET Core must be done programmatically, e.g.
+ ///
+ /// DiagnosticAbstraction.Source.Switch = new SourceSwitch("sourceSwitch", "Verbose");
+ /// DiagnosticAbstraction.Source.Listeners.Remove("Default");
+ /// DiagnosticAbstraction.Source.Listeners.Add(new ConsoleTraceListener());
+ /// DiagnosticAbstraction.Source.Listeners.Add(new TextWriterTraceListener("trace.log"));
+ ///
+ ///
+ ///
+ /// On .NET Framework, it is possible to configure via App.config, e.g.
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ /// ]]>
+ ///
+ ///
+ ///
+ public static readonly TraceSource Source = new TraceSource("SshNet.Logging");
+ ///
+ /// Logs a message to at the
+ /// level.
+ ///
+ /// The message to log.
+ /// The trace event type.
[Conditional("DEBUG")]
- public static void Log(string text)
+ public static void Log(string text, TraceEventType type = TraceEventType.Verbose)
{
-#if FEATURE_DIAGNOSTICS_TRACESOURCE
- Loggging.TraceEvent(TraceEventType.Verbose, Thread.CurrentThread.ManagedThreadId, text);
-#endif // FEATURE_DIAGNOSTICS_TRACESOURCE
+ Source.TraceEvent(type,
+ System.Environment.CurrentManagedThreadId,
+ text);
}
}
}
diff --git a/src/Renci.SshNet/Abstractions/DnsAbstraction.cs b/src/Renci.SshNet/Abstractions/DnsAbstraction.cs
index 0af35aeed..30a10fe87 100644
--- a/src/Renci.SshNet/Abstractions/DnsAbstraction.cs
+++ b/src/Renci.SshNet/Abstractions/DnsAbstraction.cs
@@ -1,6 +1,7 @@
using System;
using System.Net;
using System.Net.Sockets;
+using System.Threading.Tasks;
#if FEATURE_DNS_SYNC
#elif FEATURE_DNS_APM
@@ -24,16 +25,16 @@ internal static class DnsAbstraction
///
/// Returns the Internet Protocol (IP) addresses for the specified host.
///
- /// The host name or IP address to resolve
+ /// The host name or IP address to resolve.
///
/// An array of type that holds the IP addresses for the host that
/// is specified by the parameter.
///
- /// is null.
+ /// is .
/// An error is encountered when resolving .
public static IPAddress[] GetHostAddresses(string hostNameOrAddress)
{
- // TODO Eliminate sync variant, and implement timeout
+ /* TODO Eliminate sync variant, and implement timeout */
#if FEATURE_DNS_SYNC
return Dns.GetHostAddresses(hostNameOrAddress);
@@ -87,5 +88,20 @@ public static IPAddress[] GetHostAddresses(string hostNameOrAddress)
#endif // FEATURE_DEVICEINFORMATION_APM
#endif
}
+
+ ///
+ /// Returns the Internet Protocol (IP) addresses for the specified host.
+ ///
+ /// The host name or IP address to resolve.
+ ///
+ /// A task with result of an array of type that holds the IP addresses for the host that
+ /// is specified by the parameter.
+ ///
+ /// is .
+ /// An error is encountered when resolving .
+ public static Task GetHostAddressesAsync(string hostNameOrAddress)
+ {
+ return Dns.GetHostAddressesAsync(hostNameOrAddress);
+ }
}
}
diff --git a/src/Renci.SshNet/Abstractions/FileSystemAbstraction.cs b/src/Renci.SshNet/Abstractions/FileSystemAbstraction.cs
deleted file mode 100644
index 1bce391ed..000000000
--- a/src/Renci.SshNet/Abstractions/FileSystemAbstraction.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-
-namespace Renci.SshNet.Abstractions
-{
- internal class FileSystemAbstraction
- {
- ///
- /// Returns an enumerable collection of file information that matches a search pattern.
- ///
- ///
- /// The search string to match against the names of files.
- ///
- /// An enumerable collection of files that matches .
- ///
- /// is null.
- /// is null.
- /// The path represented by does not exist or is not valid.
- public static IEnumerable EnumerateFiles(DirectoryInfo directoryInfo, string searchPattern)
- {
- if (directoryInfo == null)
- throw new ArgumentNullException("directoryInfo");
-
-#if FEATURE_DIRECTORYINFO_ENUMERATEFILES
- return directoryInfo.EnumerateFiles(searchPattern);
-#else
- return directoryInfo.GetFiles(searchPattern);
-#endif
- }
- }
-}
diff --git a/src/Renci.SshNet/Abstractions/ReflectionAbstraction.cs b/src/Renci.SshNet/Abstractions/ReflectionAbstraction.cs
index 0c7abf5c6..d9e15a508 100644
--- a/src/Renci.SshNet/Abstractions/ReflectionAbstraction.cs
+++ b/src/Renci.SshNet/Abstractions/ReflectionAbstraction.cs
@@ -1,24 +1,16 @@
using System;
using System.Collections.Generic;
-#if FEATURE_REFLECTION_TYPEINFO
-using System.Reflection;
-#else
using System.Linq;
-#endif // FEATURE_REFLECTION_TYPEINFO
namespace Renci.SshNet.Abstractions
{
internal static class ReflectionAbstraction
{
public static IEnumerable GetCustomAttributes(this Type type, bool inherit)
- where T:Attribute
+ where T : Attribute
{
-#if FEATURE_REFLECTION_TYPEINFO
- return type.GetTypeInfo().GetCustomAttributes(inherit);
-#else
var attributes = type.GetCustomAttributes(typeof(T), inherit);
return attributes.Cast();
-#endif
}
}
}
diff --git a/src/Renci.SshNet/Abstractions/SocketAbstraction.cs b/src/Renci.SshNet/Abstractions/SocketAbstraction.cs
index 287caea66..f5f840336 100644
--- a/src/Renci.SshNet/Abstractions/SocketAbstraction.cs
+++ b/src/Renci.SshNet/Abstractions/SocketAbstraction.cs
@@ -3,6 +3,8 @@
using System.Net;
using System.Net.Sockets;
using System.Threading;
+using System.Threading.Tasks;
+
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Transport;
@@ -14,15 +16,10 @@ public static bool CanRead(Socket socket)
{
if (socket.Connected)
{
-#if FEATURE_SOCKET_POLL
return socket.Poll(-1, SelectMode.SelectRead) && socket.Available > 0;
-#else
- return true;
-#endif // FEATURE_SOCKET_POLL
}
return false;
-
}
///
@@ -31,17 +28,13 @@ public static bool CanRead(Socket socket)
///
/// The to check.
///
- /// true if can be written to; otherwise, false.
+ /// if can be written to; otherwise, .
///
public static bool CanWrite(Socket socket)
{
if (socket != null && socket.Connected)
{
-#if FEATURE_SOCKET_POLL
return socket.Poll(-1, SelectMode.SelectWrite);
-#else
- return true;
-#endif // FEATURE_SOCKET_POLL
}
return false;
@@ -50,19 +43,24 @@ public static bool CanWrite(Socket socket)
public static Socket Connect(IPEndPoint remoteEndpoint, TimeSpan connectTimeout)
{
var socket = new Socket(remoteEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
- ConnectCore(socket, remoteEndpoint, connectTimeout, true);
+ ConnectCore(socket, remoteEndpoint, connectTimeout, ownsSocket: true);
return socket;
}
public static void Connect(Socket socket, IPEndPoint remoteEndpoint, TimeSpan connectTimeout)
{
- ConnectCore(socket, remoteEndpoint, connectTimeout, false);
+ ConnectCore(socket, remoteEndpoint, connectTimeout, ownsSocket: false);
+ }
+
+ public static async Task ConnectAsync(Socket socket, IPEndPoint remoteEndpoint, CancellationToken cancellationToken)
+ {
+ await socket.ConnectAsync(remoteEndpoint, cancellationToken).ConfigureAwait(false);
}
private static void ConnectCore(Socket socket, IPEndPoint remoteEndpoint, TimeSpan connectTimeout, bool ownsSocket)
{
#if FEATURE_SOCKET_EAP
- var connectCompleted = new ManualResetEvent(false);
+ var connectCompleted = new ManualResetEvent(initialState: false);
var args = new SocketAsyncEventArgs
{
UserToken = connectCompleted,
@@ -81,8 +79,10 @@ private static void ConnectCore(Socket socket, IPEndPoint remoteEndpoint, TimeSp
// dispose Socket
socket.Dispose();
}
+
// dispose ManualResetEvent
connectCompleted.Dispose();
+
// dispose SocketAsyncEventArgs
args.Dispose();
@@ -143,7 +143,6 @@ public static void ClearReadBuffer(Socket socket)
public static int ReadPartial(Socket socket, byte[] buffer, int offset, int size, TimeSpan timeout)
{
-#if FEATURE_SOCKET_SYNC
socket.ReceiveTimeout = (int) timeout.TotalMilliseconds;
try
@@ -153,57 +152,18 @@ public static int ReadPartial(Socket socket, byte[] buffer, int offset, int size
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.TimedOut)
- throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
- "Socket read operation has timed out after {0:F0} milliseconds.", timeout.TotalMilliseconds));
- throw;
- }
-#elif FEATURE_SOCKET_EAP
- var receiveCompleted = new ManualResetEvent(false);
- var sendReceiveToken = new PartialSendReceiveToken(socket, receiveCompleted);
- var args = new SocketAsyncEventArgs
- {
- RemoteEndPoint = socket.RemoteEndPoint,
- UserToken = sendReceiveToken
- };
- args.Completed += ReceiveCompleted;
- args.SetBuffer(buffer, offset, size);
-
- try
- {
- if (socket.ReceiveAsync(args))
{
- if (!receiveCompleted.WaitOne(timeout))
- throw new SshOperationTimeoutException(
- string.Format(
- CultureInfo.InvariantCulture,
- "Socket read operation has timed out after {0:F0} milliseconds.",
- timeout.TotalMilliseconds));
- }
- else
- {
- sendReceiveToken.Process(args);
+ throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
+ "Socket read operation has timed out after {0:F0} milliseconds.",
+ timeout.TotalMilliseconds));
}
- if (args.SocketError != SocketError.Success)
- throw new SocketException((int) args.SocketError);
-
- return args.BytesTransferred;
- }
- finally
- {
- // initialize token to avoid the waithandle getting used after it's disposed
- args.UserToken = null;
- args.Dispose();
- receiveCompleted.Dispose();
+ throw;
}
-#else
- #error Receiving data from a Socket is not implemented.
-#endif
}
public static void ReadContinuous(Socket socket, byte[] buffer, int offset, int size, Action processReceivedBytesAction)
{
-#if FEATURE_SOCKET_SYNC
// do not time-out receive
socket.ReceiveTimeout = 0;
@@ -213,15 +173,20 @@ public static void ReadContinuous(Socket socket, byte[] buffer, int offset, int
{
var bytesRead = socket.Receive(buffer, offset, size, SocketFlags.None);
if (bytesRead == 0)
+ {
break;
+ }
processReceivedBytesAction(buffer, offset, bytesRead);
}
catch (SocketException ex)
{
if (IsErrorResumable(ex.SocketErrorCode))
+ {
continue;
+ }
+#pragma warning disable IDE0010 // Add missing cases
switch (ex.SocketErrorCode)
{
case SocketError.ConnectionAborted:
@@ -235,32 +200,9 @@ public static void ReadContinuous(Socket socket, byte[] buffer, int offset, int
default:
throw; // throw any other error
}
+#pragma warning restore IDE0010 // Add missing cases
}
}
-#elif FEATURE_SOCKET_EAP
- var completionWaitHandle = new ManualResetEvent(false);
- var readToken = new ContinuousReceiveToken(socket, processReceivedBytesAction, completionWaitHandle);
- var args = new SocketAsyncEventArgs
- {
- RemoteEndPoint = socket.RemoteEndPoint,
- UserToken = readToken
- };
- args.Completed += ReceiveCompleted;
- args.SetBuffer(buffer, offset, size);
-
- if (!socket.ReceiveAsync(args))
- {
- ReceiveCompleted(null, args);
- }
-
- completionWaitHandle.WaitOne();
- completionWaitHandle.Dispose();
-
- if (readToken.Exception != null)
- throw readToken.Exception;
-#else
- #error Receiving data from a Socket is not implemented.
-#endif
}
///
@@ -277,7 +219,9 @@ public static int ReadByte(Socket socket, TimeSpan timeout)
{
var buffer = new byte[1];
if (Read(socket, buffer, 0, 1, timeout) == 0)
+ {
return -1;
+ }
return buffer[0];
}
@@ -290,14 +234,14 @@ public static int ReadByte(Socket socket, TimeSpan timeout)
/// The write failed.
public static void SendByte(Socket socket, byte value)
{
- var buffer = new[] {value};
+ var buffer = new[] { value };
Send(socket, buffer, 0, 1);
}
///
/// Receives data from a bound .
///
- ///
+ /// The to read from.
/// The number of bytes to receive.
/// Specifies the amount of time after which the call will time out.
///
@@ -313,14 +257,14 @@ public static void SendByte(Socket socket, byte value)
public static byte[] Read(Socket socket, int size, TimeSpan timeout)
{
var buffer = new byte[size];
- Read(socket, buffer, 0, size, timeout);
+ _ = Read(socket, buffer, 0, size, timeout);
return buffer;
}
///
/// Receives data from a bound into a receive buffer.
///
- ///
+ /// The to read from.
/// An array of type that is the storage location for the received data.
/// The position in parameter to store the received data.
/// The number of bytes to receive.
@@ -341,11 +285,10 @@ public static byte[] Read(Socket socket, int size, TimeSpan timeout)
///
public static int Read(Socket socket, byte[] buffer, int offset, int size, TimeSpan readTimeout)
{
-#if FEATURE_SOCKET_SYNC
var totalBytesRead = 0;
var totalBytesToRead = size;
- socket.ReceiveTimeout = (int)readTimeout.TotalMilliseconds;
+ socket.ReceiveTimeout = (int) readTimeout.TotalMilliseconds;
do
{
@@ -353,7 +296,9 @@ public static int Read(Socket socket, byte[] buffer, int offset, int size, TimeS
{
var bytesRead = socket.Receive(buffer, offset + totalBytesRead, totalBytesToRead - totalBytesRead, SocketFlags.None);
if (bytesRead == 0)
+ {
return 0;
+ }
totalBytesRead += bytesRead;
}
@@ -366,56 +311,31 @@ public static int Read(Socket socket, byte[] buffer, int offset, int size, TimeS
}
if (ex.SocketErrorCode == SocketError.TimedOut)
+ {
throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
- "Socket read operation has timed out after {0:F0} milliseconds.", readTimeout.TotalMilliseconds));
+ "Socket read operation has timed out after {0:F0} milliseconds.",
+ readTimeout.TotalMilliseconds));
+ }
- throw;
+ throw;
}
}
while (totalBytesRead < totalBytesToRead);
return totalBytesRead;
-#elif FEATURE_SOCKET_EAP
- var receiveCompleted = new ManualResetEvent(false);
- var sendReceiveToken = new BlockingSendReceiveToken(socket, buffer, offset, size, receiveCompleted);
-
- var args = new SocketAsyncEventArgs
- {
- UserToken = sendReceiveToken,
- RemoteEndPoint = socket.RemoteEndPoint
- };
- args.Completed += ReceiveCompleted;
- args.SetBuffer(buffer, offset, size);
-
- try
- {
- if (socket.ReceiveAsync(args))
- {
- if (!receiveCompleted.WaitOne(readTimeout))
- throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
- "Socket read operation has timed out after {0:F0} milliseconds.", readTimeout.TotalMilliseconds));
- }
- else
- {
- sendReceiveToken.Process(args);
- }
-
- if (args.SocketError != SocketError.Success)
- throw new SocketException((int) args.SocketError);
+ }
- return sendReceiveToken.TotalBytesTransferred;
- }
- finally
- {
- // initialize token to avoid the waithandle getting used after it's disposed
- args.UserToken = null;
- args.Dispose();
- receiveCompleted.Dispose();
- }
+#if NET6_0_OR_GREATER
+ public static async Task ReadAsync(Socket socket, byte[] buffer, CancellationToken cancellationToken)
+ {
+ return await socket.ReceiveAsync(buffer, SocketFlags.None, cancellationToken).ConfigureAwait(false);
+ }
#else
-#error Receiving data from a Socket is not implemented.
-#endif
+ public static Task ReadAsync(Socket socket, byte[] buffer, CancellationToken cancellationToken)
+ {
+ return socket.ReceiveAsync(buffer, 0, buffer.Length, cancellationToken);
}
+#endif
public static void Send(Socket socket, byte[] data)
{
@@ -424,7 +344,6 @@ public static void Send(Socket socket, byte[] data)
public static void Send(Socket socket, byte[] data, int offset, int size)
{
-#if FEATURE_SOCKET_SYNC
var totalBytesSent = 0; // how many bytes are already sent
var totalBytesToSend = size;
@@ -434,8 +353,10 @@ public static void Send(Socket socket, byte[] data, int offset, int size)
{
var bytesSent = socket.Send(data, offset + totalBytesSent, totalBytesToSend - totalBytesSent, SocketFlags.None);
if (bytesSent == 0)
+ {
throw new SshConnectionException("An established connection was aborted by the server.",
DisconnectReason.ConnectionLost);
+ }
totalBytesSent += bytesSent;
}
@@ -447,53 +368,17 @@ public static void Send(Socket socket, byte[] data, int offset, int size)
ThreadAbstraction.Sleep(30);
}
else
- throw; // any serious error occurr
- }
- } while (totalBytesSent < totalBytesToSend);
-#elif FEATURE_SOCKET_EAP
- var sendCompleted = new ManualResetEvent(false);
- var sendReceiveToken = new BlockingSendReceiveToken(socket, data, offset, size, sendCompleted);
- var socketAsyncSendArgs = new SocketAsyncEventArgs
- {
- RemoteEndPoint = socket.RemoteEndPoint,
- UserToken = sendReceiveToken
- };
- socketAsyncSendArgs.SetBuffer(data, offset, size);
- socketAsyncSendArgs.Completed += SendCompleted;
-
- try
- {
- if (socket.SendAsync(socketAsyncSendArgs))
- {
- if (!sendCompleted.WaitOne())
- throw new SocketException((int) SocketError.TimedOut);
- }
- else
- {
- sendReceiveToken.Process(socketAsyncSendArgs);
+ {
+ throw; // any serious error occurr
+ }
}
-
- if (socketAsyncSendArgs.SocketError != SocketError.Success)
- throw new SocketException((int) socketAsyncSendArgs.SocketError);
-
- if (sendReceiveToken.TotalBytesTransferred == 0)
- throw new SshConnectionException("An established connection was aborted by the server.",
- DisconnectReason.ConnectionLost);
}
- finally
- {
- // initialize token to avoid the completion waithandle getting used after it's disposed
- socketAsyncSendArgs.UserToken = null;
- socketAsyncSendArgs.Dispose();
- sendCompleted.Dispose();
- }
-#else
- #error Sending data to a Socket is not implemented.
-#endif
+ while (totalBytesSent < totalBytesToSend);
}
public static bool IsErrorResumable(SocketError socketError)
{
+#pragma warning disable IDE0010 // Add missing cases
switch (socketError)
{
case SocketError.WouldBlock:
@@ -503,210 +388,15 @@ public static bool IsErrorResumable(SocketError socketError)
default:
return false;
}
+#pragma warning restore IDE0010 // Add missing cases
}
#if FEATURE_SOCKET_EAP
private static void ConnectCompleted(object sender, SocketAsyncEventArgs e)
{
var eventWaitHandle = (ManualResetEvent) e.UserToken;
- if (eventWaitHandle != null)
- eventWaitHandle.Set();
+ _ = eventWaitHandle?.Set();
}
#endif // FEATURE_SOCKET_EAP
-
-#if FEATURE_SOCKET_EAP && !FEATURE_SOCKET_SYNC
- private static void ReceiveCompleted(object sender, SocketAsyncEventArgs e)
- {
- var sendReceiveToken = (Token) e.UserToken;
- if (sendReceiveToken != null)
- sendReceiveToken.Process(e);
- }
-
- private static void SendCompleted(object sender, SocketAsyncEventArgs e)
- {
- var sendReceiveToken = (Token) e.UserToken;
- if (sendReceiveToken != null)
- sendReceiveToken.Process(e);
- }
-
- private interface Token
- {
- void Process(SocketAsyncEventArgs args);
- }
-
- private class BlockingSendReceiveToken : Token
- {
- public BlockingSendReceiveToken(Socket socket, byte[] buffer, int offset, int size, EventWaitHandle completionWaitHandle)
- {
- _socket = socket;
- _buffer = buffer;
- _offset = offset;
- _bytesToTransfer = size;
- _completionWaitHandle = completionWaitHandle;
- }
-
- public void Process(SocketAsyncEventArgs args)
- {
- if (args.SocketError == SocketError.Success)
- {
- TotalBytesTransferred += args.BytesTransferred;
-
- if (TotalBytesTransferred == _bytesToTransfer)
- {
- // finished transferring specified bytes
- _completionWaitHandle.Set();
- return;
- }
-
- if (args.BytesTransferred == 0)
- {
- // remote server closed the connection
- _completionWaitHandle.Set();
- return;
- }
-
- _offset += args.BytesTransferred;
- args.SetBuffer(_buffer, _offset, _bytesToTransfer - TotalBytesTransferred);
- ResumeOperation(args);
- return;
- }
-
- if (IsErrorResumable(args.SocketError))
- {
- ThreadAbstraction.Sleep(30);
- ResumeOperation(args);
- return;
- }
-
- // we're dealing with a (fatal) error
- _completionWaitHandle.Set();
- }
-
- private void ResumeOperation(SocketAsyncEventArgs args)
- {
- switch (args.LastOperation)
- {
- case SocketAsyncOperation.Receive:
- _socket.ReceiveAsync(args);
- break;
- case SocketAsyncOperation.Send:
- _socket.SendAsync(args);
- break;
- }
- }
-
- private readonly int _bytesToTransfer;
- public int TotalBytesTransferred { get; private set; }
- private readonly EventWaitHandle _completionWaitHandle;
- private readonly Socket _socket;
- private readonly byte[] _buffer;
- private int _offset;
- }
-
- private class PartialSendReceiveToken : Token
- {
- public PartialSendReceiveToken(Socket socket, EventWaitHandle completionWaitHandle)
- {
- _socket = socket;
- _completionWaitHandle = completionWaitHandle;
- }
-
- public void Process(SocketAsyncEventArgs args)
- {
- if (args.SocketError == SocketError.Success)
- {
- _completionWaitHandle.Set();
- return;
- }
-
- if (IsErrorResumable(args.SocketError))
- {
- ThreadAbstraction.Sleep(30);
- ResumeOperation(args);
- return;
- }
-
- // we're dealing with a (fatal) error
- _completionWaitHandle.Set();
- }
-
- private void ResumeOperation(SocketAsyncEventArgs args)
- {
- switch (args.LastOperation)
- {
- case SocketAsyncOperation.Receive:
- _socket.ReceiveAsync(args);
- break;
- case SocketAsyncOperation.Send:
- _socket.SendAsync(args);
- break;
- }
- }
-
- private readonly EventWaitHandle _completionWaitHandle;
- private readonly Socket _socket;
- }
-
- private class ContinuousReceiveToken : Token
- {
- public ContinuousReceiveToken(Socket socket, Action processReceivedBytesAction, EventWaitHandle completionWaitHandle)
- {
- _socket = socket;
- _processReceivedBytesAction = processReceivedBytesAction;
- _completionWaitHandle = completionWaitHandle;
- }
-
- public Exception Exception { get; private set; }
-
- public void Process(SocketAsyncEventArgs args)
- {
- if (args.SocketError == SocketError.Success)
- {
- if (args.BytesTransferred == 0)
- {
- // remote socket was closed
- _completionWaitHandle.Set();
- return;
- }
-
- _processReceivedBytesAction(args.Buffer, args.Offset, args.BytesTransferred);
- ResumeOperation(args);
- return;
- }
-
- if (IsErrorResumable(args.SocketError))
- {
- ThreadAbstraction.Sleep(30);
- ResumeOperation(args);
- return;
- }
-
- if (args.SocketError != SocketError.OperationAborted)
- {
- Exception = new SocketException((int) args.SocketError);
- }
-
- // we're dealing with a (fatal) error
- _completionWaitHandle.Set();
- }
-
- private void ResumeOperation(SocketAsyncEventArgs args)
- {
- switch (args.LastOperation)
- {
- case SocketAsyncOperation.Receive:
- _socket.ReceiveAsync(args);
- break;
- case SocketAsyncOperation.Send:
- _socket.SendAsync(args);
- break;
- }
- }
-
- private readonly EventWaitHandle _completionWaitHandle;
- private readonly Socket _socket;
- private readonly Action _processReceivedBytesAction;
- }
-#endif // FEATURE_SOCKET_EAP && !FEATURE_SOCKET_SYNC
}
}
diff --git a/src/Renci.SshNet/Abstractions/SocketExtensions.cs b/src/Renci.SshNet/Abstractions/SocketExtensions.cs
new file mode 100644
index 000000000..2c34c899c
--- /dev/null
+++ b/src/Renci.SshNet/Abstractions/SocketExtensions.cs
@@ -0,0 +1,134 @@
+#if !NET6_0_OR_GREATER
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Renci.SshNet.Abstractions
+{
+ // Async helpers based on https://devblogs.microsoft.com/pfxteam/awaiting-socket-operations/
+ internal static class SocketExtensions
+ {
+ private sealed class AwaitableSocketAsyncEventArgs : SocketAsyncEventArgs, INotifyCompletion
+ {
+ private static readonly Action SENTINEL = () => { };
+
+ private bool _isCancelled;
+ private Action _continuationAction;
+
+ public AwaitableSocketAsyncEventArgs()
+ {
+ Completed += (sender, e) => SetCompleted();
+ }
+
+ public AwaitableSocketAsyncEventArgs ExecuteAsync(Func func)
+ {
+ if (!func(this))
+ {
+ SetCompleted();
+ }
+
+ return this;
+ }
+
+ public void SetCompleted()
+ {
+ IsCompleted = true;
+
+ var continuation = _continuationAction ?? Interlocked.CompareExchange(ref _continuationAction, SENTINEL, comparand: null);
+ if (continuation is not null)
+ {
+ continuation();
+ }
+ }
+
+ public void SetCancelled()
+ {
+ _isCancelled = true;
+ SetCompleted();
+ }
+
+#pragma warning disable S1144 // Unused private types or members should be removed
+ public AwaitableSocketAsyncEventArgs GetAwaiter()
+#pragma warning restore S1144 // Unused private types or members should be removed
+ {
+ return this;
+ }
+
+ public bool IsCompleted { get; private set; }
+
+ void INotifyCompletion.OnCompleted(Action continuation)
+ {
+ if (_continuationAction == SENTINEL || Interlocked.CompareExchange(ref _continuationAction, continuation, comparand: null) == SENTINEL)
+ {
+ // We have already completed; run continuation asynchronously
+ _ = Task.Run(continuation);
+ }
+ }
+
+#pragma warning disable S1144 // Unused private types or members should be removed
+ public void GetResult()
+#pragma warning restore S1144 // Unused private types or members should be removed
+ {
+ if (_isCancelled)
+ {
+ throw new TaskCanceledException();
+ }
+
+ if (!IsCompleted)
+ {
+ // We don't support sync/async
+ throw new InvalidOperationException("The asynchronous operation has not yet completed.");
+ }
+
+ if (SocketError != SocketError.Success)
+ {
+ throw new SocketException((int)SocketError);
+ }
+ }
+ }
+
+ public static async Task ConnectAsync(this Socket socket, IPEndPoint remoteEndpoint, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ using (var args = new AwaitableSocketAsyncEventArgs())
+ {
+ args.RemoteEndPoint = remoteEndpoint;
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(o => ((AwaitableSocketAsyncEventArgs)o).SetCancelled(), args, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(o => ((AwaitableSocketAsyncEventArgs) o).SetCancelled(), args, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ await args.ExecuteAsync(socket.ConnectAsync);
+ }
+ }
+ }
+
+ public static async Task ReceiveAsync(this Socket socket, byte[] buffer, int offset, int length, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ using (var args = new AwaitableSocketAsyncEventArgs())
+ {
+ args.SetBuffer(buffer, offset, length);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(o => ((AwaitableSocketAsyncEventArgs) o).SetCancelled(), args, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(o => ((AwaitableSocketAsyncEventArgs) o).SetCancelled(), args, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ await args.ExecuteAsync(socket.ReceiveAsync);
+ }
+
+ return args.BytesTransferred;
+ }
+ }
+ }
+}
+#endif
diff --git a/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs b/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs
index ee21ec7ef..b3fe2bb4f 100644
--- a/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs
+++ b/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs
@@ -1,4 +1,6 @@
using System;
+using System.Threading;
+using System.Threading.Tasks;
namespace Renci.SshNet.Abstractions
{
@@ -10,24 +12,28 @@ internal static class ThreadAbstraction
/// The number of milliseconds for which the thread is suspended.
public static void Sleep(int millisecondsTimeout)
{
-#if FEATURE_THREAD_SLEEP
- System.Threading.Thread.Sleep(millisecondsTimeout);
-#elif FEATURE_THREAD_TAP
- System.Threading.Tasks.Task.Delay(millisecondsTimeout).GetAwaiter().GetResult();
-#else
- #error Suspend of the current thread is not implemented.
-#endif
+ Thread.Sleep(millisecondsTimeout);
}
- public static void ExecuteThreadLongRunning(Action action)
+ ///
+ /// Creates and starts a long-running for the specified .
+ ///
+ /// The to start.
+ /// is .
+ ///
+ /// A task that represents the execution of the specified .
+ ///
+ public static Task ExecuteThreadLongRunning(Action action)
{
-#if FEATURE_THREAD_TAP
- var taskCreationOptions = System.Threading.Tasks.TaskCreationOptions.LongRunning;
- System.Threading.Tasks.Task.Factory.StartNew(action, taskCreationOptions);
-#else
- var thread = new System.Threading.Thread(() => action());
- thread.Start();
-#endif
+ if (action is null)
+ {
+ throw new ArgumentNullException(nameof(action));
+ }
+
+ return Task.Factory.StartNew(action,
+ CancellationToken.None,
+ TaskCreationOptions.LongRunning,
+ TaskScheduler.Current);
}
///
@@ -36,16 +42,12 @@ public static void ExecuteThreadLongRunning(Action action)
/// The action to execute.
public static void ExecuteThread(Action action)
{
-#if FEATURE_THREAD_THREADPOOL
- if (action == null)
- throw new ArgumentNullException("action");
+ if (action is null)
+ {
+ throw new ArgumentNullException(nameof(action));
+ }
- System.Threading.ThreadPool.QueueUserWorkItem(o => action());
-#elif FEATURE_THREAD_TAP
- System.Threading.Tasks.Task.Run(action);
-#else
- #error Execution of action in a separate thread is not implemented.
-#endif
+ _ = ThreadPool.QueueUserWorkItem(o => action());
}
}
}
diff --git a/src/Renci.SshNet/AuthenticationMethod.cs b/src/Renci.SshNet/AuthenticationMethod.cs
index 1a285d8c8..16783f1bd 100644
--- a/src/Renci.SshNet/AuthenticationMethod.cs
+++ b/src/Renci.SshNet/AuthenticationMethod.cs
@@ -1,10 +1,9 @@
-using Renci.SshNet.Common;
-using System;
+using System;
namespace Renci.SshNet
{
///
- /// Base class for all supported authentication methods
+ /// Base class for all supported authentication methods.
///
public abstract class AuthenticationMethod : IAuthenticationMethod
{
@@ -14,7 +13,9 @@ public abstract class AuthenticationMethod : IAuthenticationMethod
///
/// The name of the authentication method.
///
+#pragma warning disable CA2119 // Seal methods that satisfy private interfaces
public abstract string Name { get; }
+#pragma warning restore CA2119 // Seal methods that satisfy private interfaces
///
/// Gets connection username.
@@ -22,7 +23,7 @@ public abstract class AuthenticationMethod : IAuthenticationMethod
public string Username { get; private set; }
///
- /// Gets list of allowed authentications.
+ /// Gets or sets the list of allowed authentications.
///
public string[] AllowedAuthentications { get; protected set; }
@@ -30,11 +31,13 @@ public abstract class AuthenticationMethod : IAuthenticationMethod
/// Initializes a new instance of the class.
///
/// The username.
- /// is whitespace or null.
+ /// is whitespace or .
protected AuthenticationMethod(string username)
{
- if (username.IsNullOrWhiteSpace())
+ if (string.IsNullOrWhiteSpace(username))
+ {
throw new ArgumentException("username");
+ }
Username = username;
}
diff --git a/src/Renci.SshNet/AuthenticationResult.cs b/src/Renci.SshNet/AuthenticationResult.cs
index 714149669..9dc54648f 100644
--- a/src/Renci.SshNet/AuthenticationResult.cs
+++ b/src/Renci.SshNet/AuthenticationResult.cs
@@ -1,7 +1,7 @@
namespace Renci.SshNet
{
///
- /// Represents possible authentication methods results
+ /// Represents possible authentication methods results.
///
public enum AuthenticationResult
{
@@ -9,10 +9,12 @@ public enum AuthenticationResult
/// Authentication was successful.
///
Success,
+
///
/// Authentication completed with partial success.
///
PartialSuccess,
+
///
/// Authentication failed.
///
diff --git a/src/Renci.SshNet/BaseClient.cs b/src/Renci.SshNet/BaseClient.cs
index 5b0e01c90..56d2145cc 100644
--- a/src/Renci.SshNet/BaseClient.cs
+++ b/src/Renci.SshNet/BaseClient.cs
@@ -1,6 +1,8 @@
using System;
using System.Net.Sockets;
using System.Threading;
+using System.Threading.Tasks;
+
using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Transport;
@@ -10,7 +12,7 @@ namespace Renci.SshNet
///
/// Serves as base class for client implementations, provides common client functionality.
///
- public abstract class BaseClient : IDisposable
+ public abstract class BaseClient : IBaseClient
{
///
/// Holds value indicating whether the connection info is owned by this client.
@@ -22,6 +24,7 @@ public abstract class BaseClient : IDisposable
private TimeSpan _keepAliveInterval;
private Timer _keepAliveTimer;
private ConnectionInfo _connectionInfo;
+ private bool _isDisposed;
///
/// Gets the current session.
@@ -66,7 +69,7 @@ private set
/// Gets a value indicating whether this client is connected to the server.
///
///
- /// true if this client is connected; otherwise, false.
+ /// if this client is connected; otherwise, .
///
/// The method was called after the client was disposed.
public bool IsConnected
@@ -99,7 +102,9 @@ public TimeSpan KeepAliveInterval
CheckDisposed();
if (value == _keepAliveInterval)
+ {
return;
+ }
if (value == SshNet.Session.InfiniteTimeSpan)
{
@@ -112,8 +117,7 @@ public TimeSpan KeepAliveInterval
{
// change the due time and interval of the timer if has already
// been created (which means the client is connected)
-
- _keepAliveTimer.Change(value, value);
+ _ = _keepAliveTimer.Change(value, value);
}
else if (IsSessionConnected())
{
@@ -125,9 +129,10 @@ public TimeSpan KeepAliveInterval
_keepAliveTimer = CreateKeepAliveTimer(value, value);
}
- // note that if the client is not yet connected, then the timer will be created with the
+ // note that if the client is not yet connected, then the timer will be created with the
// new interval when Connect() is invoked
}
+
_keepAliveInterval = value;
}
}
@@ -135,27 +140,26 @@ public TimeSpan KeepAliveInterval
///
/// Occurs when an error occurred.
///
- ///
- ///
- ///
public event EventHandler ErrorOccurred;
///
/// Occurs when host key received.
///
- ///
- ///
- ///
public event EventHandler HostKeyReceived;
+ ///
+ /// Occurs when server identification received.
+ ///
+ public event EventHandler ServerIdentificationReceived;
+
///
/// Initializes a new instance of the class.
///
/// The connection info.
/// Specified whether this instance owns the connection info.
- /// is null.
+ /// is .
///
- /// If is true, then the
+ /// If is , then the
/// connection info will be disposed when this instance is disposed.
///
protected BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
@@ -169,18 +173,23 @@ protected BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
/// The connection info.
/// Specified whether this instance owns the connection info.
/// The factory to use for creating new services.
- /// is null.
- /// is null.
+ /// is .
+ /// is .
///
- /// If is true, then the
+ /// If is , then the
/// connection info will be disposed when this instance is disposed.
///
- internal BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
+ private protected BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
{
- if (connectionInfo == null)
- throw new ArgumentNullException("connectionInfo");
- if (serviceFactory == null)
- throw new ArgumentNullException("serviceFactory");
+ if (connectionInfo is null)
+ {
+ throw new ArgumentNullException(nameof(connectionInfo));
+ }
+
+ if (serviceFactory is null)
+ {
+ throw new ArgumentNullException(nameof(serviceFactory));
+ }
ConnectionInfo = connectionInfo;
_ownsConnectionInfo = ownsConnectionInfo;
@@ -203,26 +212,29 @@ public void Connect()
// TODO (see issue #1758):
// we're not stopping the keep-alive timer and disposing the session here
- //
+ //
// we could do this but there would still be side effects as concrete
// implementations may still hang on to the original session
- //
+ //
// therefore it would be better to actually invoke the Disconnect method
// (and then the Dispose on the session) but even that would have side effects
// eg. it would remove all forwarded ports from SshClient
- //
+ //
// I think we should modify our concrete clients to better deal with a
- // disconnect. In case of SshClient this would mean not removing the
+ // disconnect. In case of SshClient this would mean not removing the
// forwarded ports on disconnect (but only on dispose ?) and link a
// forwarded port with a client instead of with a session
//
// To be discussed with Oleg (or whoever is interested)
if (IsSessionConnected())
+ {
throw new InvalidOperationException("The client is already connected.");
+ }
OnConnecting();
Session = CreateAndConnectSession();
+
try
{
// Even though the method we invoke makes you believe otherwise, at this point only
@@ -236,6 +248,66 @@ public void Connect()
DisposeSession();
throw;
}
+
+ StartKeepAliveTimer();
+ }
+
+ ///
+ /// Asynchronously connects client to the server.
+ ///
+ /// The to observe.
+ /// A that represents the asynchronous connect operation.
+ ///
+ /// The client is already connected.
+ /// The method was called after the client was disposed.
+ /// Socket connection to the SSH server or proxy server could not be established, or an error occurred while resolving the hostname.
+ /// SSH session could not be established.
+ /// Authentication of SSH session failed.
+ /// Failed to establish proxy connection.
+ public async Task ConnectAsync(CancellationToken cancellationToken)
+ {
+ CheckDisposed();
+ cancellationToken.ThrowIfCancellationRequested();
+
+ // TODO (see issue #1758):
+ // we're not stopping the keep-alive timer and disposing the session here
+ //
+ // we could do this but there would still be side effects as concrete
+ // implementations may still hang on to the original session
+ //
+ // therefore it would be better to actually invoke the Disconnect method
+ // (and then the Dispose on the session) but even that would have side effects
+ // eg. it would remove all forwarded ports from SshClient
+ //
+ // I think we should modify our concrete clients to better deal with a
+ // disconnect. In case of SshClient this would mean not removing the
+ // forwarded ports on disconnect (but only on dispose ?) and link a
+ // forwarded port with a client instead of with a session
+ //
+ // To be discussed with Oleg (or whoever is interested)
+ if (IsSessionConnected())
+ {
+ throw new InvalidOperationException("The client is already connected.");
+ }
+
+ OnConnecting();
+
+ Session = await CreateAndConnectSessionAsync(cancellationToken).ConfigureAwait(false);
+
+ try
+ {
+ // Even though the method we invoke makes you believe otherwise, at this point only
+ // the SSH session itself is connected.
+ OnConnected();
+ }
+ catch
+ {
+ // Only dispose the session as Disconnect() would have side-effects (such as remove forwarded
+ // ports in SshClient).
+ DisposeSession();
+ throw;
+ }
+
StartKeepAliveTimer();
}
@@ -268,7 +340,9 @@ public void Disconnect()
/// intervals.
///
/// The method was called after the client was disposed.
+#pragma warning disable S1133 // Deprecated code should be removed
[Obsolete("Use KeepAliveInterval to send a keep-alive message at regular intervals.")]
+#pragma warning restore S1133 // Deprecated code should be removed
public void SendKeepAlive()
{
CheckDisposed();
@@ -295,11 +369,7 @@ protected virtual void OnConnected()
///
protected virtual void OnDisconnecting()
{
- var session = Session;
- if (session != null)
- {
- session.OnDisconnecting();
- }
+ Session?.OnDisconnecting();
}
///
@@ -311,55 +381,52 @@ protected virtual void OnDisconnected()
private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
{
- var handler = ErrorOccurred;
- if (handler != null)
- {
- handler(this, e);
- }
+ ErrorOccurred?.Invoke(this, e);
}
private void Session_HostKeyReceived(object sender, HostKeyEventArgs e)
{
- var handler = HostKeyReceived;
- if (handler != null)
- {
- handler(this, e);
- }
+ HostKeyReceived?.Invoke(this, e);
}
-#region IDisposable Members
-
- private bool _isDisposed;
+ private void Session_ServerIdentificationReceived(object sender, SshIdentificationEventArgs e)
+ {
+ ServerIdentificationReceived?.Invoke(this, e);
+ }
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- DiagnosticAbstraction.Log("Disposing client.");
-
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
+ DiagnosticAbstraction.Log("Disposing client.");
+
Disconnect();
- if (_ownsConnectionInfo && _connectionInfo != null)
+ if (_ownsConnectionInfo && _connectionInfo is not null)
{
- var connectionInfoDisposable = _connectionInfo as IDisposable;
- if (connectionInfoDisposable != null)
+ if (_connectionInfo is IDisposable connectionInfoDisposable)
+ {
connectionInfoDisposable.Dispose();
+ }
+
_connectionInfo = null;
}
@@ -373,29 +440,34 @@ protected virtual void Dispose(bool disposing)
/// THe current instance is disposed.
protected void CheckDisposed()
{
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_isDisposed, this);
+#else
if (_isDisposed)
+ {
throw new ObjectDisposedException(GetType().FullName);
+ }
+#endif // NET7_0_OR_GREATER
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~BaseClient()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-#endregion
-
///
/// Stops the keep-alive timer, and waits until all timer callbacks have been
/// executed.
///
private void StopKeepAliveTimer()
{
- if (_keepAliveTimer == null)
+ if (_keepAliveTimer is null)
+ {
return;
+ }
_keepAliveTimer.Dispose();
_keepAliveTimer = null;
@@ -406,15 +478,17 @@ private void SendKeepAliveMessage()
var session = Session;
// do nothing if we have disposed or disconnected
- if (session == null)
+ if (session is null)
+ {
return;
+ }
// do not send multiple keep-alive messages concurrently
if (Monitor.TryEnter(_keepAliveLock))
{
try
{
- session.TrySendMessage(new IgnoreMessage());
+ _ = session.TrySendMessage(new IgnoreMessage());
}
finally
{
@@ -433,11 +507,15 @@ private void SendKeepAliveMessage()
private void StartKeepAliveTimer()
{
if (_keepAliveInterval == SshNet.Session.InfiniteTimeSpan)
+ {
return;
+ }
if (_keepAliveTimer != null)
+ {
// timer is already started
return;
+ }
_keepAliveTimer = CreateKeepAliveTimer(_keepAliveInterval, _keepAliveInterval);
}
@@ -458,6 +536,7 @@ private Timer CreateKeepAliveTimer(TimeSpan dueTime, TimeSpan period)
private ISession CreateAndConnectSession()
{
var session = _serviceFactory.CreateSession(ConnectionInfo, _serviceFactory.CreateSocketFactory());
+ session.ServerIdentificationReceived += Session_ServerIdentificationReceived;
session.HostKeyReceived += Session_HostKeyReceived;
session.ErrorOccured += Session_ErrorOccured;
@@ -473,15 +552,35 @@ private ISession CreateAndConnectSession()
}
}
+ private async Task CreateAndConnectSessionAsync(CancellationToken cancellationToken)
+ {
+ var session = _serviceFactory.CreateSession(ConnectionInfo, _serviceFactory.CreateSocketFactory());
+ session.ServerIdentificationReceived += Session_ServerIdentificationReceived;
+ session.HostKeyReceived += Session_HostKeyReceived;
+ session.ErrorOccured += Session_ErrorOccured;
+
+ try
+ {
+ await session.ConnectAsync(cancellationToken).ConfigureAwait(false);
+ return session;
+ }
+ catch
+ {
+ DisposeSession(session);
+ throw;
+ }
+ }
+
private void DisposeSession(ISession session)
{
session.ErrorOccured -= Session_ErrorOccured;
session.HostKeyReceived -= Session_HostKeyReceived;
+ session.ServerIdentificationReceived -= Session_ServerIdentificationReceived;
session.Dispose();
}
///
- /// Disposes the SSH session, and assigns null to .
+ /// Disposes the SSH session, and assigns to .
///
private void DisposeSession()
{
@@ -497,7 +596,7 @@ private void DisposeSession()
/// Returns a value indicating whether the SSH session is established.
///
///
- /// true if the SSH session is established; otherwise, false.
+ /// if the SSH session is established; otherwise, .
///
private bool IsSessionConnected()
{
diff --git a/src/Renci.SshNet/Channels/Channel.cs b/src/Renci.SshNet/Channels/Channel.cs
index a6311a981..25975872d 100644
--- a/src/Renci.SshNet/Channels/Channel.cs
+++ b/src/Renci.SshNet/Channels/Channel.cs
@@ -1,11 +1,12 @@
using System;
+using System.Globalization;
using System.Net.Sockets;
using System.Threading;
+
+using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
using Renci.SshNet.Messages;
using Renci.SshNet.Messages.Connection;
-using System.Globalization;
-using Renci.SshNet.Abstractions;
namespace Renci.SshNet.Channels
{
@@ -14,21 +15,23 @@ namespace Renci.SshNet.Channels
///
internal abstract class Channel : IChannel
{
- private EventWaitHandle _channelClosedWaitHandle = new ManualResetEvent(false);
- private EventWaitHandle _channelServerWindowAdjustWaitHandle = new ManualResetEvent(false);
private readonly object _serverWindowSizeLock = new object();
+ private readonly object _messagingLock = new object();
private readonly uint _initialWindowSize;
+ private readonly ISession _session;
+ private EventWaitHandle _channelClosedWaitHandle = new ManualResetEvent(initialState: false);
+ private EventWaitHandle _channelServerWindowAdjustWaitHandle = new ManualResetEvent(initialState: false);
private uint? _remoteWindowSize;
private uint? _remoteChannelNumber;
private uint? _remotePacketSize;
- private ISession _session;
+ private bool _isDisposed;
///
/// Holds a value indicating whether the SSH_MSG_CHANNEL_CLOSE has been sent to the remote party.
///
///
- /// true when a SSH_MSG_CHANNEL_CLOSE message has been sent to the other party;
- /// otherwise, false.
+ /// when a SSH_MSG_CHANNEL_CLOSE message has been sent to the other party;
+ /// otherwise, .
///
private bool _closeMessageSent;
@@ -37,8 +40,8 @@ internal abstract class Channel : IChannel
/// party.
///
///
- /// true when a SSH_MSG_CHANNEL_CLOSE message has been received from the other party;
- /// otherwise, false.
+ /// when a SSH_MSG_CHANNEL_CLOSE message has been received from the other party;
+ /// otherwise, .
///
private bool _closeMessageReceived;
@@ -46,8 +49,8 @@ internal abstract class Channel : IChannel
/// Holds a value indicating whether the SSH_MSG_CHANNEL_EOF has been received from the other party.
///
///
- /// true when a SSH_MSG_CHANNEL_EOF message has been received from the other party;
- /// otherwise, false.
+ /// when a SSH_MSG_CHANNEL_EOF message has been received from the other party;
+ /// otherwise, .
///
private bool _eofMessageReceived;
@@ -55,8 +58,8 @@ internal abstract class Channel : IChannel
/// Holds a value indicating whether the SSH_MSG_CHANNEL_EOF has been sent to the remote party.
///
///
- /// true when a SSH_MSG_CHANNEL_EOF message has been sent to the remote party;
- /// otherwise, false.
+ /// when a SSH_MSG_CHANNEL_EOF message has been sent to the remote party;
+ /// otherwise, .
///
private bool _eofMessageSent;
@@ -66,7 +69,7 @@ internal abstract class Channel : IChannel
public event EventHandler Exception;
///
- /// Initializes a new instance.
+ /// Initializes a new instance of the class.
///
/// The session.
/// The local channel number.
@@ -155,7 +158,10 @@ public uint RemoteChannelNumber
get
{
if (!_remoteChannelNumber.HasValue)
+ {
throw CreateRemoteChannelInfoNotAvailableException();
+ }
+
return _remoteChannelNumber.Value;
}
private set
@@ -177,7 +183,10 @@ public uint RemotePacketSize
get
{
if (!_remotePacketSize.HasValue)
+ {
throw CreateRemoteChannelInfoNotAvailableException();
+ }
+
return _remotePacketSize.Value;
}
private set
@@ -197,7 +206,10 @@ public uint RemoteWindowSize
get
{
if (!_remoteWindowSize.HasValue)
+ {
throw CreateRemoteChannelInfoNotAvailableException();
+ }
+
return _remoteWindowSize.Value;
}
private set
@@ -207,15 +219,13 @@ private set
}
///
- /// Gets a value indicating whether this channel is open.
+ /// Gets or sets a value indicating whether this channel is open.
///
///
- /// true if this channel is open; otherwise, false.
+ /// if this channel is open; otherwise, .
///
public bool IsOpen { get; protected set; }
- #region Message events
-
///
/// Occurs when is received.
///
@@ -251,13 +261,11 @@ private set
///
public event EventHandler RequestFailed;
- #endregion
-
///
/// Gets a value indicating whether the session is connected.
///
///
- /// true if the session is connected; otherwise, false.
+ /// if the session is connected; otherwise, .
///
protected bool IsConnected
{
@@ -277,11 +285,17 @@ protected IConnectionInfo ConnectionInfo
/// Gets the session semaphore to control number of session channels.
///
/// The session semaphore.
- protected SemaphoreLight SessionSemaphore
+ protected SemaphoreSlim SessionSemaphore
{
get { return _session.SessionSemaphore; }
}
+ ///
+ /// Initializes the information on the remote channel.
+ ///
+ /// The remote channel number.
+ /// The remote window size.
+ /// The remote packet size.
protected void InitializeRemoteInfo(uint remoteChannelNumber, uint remoteWindowSize, uint remotePacketSize)
{
RemoteChannelNumber = remoteChannelNumber;
@@ -320,7 +334,9 @@ public void SendData(byte[] data, int offset, int size)
{
// send channel messages only while channel is open
if (!IsOpen)
+ {
return;
+ }
var totalBytesToSend = size;
while (totalBytesToSend > 0)
@@ -338,8 +354,6 @@ public void SendData(byte[] data, int offset, int size)
}
}
- #region Channel virtual methods
-
///
/// Called when channel window need to be adjust.
///
@@ -350,7 +364,8 @@ protected virtual void OnWindowAdjust(uint bytesToAdd)
{
RemoteWindowSize += bytesToAdd;
}
- _channelServerWindowAdjustWaitHandle.Set();
+
+ _ = _channelServerWindowAdjustWaitHandle.Set();
}
///
@@ -361,9 +376,7 @@ protected virtual void OnData(byte[] data)
{
AdjustDataWindow(data);
- var dataReceived = DataReceived;
- if (dataReceived != null)
- dataReceived(this, new ChannelDataEventArgs(LocalChannelNumber, data));
+ DataReceived?.Invoke(this, new ChannelDataEventArgs(LocalChannelNumber, data));
}
///
@@ -375,9 +388,7 @@ protected virtual void OnExtendedData(byte[] data, uint dataTypeCode)
{
AdjustDataWindow(data);
- var extendedDataReceived = ExtendedDataReceived;
- if (extendedDataReceived != null)
- extendedDataReceived(this, new ChannelExtendedDataEventArgs(LocalChannelNumber, data, dataTypeCode));
+ ExtendedDataReceived?.Invoke(this, new ChannelExtendedDataEventArgs(LocalChannelNumber, data, dataTypeCode));
}
///
@@ -387,9 +398,7 @@ protected virtual void OnEof()
{
_eofMessageReceived = true;
- var endOfData = EndOfData;
- if (endOfData != null)
- endOfData(this, new ChannelEventArgs(LocalChannelNumber));
+ EndOfData?.Invoke(this, new ChannelEventArgs(LocalChannelNumber));
}
///
@@ -404,7 +413,9 @@ protected virtual void OnClose()
// be blocked waiting for this signal.
var channelClosedWaitHandle = _channelClosedWaitHandle;
if (channelClosedWaitHandle != null)
- channelClosedWaitHandle.Set();
+ {
+ _ = channelClosedWaitHandle.Set();
+ }
// close the channel
Close();
@@ -416,19 +427,15 @@ protected virtual void OnClose()
/// Channel request information.
protected virtual void OnRequest(RequestInfo info)
{
- var requestReceived = RequestReceived;
- if (requestReceived != null)
- requestReceived(this, new ChannelRequestEventArgs(info));
+ RequestReceived?.Invoke(this, new ChannelRequestEventArgs(info));
}
///
- /// Called when channel request was successful
+ /// Called when channel request was successful.
///
protected virtual void OnSuccess()
{
- var requestSuccessed = RequestSucceeded;
- if (requestSuccessed != null)
- requestSuccessed(this, new ChannelEventArgs(LocalChannelNumber));
+ RequestSucceeded?.Invoke(this, new ChannelEventArgs(LocalChannelNumber));
}
///
@@ -436,24 +443,16 @@ protected virtual void OnSuccess()
///
protected virtual void OnFailure()
{
- var requestFailed = RequestFailed;
- if (requestFailed != null)
- requestFailed(this, new ChannelEventArgs(LocalChannelNumber));
+ RequestFailed?.Invoke(this, new ChannelEventArgs(LocalChannelNumber));
}
- #endregion // Channel virtual methods
-
///
/// Raises event.
///
/// The exception.
private void RaiseExceptionEvent(Exception exception)
{
- var handlers = Exception;
- if (handlers != null)
- {
- handlers(this, new ExceptionEventArgs(exception));
- }
+ Exception?.Invoke(this, new ExceptionEventArgs(exception));
}
///
@@ -461,11 +460,11 @@ private void RaiseExceptionEvent(Exception exception)
///
/// The message to send.
///
- /// true if the message was sent to the server; otherwise, false.
+ /// if the message was sent to the server; otherwise, .
///
/// The size of the packet exceeds the maximum size defined by the protocol.
///
- /// This methods returns false when the attempt to send the message results in a
+ /// This methods returns when the attempt to send the message results in a
/// or a .
///
private bool TrySendMessage(Message message)
@@ -479,9 +478,11 @@ private bool TrySendMessage(Message message)
/// The message.
protected void SendMessage(Message message)
{
- // send channel messages only while channel is open
+ // Send channel messages only while channel is open
if (!IsOpen)
+ {
return;
+ }
_session.SendMessage(message);
}
@@ -493,9 +494,11 @@ protected void SendMessage(Message message)
public void SendEof()
{
if (!IsOpen)
+ {
throw CreateChannelClosedException();
+ }
- lock (this)
+ lock (_messagingLock)
{
_session.SendMessage(new ChannelEofMessage(RemoteChannelNumber));
_eofMessageSent = true;
@@ -516,14 +519,16 @@ protected void WaitOnHandle(WaitHandle waitHandle)
///
protected virtual void Close()
{
- // synchronize sending SSH_MSG_CHANNEL_EOF and SSH_MSG_CHANNEL_CLOSE to ensure that these messages
- // are sent in that other; when both the client and the server attempt to close the channel at the
- // same time we would otherwise risk sending the SSH_MSG_CHANNEL_EOF after the SSH_MSG_CHANNEL_CLOSE
- // message causing the server to disconnect the session.
+ /*
+ * Synchronize sending SSH_MSG_CHANNEL_EOF and SSH_MSG_CHANNEL_CLOSE to ensure that these messages
+ * are sent in that other; when both the client and the server attempt to close the channel at the
+ * same time we would otherwise risk sending the SSH_MSG_CHANNEL_EOF after the SSH_MSG_CHANNEL_CLOSE
+ * message causing the server to disconnect the session.
+ */
- lock (this)
+ lock (_messagingLock)
{
- // send EOF message first the following conditions are met:
+ // Send EOF message first the following conditions are met:
// * we have not sent a SSH_MSG_CHANNEL_EOF message
// * remote party has not already sent a SSH_MSG_CHANNEL_EOF message
// * remote party has not already sent a SSH_MSG_CHANNEL_CLOSE message
@@ -565,11 +570,7 @@ protected virtual void Close()
if (_closeMessageReceived)
{
// raise event signaling that both ends of the channel have been closed
- var closed = Closed;
- if (closed != null)
- {
- closed(this, new ChannelEventArgs(LocalChannelNumber));
- }
+ Closed?.Invoke(this, new ChannelEventArgs(LocalChannelNumber));
}
}
}
@@ -623,8 +624,6 @@ private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
}
}
- #region Channel message event handlers
-
private void OnChannelWindowAdjust(object sender, MessageEventArgs e)
{
if (e.Message.LocalChannelNumber == LocalChannelNumber)
@@ -706,14 +705,12 @@ private void OnChannelRequest(object sender, MessageEventArgs
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
- if (_isDisposed)
- return;
-
- if (disposing)
+ if (!_isDisposed && disposing)
{
Close();
var session = _session;
- if (session != null)
+ if (session is not null)
{
- _session = null;
session.ChannelWindowAdjustReceived -= OnChannelWindowAdjust;
session.ChannelDataReceived -= OnChannelData;
session.ChannelExtendedDataReceived -= OnChannelExtendedData;
@@ -858,14 +847,14 @@ protected virtual void Dispose(bool disposing)
}
var channelClosedWaitHandle = _channelClosedWaitHandle;
- if (channelClosedWaitHandle != null)
+ if (channelClosedWaitHandle is not null)
{
_channelClosedWaitHandle = null;
channelClosedWaitHandle.Dispose();
}
var channelServerWindowAdjustWaitHandle = _channelServerWindowAdjustWaitHandle;
- if (channelServerWindowAdjustWaitHandle != null)
+ if (channelServerWindowAdjustWaitHandle is not null)
{
_channelServerWindowAdjustWaitHandle = null;
channelServerWindowAdjustWaitHandle.Dispose();
@@ -876,14 +865,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~Channel()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion // IDisposable Members
}
}
diff --git a/src/Renci.SshNet/Channels/ChannelDirectTcpip.cs b/src/Renci.SshNet/Channels/ChannelDirectTcpip.cs
index b6ba7a0ba..6c521bce2 100644
--- a/src/Renci.SshNet/Channels/ChannelDirectTcpip.cs
+++ b/src/Renci.SshNet/Channels/ChannelDirectTcpip.cs
@@ -11,17 +11,17 @@ namespace Renci.SshNet.Channels
///
/// Implements "direct-tcpip" SSH channel.
///
- internal class ChannelDirectTcpip : ClientChannel, IChannelDirectTcpip
+ internal sealed class ChannelDirectTcpip : ClientChannel, IChannelDirectTcpip
{
private readonly object _socketLock = new object();
- private EventWaitHandle _channelOpen = new AutoResetEvent(false);
- private EventWaitHandle _channelData = new AutoResetEvent(false);
+ private EventWaitHandle _channelOpen = new AutoResetEvent(initialState: false);
+ private EventWaitHandle _channelData = new AutoResetEvent(initialState: false);
private IForwardedPort _forwardedPort;
private Socket _socket;
///
- /// Initializes a new instance.
+ /// Initializes a new instance of the class.
///
/// The session.
/// The local channel number.
@@ -46,9 +46,14 @@ public override ChannelTypes ChannelType
public void Open(string remoteHost, uint port, IForwardedPort forwardedPort, Socket socket)
{
if (IsOpen)
+ {
throw new SshException("Channel is already open.");
+ }
+
if (!IsConnected)
+ {
throw new SshException("Session is not connected.");
+ }
_socket = socket;
_forwardedPort = forwardedPort;
@@ -56,10 +61,13 @@ public void Open(string remoteHost, uint port, IForwardedPort forwardedPort, Soc
var ep = (IPEndPoint) socket.RemoteEndPoint;
- // open channel
- SendMessage(new ChannelOpenMessage(LocalChannelNumber, LocalWindowSize, LocalPacketSize,
- new DirectTcpipChannelInfo(remoteHost, port, ep.Address.ToString(), (uint) ep.Port)));
- // Wait for channel to open
+ // Open channel
+ SendMessage(new ChannelOpenMessage(LocalChannelNumber,
+ LocalWindowSize,
+ LocalPacketSize,
+ new DirectTcpipChannelInfo(remoteHost, port, ep.Address.ToString(), (uint) ep.Port)));
+
+ // Wait for channel to open
WaitOnHandle(_channelOpen);
}
@@ -82,9 +90,11 @@ private void ForwardedPort_Closing(object sender, EventArgs eventArgs)
///
public void Bind()
{
- // Cannot bind if channel is not open
+ // Cannot bind if channel is not open
if (!IsOpen)
+ {
return;
+ }
var buffer = new byte[RemotePacketSize];
@@ -103,13 +113,17 @@ public void Bind()
///
private void CloseSocket()
{
- if (_socket == null)
+ if (_socket is null)
+ {
return;
+ }
lock (_socketLock)
{
- if (_socket == null)
+ if (_socket is null)
+ {
return;
+ }
// closing a socket actually disposes the socket, so we can safely dereference
// the field to avoid entering the lock again later
@@ -124,13 +138,17 @@ private void CloseSocket()
/// One of the values that specifies the operation that will no longer be allowed.
private void ShutdownSocket(SocketShutdown how)
{
- if (_socket == null)
+ if (_socket is null)
+ {
return;
+ }
lock (_socketLock)
{
if (!_socket.IsConnected())
+ {
return;
+ }
try
{
@@ -199,14 +217,14 @@ protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initia
{
base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
- _channelOpen.Set();
+ _ = _channelOpen.Set();
}
protected override void OnOpenFailure(uint reasonCode, string description, string language)
{
base.OnOpenFailure(reasonCode, description, language);
- _channelOpen.Set();
+ _ = _channelOpen.Set();
}
///
diff --git a/src/Renci.SshNet/Channels/ChannelForwardedTcpip.cs b/src/Renci.SshNet/Channels/ChannelForwardedTcpip.cs
index 7d731b9e5..a8382015a 100644
--- a/src/Renci.SshNet/Channels/ChannelForwardedTcpip.cs
+++ b/src/Renci.SshNet/Channels/ChannelForwardedTcpip.cs
@@ -10,14 +10,14 @@ namespace Renci.SshNet.Channels
///
/// Implements "forwarded-tcpip" SSH channel.
///
- internal class ChannelForwardedTcpip : ServerChannel, IChannelForwardedTcpip
+ internal sealed class ChannelForwardedTcpip : ServerChannel, IChannelForwardedTcpip
{
private readonly object _socketShutdownAndCloseLock = new object();
private Socket _socket;
private IForwardedPort _forwardedPort;
///
- /// Initializes a new instance.
+ /// Initializes a new instance of the class.
///
/// The session.
/// The local channel number.
@@ -69,17 +69,17 @@ public void Bind(IPEndPoint remoteEndpoint, IForwardedPort forwardedPort)
_forwardedPort = forwardedPort;
_forwardedPort.Closing += ForwardedPort_Closing;
- // Try to connect to the socket
+ // Try to connect to the socket
try
{
_socket = SocketAbstraction.Connect(remoteEndpoint, ConnectionInfo.Timeout);
- // send channel open confirmation message
+ // Send channel open confirmation message
SendMessage(new ChannelOpenConfirmationMessage(RemoteChannelNumber, LocalWindowSize, LocalPacketSize, LocalChannelNumber));
}
catch (Exception exp)
{
- // send channel open failure message
+ // Send channel open failure message
SendMessage(new ChannelOpenFailureMessage(RemoteChannelNumber, exp.ToString(), ChannelOpenFailureMessage.ConnectFailed, "en"));
throw;
@@ -119,14 +119,18 @@ private void ForwardedPort_Closing(object sender, EventArgs eventArgs)
/// One of the values that specifies the operation that will no longer be allowed.
private void ShutdownSocket(SocketShutdown how)
{
- if (_socket == null)
+ if (_socket is null)
+ {
return;
+ }
lock (_socketShutdownAndCloseLock)
{
var socket = _socket;
if (!socket.IsConnected())
+ {
return;
+ }
try
{
@@ -145,8 +149,10 @@ private void ShutdownSocket(SocketShutdown how)
///
private void CloseSocket()
{
- if (_socket == null)
+ if (_socket is null)
+ {
return;
+ }
lock (_socketShutdownAndCloseLock)
{
diff --git a/src/Renci.SshNet/Channels/ChannelSession.cs b/src/Renci.SshNet/Channels/ChannelSession.cs
index 38e13096b..f222fc647 100644
--- a/src/Renci.SshNet/Channels/ChannelSession.cs
+++ b/src/Renci.SshNet/Channels/ChannelSession.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
+
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Connection;
@@ -13,7 +14,7 @@ namespace Renci.SshNet.Channels
internal sealed class ChannelSession : ClientChannel, IChannelSession
{
///
- /// Counts failed channel open attempts
+ /// Counts failed channel open attempts.
///
private int _failedOpenAttempts;
@@ -28,16 +29,16 @@ internal sealed class ChannelSession : ClientChannel, IChannelSession
private int _sessionSemaphoreObtained;
///
- /// Wait handle to signal when response was received to open the channel
+ /// Wait handle to signal when response was received to open the channel.
///
- private EventWaitHandle _channelOpenResponseWaitHandle = new AutoResetEvent(false);
+ private EventWaitHandle _channelOpenResponseWaitHandle = new AutoResetEvent(initialState: false);
- private EventWaitHandle _channelRequestResponse = new ManualResetEvent(false);
+ private EventWaitHandle _channelRequestResponse = new ManualResetEvent(initialState: false);
private bool _channelRequestSucces;
///
- /// Initializes a new instance.
+ /// Initializes a new instance of the class.
///
/// The session.
/// The local channel number.
@@ -64,7 +65,7 @@ public override ChannelTypes ChannelType
///
public void Open()
{
- // Try to open channel several times
+ // Try to open channel several times
while (!IsOpen && _failedOpenAttempts < ConnectionInfo.RetryAttempts)
{
SendChannelOpenMessage();
@@ -81,7 +82,9 @@ public void Open()
}
if (!IsOpen)
+ {
throw new SshException(string.Format(CultureInfo.CurrentCulture, "Failed to open a channel after {0} attempts.", _failedOpenAttempts));
+ }
}
///
@@ -93,7 +96,8 @@ public void Open()
protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
{
base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
- _channelOpenResponseWaitHandle.Set();
+
+ _ = _channelOpenResponseWaitHandle.Set();
}
///
@@ -106,7 +110,7 @@ protected override void OnOpenFailure(uint reasonCode, string description, strin
{
_failedOpenAttempts++;
ReleaseSemaphore();
- _channelOpenResponseWaitHandle.Set();
+ _ = _channelOpenResponseWaitHandle.Set();
}
protected override void Close()
@@ -125,11 +129,11 @@ protected override void Close()
/// The height.
/// The terminal mode values.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint rows, uint width, uint height, IDictionary terminalModeValues)
{
- _channelRequestResponse.Reset();
+ _ = _channelRequestResponse.Reset();
SendMessage(new ChannelRequestMessage(RemoteChannelNumber, new PseudoTerminalRequestInfo(environmentVariable, columns, rows, width, height, terminalModeValues)));
WaitOnHandle(_channelRequestResponse);
return _channelRequestSucces;
@@ -138,16 +142,16 @@ public bool SendPseudoTerminalRequest(string environmentVariable, uint columns,
///
/// Sends the X11 forwarding request.
///
- /// if set to true the it is single connection.
+ /// if set to the it is single connection.
/// The protocol.
/// The cookie.
/// The screen number.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendX11ForwardingRequest(bool isSingleConnection, string protocol, byte[] cookie, uint screenNumber)
{
- _channelRequestResponse.Reset();
+ _ = _channelRequestResponse.Reset();
SendMessage(new ChannelRequestMessage(RemoteChannelNumber, new X11ForwardingRequestInfo(isSingleConnection, protocol, cookie, screenNumber)));
WaitOnHandle(_channelRequestResponse);
return _channelRequestSucces;
@@ -159,11 +163,11 @@ public bool SendX11ForwardingRequest(bool isSingleConnection, string protocol, b
/// Name of the variable.
/// The variable value.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendEnvironmentVariableRequest(string variableName, string variableValue)
{
- _channelRequestResponse.Reset();
+ _ = _channelRequestResponse.Reset();
SendMessage(new ChannelRequestMessage(RemoteChannelNumber, new EnvironmentVariableRequestInfo(variableName, variableValue)));
WaitOnHandle(_channelRequestResponse);
return _channelRequestSucces;
@@ -173,11 +177,11 @@ public bool SendEnvironmentVariableRequest(string variableName, string variableV
/// Sends the shell request.
///
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendShellRequest()
{
- _channelRequestResponse.Reset();
+ _ = _channelRequestResponse.Reset();
SendMessage(new ChannelRequestMessage(RemoteChannelNumber, new ShellRequestInfo()));
WaitOnHandle(_channelRequestResponse);
return _channelRequestSucces;
@@ -188,11 +192,11 @@ public bool SendShellRequest()
///
/// The command.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendExecRequest(string command)
{
- _channelRequestResponse.Reset();
+ _ = _channelRequestResponse.Reset();
SendMessage(new ChannelRequestMessage(RemoteChannelNumber, new ExecRequestInfo(command, ConnectionInfo.Encoding)));
WaitOnHandle(_channelRequestResponse);
return _channelRequestSucces;
@@ -203,11 +207,11 @@ public bool SendExecRequest(string command)
///
/// Length of the break.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendBreakRequest(uint breakLength)
{
- _channelRequestResponse.Reset();
+ _ = _channelRequestResponse.Reset();
SendMessage(new ChannelRequestMessage(RemoteChannelNumber, new BreakRequestInfo(breakLength)));
WaitOnHandle(_channelRequestResponse);
return _channelRequestSucces;
@@ -218,11 +222,11 @@ public bool SendBreakRequest(uint breakLength)
///
/// The subsystem.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendSubsystemRequest(string subsystem)
{
- _channelRequestResponse.Reset();
+ _ = _channelRequestResponse.Reset();
SendMessage(new ChannelRequestMessage(RemoteChannelNumber, new SubsystemRequestInfo(subsystem)));
WaitOnHandle(_channelRequestResponse);
return _channelRequestSucces;
@@ -236,7 +240,7 @@ public bool SendSubsystemRequest(string subsystem)
/// The width.
/// The height.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendWindowChangeRequest(uint columns, uint rows, uint width, uint height)
{
@@ -247,9 +251,9 @@ public bool SendWindowChangeRequest(uint columns, uint rows, uint width, uint he
///
/// Sends the local flow request.
///
- /// if set to true [client can do].
+ /// if set to [client can do].
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendLocalFlowRequest(bool clientCanDo)
{
@@ -262,7 +266,7 @@ public bool SendLocalFlowRequest(bool clientCanDo)
///
/// Name of the signal.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendSignalRequest(string signalName)
{
@@ -275,7 +279,7 @@ public bool SendSignalRequest(string signalName)
///
/// The exit status.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendExitStatusRequest(uint exitStatus)
{
@@ -287,11 +291,11 @@ public bool SendExitStatusRequest(uint exitStatus)
/// Sends the exit signal request.
///
/// Name of the signal.
- /// if set to true [core dumped].
+ /// if set to [core dumped].
/// The error message.
/// The language.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendExitSignalRequest(string signalName, bool coreDumped, string errorMessage, string language)
{
@@ -303,11 +307,11 @@ public bool SendExitSignalRequest(string signalName, bool coreDumped, string err
/// Sends eow@openssh.com request.
///
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendEndOfWriteRequest()
{
- _channelRequestResponse.Reset();
+ _ = _channelRequestResponse.Reset();
SendMessage(new ChannelRequestMessage(RemoteChannelNumber, new EndOfWriteRequestInfo()));
WaitOnHandle(_channelRequestResponse);
return _channelRequestSucces;
@@ -317,27 +321,25 @@ public bool SendEndOfWriteRequest()
/// Sends keepalive@openssh.com request.
///
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
public bool SendKeepAliveRequest()
{
- _channelRequestResponse.Reset();
+ _ = _channelRequestResponse.Reset();
SendMessage(new ChannelRequestMessage(RemoteChannelNumber, new KeepAliveRequestInfo()));
WaitOnHandle(_channelRequestResponse);
return _channelRequestSucces;
}
///
- /// Called when channel request was successful
+ /// Called when channel request was successful.
///
protected override void OnSuccess()
{
base.OnSuccess();
- _channelRequestSucces = true;
- var channelRequestResponse = _channelRequestResponse;
- if (channelRequestResponse != null)
- channelRequestResponse.Set();
+ _channelRequestSucces = true;
+ _ = _channelRequestResponse?.Set();
}
///
@@ -346,11 +348,9 @@ protected override void OnSuccess()
protected override void OnFailure()
{
base.OnFailure();
- _channelRequestSucces = false;
- var channelRequestResponse = _channelRequestResponse;
- if (channelRequestResponse != null)
- channelRequestResponse.Set();
+ _channelRequestSucces = false;
+ _ = _channelRequestResponse?.Set();
}
///
@@ -394,7 +394,7 @@ protected override void OnFailure()
///
private void SendChannelOpenMessage()
{
- // do not allow open to be ChannelOpenMessage to be sent again until we've
+ // do not allow the ChannelOpenMessage to be sent again until we've
// had a response on the previous attempt for the current channel
if (Interlocked.CompareExchange(ref _sessionSemaphoreObtained, 1, 0) == 0)
{
@@ -407,9 +407,9 @@ private void SendChannelOpenMessage()
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
@@ -442,7 +442,9 @@ protected override void Dispose(bool disposing)
private void ReleaseSemaphore()
{
if (Interlocked.CompareExchange(ref _sessionSemaphoreObtained, 0, 1) == 1)
- SessionSemaphore.Release();
+ {
+ _ = SessionSemaphore.Release();
+ }
}
}
}
diff --git a/src/Renci.SshNet/Channels/ChannelTypes.cs b/src/Renci.SshNet/Channels/ChannelTypes.cs
index 230420232..cd5e0ed0a 100644
--- a/src/Renci.SshNet/Channels/ChannelTypes.cs
+++ b/src/Renci.SshNet/Channels/ChannelTypes.cs
@@ -1,5 +1,4 @@
-
-namespace Renci.SshNet.Channels
+namespace Renci.SshNet.Channels
{
///
/// Lists channel types as defined by the protocol.
@@ -7,19 +6,22 @@ namespace Renci.SshNet.Channels
internal enum ChannelTypes
{
///
- /// session
+ /// Session.
///
Session,
+
///
- /// x11
+ /// X11.
///
X11,
+
///
- /// forwarded-tcpip
+ /// Forwarded-tcpip.
///
ForwardedTcpip,
+
///
- /// direct-tcpip
+ /// Direct-tcpip.
///
DirectTcpip
}
diff --git a/src/Renci.SshNet/Channels/ClientChannel.cs b/src/Renci.SshNet/Channels/ClientChannel.cs
index 844c18660..ea4bfe164 100644
--- a/src/Renci.SshNet/Channels/ClientChannel.cs
+++ b/src/Renci.SshNet/Channels/ClientChannel.cs
@@ -7,7 +7,7 @@ namespace Renci.SshNet.Channels
internal abstract class ClientChannel : Channel
{
///
- /// Initializes a new instance.
+ /// Initializes a new instance of the class.
///
/// The session.
/// The local channel number.
@@ -43,15 +43,13 @@ protected virtual void OnOpenConfirmation(uint remoteChannelNumber, uint initial
// Channel is consider to be open when confirmation message was received
IsOpen = true;
- var openConfirmed = OpenConfirmed;
- if (openConfirmed != null)
- openConfirmed(this, new ChannelOpenConfirmedEventArgs(remoteChannelNumber, initialWindowSize, maximumPacketSize));
+ OpenConfirmed?.Invoke(this, new ChannelOpenConfirmedEventArgs(remoteChannelNumber, initialWindowSize, maximumPacketSize));
}
///
/// Send message to open a channel.
///
- /// Message to send
+ /// Message to send.
/// The client is not connected.
/// The operation timed out.
/// The size of the packet exceeds the maximum size defined by the protocol.
@@ -68,9 +66,7 @@ protected void SendMessage(ChannelOpenMessage message)
/// The language.
protected virtual void OnOpenFailure(uint reasonCode, string description, string language)
{
- var openFailed = OpenFailed;
- if (openFailed != null)
- openFailed(this, new ChannelOpenFailedEventArgs(LocalChannelNumber, reasonCode, description, language));
+ OpenFailed?.Invoke(this, new ChannelOpenFailedEventArgs(LocalChannelNumber, reasonCode, description, language));
}
private void OnChannelOpenConfirmation(object sender, MessageEventArgs e)
@@ -79,8 +75,9 @@ private void OnChannelOpenConfirmation(object sender, MessageEventArgs
/// The session.
///
- /// Does nothing when is null.
+ /// Does nothing when is .
///
private void UnsubscribeFromSessionEvents(ISession session)
{
- if (session == null)
+ if (session is null)
+ {
return;
+ }
session.ChannelOpenConfirmationReceived -= OnChannelOpenConfirmation;
session.ChannelOpenFailureReceived -= OnChannelOpenFailure;
diff --git a/src/Renci.SshNet/Channels/IChannel.cs b/src/Renci.SshNet/Channels/IChannel.cs
index 005a8754c..77a757307 100644
--- a/src/Renci.SshNet/Channels/IChannel.cs
+++ b/src/Renci.SshNet/Channels/IChannel.cs
@@ -73,7 +73,7 @@ internal interface IChannel : IDisposable
/// Gets a value indicating whether this channel is open.
///
///
- /// true if this channel is open; otherwise, false.
+ /// if this channel is open; otherwise, .
///
bool IsOpen { get; }
diff --git a/src/Renci.SshNet/Channels/IChannelDirectTcpip.cs b/src/Renci.SshNet/Channels/IChannelDirectTcpip.cs
index 6f50e778a..eb71bf3df 100644
--- a/src/Renci.SshNet/Channels/IChannelDirectTcpip.cs
+++ b/src/Renci.SshNet/Channels/IChannelDirectTcpip.cs
@@ -18,7 +18,7 @@ internal interface IChannelDirectTcpip : IDisposable
/// Gets a value indicating whether this channel is open.
///
///
- /// true if this channel is open; otherwise, false.
+ /// if this channel is open; otherwise, .
///
bool IsOpen { get; }
diff --git a/src/Renci.SshNet/Channels/IChannelSession.cs b/src/Renci.SshNet/Channels/IChannelSession.cs
index 1599ce22c..13c2e2304 100644
--- a/src/Renci.SshNet/Channels/IChannelSession.cs
+++ b/src/Renci.SshNet/Channels/IChannelSession.cs
@@ -23,20 +23,24 @@ internal interface IChannelSession : IChannel
/// The height.
/// The terminal mode values.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
- bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint rows, uint width, uint height,
- IDictionary terminalModeValues);
+ bool SendPseudoTerminalRequest(string environmentVariable,
+ uint columns,
+ uint rows,
+ uint width,
+ uint height,
+ IDictionary terminalModeValues);
///
/// Sends the X11 forwarding request.
///
- /// if set to true the it is single connection.
+ /// if set to the it is single connection.
/// The protocol.
/// The cookie.
/// The screen number.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendX11ForwardingRequest(bool isSingleConnection, string protocol, byte[] cookie, uint screenNumber);
@@ -46,7 +50,7 @@ bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint ro
/// Name of the variable.
/// The variable value.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendEnvironmentVariableRequest(string variableName, string variableValue);
@@ -54,7 +58,7 @@ bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint ro
/// Sends the shell request.
///
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendShellRequest();
@@ -63,7 +67,7 @@ bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint ro
///
/// The command.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendExecRequest(string command);
@@ -72,7 +76,7 @@ bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint ro
///
/// Length of the break.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendBreakRequest(uint breakLength);
@@ -81,7 +85,7 @@ bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint ro
///
/// The subsystem.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendSubsystemRequest(string subsystem);
@@ -93,16 +97,16 @@ bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint ro
/// The width.
/// The height.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendWindowChangeRequest(uint columns, uint rows, uint width, uint height);
///
/// Sends the local flow request.
///
- /// if set to true [client can do].
+ /// if set to [client can do].
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendLocalFlowRequest(bool clientCanDo);
@@ -111,7 +115,7 @@ bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint ro
///
/// Name of the signal.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendSignalRequest(string signalName);
@@ -120,7 +124,7 @@ bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint ro
///
/// The exit status.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendExitStatusRequest(uint exitStatus);
@@ -128,11 +132,11 @@ bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint ro
/// Sends the exit signal request.
///
/// Name of the signal.
- /// if set to true [core dumped].
+ /// if set to [core dumped].
/// The error message.
/// The language.
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendExitSignalRequest(string signalName, bool coreDumped, string errorMessage, string language);
@@ -140,7 +144,7 @@ bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint ro
/// Sends eow@openssh.com request.
///
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendEndOfWriteRequest();
@@ -148,7 +152,7 @@ bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint ro
/// Sends keepalive@openssh.com request.
///
///
- /// true if request was successful; otherwise false.
+ /// if request was successful; otherwise .
///
bool SendKeepAliveRequest();
}
diff --git a/src/Renci.SshNet/Channels/ServerChannel.cs b/src/Renci.SshNet/Channels/ServerChannel.cs
index dc5378b31..1a70ee9f6 100644
--- a/src/Renci.SshNet/Channels/ServerChannel.cs
+++ b/src/Renci.SshNet/Channels/ServerChannel.cs
@@ -5,7 +5,7 @@ namespace Renci.SshNet.Channels
internal abstract class ServerChannel : Channel
{
///
- /// Initializes a new instance.
+ /// Initializes a new instance of the class.
///
/// The session.
/// The local channel number.
@@ -14,7 +14,13 @@ internal abstract class ServerChannel : Channel
/// The remote channel number.
/// The window size of the remote party.
/// The maximum size of a data packet that we can send to the remote party.
- protected ServerChannel(ISession session, uint localChannelNumber, uint localWindowSize, uint localPacketSize, uint remoteChannelNumber, uint remoteWindowSize, uint remotePacketSize)
+ protected ServerChannel(ISession session,
+ uint localChannelNumber,
+ uint localWindowSize,
+ uint localPacketSize,
+ uint remoteChannelNumber,
+ uint remoteWindowSize,
+ uint remotePacketSize)
: base(session, localChannelNumber, localWindowSize, localPacketSize)
{
InitializeRemoteInfo(remoteChannelNumber, remoteWindowSize, remotePacketSize);
@@ -22,10 +28,10 @@ protected ServerChannel(ISession session, uint localChannelNumber, uint localWin
protected void SendMessage(ChannelOpenConfirmationMessage message)
{
- // No need to check whether channel is open when trying to open a channel
+ // No need to check whether channel is open when trying to open a channel
Session.SendMessage(message);
- // When we act as server, consider the channel open when we've sent the
+ // When we act as server, consider the channel open when we've sent the
// confirmation message to the peer
IsOpen = true;
}
diff --git a/src/Renci.SshNet/CipherInfo.cs b/src/Renci.SshNet/CipherInfo.cs
index 2641437b0..2c9832a19 100644
--- a/src/Renci.SshNet/CipherInfo.cs
+++ b/src/Renci.SshNet/CipherInfo.cs
@@ -5,7 +5,7 @@
namespace Renci.SshNet
{
///
- /// Holds information about key size and cipher to use
+ /// Holds information about key size and cipher to use.
///
public class CipherInfo
{
@@ -30,7 +30,7 @@ public class CipherInfo
public CipherInfo(int keySize, Func cipher)
{
KeySize = keySize;
- Cipher = (key, iv) => (cipher(key.Take(KeySize / 8), iv));
+ Cipher = (key, iv) => cipher(key.Take(KeySize / 8), iv);
}
}
}
diff --git a/src/Renci.SshNet/ClientAuthentication.cs b/src/Renci.SshNet/ClientAuthentication.cs
index f0b31f872..5de87e536 100644
--- a/src/Renci.SshNet/ClientAuthentication.cs
+++ b/src/Renci.SshNet/ClientAuthentication.cs
@@ -1,22 +1,29 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
+
using Renci.SshNet.Common;
namespace Renci.SshNet
{
- internal class ClientAuthentication : IClientAuthentication
+ ///
+ /// Represents a mechanism to authenticate a given client.
+ ///
+ internal sealed class ClientAuthentication : IClientAuthentication
{
private readonly int _partialSuccessLimit;
///
- /// Initializes a new instance.
+ /// Initializes a new instance of the class.
///
/// The number of times an authentication attempt with any given can result in before it is disregarded.
/// is less than one.
public ClientAuthentication(int partialSuccessLimit)
{
if (partialSuccessLimit < 1)
- throw new ArgumentOutOfRangeException("partialSuccessLimit", "Cannot be less than one.");
+ {
+ throw new ArgumentOutOfRangeException(nameof(partialSuccessLimit), "Cannot be less than one.");
+ }
_partialSuccessLimit = partialSuccessLimit;
}
@@ -35,17 +42,25 @@ internal int PartialSuccessLimit
}
///
- /// Attempts to authentication for a given using the
- /// of the specified .
+ /// Attempts to perform authentication for a given using the
+ /// of the specified
+ /// .
///
/// A to use for authenticating.
/// The for which to perform authentication.
+ /// or is .
+ /// Failed to authenticate the client.
public void Authenticate(IConnectionInfoInternal connectionInfo, ISession session)
{
- if (connectionInfo == null)
- throw new ArgumentNullException("connectionInfo");
- if (session == null)
- throw new ArgumentNullException("session");
+ if (connectionInfo is null)
+ {
+ throw new ArgumentNullException(nameof(connectionInfo));
+ }
+
+ if (session is null)
+ {
+ throw new ArgumentNullException(nameof(session));
+ }
session.RegisterMessage("SSH_MSG_USERAUTH_FAILURE");
session.RegisterMessage("SSH_MSG_USERAUTH_SUCCESS");
@@ -95,8 +110,14 @@ private bool TryAuthenticate(ISession session,
var matchingAuthenticationMethods = authenticationState.GetSupportedAuthenticationMethods(allowedAuthenticationMethods);
if (matchingAuthenticationMethods.Count == 0)
{
- authenticationException = new SshAuthenticationException(string.Format("No suitable authentication method found to complete authentication ({0}).",
- string.Join(",", allowedAuthenticationMethods)));
+ authenticationException = new SshAuthenticationException(string.Format(CultureInfo.InvariantCulture,
+ "No suitable authentication method found to complete authentication ({0}).",
+#if NET || NETSTANDARD2_1_OR_GREATER
+ string.Join(',', allowedAuthenticationMethods)))
+#else
+ string.Join(",", allowedAuthenticationMethods)))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ ;
return false;
}
@@ -106,7 +127,7 @@ private bool TryAuthenticate(ISession session,
// methods after a partial success
if (authenticationState.GetPartialSuccessCount(authenticationMethod) >= _partialSuccessLimit)
{
- // TODO Get list of all authentication methods that have reached the partial success limit?
+ /* TODO Get list of all authentication methods that have reached the partial success limit? */
authenticationException = new SshAuthenticationException(string.Format("Reached authentication attempt limit for method ({0}).",
authenticationMethod.Name));
@@ -122,6 +143,7 @@ private bool TryAuthenticate(ISession session,
{
authenticationResult = AuthenticationResult.Success;
}
+
break;
case AuthenticationResult.Failure:
authenticationState.RecordFailure(authenticationMethod);
@@ -130,16 +152,20 @@ private bool TryAuthenticate(ISession session,
case AuthenticationResult.Success:
authenticationException = null;
break;
+ default:
+ break;
}
if (authenticationResult == AuthenticationResult.Success)
+ {
return true;
+ }
}
return false;
}
- private class AuthenticationState
+ private sealed class AuthenticationState
{
private readonly IList _supportedAuthenticationMethods;
@@ -181,10 +207,9 @@ public void RecordFailure(IAuthenticationMethod authenticationMethod)
/// An for which to record the result of an authentication attempt.
public void RecordPartialSuccess(IAuthenticationMethod authenticationMethod)
{
- int partialSuccessCount;
- if (_authenticationMethodPartialSuccessRegister.TryGetValue(authenticationMethod, out partialSuccessCount))
+ if (_authenticationMethodPartialSuccessRegister.TryGetValue(authenticationMethod, out var partialSuccessCount))
{
- _authenticationMethodPartialSuccessRegister[authenticationMethod] = ++partialSuccessCount;
+ _authenticationMethodPartialSuccessRegister[authenticationMethod] = partialSuccessCount + 1;
}
else
{
@@ -203,11 +228,11 @@ public void RecordPartialSuccess(IAuthenticationMethod authenticationMethod)
///
public int GetPartialSuccessCount(IAuthenticationMethod authenticationMethod)
{
- int partialSuccessCount;
- if (_authenticationMethodPartialSuccessRegister.TryGetValue(authenticationMethod, out partialSuccessCount))
+ if (_authenticationMethodPartialSuccessRegister.TryGetValue(authenticationMethod, out var partialSuccessCount))
{
return partialSuccessCount;
}
+
return 0;
}
@@ -270,7 +295,9 @@ public IEnumerable GetActiveAuthenticationMethods(List GetActiveAuthenticationMethods(List
- /// Provides additional information for asynchronous command execution
+ /// Provides additional information for asynchronous command execution.
///
public class CommandAsyncResult : IAsyncResult
{
@@ -27,8 +27,6 @@ internal CommandAsyncResult()
/// Total bytes sent.
public int BytesSent { get; set; }
- #region IAsyncResult Members
-
///
/// Gets a user-defined object that qualifies or contains information about an asynchronous operation.
///
@@ -36,32 +34,36 @@ internal CommandAsyncResult()
public object AsyncState { get; internal set; }
///
- /// Gets a that is used to wait for an asynchronous operation to complete.
+ /// Gets a that is used to wait for an asynchronous operation to complete.
///
- /// A that is used to wait for an asynchronous operation to complete.
+ ///
+ /// A that is used to wait for an asynchronous operation to complete.
+ ///
public WaitHandle AsyncWaitHandle { get; internal set; }
///
- /// Gets a value that indicates whether the asynchronous operation completed synchronously.
+ /// Gets a value indicating whether the asynchronous operation completed synchronously.
///
- /// true if the asynchronous operation completed synchronously; otherwise, false.
+ ///
+ /// true if the asynchronous operation completed synchronously; otherwise, false.
+ ///
public bool CompletedSynchronously { get; internal set; }
///
- /// Gets a value that indicates whether the asynchronous operation has completed.
+ /// Gets a value indicating whether the asynchronous operation has completed.
///
- /// true if the operation is complete; otherwise, false.
+ ///
+ /// true if the operation is complete; otherwise, false.
+ ///
public bool IsCompleted { get; internal set; }
- #endregion
-
///
- /// Gets a value indicating whether was already called for this
+ /// Gets or sets a value indicating whether was already called for this
/// .
///
///
- /// true if was already called for this ;
- /// otherwise, false.
+ /// if was already called for this ;
+ /// otherwise, .
///
internal bool EndCalled { get; set; }
}
diff --git a/src/Renci.SshNet/Common/ASCIIEncoding.cs b/src/Renci.SshNet/Common/ASCIIEncoding.cs
deleted file mode 100644
index f41c49de8..000000000
--- a/src/Renci.SshNet/Common/ASCIIEncoding.cs
+++ /dev/null
@@ -1,167 +0,0 @@
-#if !FEATURE_ENCODING_ASCII
-
-using System;
-using System.Text;
-
-namespace Renci.SshNet.Common
-{
- ///
- /// Implementation of ASCII Encoding
- ///
- public class ASCIIEncoding : Encoding
- {
- private readonly char _fallbackChar;
-
- private static readonly char[] ByteToChar;
-
- static ASCIIEncoding()
- {
- if (ByteToChar == null)
- {
- ByteToChar = new char[128];
- var ch = '\0';
- for (byte i = 0; i < 128; i++)
- {
- ByteToChar[i] = ch++;
- }
- }
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- public ASCIIEncoding()
- {
- _fallbackChar = '?';
- }
-
- ///
- /// Calculates the number of bytes produced by encoding a set of characters from the specified character array.
- ///
- /// The character array containing the set of characters to encode.
- /// The index of the first character to encode.
- /// The number of characters to encode.
- ///
- /// The number of bytes produced by encoding the specified characters.
- ///
- /// is null.
- /// or is less than zero.-or- and do not denote a valid range in .
- public override int GetByteCount(char[] chars, int index, int count)
- {
- return count;
- }
-
- ///
- /// Encodes a set of characters from the specified character array into the specified byte array.
- ///
- /// The character array containing the set of characters to encode.
- /// The index of the first character to encode.
- /// The number of characters to encode.
- /// The byte array to contain the resulting sequence of bytes.
- /// The index at which to start writing the resulting sequence of bytes.
- ///
- /// The actual number of bytes written into .
- ///
- /// is null.-or- is null.
- /// or or is less than zero.-or- and do not denote a valid range in .-or- is not a valid index in .
- /// does not have enough capacity from to the end of the array to accommodate the resulting bytes.
- public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
- {
- for (var i = 0; i < charCount && i < chars.Length; i++)
- {
- var b = (byte)chars[i + charIndex];
-
- if (b > 127)
- b = (byte) _fallbackChar;
-
- bytes[i + byteIndex] = b;
- }
- return charCount;
- }
-
- ///
- /// Calculates the number of characters produced by decoding a sequence of bytes from the specified byte array.
- ///
- /// The byte array containing the sequence of bytes to decode.
- /// The index of the first byte to decode.
- /// The number of bytes to decode.
- ///
- /// The number of characters produced by decoding the specified sequence of bytes.
- ///
- /// is null.
- /// or is less than zero.-or- and do not denote a valid range in .
- public override int GetCharCount(byte[] bytes, int index, int count)
- {
- return count;
- }
-
- ///
- /// Decodes a sequence of bytes from the specified byte array into the specified character array.
- ///
- /// The byte array containing the sequence of bytes to decode.
- /// The index of the first byte to decode.
- /// The number of bytes to decode.
- /// The character array to contain the resulting set of characters.
- /// The index at which to start writing the resulting set of characters.
- ///
- /// The actual number of characters written into .
- ///
- /// is null.-or- is null.
- /// or or is less than zero.-or- and do not denote a valid range in .-or- is not a valid index in .
- /// does not have enough capacity from to the end of the array to accommodate the resulting characters.
- public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
- {
- for (var i = 0; i < byteCount; i++)
- {
- var b = bytes[i + byteIndex];
- char ch;
-
- if (b > 127)
- {
- ch = _fallbackChar;
- }
- else
- {
- ch = ByteToChar[b];
- }
-
- chars[i + charIndex] = ch;
- }
- return byteCount;
- }
-
- ///
- /// Calculates the maximum number of bytes produced by encoding the specified number of characters.
- ///
- /// The number of characters to encode.
- ///
- /// The maximum number of bytes produced by encoding the specified number of characters.
- ///
- /// is less than zero.
- public override int GetMaxByteCount(int charCount)
- {
- if (charCount < 0)
- throw new ArgumentOutOfRangeException("charCount", "Non-negative number required.");
-
- return charCount + 1;
- }
-
- ///
- /// Calculates the maximum number of characters produced by decoding the specified number of bytes.
- ///
- /// The number of bytes to decode.
- ///
- /// The maximum number of characters produced by decoding the specified number of bytes.
- ///
- /// is less than zero.
- public override int GetMaxCharCount(int byteCount)
- {
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException("byteCount", "Non-negative number required.");
-
- return byteCount;
- }
- }
-}
-
-#endif // !FEATURE_ENCODING_ASCII
\ No newline at end of file
diff --git a/src/Renci.SshNet/Common/Array.cs b/src/Renci.SshNet/Common/Array.cs
deleted file mode 100644
index c11c3565a..000000000
--- a/src/Renci.SshNet/Common/Array.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace Renci.SshNet.Common
-{
- internal static class Array
- {
- public static readonly T[] Empty = new T[0];
- }
-}
diff --git a/src/Renci.SshNet/Common/AsyncResult.cs b/src/Renci.SshNet/Common/AsyncResult.cs
index 3466a030b..5f62b1b4a 100644
--- a/src/Renci.SshNet/Common/AsyncResult.cs
+++ b/src/Renci.SshNet/Common/AsyncResult.cs
@@ -8,36 +8,18 @@ namespace Renci.SshNet.Common
///
public abstract class AsyncResult : IAsyncResult
{
- // Fields set at construction which never change while operation is pending
- private readonly AsyncCallback _asyncCallback;
-
- private readonly object _asyncState;
-
- // Field set at construction which do change after operation completes
private const int StatePending = 0;
private const int StateCompletedSynchronously = 1;
private const int StateCompletedAsynchronously = 2;
+ private readonly AsyncCallback _asyncCallback;
+ private readonly object _asyncState;
private int _completedState = StatePending;
-
- // Field that may or may not get set depending on usage
private ManualResetEvent _asyncWaitHandle;
-
- // Fields set when operation completes
private Exception _exception;
- ///
- /// Gets or sets a value indicating whether has been called on the current
- /// .
- ///
- ///
- /// true if has been called on the current ;
- /// otherwise, false.
- ///
- public bool EndInvokeCalled { get; private set; }
-
///
/// Initializes a new instance of the class.
///
@@ -49,37 +31,43 @@ protected AsyncResult(AsyncCallback asyncCallback, object state)
_asyncState = state;
}
+ ///
+ /// Gets a value indicating whether has been called on the current .
+ ///
+ ///
+ /// if has been called on the current ;
+ /// otherwise, .
+ ///
+ public bool EndInvokeCalled { get; private set; }
+
///
/// Marks asynchronous operation as completed.
///
/// The exception.
- /// if set to true [completed synchronously].
+ /// If set to , completed synchronously.
public void SetAsCompleted(Exception exception, bool completedSynchronously)
{
// Passing null for exception means no error occurred; this is the common case
_exception = exception;
- // The m_CompletedState field MUST be set prior calling the callback
+ // The '_completedState' field MUST be set prior calling the callback
var prevState = Interlocked.Exchange(ref _completedState,
- completedSynchronously ? StateCompletedSynchronously : StateCompletedAsynchronously);
+ completedSynchronously ? StateCompletedSynchronously : StateCompletedAsynchronously);
+
if (prevState != StatePending)
+ {
throw new InvalidOperationException("You can set a result only once");
+ }
// If the event exists, set it
- if (_asyncWaitHandle != null)
- {
- _asyncWaitHandle.Set();
- }
+ _ = _asyncWaitHandle?.Set();
// If a callback method was set, call it
- if (_asyncCallback != null)
- {
- _asyncCallback(this);
- }
+ _asyncCallback?.Invoke(this);
}
///
- /// Waits until the asynchronous operation completes, and then returns.
+ /// Waits until the asynchronous operation completes, and then returns.
///
internal void EndInvoke()
{
@@ -87,7 +75,7 @@ internal void EndInvoke()
if (!IsCompleted)
{
// If the operation isn't done, wait for it
- AsyncWaitHandle.WaitOne();
+ _ = AsyncWaitHandle.WaitOne();
_asyncWaitHandle = null; // Allow early GC
AsyncWaitHandle.Dispose();
}
@@ -96,21 +84,28 @@ internal void EndInvoke()
// Operation is done: if an exception occurred, throw it
if (_exception != null)
+ {
throw _exception;
+ }
}
- #region Implementation of IAsyncResult
-
///
/// Gets a user-defined object that qualifies or contains information about an asynchronous operation.
///
- /// A user-defined object that qualifies or contains information about an asynchronous operation.
- public object AsyncState { get { return _asyncState; } }
+ ///
+ /// A user-defined object that qualifies or contains information about an asynchronous operation.
+ ///
+ public object AsyncState
+ {
+ get { return _asyncState; }
+ }
///
- /// Gets a value that indicates whether the asynchronous operation completed synchronously.
+ /// Gets a value indicating whether the asynchronous operation completed synchronously.
///
- /// true if the asynchronous operation completed synchronously; otherwise, false.
+ ///
+ /// if the asynchronous operation completed synchronously; otherwise, .
+ ///
public bool CompletedSynchronously
{
get { return _completedState == StateCompletedSynchronously; }
@@ -119,16 +114,18 @@ public bool CompletedSynchronously
///
/// Gets a that is used to wait for an asynchronous operation to complete.
///
- /// A that is used to wait for an asynchronous operation to complete.
+ ///
+ /// A that is used to wait for an asynchronous operation to complete.
+ ///
public WaitHandle AsyncWaitHandle
{
get
{
- if (_asyncWaitHandle == null)
+ if (_asyncWaitHandle is null)
{
var done = IsCompleted;
var mre = new ManualResetEvent(done);
- if (Interlocked.CompareExchange(ref _asyncWaitHandle, mre, null) != null)
+ if (Interlocked.CompareExchange(ref _asyncWaitHandle, mre, comparand: null) != null)
{
// Another thread created this object's event; dispose the event we just created
mre.Dispose();
@@ -137,72 +134,25 @@ public WaitHandle AsyncWaitHandle
{
if (!done && IsCompleted)
{
- // If the operation wasn't done when we created
- // the event but now it is done, set the event
- _asyncWaitHandle.Set();
+ // If the operation wasn't done when we created the event but now it is done, set the event
+ _ = _asyncWaitHandle.Set();
}
}
}
+
return _asyncWaitHandle;
}
}
///
- /// Gets a value that indicates whether the asynchronous operation has completed.
+ /// Gets a value indicating whether the asynchronous operation has completed.
///
///
- /// true if the operation is complete; otherwise, false.
+ /// if the operation is complete; otherwise, .
+ ///
public bool IsCompleted
{
get { return _completedState != StatePending; }
}
-
- #endregion
- }
-
- ///
- /// Base class to encapsulates the results of an asynchronous operation that returns result.
- ///
- /// The type of the result.
- public abstract class AsyncResult : AsyncResult
- {
- // Field set when operation completes
- private TResult _result;
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The async callback.
- /// The state.
- protected AsyncResult(AsyncCallback asyncCallback, object state)
- : base(asyncCallback, state)
- {
- }
-
- ///
- /// Marks asynchronous operation as completed.
- ///
- /// The result.
- /// if set to true [completed synchronously].
- public void SetAsCompleted(TResult result, bool completedSynchronously)
- {
- // Save the asynchronous operation's result
- _result = result;
-
- // Tell the base class that the operation completed successfully (no exception)
- SetAsCompleted(null, completedSynchronously);
- }
-
- ///
- /// Waits until the asynchronous operation completes, and then returns the value generated by the asynchronous operation.
- ///
- ///
- /// The invocation result.
- ///
- public new TResult EndInvoke()
- {
- base.EndInvoke(); // Wait until operation has completed
- return _result; // Return the result (if above didn't throw)
- }
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Common/AsyncResult{TResult}.cs b/src/Renci.SshNet/Common/AsyncResult{TResult}.cs
new file mode 100644
index 000000000..b5ab54122
--- /dev/null
+++ b/src/Renci.SshNet/Common/AsyncResult{TResult}.cs
@@ -0,0 +1,50 @@
+using System;
+
+namespace Renci.SshNet.Common
+{
+ ///
+ /// Base class to encapsulates the results of an asynchronous operation that returns result.
+ ///
+ /// The type of the result.
+ public abstract class AsyncResult : AsyncResult
+ {
+ // Field set when operation completes
+ private TResult _result;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The async callback.
+ /// The state.
+ protected AsyncResult(AsyncCallback asyncCallback, object state)
+ : base(asyncCallback, state)
+ {
+ }
+
+ ///
+ /// Marks asynchronous operation as completed.
+ ///
+ /// The result.
+ /// if set to [completed synchronously].
+ public void SetAsCompleted(TResult result, bool completedSynchronously)
+ {
+ // Save the asynchronous operation's result
+ _result = result;
+
+ // Tell the base class that the operation completed successfully (no exception)
+ SetAsCompleted(exception: null, completedSynchronously);
+ }
+
+ ///
+ /// Waits until the asynchronous operation completes, and then returns the value generated by the asynchronous operation.
+ ///
+ ///
+ /// The invocation result.
+ ///
+ public new TResult EndInvoke()
+ {
+ base.EndInvoke(); // Wait until operation has completed
+ return _result; // Return the result (if above didn't throw)
+ }
+ }
+}
diff --git a/src/Renci.SshNet/Common/AuthenticationBannerEventArgs.cs b/src/Renci.SshNet/Common/AuthenticationBannerEventArgs.cs
index 308105d4c..790ba034a 100644
--- a/src/Renci.SshNet/Common/AuthenticationBannerEventArgs.cs
+++ b/src/Renci.SshNet/Common/AuthenticationBannerEventArgs.cs
@@ -1,7 +1,7 @@
namespace Renci.SshNet.Common
{
///
- /// Provides data for event.
+ /// Provides data for event.
///
public class AuthenticationBannerEventArgs : AuthenticationEventArgs
{
diff --git a/src/Renci.SshNet/Common/AuthenticationEventArgs.cs b/src/Renci.SshNet/Common/AuthenticationEventArgs.cs
index dfeadbcc1..4546d318f 100644
--- a/src/Renci.SshNet/Common/AuthenticationEventArgs.cs
+++ b/src/Renci.SshNet/Common/AuthenticationEventArgs.cs
@@ -7,11 +7,6 @@ namespace Renci.SshNet.Common
///
public abstract class AuthenticationEventArgs : EventArgs
{
- ///
- /// Gets the username.
- ///
- public string Username { get; private set; }
-
///
/// Initializes a new instance of the class.
///
@@ -20,5 +15,10 @@ protected AuthenticationEventArgs(string username)
{
Username = username;
}
+
+ ///
+ /// Gets the username.
+ ///
+ public string Username { get; }
}
}
diff --git a/src/Renci.SshNet/Common/AuthenticationPasswordChangeEventArgs.cs b/src/Renci.SshNet/Common/AuthenticationPasswordChangeEventArgs.cs
index f6d829123..f4b4a3d8e 100644
--- a/src/Renci.SshNet/Common/AuthenticationPasswordChangeEventArgs.cs
+++ b/src/Renci.SshNet/Common/AuthenticationPasswordChangeEventArgs.cs
@@ -1,18 +1,10 @@
namespace Renci.SshNet.Common
{
///
- /// Provides data for event.
+ /// Provides data for event.
///
public class AuthenticationPasswordChangeEventArgs : AuthenticationEventArgs
{
- ///
- /// Gets or sets the new password.
- ///
- ///
- /// The new password.
- ///
- public byte[] NewPassword { get; set; }
-
///
/// Initializes a new instance of the class.
///
@@ -21,5 +13,13 @@ public AuthenticationPasswordChangeEventArgs(string username)
: base(username)
{
}
+
+ ///
+ /// Gets or sets the new password.
+ ///
+ ///
+ /// The new password.
+ ///
+ public byte[] NewPassword { get; set; }
}
}
diff --git a/src/Renci.SshNet/Common/AuthenticationPrompt.cs b/src/Renci.SshNet/Common/AuthenticationPrompt.cs
index 15d7a982c..b3e46c97b 100644
--- a/src/Renci.SshNet/Common/AuthenticationPrompt.cs
+++ b/src/Renci.SshNet/Common/AuthenticationPrompt.cs
@@ -1,27 +1,40 @@
namespace Renci.SshNet.Common
{
///
- /// Provides prompt information when is raised
+ /// Provides prompt information when is raised.
///
public class AuthenticationPrompt
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The sequence id.
+ /// if set to the user input should be echoed.
+ /// The request.
+ public AuthenticationPrompt(int id, bool isEchoed, string request)
+ {
+ Id = id;
+ IsEchoed = isEchoed;
+ Request = request;
+ }
+
///
/// Gets the prompt sequence id.
///
- public int Id { get; private set; }
+ public int Id { get; }
///
- /// Gets or sets a value indicating whether the user input should be echoed as characters are typed.
+ /// Gets a value indicating whether the user input should be echoed as characters are typed.
///
///
- /// true if the user input should be echoed as characters are typed; otherwise, false.
+ /// if the user input should be echoed as characters are typed; otherwise, .
///
- public bool IsEchoed { get; private set; }
+ public bool IsEchoed { get; }
///
/// Gets server information request.
///
- public string Request { get; private set; }
+ public string Request { get; }
///
/// Gets or sets server information response.
@@ -30,18 +43,5 @@ public class AuthenticationPrompt
/// The response.
///
public string Response { get; set; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The sequence id.
- /// if set to true the user input should be echoed.
- /// The request.
- public AuthenticationPrompt(int id, bool isEchoed, string request)
- {
- Id = id;
- IsEchoed = isEchoed;
- Request = request;
- }
}
}
diff --git a/src/Renci.SshNet/Common/AuthenticationPromptEventArgs.cs b/src/Renci.SshNet/Common/AuthenticationPromptEventArgs.cs
index 9e2207289..3a2562ae1 100644
--- a/src/Renci.SshNet/Common/AuthenticationPromptEventArgs.cs
+++ b/src/Renci.SshNet/Common/AuthenticationPromptEventArgs.cs
@@ -3,25 +3,10 @@
namespace Renci.SshNet.Common
{
///
- /// Provides data for event.
+ /// Provides data for event.
///
public class AuthenticationPromptEventArgs : AuthenticationEventArgs
{
- ///
- /// Gets prompt language.
- ///
- public string Language { get; private set; }
-
- ///
- /// Gets prompt instruction.
- ///
- public string Instruction { get; private set; }
-
- ///
- /// Gets server information request prompts.
- ///
- public IEnumerable Prompts { get; private set; }
-
///
/// Initializes a new instance of the class.
///
@@ -29,12 +14,27 @@ public class AuthenticationPromptEventArgs : AuthenticationEventArgs
/// The instruction.
/// The language.
/// The information request prompts.
- public AuthenticationPromptEventArgs(string username, string instruction, string language, IEnumerable prompts)
+ public AuthenticationPromptEventArgs(string username, string instruction, string language, IReadOnlyList prompts)
: base(username)
{
Instruction = instruction;
Language = language;
Prompts = prompts;
}
+
+ ///
+ /// Gets prompt language.
+ ///
+ public string Language { get; }
+
+ ///
+ /// Gets prompt instruction.
+ ///
+ public string Instruction { get; }
+
+ ///
+ /// Gets server information request prompts.
+ ///
+ public IReadOnlyList Prompts { get; }
}
}
diff --git a/src/Renci.SshNet/Common/BigInteger.cs b/src/Renci.SshNet/Common/BigInteger.cs
index 611b74dde..53a659daf 100644
--- a/src/Renci.SshNet/Common/BigInteger.cs
+++ b/src/Renci.SshNet/Common/BigInteger.cs
@@ -1,9 +1,11 @@
-//
+#pragma warning disable SA1028 // Code should not contain trailing whitespace
+#pragma warning disable SA1515 // Single-line comment should be preceded by blank line
+//
// System.Numerics.BigInteger
//
// Authors:
-// Rodrigo Kumpera (rkumpera@novell.com)
-// Marek Safar
+// Rodrigo Kumpera (rkumpera@novell.com)
+// Marek Safar
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
// Copyright (C) 2014 Xamarin Inc (http://www.xamarin.com)
@@ -44,46 +46,41 @@
*
*
* ***************************************************************************/
-//
-// slashdocs based on MSDN
+#pragma warning restore SA1515 // Single-line comment should be preceded by blank line
+#pragma warning restore SA1028 // Code should not contain trailing whitespace
using System;
using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
using System.Globalization;
+
using Renci.SshNet.Abstractions;
/*
-Optimization
- Have proper popcount function for IsPowerOfTwo
- Use unsafe ops to avoid bounds check
- CoreAdd could avoid some resizes by checking for equal sized array that top overflow
- For bitwise operators, hoist the conditionals out of their main loop
- Optimize BitScanBackward
- Use a carry variable to make shift opts do half the number of array ops.
- Schoolbook multiply is O(n^2), use Karatsuba /Toom-3 for large numbers
-*/
+ * Optimization:
+ * - Have proper popcount function for IsPowerOfTwo
+ * - Use unsafe ops to avoid bounds check
+ * - CoreAdd could avoid some resizes by checking for equal sized array that top overflow
+ * - For bitwise operators, hoist the conditionals out of their main loop
+ * - Optimize BitScanBackward
+ * - Use a carry variable to make shift opts do half the number of array ops.
+ * -Schoolbook multiply is O(n^2), use Karatsuba /Toom-3 for large numbers
+ */
namespace Renci.SshNet.Common
{
///
/// Represents an arbitrarily large signed integer.
///
- [SuppressMessage("ReSharper", "EmptyEmbeddedStatement")]
- [SuppressMessage("ReSharper", "RedundantCast")]
- [SuppressMessage("ReSharper", "RedundantAssignment")]
- [SuppressMessage("ReSharper", "SuggestBaseTypeForParameter")]
- [SuppressMessage("ReSharper", "MergeConditionalExpression")]
public struct BigInteger : IComparable, IFormattable, IComparable, IEquatable
{
+ private const ulong Base = 0x100000000;
+ private const int Bias = 1075;
+ private const int DecimalSignMask = unchecked((int)0x80000000);
+
private static readonly BigInteger ZeroSingleton = new BigInteger(0);
private static readonly BigInteger OneSingleton = new BigInteger(1);
private static readonly BigInteger MinusOneSingleton = new BigInteger(-1);
- private const ulong Base = 0x100000000;
- private const int Bias = 1075;
- private const int DecimalSignMask = unchecked((int) 0x80000000);
-
- //LSB on [0]
+ // LSB on [0]
private readonly uint[] _data;
private readonly short _sign;
@@ -95,21 +92,25 @@ public struct BigInteger : IComparable, IFormattable, IComparable, I
///
/// The number of the bit used.
///
- public int BitLength
+ public readonly int BitLength
{
get
{
if (_sign == 0)
+ {
return 0;
+ }
var msbIndex = _data.Length - 1;
while (_data[msbIndex] == 0)
+ {
msbIndex--;
+ }
var msbBitCount = BitScanBackward(_data[msbIndex]) + 1;
- return msbIndex * 4 * 8 + msbBitCount + ((_sign > 0) ? 0 : 1);
+ return (msbIndex * 4 * 8) + msbBitCount + ((_sign > 0) ? 0 : 1);
}
}
@@ -129,21 +130,27 @@ public static BigInteger ModInverse(BigInteger bi, BigInteger modulus)
while (!b.IsZero)
{
if (b.IsOne)
+ {
return p1;
+ }
p0 += (a / b) * p1;
a %= b;
if (a.IsZero)
+ {
break;
+ }
if (a.IsOne)
+ {
return modulus - p0;
+ }
p1 += (b / a) * p0;
b %= a;
-
}
+
return 0;
}
@@ -158,8 +165,11 @@ public static BigInteger ModInverse(BigInteger bi, BigInteger modulus)
public static BigInteger PositiveMod(BigInteger dividend, BigInteger divisor)
{
var result = dividend % divisor;
+
if (result < 0)
+ {
result += divisor;
+ }
return result;
}
@@ -171,9 +181,9 @@ public static BigInteger PositiveMod(BigInteger dividend, BigInteger divisor)
/// A random number of the specified length.
public static BigInteger Random(int bitLength)
{
- var bytesArray = new byte[bitLength / 8 + (((bitLength % 8) > 0) ? 1 : 0)];
+ var bytesArray = new byte[(bitLength / 8) + (((bitLength % 8) > 0) ? 1 : 0)];
CryptoAbstraction.GenerateRandom(bytesArray);
- bytesArray[bytesArray.Length - 1] = (byte) (bytesArray[bytesArray.Length - 1] & 0x7F); // Ensure not a negative value
+ bytesArray[bytesArray.Length - 1] = (byte) (bytesArray[bytesArray.Length - 1] & 0x7F); // Ensure not a negative value
return new BigInteger(bytesArray);
}
@@ -199,12 +209,14 @@ public BigInteger(int value)
else if (value > 0)
{
_sign = 1;
- _data = new[] {(uint) value};
+ _data = new[] { (uint) value };
}
else
{
_sign = -1;
- _data = new[] {(uint) -value};
+#pragma warning disable SA1021 // Negative signs should be spaced correctly
+ _data = new[] { (uint) -value };
+#pragma warning restore SA1021 // Negative signs should be spaced correctly
}
}
@@ -247,7 +259,9 @@ public BigInteger(long value)
_data = new uint[high != 0 ? 2 : 1];
_data[0] = low;
if (high != 0)
+ {
_data[1] = high;
+ }
}
else
{
@@ -259,7 +273,9 @@ public BigInteger(long value)
_data = new uint[high != 0 ? 2 : 1];
_data[0] = low;
if (high != 0)
+ {
_data[1] = high;
+ }
}
}
@@ -278,34 +294,18 @@ public BigInteger(ulong value)
else
{
_sign = 1;
- var low = (uint)value;
- var high = (uint)(value >> 32);
+ var low = (uint) value;
+ var high = (uint) (value >> 32);
_data = new uint[high != 0 ? 2 : 1];
_data[0] = low;
if (high != 0)
+ {
_data[1] = high;
+ }
}
}
- private static bool Negative(byte[] v)
- {
- return ((v[7] & 0x80) != 0);
- }
-
- private static ushort Exponent(byte[] v)
- {
- return (ushort)((((ushort)(v[7] & 0x7F)) << (ushort)4) | (((ushort)(v[6] & 0xF0)) >> 4));
- }
-
- private static ulong Mantissa(byte[] v)
- {
- var i1 = ((uint)v[0] | ((uint)v[1] << 8) | ((uint)v[2] << 16) | ((uint)v[3] << 24));
- var i2 = ((uint)v[4] | ((uint)v[5] << 8) | ((uint)(v[6] & 0xF) << 16));
-
- return (ulong)((ulong)i1 | ((ulong)i2 << 32));
- }
-
///
/// Initializes a new instance of the structure using a double-precision floating-point value.
///
@@ -313,7 +313,9 @@ private static ulong Mantissa(byte[] v)
public BigInteger(double value)
{
if (double.IsNaN(value) || double.IsInfinity(value))
+ {
throw new OverflowException();
+ }
var bytes = BitConverter.GetBytes(value);
var mantissa = Mantissa(bytes);
@@ -329,7 +331,7 @@ public BigInteger(double value)
}
var res = Negative(bytes) ? MinusOne : One;
- res = res << (exponent - 0x3ff);
+ res <<= exponent - 0x3ff;
_sign = res._sign;
_data = res._data;
}
@@ -341,7 +343,7 @@ public BigInteger(double value)
BigInteger res = mantissa;
res = exponent > Bias ? res << (exponent - Bias) : res >> (Bias - exponent);
- _sign = (short)(Negative(bytes) ? -1 : 1);
+ _sign = (short) (Negative(bytes) ? -1 : 1);
_data = res._data;
}
}
@@ -350,7 +352,8 @@ public BigInteger(double value)
/// Initializes a new instance of the structure using a single-precision floating-point value.
///
/// A single-precision floating-point value.
- public BigInteger(float value) : this((double)value)
+ public BigInteger(float value)
+ : this((double) value)
{
}
@@ -364,7 +367,10 @@ public BigInteger(decimal value)
var bits = decimal.GetBits(decimal.Truncate(value));
var size = 3;
- while (size > 0 && bits[size - 1] == 0) size--;
+ while (size > 0 && bits[size - 1] == 0)
+ {
+ size--;
+ }
if (size == 0)
{
@@ -373,26 +379,33 @@ public BigInteger(decimal value)
return;
}
- _sign = (short)((bits[3] & DecimalSignMask) != 0 ? -1 : 1);
+ _sign = (short) ((bits[3] & DecimalSignMask) != 0 ? -1 : 1);
_data = new uint[size];
- _data[0] = (uint)bits[0];
+ _data[0] = (uint) bits[0];
if (size > 1)
- _data[1] = (uint)bits[1];
+ {
+ _data[1] = (uint) bits[1];
+ }
+
if (size > 2)
- _data[2] = (uint)bits[2];
+ {
+ _data[2] = (uint) bits[2];
+ }
}
///
/// Initializes a new instance of the structure using the values in a byte array.
///
/// An array of values in little-endian order.
- /// is null.
+ /// is .
[CLSCompliant(false)]
public BigInteger(byte[] value)
{
- if (value == null)
- throw new ArgumentNullException("value");
+ if (value is null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
var len = value.Length;
@@ -404,11 +417,17 @@ public BigInteger(byte[] value)
}
if ((value[len - 1] & 0x80) != 0)
+ {
_sign = -1;
+ }
else
+ {
_sign = 1;
+ }
+#pragma warning disable CA1508 // Avoid dead conditional code | this is the following bug in the analyzer rule: https://github.com/dotnet/roslyn-analyzers/issues/6991
if (_sign == 1)
+#pragma warning restore CA1508 // Avoid dead conditional code
{
while (value[len - 1] == 0)
{
@@ -423,7 +442,9 @@ public BigInteger(byte[] value)
int size;
var fullWords = size = len / 4;
if ((len & 0x3) != 0)
+ {
++size;
+ }
_data = new uint[size];
var j = 0;
@@ -434,12 +455,15 @@ public BigInteger(byte[] value)
(uint) (value[j++] << 16) |
(uint) (value[j++] << 24);
}
+
size = len & 0x3;
if (size > 0)
{
var idx = _data.Length - 1;
for (var i = 0; i < size; ++i)
- _data[idx] |= (uint)(value[j++] << (i * 8));
+ {
+ _data[idx] |= (uint) (value[j++] << (i * 8));
+ }
}
}
else
@@ -447,7 +471,9 @@ public BigInteger(byte[] value)
int size;
var fullWords = size = len / 4;
if ((len & 0x3) != 0)
+ {
++size;
+ }
_data = new uint[size];
@@ -462,11 +488,12 @@ public BigInteger(byte[] value)
(uint) (value[j++] << 16) |
(uint) (value[j++] << 24);
- sub = (ulong)word - borrow;
- word = (uint)sub;
- borrow = (uint)(sub >> 32) & 0x1u;
+ sub = (ulong) word - borrow;
+ word = (uint) sub;
+ borrow = (uint) (sub >> 32) & 0x1u;
_data[i] = ~word;
}
+
size = len & 0x3;
if (size > 0)
@@ -475,63 +502,96 @@ public BigInteger(byte[] value)
uint storeMask = 0;
for (var i = 0; i < size; ++i)
{
- word |= (uint)(value[j++] << (i * 8));
+ word |= (uint) (value[j++] << (i * 8));
storeMask = (storeMask << 8) | 0xFF;
}
sub = word - borrow;
- word = (uint)sub;
- borrow = (uint)(sub >> 32) & 0x1u;
+ word = (uint) sub;
+ borrow = (uint) (sub >> 32) & 0x1u;
if ((~word & storeMask) == 0)
+ {
Array.Resize(ref _data, _data.Length - 1);
+ }
else
+ {
_data[_data.Length - 1] = ~word & storeMask;
+ }
}
- if (borrow != 0) //FIXME I believe this can't happen, can someone write a test for it?
+
+ if (borrow != 0)
+ {
+#pragma warning disable CA2201 // Do not raise reserved exception types
throw new Exception("non zero final carry");
+#pragma warning restore CA2201 // Do not raise reserved exception types
+ }
}
}
+ private static bool Negative(byte[] v)
+ {
+ return (v[7] & 0x80) != 0;
+ }
+
+ private static ushort Exponent(byte[] v)
+ {
+ return (ushort)((((ushort)(v[7] & 0x7F)) << (ushort)4) | (((ushort)(v[6] & 0xF0)) >> 4));
+ }
+
+ private static ulong Mantissa(byte[] v)
+ {
+ var i1 = (uint)v[0] | ((uint)v[1] << 8) | ((uint)v[2] << 16) | ((uint)v[3] << 24);
+ var i2 = (uint)v[4] | ((uint)v[5] << 8) | ((uint)(v[6] & 0xF) << 16);
+
+ return (ulong) i1 | ((ulong) i2 << 32);
+ }
+
///
- /// Indicates whether the value of the current object is an even number.
+ /// Gets a value indicating whether the value of the current object is an even number.
///
///
- /// true if the value of the BigInteger object is an even number; otherwise, false.
+ /// if the value of the object is an even number; otherwise, .
///
- public bool IsEven
+ public readonly bool IsEven
{
get { return _sign == 0 || (_data[0] & 0x1) == 0; }
}
///
- /// Indicates whether the value of the current object is .
+ /// Gets a value indicating whether the value of the current object is .
///
///
- /// true if the value of the object is ;
- /// otherwise, false.
+ /// if the value of the object is ;
+ /// otherwise, .
///
- public bool IsOne
+ public readonly bool IsOne
{
get { return _sign == 1 && _data.Length == 1 && _data[0] == 1; }
}
-
- //Gem from Hacker's Delight
- //Returns the number of bits set in @x
- static int PopulationCount(uint x)
+ // Gem from Hacker's Delight
+ // Returns the number of bits set in @x
+ private static int PopulationCount(uint x)
{
- x = x - ((x >> 1) & 0x55555555);
+ x -= (x >> 1) & 0x55555555;
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x + (x >> 4)) & 0x0F0F0F0F;
- x = x + (x >> 8);
- x = x + (x >> 16);
- return (int)(x & 0x0000003F);
+ x += x >> 8;
+ x += x >> 16;
+ return (int) (x & 0x0000003F);
}
- //Based on code by Zilong Tan on Ulib released under MIT license
- //Returns the number of bits set in @x
- static int PopulationCount(ulong x)
+ ///
+ /// Returns the number of bits set in .
+ ///
+ ///
+ /// The number of bits set in .
+ ///
+ ///
+ /// Based on code by Zilong Tan on Ulib released under MIT license.
+ ///
+ private static int PopulationCount(ulong x)
{
x -= (x >> 1) & 0x5555555555555555UL;
x = (x & 0x3333333333333333UL) + ((x >> 2) & 0x3333333333333333UL);
@@ -539,7 +599,7 @@ static int PopulationCount(ulong x)
return (int)((x * 0x0101010101010101UL) >> 56);
}
- static int LeadingZeroCount(uint value)
+ private static int LeadingZeroCount(uint value)
{
value |= value >> 1;
value |= value >> 2;
@@ -549,7 +609,7 @@ static int LeadingZeroCount(uint value)
return 32 - PopulationCount(value); // 32 = bits in uint
}
- static int LeadingZeroCount(ulong value)
+ private static int LeadingZeroCount(ulong value)
{
value |= value >> 1;
value |= value >> 2;
@@ -560,7 +620,7 @@ static int LeadingZeroCount(ulong value)
return 64 - PopulationCount(value); // 64 = bits in ulong
}
- static double BuildDouble(int sign, ulong mantissa, int exponent)
+ private static double BuildDouble(int sign, ulong mantissa, int exponent)
{
const int exponentBias = 1023;
const int mantissaLength = 52;
@@ -581,6 +641,7 @@ static double BuildDouble(int sign, ulong mantissa, int exponent)
{
return sign > 0 ? double.PositiveInfinity : double.NegativeInfinity;
}
+
if (offset < 0)
{
mantissa >>= -offset;
@@ -596,7 +657,9 @@ static double BuildDouble(int sign, ulong mantissa, int exponent)
mantissa <<= offset;
exponent -= offset;
}
- mantissa = mantissa & mantissaMask;
+
+ mantissa &= mantissaMask;
+
if ((exponent & exponentMask) == exponent)
{
unchecked
@@ -606,49 +669,59 @@ static double BuildDouble(int sign, ulong mantissa, int exponent)
{
bits |= negativeMark;
}
+
return BitConverter.Int64BitsToDouble((long)bits);
}
}
+
return sign > 0 ? double.PositiveInfinity : double.NegativeInfinity;
}
///
- /// Indicates whether the value of the current object is a power of two.
+ /// Gets a value Indicating whether the value of the current object is a power of two.
///
///
- /// true if the value of the object is a power of two;
- /// otherwise, false.
+ /// if the value of the object is a power of two;
+ /// otherwise, .
///
- public bool IsPowerOfTwo
+ public readonly bool IsPowerOfTwo
{
get
{
- var foundBit = false;
if (_sign != 1)
+ {
return false;
- //This function is pop count == 1 for positive numbers
+ }
+
+ var foundBit = false;
+
+ // This function is pop count == 1 for positive numbers
foreach (var bit in _data)
{
var p = PopulationCount(bit);
if (p > 0)
{
if (p > 1 || foundBit)
+ {
return false;
+ }
+
foundBit = true;
}
}
+
return foundBit;
}
}
///
- /// Indicates whether the value of the current object is .
+ /// Gets a value indicating whether the value of the current object is .
///
///
- /// true if the value of the object is ;
- /// otherwise, false.
+ /// if the value of the object is ;
+ /// otherwise, .
///
- public bool IsZero
+ public readonly bool IsZero
{
get { return _sign == 0; }
}
@@ -659,7 +732,7 @@ public bool IsZero
///
/// A number that indicates the sign of the object.
///
- public int Sign
+ public readonly int Sign
{
get { return _sign; }
}
@@ -704,24 +777,39 @@ public static BigInteger Zero
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator int(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- if (value._data == null)
+ if (value._data is null)
+ {
return 0;
+ }
+
if (value._data.Length > 1)
+ {
throw new OverflowException();
+ }
+
var data = value._data[0];
if (value._sign == 1)
{
- if (data > (uint)int.MaxValue)
+ if (data > (uint) int.MaxValue)
+ {
throw new OverflowException();
+ }
+
return (int)data;
}
+
if (value._sign == -1)
{
if (data > 0x80000000u)
+ {
throw new OverflowException();
+ }
+
return -(int)data;
}
@@ -736,12 +824,20 @@ public static explicit operator int(BigInteger value)
/// An object that contains the value of the parameter.
///
[CLSCompliant(false)]
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator uint(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- if (value._data == null)
+ if (value._data is null)
+ {
return 0;
+ }
+
if (value._data.Length > 1 || value._sign == -1)
+ {
throw new OverflowException();
+ }
+
return value._data[0];
}
@@ -752,28 +848,38 @@ public static explicit operator uint(BigInteger value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator short(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- var val = (int)value;
- if (val < short.MinValue || val > short.MaxValue)
+ var val = (int) value;
+ if (val is < short.MinValue or > short.MaxValue)
+ {
throw new OverflowException();
- return (short)val;
+ }
+
+ return (short) val;
}
///
- ///
+ /// Defines an explicit conversion of a object to a 16-bit unsigned integer value.
///
- ///
+ /// The value to convert to a 16-bit unsigned integer.
///
/// An object that contains the value of the parameter.
///
- [CLSCompliantAttribute(false)]
+ [CLSCompliant(false)]
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator ushort(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- var val = (uint)value;
+ var val = (uint) value;
if (val > ushort.MaxValue)
+ {
throw new OverflowException();
- return (ushort)val;
+ }
+
+ return (ushort) val;
}
///
@@ -783,12 +889,17 @@ public static explicit operator ushort(BigInteger value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator byte(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- var val = (uint)value;
+ var val = (uint) value;
if (val > byte.MaxValue)
+ {
throw new OverflowException();
- return (byte)val;
+ }
+
+ return (byte) val;
}
///
@@ -799,12 +910,17 @@ public static explicit operator byte(BigInteger value)
/// An object that contains the value of the parameter.
///
[CLSCompliant(false)]
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator sbyte(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- var val = (int)value;
- if (val < sbyte.MinValue || val > sbyte.MaxValue)
+ var val = (int) value;
+ if (val is < sbyte.MinValue or > sbyte.MaxValue)
+ {
throw new OverflowException();
- return (sbyte)val;
+ }
+
+ return (sbyte) val;
}
///
@@ -814,20 +930,29 @@ public static explicit operator sbyte(BigInteger value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator long(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- if (value._data == null)
+ if (value._data is null)
+ {
return 0;
+ }
if (value._data.Length > 2)
+ {
throw new OverflowException();
+ }
var low = value._data[0];
if (value._data.Length == 1)
{
if (value._sign == 1)
- return (long)low;
+ {
+ return (long) low;
+ }
+
var res = (long)low;
return -res;
}
@@ -837,7 +962,10 @@ public static explicit operator long(BigInteger value)
if (value._sign == 1)
{
if (high >= 0x80000000u)
+ {
throw new OverflowException();
+ }
+
return (((long)high) << 32) | low;
}
@@ -853,7 +981,10 @@ long.MinValue works fine since it's bigint encoding looks like a negative
var result = -((((long)high) << 32) | (long)low);
if (result > 0)
+ {
throw new OverflowException();
+ }
+
return result;
}
@@ -865,16 +996,25 @@ long.MinValue works fine since it's bigint encoding looks like a negative
/// An object that contains the value of the parameter.
///
[CLSCompliant(false)]
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator ulong(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- if (value._data == null)
+ if (value._data is null)
+ {
return 0;
+ }
+
if (value._data.Length > 2 || value._sign == -1)
+ {
throw new OverflowException();
+ }
var low = value._data[0];
if (value._data.Length == 1)
+ {
return low;
+ }
var high = value._data[1];
return (((ulong)high) << 32) | low;
@@ -887,17 +1027,21 @@ public static explicit operator ulong(BigInteger value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator double(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- if (value._data == null)
+ if (value._data is null)
+ {
return 0.0;
+ }
switch (value._data.Length)
{
case 1:
return BuildDouble(value._sign, value._data[0], 0);
case 2:
- return BuildDouble(value._sign, (ulong)value._data[1] << 32 | (ulong)value._data[0], 0);
+ return BuildDouble(value._sign, (ulong) value._data[1] << 32 | (ulong) value._data[0], 0);
default:
var index = value._data.Length - 1;
var word = value._data[index];
@@ -912,6 +1056,7 @@ public static explicit operator double(BigInteger value)
{
mantissa >>= -missing;
}
+
return BuildDouble(value._sign, mantissa, ((value._data.Length - 2) * 32) - missing);
}
}
@@ -923,9 +1068,11 @@ public static explicit operator double(BigInteger value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator float(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- return (float)(double)value;
+ return (float) (double) value;
}
///
@@ -935,22 +1082,36 @@ public static explicit operator float(BigInteger value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator decimal(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- if (value._data == null)
+ if (value._data is null)
+ {
return decimal.Zero;
+ }
var data = value._data;
if (data.Length > 3)
+ {
throw new OverflowException();
+ }
int lo = 0, mi = 0, hi = 0;
if (data.Length > 2)
- hi = (int)data[2];
+ {
+ hi = (int) data[2];
+ }
+
if (data.Length > 1)
- mi = (int)data[1];
+ {
+ mi = (int) data[1];
+ }
+
if (data.Length > 0)
- lo = (int)data[0];
+ {
+ lo = (int) data[0];
+ }
return new decimal(lo, mi, hi, value._sign < 0, 0);
}
@@ -962,7 +1123,9 @@ public static explicit operator decimal(BigInteger value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static implicit operator BigInteger(int value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return new BigInteger(value);
}
@@ -975,7 +1138,9 @@ public static implicit operator BigInteger(int value)
/// An object that contains the value of the parameter.
///
[CLSCompliant(false)]
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static implicit operator BigInteger(uint value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return new BigInteger(value);
}
@@ -987,7 +1152,9 @@ public static implicit operator BigInteger(uint value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static implicit operator BigInteger(short value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return new BigInteger(value);
}
@@ -999,8 +1166,10 @@ public static implicit operator BigInteger(short value)
///
/// An object that contains the value of the parameter.
///
- [CLSCompliantAttribute(false)]
+ [CLSCompliant(false)]
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static implicit operator BigInteger(ushort value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return new BigInteger(value);
}
@@ -1012,20 +1181,24 @@ public static implicit operator BigInteger(ushort value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static implicit operator BigInteger(byte value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return new BigInteger(value);
}
///
- ///
+ /// Defines an implicit conversion of a signed byte to a value.
///
/// The value to convert to a .
///
/// An object that contains the value of the parameter.
///
[CLSCompliant(false)]
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static implicit operator BigInteger(sbyte value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return new BigInteger(value);
}
@@ -1037,7 +1210,9 @@ public static implicit operator BigInteger(sbyte value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static implicit operator BigInteger(long value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return new BigInteger(value);
}
@@ -1050,7 +1225,9 @@ public static implicit operator BigInteger(long value)
/// An object that contains the value of the parameter.
///
[CLSCompliant(false)]
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static implicit operator BigInteger(ulong value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return new BigInteger(value);
}
@@ -1062,7 +1239,9 @@ public static implicit operator BigInteger(ulong value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator BigInteger(double value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return new BigInteger(value);
}
@@ -1074,7 +1253,9 @@ public static explicit operator BigInteger(double value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator BigInteger(float value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return new BigInteger(value);
}
@@ -1086,7 +1267,9 @@ public static explicit operator BigInteger(float value)
///
/// An object that contains the value of the parameter.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static explicit operator BigInteger(decimal value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return new BigInteger(value);
}
@@ -1102,20 +1285,32 @@ public static explicit operator BigInteger(decimal value)
public static BigInteger operator +(BigInteger left, BigInteger right)
{
if (left._sign == 0)
+ {
return right;
+ }
+
if (right._sign == 0)
+ {
return left;
+ }
if (left._sign == right._sign)
+ {
return new BigInteger(left._sign, CoreAdd(left._data, right._data));
+ }
var r = CoreCompare(left._data, right._data);
if (r == 0)
+ {
return Zero;
+ }
- if (r > 0) //left > right
+ if (r > 0)
+ {
+ // left > right
return new BigInteger(left._sign, CoreSub(left._data, right._data));
+ }
return new BigInteger(right._sign, CoreSub(right._data, left._data));
}
@@ -1131,19 +1326,31 @@ public static explicit operator BigInteger(decimal value)
public static BigInteger operator -(BigInteger left, BigInteger right)
{
if (right._sign == 0)
+ {
return left;
+ }
+
if (left._sign == 0)
- return new BigInteger((short)-right._sign, right._data);
+ {
+#pragma warning disable SA1021 // Negative signs should be spaced correctly
+ return new BigInteger((short) -right._sign, right._data);
+#pragma warning restore SA1021 // Negative signs should be spaced correctly
+ }
if (left._sign == right._sign)
{
var r = CoreCompare(left._data, right._data);
if (r == 0)
+ {
return Zero;
+ }
- if (r > 0) //left > right
+ if (r > 0)
+ {
+ // left > right
return new BigInteger(left._sign, CoreSub(left._data, right._data));
+ }
return new BigInteger((short)-right._sign, CoreSub(right._data, left._data));
}
@@ -1162,19 +1369,27 @@ public static explicit operator BigInteger(decimal value)
public static BigInteger operator *(BigInteger left, BigInteger right)
{
if (left._sign == 0 || right._sign == 0)
+ {
return Zero;
+ }
if (left._data[0] == 1 && left._data.Length == 1)
{
if (left._sign == 1)
+ {
return right;
+ }
+
return new BigInteger((short)-right._sign, right._data);
}
if (right._data[0] == 1 && right._data.Length == 1)
{
if (right._sign == 1)
+ {
return left;
+ }
+
return new BigInteger((short)-left._sign, left._data);
}
@@ -1191,7 +1406,7 @@ public static explicit operator BigInteger(decimal value)
ulong carry = 0;
for (var j = 0; j < b.Length; ++j)
{
- carry = carry + ((ulong)ai) * b[j] + res[k];
+ carry = carry + (((ulong) ai) * b[j]) + res[k];
res[k++] = (uint)carry;
carry >>= 32;
}
@@ -1205,9 +1420,15 @@ public static explicit operator BigInteger(decimal value)
}
int m;
- for (m = res.Length - 1; m >= 0 && res[m] == 0; --m) ;
+ for (m = res.Length - 1; m >= 0 && res[m] == 0; --m)
+ {
+ // Intentionally empty block
+ }
+
if (m < res.Length - 1)
+ {
Array.Resize(ref res, m + 1);
+ }
return new BigInteger((short) (left._sign*right._sign), res);
}
@@ -1224,22 +1445,32 @@ public static explicit operator BigInteger(decimal value)
public static BigInteger operator /(BigInteger dividend, BigInteger divisor)
{
if (divisor._sign == 0)
+ {
throw new DivideByZeroException();
+ }
if (dividend._sign == 0)
+ {
return dividend;
+ }
- uint[] quotient;
- uint[] remainderValue;
-
- DivModUnsigned(dividend._data, divisor._data, out quotient, out remainderValue);
+ DivModUnsigned(dividend._data, divisor._data, out var quotient, out _);
int i;
- for (i = quotient.Length - 1; i >= 0 && quotient[i] == 0; --i) ;
+ for (i = quotient.Length - 1; i >= 0 && quotient[i] == 0; --i)
+ {
+ // Intentionally empty block
+ }
+
if (i == -1)
+ {
return Zero;
+ }
+
if (i < quotient.Length - 1)
+ {
Array.Resize(ref quotient, i + 1);
+ }
return new BigInteger((short)(dividend._sign * divisor._sign), quotient);
}
@@ -1255,23 +1486,33 @@ public static explicit operator BigInteger(decimal value)
public static BigInteger operator %(BigInteger dividend, BigInteger divisor)
{
if (divisor._sign == 0)
+ {
throw new DivideByZeroException();
+ }
if (dividend._sign == 0)
+ {
return dividend;
+ }
- uint[] quotient;
- uint[] remainderValue;
-
- DivModUnsigned(dividend._data, divisor._data, out quotient, out remainderValue);
+ DivModUnsigned(dividend._data, divisor._data, out _, out var remainderValue);
int i;
- for (i = remainderValue.Length - 1; i >= 0 && remainderValue[i] == 0; --i) ;
+ for (i = remainderValue.Length - 1; i >= 0 && remainderValue[i] == 0; --i)
+ {
+ // Intentionally empty block
+ }
+
if (i == -1)
+ {
return Zero;
+ }
if (i < remainderValue.Length - 1)
+ {
Array.Resize(ref remainderValue, i + 1);
+ }
+
return new BigInteger(dividend._sign, remainderValue);
}
@@ -1279,14 +1520,19 @@ public static explicit operator BigInteger(decimal value)
/// Negates a specified value.
///
/// The value to negate.
- ///
+ ///
/// The result of the parameter multiplied by negative one (-1).
///
public static BigInteger operator -(BigInteger value)
{
- if (value._data == null)
+ if (value._data is null)
+ {
return value;
- return new BigInteger((short)-value._sign, value._data);
+ }
+
+#pragma warning disable SA1021 // Negative signs should be spaced correctly
+ return new BigInteger((short) -value._sign, value._data);
+#pragma warning restore SA1021 // Negative signs should be spaced correctly
}
///
@@ -1299,7 +1545,9 @@ public static explicit operator BigInteger(decimal value)
///
/// The sign of the operand is unchanged.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static BigInteger operator +(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
return value;
}
@@ -1311,19 +1559,28 @@ public static explicit operator BigInteger(decimal value)
///
/// The value of the parameter incremented by 1.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static BigInteger operator ++(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- if (value._data == null)
+ if (value._data is null)
+ {
return One;
+ }
var sign = value._sign;
var data = value._data;
if (data.Length == 1)
{
if (sign == -1 && data[0] == 1)
+ {
return Zero;
+ }
+
if (sign == 0)
+ {
return One;
+ }
}
data = sign == -1 ? CoreSub(data, 1) : CoreAdd(data, 1);
@@ -1338,19 +1595,28 @@ public static explicit operator BigInteger(decimal value)
///
/// The value of the parameter decremented by 1.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static BigInteger operator --(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- if (value._data == null)
+ if (value._data is null)
+ {
return MinusOne;
+ }
var sign = value._sign;
var data = value._data;
if (data.Length == 1)
{
if (sign == 1 && data[0] == 1)
+ {
return Zero;
+ }
+
if (sign == 0)
+ {
return MinusOne;
+ }
}
data = sign == -1 ? CoreAdd(data, 1) : CoreSub(data, 1);
@@ -1366,13 +1632,19 @@ public static explicit operator BigInteger(decimal value)
///
/// The result of the bitwise And operation.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static BigInteger operator &(BigInteger left, BigInteger right)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
if (left._sign == 0)
+ {
return left;
+ }
if (right._sign == 0)
+ {
return right;
+ }
var a = left._data;
var b = right._data;
@@ -1390,7 +1662,10 @@ public static explicit operator BigInteger(decimal value)
{
uint va = 0;
if (i < a.Length)
+ {
va = a[i];
+ }
+
if (ls == -1)
{
ac = ~va + ac;
@@ -1400,7 +1675,10 @@ public static explicit operator BigInteger(decimal value)
uint vb = 0;
if (i < b.Length)
+ {
vb = b[i];
+ }
+
if (rs == -1)
{
bc = ~vb + bc;
@@ -1420,12 +1698,20 @@ public static explicit operator BigInteger(decimal value)
result[i] = word;
}
- for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ;
+ for (i = result.Length - 1; i >= 0 && result[i] == 0; --i)
+ {
+ // Intentionally empty block
+ }
+
if (i == -1)
+ {
return Zero;
+ }
if (i < result.Length - 1)
+ {
Array.Resize(ref result, i + 1);
+ }
return new BigInteger(negRes ? (short)-1 : (short)1, result);
}
@@ -1438,13 +1724,19 @@ public static explicit operator BigInteger(decimal value)
///
/// The result of the bitwise Or operation.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static BigInteger operator |(BigInteger left, BigInteger right)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
if (left._sign == 0)
+ {
return right;
+ }
if (right._sign == 0)
+ {
return left;
+ }
var a = left._data;
var b = right._data;
@@ -1462,7 +1754,10 @@ public static explicit operator BigInteger(decimal value)
{
uint va = 0;
if (i < a.Length)
+ {
va = a[i];
+ }
+
if (ls == -1)
{
ac = ~va + ac;
@@ -1472,7 +1767,10 @@ public static explicit operator BigInteger(decimal value)
uint vb = 0;
if (i < b.Length)
+ {
vb = b[i];
+ }
+
if (rs == -1)
{
bc = ~vb + bc;
@@ -1492,12 +1790,20 @@ public static explicit operator BigInteger(decimal value)
result[i] = word;
}
- for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ;
+ for (i = result.Length - 1; i >= 0 && result[i] == 0; --i)
+ {
+ // Intentionally empty block
+ }
+
if (i == -1)
+ {
return Zero;
+ }
if (i < result.Length - 1)
+ {
Array.Resize(ref result, i + 1);
+ }
return new BigInteger(negRes ? (short)-1 : (short)1, result);
}
@@ -1510,13 +1816,19 @@ public static explicit operator BigInteger(decimal value)
///
/// The result of the bitwise Or operation.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static BigInteger operator ^(BigInteger left, BigInteger right)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
if (left._sign == 0)
+ {
return right;
+ }
if (right._sign == 0)
+ {
return left;
+ }
var a = left._data;
var b = right._data;
@@ -1534,7 +1846,10 @@ public static explicit operator BigInteger(decimal value)
{
uint va = 0;
if (i < a.Length)
+ {
va = a[i];
+ }
+
if (ls == -1)
{
ac = ~va + ac;
@@ -1544,7 +1859,10 @@ public static explicit operator BigInteger(decimal value)
uint vb = 0;
if (i < b.Length)
+ {
vb = b[i];
+ }
+
if (rs == -1)
{
bc = ~vb + bc;
@@ -1564,12 +1882,20 @@ public static explicit operator BigInteger(decimal value)
result[i] = word;
}
- for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ;
+ for (i = result.Length - 1; i >= 0 && result[i] == 0; --i)
+ {
+ // Intentionally empty block
+ }
+
if (i == -1)
+ {
return Zero;
+ }
if (i < result.Length - 1)
+ {
Array.Resize(ref result, i + 1);
+ }
return new BigInteger(negRes ? (short)-1 : (short)1, result);
}
@@ -1581,10 +1907,14 @@ public static explicit operator BigInteger(decimal value)
///
/// The bitwise one's complement of .
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static BigInteger operator ~(BigInteger value)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- if (value._data == null)
+ if (value._data is null)
+ {
return MinusOne;
+ }
var data = value._data;
int sign = value._sign;
@@ -1618,26 +1948,42 @@ public static explicit operator BigInteger(decimal value)
result[i] = word;
}
- for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ;
+ for (i = result.Length - 1; i >= 0 && result[i] == 0; --i)
+ {
+ // Intentionally empty block
+ }
+
if (i == -1)
+ {
return Zero;
+ }
if (i < result.Length - 1)
+ {
Array.Resize(ref result, i + 1);
+ }
return new BigInteger(negRes ? (short)-1 : (short)1, result);
}
- //returns the 0-based index of the most significant set bit
- //returns 0 if no bit is set, so extra care when using it
- static int BitScanBackward(uint word)
+ ///
+ /// Returns the zero-based index of the most significant set bit.
+ ///
+ /// The value to scan.
+ ///
+ /// The zero-based index of the most significant set bit, or zero if no bit is set.
+ ///
+ private static int BitScanBackward(uint word)
{
for (var i = 31; i >= 0; --i)
{
var mask = 1u << i;
if ((word & mask) == mask)
+ {
return i;
+ }
}
+
return 0;
}
@@ -1649,12 +1995,19 @@ static int BitScanBackward(uint word)
///
/// A value that has been shifted to the left by the specified number of bits.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static BigInteger operator <<(BigInteger value, int shift)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
- if (shift == 0 || value._data == null)
+ if (shift == 0 || value._data is null)
+ {
return value;
+ }
+
if (shift < 0)
+ {
return value >> -shift;
+ }
var data = value._data;
int sign = value._sign;
@@ -1684,7 +2037,9 @@ static int BitScanBackward(uint word)
var word = data[i];
res[i + idxShift] |= word << bitShift;
if (i + idxShift + 1 < res.Length)
+ {
res[i + idxShift + 1] = word >> carryShift;
+ }
}
}
@@ -1699,12 +2054,19 @@ static int BitScanBackward(uint word)
///
/// A value that has been shifted to the right by the specified number of bits.
///
+#pragma warning disable CA2225 // Operator overloads have named alternates
public static BigInteger operator >>(BigInteger value, int shift)
+#pragma warning restore CA2225 // Operator overloads have named alternates
{
if (shift == 0 || value._sign == 0)
+ {
return value;
+ }
+
if (shift < 0)
+ {
return value << -shift;
+ }
var data = value._data;
int sign = value._sign;
@@ -1715,14 +2077,15 @@ static int BitScanBackward(uint word)
var extraWords = idxShift;
if (bitShift > topMostIdx)
+ {
++extraWords;
+ }
+
var size = data.Length - extraWords;
if (size <= 0)
{
- if (sign == 1)
- return Zero;
- return MinusOne;
+ return sign == 1 ? Zero : MinusOne;
}
var res = new uint[size];
@@ -1735,7 +2098,9 @@ static int BitScanBackward(uint word)
var word = data[i];
if (i - idxShift < res.Length)
+ {
res[i - idxShift] |= word >> bitShift;
+ }
}
}
else
@@ -1745,14 +2110,18 @@ static int BitScanBackward(uint word)
var word = data[i];
if (i - idxShift < res.Length)
+ {
res[i - idxShift] |= word >> bitShift;
+ }
+
if (i - idxShift - 1 >= 0)
+ {
res[i - idxShift - 1] = word << carryShift;
+ }
}
-
}
- //Round down instead of toward zero
+ // Round down instead of toward zero
if (sign == -1)
{
for (var i = 0; i < idxShift; i++)
@@ -1764,6 +2133,7 @@ static int BitScanBackward(uint word)
return tmp;
}
}
+
if (bitShift > 0 && (data[idxShift] << carryShift) != 0u)
{
var tmp = new BigInteger((short)sign, res);
@@ -1771,6 +2141,7 @@ static int BitScanBackward(uint word)
return tmp;
}
}
+
return new BigInteger((short)sign, res);
}
@@ -1781,7 +2152,7 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is less than ; otherwise, false.
+ /// if is less than ; otherwise, .
///
public static bool operator <(BigInteger left, BigInteger right)
{
@@ -1794,36 +2165,34 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if left is than ; otherwise, false.
+ /// if left is than ; otherwise, .
///
public static bool operator <(BigInteger left, long right)
{
return left.CompareTo(right) < 0;
}
-
///
/// Returns a value that indicates whether a 64-bit signed integer is less than a value.
///
/// The first value to compare.
/// The second value to compare.
///
- /// true if is less than ;
- /// otherwise, false.
+ /// if is less than ;
+ /// otherwise, .
///
public static bool operator <(long left, BigInteger right)
{
return right.CompareTo(left) > 0;
}
-
///
/// Returns a value that indicates whether a 64-bit signed integer is less than a value.
///
/// The first value to compare.
/// The second value to compare.
///
- /// true if is less than ; otherwise, false.
+ /// if is less than ; otherwise, .
///
[CLSCompliant(false)]
public static bool operator <(BigInteger left, ulong right)
@@ -1837,7 +2206,7 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is less than ; otherwise, false.
+ /// if is less than ; otherwise, .
///
[CLSCompliant(false)]
public static bool operator <(ulong left, BigInteger right)
@@ -1852,8 +2221,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is less than or equal to ;
- /// otherwise, false.
+ /// if is less than or equal to ;
+ /// otherwise, .
///
public static bool operator <=(BigInteger left, BigInteger right)
{
@@ -1867,8 +2236,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is less than or equal to ;
- /// otherwise, false.
+ /// if is less than or equal to ;
+ /// otherwise, .
///
public static bool operator <=(BigInteger left, long right)
{
@@ -1881,8 +2250,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is less than or equal to ;
- /// otherwise, false.
+ /// if is less than or equal to ;
+ /// otherwise, .
///
public static bool operator <=(long left, BigInteger right)
{
@@ -1896,8 +2265,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is less than or equal to ;
- /// otherwise, false.
+ /// if is less than or equal to ;
+ /// otherwise, .
///
[CLSCompliant(false)]
public static bool operator <=(BigInteger left, ulong right)
@@ -1912,8 +2281,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is less than or equal to ;
- /// otherwise, false.
+ /// if is less than or equal to ;
+ /// otherwise, .
///
[CLSCompliant(false)]
public static bool operator <=(ulong left, BigInteger right)
@@ -1928,8 +2297,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is greater than ;
- /// otherwise, false.
+ /// if is greater than ;
+ /// otherwise, .
///
public static bool operator >(BigInteger left, BigInteger right)
{
@@ -1942,8 +2311,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is greater than ;
- /// otherwise, false.
+ /// if is greater than ;
+ /// otherwise, .
///
public static bool operator >(BigInteger left, long right)
{
@@ -1956,8 +2325,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is greater than ;
- /// otherwise, false.
+ /// if is greater than ;
+ /// otherwise, .
///
public static bool operator >(long left, BigInteger right)
{
@@ -1970,8 +2339,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is greater than ;
- /// otherwise, false.
+ /// if is greater than ;
+ /// otherwise, .
///
[CLSCompliant(false)]
public static bool operator >(BigInteger left, ulong right)
@@ -1985,8 +2354,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is greater than ;
- /// otherwise, false.
+ /// if is greater than ;
+ /// otherwise, .
///
[CLSCompliant(false)]
public static bool operator >(ulong left, BigInteger right)
@@ -2001,8 +2370,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is greater than ;
- /// otherwise, false.
+ /// if is greater than ;
+ /// otherwise, .
///
public static bool operator >=(BigInteger left, BigInteger right)
{
@@ -2016,8 +2385,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is greater than ;
- /// otherwise, false.
+ /// if is greater than ;
+ /// otherwise, .
///
public static bool operator >=(BigInteger left, long right)
{
@@ -2031,8 +2400,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is greater than ;
- /// otherwise, false.
+ /// if is greater than ;
+ /// otherwise, .
///
public static bool operator >=(long left, BigInteger right)
{
@@ -2046,8 +2415,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is greater than ;
- /// otherwise, false.
+ /// if is greater than ;
+ /// otherwise, .
///
[CLSCompliant(false)]
public static bool operator >=(BigInteger left, ulong right)
@@ -2062,8 +2431,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if is greater than ;
- /// otherwise, false.
+ /// if is greater than ;
+ /// otherwise, .
///
[CLSCompliant(false)]
public static bool operator >=(ulong left, BigInteger right)
@@ -2077,8 +2446,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if the and parameters have the same value;
- /// otherwise, false.
+ /// if the and parameters have the same value;
+ /// otherwise, .
///
public static bool operator ==(BigInteger left, BigInteger right)
{
@@ -2091,8 +2460,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if the and parameters have the same value;
- /// otherwise, false.
+ /// if the and parameters have the same value;
+ /// otherwise, .
///
public static bool operator ==(BigInteger left, long right)
{
@@ -2105,8 +2474,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if the and parameters have the same value;
- /// otherwise, false.
+ /// if the and parameters have the same value;
+ /// otherwise, .
///
public static bool operator ==(long left, BigInteger right)
{
@@ -2119,8 +2488,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if the and parameters have the same value;
- /// otherwise, false.
+ /// if the and parameters have the same value;
+ /// otherwise, .
///
[CLSCompliant(false)]
public static bool operator ==(BigInteger left, ulong right)
@@ -2134,8 +2503,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if the and parameters have the same value;
- /// otherwise, false.
+ /// if the and parameters have the same value;
+ /// otherwise, .
///
[CLSCompliant(false)]
public static bool operator ==(ulong left, BigInteger right)
@@ -2149,8 +2518,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if and are not equal;
- /// otherwise, false.
+ /// if and are not equal;
+ /// otherwise, .
///
public static bool operator !=(BigInteger left, BigInteger right)
{
@@ -2163,8 +2532,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if and are not equal;
- /// otherwise, false.
+ /// if and are not equal;
+ /// otherwise, .
///
public static bool operator !=(BigInteger left, long right)
{
@@ -2177,8 +2546,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if and are not equal;
- /// otherwise, false.
+ /// if and are not equal;
+ /// otherwise, .
///
public static bool operator !=(long left, BigInteger right)
{
@@ -2191,8 +2560,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if and are not equal;
- /// otherwise, false.
+ /// if and are not equal;
+ /// otherwise, .
///
[CLSCompliant(false)]
public static bool operator !=(BigInteger left, ulong right)
@@ -2206,8 +2575,8 @@ static int BitScanBackward(uint word)
/// The first value to compare.
/// The second value to compare.
///
- /// true if and are not equal;
- /// otherwise, false.
+ /// if and are not equal;
+ /// otherwise, .
///
[CLSCompliant(false)]
public static bool operator !=(ulong left, BigInteger right)
@@ -2220,15 +2589,18 @@ static int BitScanBackward(uint word)
///
/// The object to compare.
///
- /// true if the parameter is a object or a type capable
+ /// if the parameter is a object or a type capable
/// of implicit conversion to a value, and its value is equal to the value of the
- /// current object; otherwise, false.
+ /// current object; otherwise, .
///
- public override bool Equals(object obj)
+ public override readonly bool Equals(object obj)
{
- if (!(obj is BigInteger))
+ if (obj is not BigInteger other)
+ {
return false;
- return Equals((BigInteger)obj);
+ }
+
+ return Equals(other);
}
///
@@ -2237,24 +2609,32 @@ public override bool Equals(object obj)
///
/// The object to compare.
///
- /// true if this object and have the same value;
- /// otherwise, false.
+ /// if this object and have the same value;
+ /// otherwise, .
///
- public bool Equals(BigInteger other)
+ public readonly bool Equals(BigInteger other)
{
if (_sign != other._sign)
+ {
return false;
+ }
var alen = _data != null ? _data.Length : 0;
var blen = other._data != null ? other._data.Length : 0;
if (alen != blen)
+ {
return false;
+ }
+
for (var i = 0; i < alen; ++i)
{
if (_data[i] != other._data[i])
+ {
return false;
+ }
}
+
return true;
}
@@ -2263,42 +2643,35 @@ public bool Equals(BigInteger other)
///
/// The signed 64-bit integer value to compare.
///
- /// true if the signed 64-bit integer and the current instance have the same value; otherwise, false.
+ /// if the signed 64-bit integer and the current instance have the same value; otherwise, .
///
- public bool Equals(long other)
+ public readonly bool Equals(long other)
{
return CompareTo(other) == 0;
}
///
- /// Converts the numeric value of the current object to its equivalent string representation.
+ /// Returns a value that indicates whether the current instance and an unsigned 64-bit integer have the same value.
///
+ /// The unsigned 64-bit integer to compare.
///
- /// The string representation of the current value.
+ /// if the current instance and the unsigned 64-bit integer have the same value; otherwise, .
///
- public override string ToString()
+ [CLSCompliant(false)]
+ public readonly bool Equals(ulong other)
{
- return ToString(10, null);
+ return CompareTo(other) == 0;
}
- private string ToStringWithPadding(string format, uint radix, IFormatProvider provider)
+ ///
+ /// Converts the numeric value of the current object to its equivalent string representation.
+ ///
+ ///
+ /// The string representation of the current value.
+ ///
+ public override readonly string ToString()
{
- if (format.Length > 1)
- {
- var precision = Convert.ToInt32(format.Substring(1), CultureInfo.InvariantCulture.NumberFormat);
- var baseStr = ToString(radix, provider);
- if (baseStr.Length < precision)
- {
- var additional = new string('0', precision - baseStr.Length);
- if (baseStr[0] != '-')
- {
- return additional + baseStr;
- }
- return "-" + additional + baseStr.Substring(1);
- }
- return baseStr;
- }
- return ToString(radix, provider);
+ return ToString(10, provider: null);
}
///
@@ -2311,23 +2684,23 @@ private string ToStringWithPadding(string format, uint radix, IFormatProvider pr
/// parameter.
///
/// is not a valid format string.
- public string ToString(string format)
+ public readonly string ToString(string format)
{
- return ToString(format, null);
+ return ToString(format, formatProvider: null);
}
///
/// Converts the numeric value of the current object to its equivalent string representation
- /// by using the specified culture-specific formatting information.
+ /// by using the specified culture-specific formatting information.
///
/// An object that supplies culture-specific formatting information.
///
/// The string representation of the current value in the format specified by the
/// parameter.
///
- public string ToString(IFormatProvider provider)
+ public readonly string ToString(IFormatProvider provider)
{
- return ToString(null, provider);
+ return ToString(format: null, provider);
}
///
@@ -2335,15 +2708,17 @@ public string ToString(IFormatProvider provider)
/// by using the specified format and culture-specific format information.
///
/// A standard or custom numeric format string.
- /// An object that supplies culture-specific formatting information.
+ /// An object that supplies culture-specific formatting information.
///
/// The string representation of the current value as specified by the
- /// and parameters.
+ /// and parameters.
///
- public string ToString(string format, IFormatProvider provider)
+ public readonly string ToString(string format, IFormatProvider formatProvider)
{
if (string.IsNullOrEmpty(format))
- return ToString(10, provider);
+ {
+ return ToString(10, formatProvider);
+ }
switch (format[0])
{
@@ -2353,15 +2728,42 @@ public string ToString(string format, IFormatProvider provider)
case 'G':
case 'r':
case 'R':
- return ToStringWithPadding(format, 10, provider);
+ return ToStringWithPadding(format, 10, formatProvider);
case 'x':
case 'X':
- return ToStringWithPadding(format, 16, null);
+ return ToStringWithPadding(format, 16, provider: null);
default:
throw new FormatException(string.Format("format '{0}' not implemented", format));
}
}
+ private readonly string ToStringWithPadding(string format, uint radix, IFormatProvider provider)
+ {
+ if (format.Length > 1)
+ {
+ var precision = Convert.ToInt32(format.Substring(1), CultureInfo.InvariantCulture.NumberFormat);
+ var baseStr = ToString(radix, provider);
+ if (baseStr.Length < precision)
+ {
+ var additional = new string('0', precision - baseStr.Length);
+ if (baseStr[0] != '-')
+ {
+ return additional + baseStr;
+ }
+
+#if NET
+ return string.Concat("-", additional, baseStr.AsSpan(1));
+#else
+ return "-" + additional + baseStr.Substring(1);
+#endif // NET
+ }
+
+ return baseStr;
+ }
+
+ return ToString(radix, provider);
+ }
+
private static uint[] MakeTwoComplement(uint[] v)
{
var res = new uint[v.Length];
@@ -2370,9 +2772,9 @@ private static uint[] MakeTwoComplement(uint[] v)
for (var i = 0; i < v.Length; ++i)
{
var word = v[i];
- carry = (ulong)~word + carry;
- word = (uint)carry;
- carry = (uint)(carry >> 32);
+ carry = (ulong) ~word + carry;
+ word = (uint) carry;
+ carry = (uint) (carry >> 32);
res[i] = word;
}
@@ -2380,56 +2782,77 @@ private static uint[] MakeTwoComplement(uint[] v)
var idx = FirstNonFfByte(last);
uint mask = 0xFF;
for (var i = 1; i < idx; ++i)
+ {
mask = (mask << 8) | 0xFF;
+ }
res[res.Length - 1] = last & mask;
return res;
}
- private string ToString(uint radix, IFormatProvider provider)
+ private readonly string ToString(uint radix, IFormatProvider provider)
{
const string characterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (characterSet.Length < radix)
- throw new ArgumentException("charSet length less than radix", "characterSet");
+ {
+ throw new ArgumentException("charSet length less than radix", nameof(radix));
+ }
+
if (radix == 1)
- throw new ArgumentException("There is no such thing as radix one notation", "radix");
+ {
+ throw new ArgumentException("There is no such thing as radix one notation", nameof(radix));
+ }
if (_sign == 0)
+ {
return "0";
+ }
+
if (_data.Length == 1 && _data[0] == 1)
+ {
return _sign == 1 ? "1" : "-1";
+ }
- var digits = new List(1 + _data.Length * 3 / 10);
+ var digits = new List(1 + ((_data.Length * 3) / 10));
BigInteger a;
if (_sign == 1)
+ {
a = this;
+ }
else
{
var dt = _data;
if (radix > 10)
+ {
dt = MakeTwoComplement(dt);
+ }
+
a = new BigInteger(1, dt);
}
while (a != 0)
{
- BigInteger rem;
- a = DivRem(a, radix, out rem);
- digits.Add(characterSet[(int)rem]);
+ a = DivRem(a, radix, out var rem);
+ digits.Add(characterSet[(int) rem]);
}
if (_sign == -1 && radix == 10)
{
NumberFormatInfo info = null;
if (provider != null)
+ {
info = provider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;
+ }
+
if (info != null)
{
var str = info.NegativeSign;
for (var i = str.Length - 1; i >= 0; --i)
+ {
digits.Add(str[i]);
+ }
}
else
{
@@ -2439,7 +2862,9 @@ private string ToString(uint radix, IFormatProvider provider)
var last = digits[digits.Count - 1];
if (_sign == 1 && radix > 10 && (last < '0' || last > '9'))
+ {
digits.Add('0');
+ }
digits.Reverse();
@@ -2453,15 +2878,15 @@ private string ToString(uint radix, IFormatProvider provider)
///
/// A value that is equivalent to the number specified in the parameter.
///
- /// is null.
+ /// is .
/// is not in the correct format.
public static BigInteger Parse(string value)
{
- Exception ex;
- BigInteger result;
-
- if (!Parse(value, false, out result, out ex))
+ if (!Parse(value, tryParse: false, out var result, out var ex))
+ {
throw ex;
+ }
+
return result;
}
@@ -2478,11 +2903,11 @@ public static BigInteger Parse(string value)
/// -or-
/// includes the or flag along with another value.
///
- /// is null.
+ /// is .
/// does not comply with the input pattern specified by .
public static BigInteger Parse(string value, NumberStyles style)
{
- return Parse(value, style, null);
+ return Parse(value, style, provider: null);
}
///
@@ -2493,7 +2918,7 @@ public static BigInteger Parse(string value, NumberStyles style)
///
/// A value that is equivalent to the number specified in the parameter.
///
- /// is null.
+ /// is .
/// is not in the correct format.
public static BigInteger Parse(string value, IFormatProvider provider)
{
@@ -2514,15 +2939,14 @@ public static BigInteger Parse(string value, IFormatProvider provider)
/// -or-
/// includes the or flag along with another value.
///
- /// is null.
+ /// is .
/// does not comply with the input pattern specified by .
public static BigInteger Parse(string value, NumberStyles style, IFormatProvider provider)
{
- Exception exc;
- BigInteger res;
-
- if (!Parse(value, style, provider, false, out res, out exc))
+ if (!Parse(value, style, provider, tryParse: false, out var res, out var exc))
+ {
throw exc;
+ }
return res;
}
@@ -2532,15 +2956,14 @@ public static BigInteger Parse(string value, NumberStyles style, IFormatProvider
/// returns a value that indicates whether the conversion succeeded.
///
/// The string representation of a number.
- /// When this method returns, contains the equivalent to the number that is contained in value, or zero (0) if the conversion fails. The conversion fails if the parameter is null or is not of the correct format. This parameter is passed uninitialized.
+ /// When this method returns, contains the equivalent to the number that is contained in value, or zero (0) if the conversion fails. The conversion fails if the parameter is or is not of the correct format. This parameter is passed uninitialized.
///
- /// true if was converted successfully; otherwise, false.
+ /// if was converted successfully; otherwise, .
///
- /// is null.
+ /// is .
public static bool TryParse(string value, out BigInteger result)
{
- Exception ex;
- return Parse(value, true, out result, out ex);
+ return Parse(value, tryParse: true, out result, out _);
}
///
@@ -2550,9 +2973,9 @@ public static bool TryParse(string value, out BigInteger result)
/// The string representation of a number.
/// A bitwise combination of enumeration values that indicates the style elements that can be present in .
/// An object that supplies culture-specific formatting information about .
- /// When this method returns, contains the equivalent to the number that is contained in value, or if the conversion fails. The conversion fails if the parameter is null or is not of the correct format. This parameter is passed uninitialized.
+ /// When this method returns, contains the equivalent to the number that is contained in value, or if the conversion fails. The conversion fails if the parameter is or is not of the correct format. This parameter is passed uninitialized.
///
- /// true if was converted successfully; otherwise, false.
+ /// if was converted successfully; otherwise, .
///
///
/// is not a value.
@@ -2561,8 +2984,7 @@ public static bool TryParse(string value, out BigInteger result)
///
public static bool TryParse(string value, NumberStyles style, IFormatProvider provider, out BigInteger result)
{
- Exception exc;
- if (!Parse(value, style, provider, true, out result, out exc))
+ if (!Parse(value, style, provider, tryParse: true, out result, out _))
{
result = Zero;
return false;
@@ -2571,22 +2993,30 @@ public static bool TryParse(string value, NumberStyles style, IFormatProvider pr
return true;
}
+#pragma warning disable S4136 // Method overloads should be grouped together
private static bool Parse(string value, NumberStyles style, IFormatProvider fp, bool tryParse, out BigInteger result, out Exception exc)
+#pragma warning restore S4136 // Method overloads should be grouped together
{
result = Zero;
exc = null;
- if (value == null)
+ if (value is null)
{
if (!tryParse)
- exc = new ArgumentNullException("value");
+ {
+ exc = new ArgumentNullException(nameof(value));
+ }
+
return false;
}
if (value.Length == 0)
{
if (!tryParse)
+ {
exc = GetFormatException();
+ }
+
return false;
}
@@ -2596,27 +3026,31 @@ private static bool Parse(string value, NumberStyles style, IFormatProvider fp,
var typeNfi = typeof(NumberFormatInfo);
nfi = (NumberFormatInfo) fp.GetFormat(typeNfi);
}
- if (nfi == null)
- nfi = NumberFormatInfo.CurrentInfo;
+
+ nfi ??= NumberFormatInfo.CurrentInfo;
if (!CheckStyle(style, tryParse, ref exc))
+ {
return false;
+ }
- var allowCurrencySymbol = (style & NumberStyles.AllowCurrencySymbol) != 0;
- var allowHexSpecifier = (style & NumberStyles.AllowHexSpecifier) != 0;
- var allowThousands = (style & NumberStyles.AllowThousands) != 0;
- var allowDecimalPoint = (style & NumberStyles.AllowDecimalPoint) != 0;
- var allowParentheses = (style & NumberStyles.AllowParentheses) != 0;
- var allowTrailingSign = (style & NumberStyles.AllowTrailingSign) != 0;
- var allowLeadingSign = (style & NumberStyles.AllowLeadingSign) != 0;
- var allowTrailingWhite = (style & NumberStyles.AllowTrailingWhite) != 0;
- var allowLeadingWhite = (style & NumberStyles.AllowLeadingWhite) != 0;
- var allowExponent = (style & NumberStyles.AllowExponent) != 0;
+ var allowCurrencySymbol = (style & NumberStyles.AllowCurrencySymbol) == NumberStyles.AllowCurrencySymbol;
+ var allowHexSpecifier = (style & NumberStyles.AllowHexSpecifier) == NumberStyles.AllowHexSpecifier;
+ var allowThousands = (style & NumberStyles.AllowThousands) == NumberStyles.AllowThousands;
+ var allowDecimalPoint = (style & NumberStyles.AllowDecimalPoint) == NumberStyles.AllowDecimalPoint;
+ var allowParentheses = (style & NumberStyles.AllowParentheses) == NumberStyles.AllowParentheses;
+ var allowTrailingSign = (style & NumberStyles.AllowTrailingSign) == NumberStyles.AllowTrailingSign;
+ var allowLeadingSign = (style & NumberStyles.AllowLeadingSign) == NumberStyles.AllowLeadingSign;
+ var allowTrailingWhite = (style & NumberStyles.AllowTrailingWhite) == NumberStyles.AllowTrailingWhite;
+ var allowLeadingWhite = (style & NumberStyles.AllowLeadingWhite) == NumberStyles.AllowLeadingWhite;
+ var allowExponent = (style & NumberStyles.AllowExponent) == NumberStyles.AllowExponent;
var pos = 0;
- if (allowLeadingWhite && !JumpOverWhitespace(ref pos, value, true, tryParse, ref exc))
+ if (allowLeadingWhite && !JumpOverWhitespace(ref pos, value, reportError: true, tryParse, ref exc))
+ {
return false;
+ }
var foundOpenParentheses = false;
var negative = false;
@@ -2628,23 +3062,31 @@ private static bool Parse(string value, NumberStyles style, IFormatProvider fp,
{
foundOpenParentheses = true;
foundSign = true;
- negative = true; // MS always make the number negative when there parentheses
- // even when NumberFormatInfo.NumberNegativePattern != 0!!!
+ negative = true; // MS always make the number negative when there parentheses, even when NumberFormatInfo.NumberNegativePattern != 0
pos++;
- if (allowLeadingWhite && !JumpOverWhitespace(ref pos, value, true, tryParse, ref exc))
+
+ if (allowLeadingWhite && !JumpOverWhitespace(ref pos, value, reportError: true, tryParse, ref exc))
+ {
return false;
+ }
if (value.Substring(pos, nfi.NegativeSign.Length) == nfi.NegativeSign)
{
if (!tryParse)
+ {
exc = GetFormatException();
+ }
+
return false;
}
if (value.Substring(pos, nfi.PositiveSign.Length) == nfi.PositiveSign)
{
if (!tryParse)
+ {
exc = GetFormatException();
+ }
+
return false;
}
}
@@ -2655,15 +3097,18 @@ private static bool Parse(string value, NumberStyles style, IFormatProvider fp,
FindSign(ref pos, value, nfi, ref foundSign, ref negative);
if (foundSign)
{
- if (allowLeadingWhite && !JumpOverWhitespace(ref pos, value, true, tryParse, ref exc))
+ if (allowLeadingWhite && !JumpOverWhitespace(ref pos, value, reportError: true, tryParse, ref exc))
+ {
return false;
+ }
+
if (allowCurrencySymbol)
{
- FindCurrency(ref pos, value, nfi,
- ref foundCurrency);
- if (foundCurrency && allowLeadingWhite &&
- !JumpOverWhitespace(ref pos, value, true, tryParse, ref exc))
+ FindCurrency(ref pos, value, nfi, ref foundCurrency);
+ if (foundCurrency && allowLeadingWhite && !JumpOverWhitespace(ref pos, value, reportError: true, tryParse, ref exc))
+ {
return false;
+ }
}
}
}
@@ -2674,17 +3119,20 @@ private static bool Parse(string value, NumberStyles style, IFormatProvider fp,
FindCurrency(ref pos, value, nfi, ref foundCurrency);
if (foundCurrency)
{
- if (allowLeadingWhite && !JumpOverWhitespace(ref pos, value, true, tryParse, ref exc))
+ if (allowLeadingWhite && !JumpOverWhitespace(ref pos, value, reportError: true, tryParse, ref exc))
+ {
return false;
+ }
+
if (foundCurrency)
{
if (!foundSign && allowLeadingSign)
{
- FindSign(ref pos, value, nfi, ref foundSign,
- ref negative);
- if (foundSign && allowLeadingWhite &&
- !JumpOverWhitespace(ref pos, value, true, tryParse, ref exc))
+ FindSign(ref pos, value, nfi, ref foundSign, ref negative);
+ if (foundSign && allowLeadingWhite && !JumpOverWhitespace(ref pos, value, reportError: true, tryParse, ref exc))
+ {
return false;
+ }
}
}
}
@@ -2698,13 +3146,14 @@ private static bool Parse(string value, NumberStyles style, IFormatProvider fp,
// Number stuff
while (pos < value.Length)
{
-
if (!ValidDigit(value[pos], allowHexSpecifier))
{
if (allowThousands &&
(FindOther(ref pos, value, nfi.NumberGroupSeparator)
|| FindOther(ref pos, value, nfi.CurrencyGroupSeparator)))
+ {
continue;
+ }
if (allowDecimalPoint && decimalPointPos < 0 &&
(FindOther(ref pos, value, nfi.NumberDecimalSeparator)
@@ -2724,32 +3173,43 @@ private static bool Parse(string value, NumberStyles style, IFormatProvider fp,
var hexDigit = value[pos++];
byte digitValue;
if (char.IsDigit(hexDigit))
- digitValue = (byte)(hexDigit - '0');
+ {
+ digitValue = (byte) (hexDigit - '0');
+ }
else if (char.IsLower(hexDigit))
- digitValue = (byte)(hexDigit - 'a' + 10);
+ {
+ digitValue = (byte) (hexDigit - 'a' + 10);
+ }
else
- digitValue = (byte)(hexDigit - 'A' + 10);
+ {
+ digitValue = (byte) (hexDigit - 'A' + 10);
+ }
if (firstHexDigit && digitValue >= 8)
+ {
negative = true;
+ }
- number = number * 16 + digitValue;
+ number = (number * 16) + digitValue;
firstHexDigit = false;
continue;
}
- number = number * 10 + (byte)(value[pos++] - '0');
+ number = (number * 10) + (byte)(value[pos++] - '0');
}
// Post number stuff
if (nDigits == 0)
{
if (!tryParse)
+ {
exc = GetFormatException();
+ }
+
return false;
}
- //Signed hex value (Two's Complement)
+ // Signed hex value (Two's Complement)
if (allowHexSpecifier && negative)
{
var mask = Pow(16, nDigits) - 1;
@@ -2758,8 +3218,12 @@ private static bool Parse(string value, NumberStyles style, IFormatProvider fp,
var exponent = 0;
if (allowExponent)
+ {
if (FindExponent(ref pos, value, ref exponent, tryParse, ref exc) && exc != null)
+ {
return false;
+ }
+ }
if (allowTrailingSign && !foundSign)
{
@@ -2767,65 +3231,90 @@ private static bool Parse(string value, NumberStyles style, IFormatProvider fp,
FindSign(ref pos, value, nfi, ref foundSign, ref negative);
if (foundSign && pos < value.Length)
{
- if (allowTrailingWhite && !JumpOverWhitespace(ref pos, value, true, tryParse, ref exc))
+ if (allowTrailingWhite && !JumpOverWhitespace(ref pos, value, reportError: true, tryParse, ref exc))
+ {
return false;
+ }
}
}
if (allowCurrencySymbol && !foundCurrency)
{
- if (allowTrailingWhite && pos < value.Length && !JumpOverWhitespace(ref pos, value, false, tryParse, ref exc))
+ if (allowTrailingWhite && pos < value.Length && !JumpOverWhitespace(ref pos, value, reportError: false, tryParse, ref exc))
+ {
return false;
+ }
// Currency + sign
FindCurrency(ref pos, value, nfi, ref foundCurrency);
if (foundCurrency && pos < value.Length)
{
- if (allowTrailingWhite && !JumpOverWhitespace(ref pos, value, true, tryParse, ref exc))
+ if (allowTrailingWhite && !JumpOverWhitespace(ref pos, value, reportError: true, tryParse, ref exc))
+ {
return false;
+ }
+
if (!foundSign && allowTrailingSign)
- FindSign(ref pos, value, nfi, ref foundSign,
- ref negative);
+ {
+ FindSign(ref pos, value, nfi, ref foundSign, ref negative);
+ }
}
}
- if (allowTrailingWhite && pos < value.Length && !JumpOverWhitespace(ref pos, value, false, tryParse, ref exc))
+ if (allowTrailingWhite && pos < value.Length && !JumpOverWhitespace(ref pos, value, reportError: false, tryParse, ref exc))
+ {
return false;
+ }
if (foundOpenParentheses)
{
if (pos >= value.Length || value[pos++] != ')')
{
if (!tryParse)
+ {
exc = GetFormatException();
+ }
+
return false;
}
- if (allowTrailingWhite && pos < value.Length && !JumpOverWhitespace(ref pos, value, false, tryParse, ref exc))
+
+ if (allowTrailingWhite && pos < value.Length && !JumpOverWhitespace(ref pos, value, reportError: false, tryParse, ref exc))
+ {
return false;
+ }
}
if (pos < value.Length && value[pos] != '\u0000')
{
if (!tryParse)
+ {
exc = GetFormatException();
+ }
+
return false;
}
if (decimalPointPos >= 0)
+ {
exponent = exponent - nDigits + decimalPointPos;
+ }
if (exponent < 0)
{
- //
// Any non-zero values after decimal point are not allowed
- //
- BigInteger remainder;
- number = DivRem(number, Pow(10, -exponent), out remainder);
+ number = DivRem(number, Pow(10, -exponent), out var remainder);
if (!remainder.IsZero)
{
if (!tryParse)
- exc = new OverflowException("Value too large or too small. exp=" + exponent + " rem = " + remainder + " pow = " + Pow(10, -exponent));
+ {
+ exc = new OverflowException(string.Format(CultureInfo.InvariantCulture,
+ "Value too large or too small. exp= {0} rem = {1} pow = {2}",
+ exponent,
+ remainder,
+ Pow(10, -exponent)));
+ }
+
return false;
}
}
@@ -2835,38 +3324,55 @@ private static bool Parse(string value, NumberStyles style, IFormatProvider fp,
}
if (number._sign == 0)
+ {
result = number;
+ }
else if (negative)
+ {
result = new BigInteger(-1, number._data);
+ }
else
+ {
result = new BigInteger(1, number._data);
+ }
return true;
}
private static bool CheckStyle(NumberStyles style, bool tryParse, ref Exception exc)
{
- if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ if ((style & NumberStyles.AllowHexSpecifier) == NumberStyles.AllowHexSpecifier)
{
var ne = style ^ NumberStyles.AllowHexSpecifier;
- if ((ne & NumberStyles.AllowLeadingWhite) != 0)
+ if ((ne & NumberStyles.AllowLeadingWhite) == NumberStyles.AllowLeadingWhite)
+ {
ne ^= NumberStyles.AllowLeadingWhite;
- if ((ne & NumberStyles.AllowTrailingWhite) != 0)
+ }
+
+ if ((ne & NumberStyles.AllowTrailingWhite) == NumberStyles.AllowTrailingWhite)
+ {
ne ^= NumberStyles.AllowTrailingWhite;
- if (ne != 0)
+ }
+
+ if (ne != NumberStyles.None)
{
if (!tryParse)
- exc = new ArgumentException(
- "With AllowHexSpecifier only " +
- "AllowLeadingWhite and AllowTrailingWhite " +
- "are permitted.");
+ {
+ exc = new ArgumentException("With AllowHexSpecifier only " +
+ "AllowLeadingWhite and AllowTrailingWhite " +
+ "are permitted.");
+ }
+
return false;
}
}
else if ((uint)style > (uint)NumberStyles.Any)
{
if (!tryParse)
+ {
exc = new ArgumentException("Not a valid number style");
+ }
+
return false;
}
@@ -2876,12 +3382,17 @@ private static bool CheckStyle(NumberStyles style, bool tryParse, ref Exception
private static bool JumpOverWhitespace(ref int pos, string s, bool reportError, bool tryParse, ref Exception exc)
{
while (pos < s.Length && char.IsWhiteSpace(s[pos]))
+ {
pos++;
+ }
if (reportError && pos >= s.Length)
{
if (!tryParse)
+ {
exc = GetFormatException();
+ }
+
return false;
}
@@ -2960,8 +3471,8 @@ private static bool FindExponent(ref int pos, string s, ref int exponent, bool t
}
// Reduce the risk of throwing an overflow exc
- exp = checked(exp * 10 - (int)(s[i] - '0'));
- if (exp < int.MinValue || exp > int.MaxValue)
+ exp = checked((exp * 10) - (s[i] - '0'));
+ if (exp is < int.MinValue or > int.MaxValue)
{
exc = tryParse ? null : new OverflowException("Value too large or too small.");
return true;
@@ -2970,7 +3481,9 @@ private static bool FindExponent(ref int pos, string s, ref int exponent, bool t
// exp value saved as negative
if (!negative)
+ {
exp = -exp;
+ }
exc = null;
exponent = (int) exp;
@@ -2993,12 +3506,14 @@ private static bool FindOther(ref int pos, string s, string other)
private static bool ValidDigit(char e, bool allowHex)
{
if (allowHex)
+ {
return char.IsDigit(e) || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
+ }
return char.IsDigit(e);
}
- private static Exception GetFormatException()
+ private static FormatException GetFormatException()
{
return new FormatException("Input string was not in the correct format");
}
@@ -3014,10 +3529,14 @@ private static bool ProcessTrailingWhitespace(bool tryParse, string s, int posit
if (c != 0 && !char.IsWhiteSpace(c))
{
if (!tryParse)
+ {
exc = GetFormatException();
+ }
+
return false;
}
}
+
return true;
}
@@ -3029,10 +3548,13 @@ private static bool Parse(string value, bool tryParse, out BigInteger result, ou
result = Zero;
exc = null;
- if (value == null)
+ if (value is null)
{
if (!tryParse)
- exc = new ArgumentNullException("value");
+ {
+ exc = new ArgumentNullException(nameof(value));
+ }
+
return false;
}
@@ -3043,13 +3565,18 @@ private static bool Parse(string value, bool tryParse, out BigInteger result, ou
{
c = value[i];
if (!char.IsWhiteSpace(c))
+ {
break;
+ }
}
if (i == len)
{
if (!tryParse)
+ {
exc = GetFormatException();
+ }
+
return false;
}
@@ -3059,7 +3586,9 @@ private static bool Parse(string value, bool tryParse, out BigInteger result, ou
var positive = info.PositiveSign;
if (string.CompareOrdinal(value, i, positive, 0, positive.Length) == 0)
+ {
i += positive.Length;
+ }
else if (string.CompareOrdinal(value, i, negative, 0, negative.Length) == 0)
{
sign = -1;
@@ -3077,31 +3606,44 @@ private static bool Parse(string value, bool tryParse, out BigInteger result, ou
continue;
}
- if (c >= '0' && c <= '9')
+ if (c is >= '0' and <= '9')
{
- var d = (byte)(c - '0');
+ var d = (byte) (c - '0');
- val = val * 10 + d;
+ val = (val * 10) + d;
digitsSeen = true;
}
else if (!ProcessTrailingWhitespace(tryParse, value, i, ref exc))
+ {
return false;
+ }
}
if (!digitsSeen)
{
if (!tryParse)
+ {
exc = GetFormatException();
+ }
+
return false;
}
if (val._sign == 0)
+ {
result = val;
+ }
+#pragma warning disable CA1508 // Avoid dead conditional code | this is the following bug in the analyzer rule: https://github.com/dotnet/roslyn-analyzers/issues/6991
else if (sign == -1)
+#pragma warning restore CA1508 // Avoid dead conditional code
+ {
result = new BigInteger(-1, val._data);
+ }
else
+ {
result = new BigInteger(1, val._data);
+ }
return true;
}
@@ -3120,16 +3662,26 @@ public static BigInteger Min(BigInteger left, BigInteger right)
int rs = right._sign;
if (ls < rs)
+ {
return left;
+ }
+
if (rs < ls)
+ {
return right;
+ }
var r = CoreCompare(left._data, right._data);
if (ls == -1)
+ {
r = -r;
+ }
if (r <= 0)
+ {
return left;
+ }
+
return right;
}
@@ -3147,16 +3699,26 @@ public static BigInteger Max(BigInteger left, BigInteger right)
int rs = right._sign;
if (ls > rs)
+ {
return left;
+ }
+
if (rs > ls)
+ {
return right;
+ }
var r = CoreCompare(left._data, right._data);
if (ls == -1)
+ {
r = -r;
+ }
if (r >= 0)
+ {
return left;
+ }
+
return right;
}
@@ -3169,7 +3731,7 @@ public static BigInteger Max(BigInteger left, BigInteger right)
///
public static BigInteger Abs(BigInteger value)
{
- return new BigInteger((short)Math.Abs(value._sign), value._data);
+ return new BigInteger(Math.Abs(value._sign), value._data);
}
///
@@ -3185,7 +3747,9 @@ public static BigInteger Abs(BigInteger value)
public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out BigInteger remainder)
{
if (divisor._sign == 0)
+ {
throw new DivideByZeroException();
+ }
if (dividend._sign == 0)
{
@@ -3193,13 +3757,14 @@ public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out Big
return dividend;
}
- uint[] quotient;
- uint[] remainderValue;
-
- DivModUnsigned(dividend._data, divisor._data, out quotient, out remainderValue);
+ DivModUnsigned(dividend._data, divisor._data, out var quotient, out var remainderValue);
int i;
- for (i = remainderValue.Length - 1; i >= 0 && remainderValue[i] == 0; --i) ;
+ for (i = remainderValue.Length - 1; i >= 0 && remainderValue[i] == 0; --i)
+ {
+ // Intentionally empty block
+ }
+
if (i == -1)
{
remainder = Zero;
@@ -3207,15 +3772,27 @@ public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out Big
else
{
if (i < remainderValue.Length - 1)
+ {
Array.Resize(ref remainderValue, i + 1);
+ }
+
remainder = new BigInteger(dividend._sign, remainderValue);
}
- for (i = quotient.Length - 1; i >= 0 && quotient[i] == 0; --i) ;
+ for (i = quotient.Length - 1; i >= 0 && quotient[i] == 0; --i)
+ {
+ // Intentionally empty block
+ }
+
if (i == -1)
+ {
return Zero;
+ }
+
if (i < quotient.Length - 1)
+ {
Array.Resize(ref quotient, i + 1);
+ }
return new BigInteger((short)(dividend._sign * divisor._sign), quotient);
}
@@ -3231,23 +3808,37 @@ public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out Big
public static BigInteger Pow(BigInteger value, int exponent)
{
if (exponent < 0)
- throw new ArgumentOutOfRangeException("exponent", "exp must be >= 0");
+ {
+ throw new ArgumentOutOfRangeException(nameof(exponent), "exp must be >= 0");
+ }
+
if (exponent == 0)
+ {
return One;
+ }
+
if (exponent == 1)
+ {
return value;
+ }
var result = One;
while (exponent != 0)
{
if ((exponent & 1) != 0)
- result = result * value;
+ {
+ result *= value;
+ }
+
if (exponent == 1)
+ {
break;
+ }
- value = value * value;
+ value *= value;
exponent >>= 1;
}
+
return result;
}
@@ -3265,24 +3856,34 @@ public static BigInteger Pow(BigInteger value, int exponent)
public static BigInteger ModPow(BigInteger value, BigInteger exponent, BigInteger modulus)
{
if (exponent._sign == -1)
- throw new ArgumentOutOfRangeException("exponent", "power must be >= 0");
+ {
+ throw new ArgumentOutOfRangeException(nameof(exponent), "power must be >= 0");
+ }
+
if (modulus._sign == 0)
+ {
throw new DivideByZeroException();
+ }
var result = One % modulus;
while (exponent._sign != 0)
{
if (!exponent.IsEven)
{
- result = result * value;
- result = result % modulus;
+ result *= value;
+ result %= modulus;
}
+
if (exponent.IsOne)
+ {
break;
- value = value * value;
- value = value % modulus;
+ }
+
+ value *= value;
+ value %= modulus;
exponent >>= 1;
}
+
return result;
}
@@ -3297,13 +3898,24 @@ public static BigInteger ModPow(BigInteger value, BigInteger exponent, BigIntege
public static BigInteger GreatestCommonDivisor(BigInteger left, BigInteger right)
{
if (left._sign != 0 && left._data.Length == 1 && left._data[0] == 1)
+ {
return One;
+ }
+
if (right._sign != 0 && right._data.Length == 1 && right._data[0] == 1)
+ {
return One;
+ }
+
if (left.IsZero)
+ {
return Abs(right);
+ }
+
if (right.IsZero)
+ {
return Abs(left);
+ }
var x = new BigInteger(1, left._data);
var y = new BigInteger(1, right._data);
@@ -3315,16 +3927,19 @@ public static BigInteger GreatestCommonDivisor(BigInteger left, BigInteger right
g = x;
x = y % x;
y = g;
+ }
+ if (x.IsZero)
+ {
+ return g;
}
- if (x.IsZero) return g;
// TODO: should we have something here if we can convert to long?
- //
- // Now we can just do it with single precision. I am using the binary gcd method,
- // as it should be faster.
- //
+ /*
+ * Now we can just do it with single precision. I am using the binary gcd method,
+ * as it should be faster.
+ */
var yy = x._data[0];
var xx = (uint)(y % yy);
@@ -3333,24 +3948,40 @@ public static BigInteger GreatestCommonDivisor(BigInteger left, BigInteger right
while (((xx | yy) & 1) == 0)
{
- xx >>= 1; yy >>= 1; t++;
+ xx >>= 1;
+ yy >>= 1;
+ t++;
}
+
while (xx != 0)
{
- while ((xx & 1) == 0) xx >>= 1;
- while ((yy & 1) == 0) yy >>= 1;
+ while ((xx & 1) == 0)
+ {
+ xx >>= 1;
+ }
+
+ while ((yy & 1) == 0)
+ {
+ yy >>= 1;
+ }
+
if (xx >= yy)
+ {
xx = (xx - yy) >> 1;
+ }
else
+ {
yy = (yy - xx) >> 1;
+ }
}
return yy << t;
}
- /*LAMESPEC Log doesn't specify to how many ulp is has to be precise
- We are equilavent to MS with about 2 ULP
- */
+ /*
+ * LAMESPEC Log doesn't specify to how many ulp is has to be precise
+ * We are equilavent to MS with about 2 ULP
+ */
///
/// Returns the logarithm of a specified number in a specified base.
@@ -3358,20 +3989,26 @@ We are equilavent to MS with about 2 ULP
/// A number whose logarithm is to be found.
/// The base of the logarithm.
///
- /// The base logarithm of value,
+ /// The base logarithm of value.
///
/// The log of is out of range of the data type.
public static double Log(BigInteger value, double baseValue)
{
if (value._sign == -1 || baseValue == 1.0d || baseValue == -1.0d ||
baseValue == double.NegativeInfinity || double.IsNaN(baseValue))
+ {
return double.NaN;
+ }
- if (baseValue == 0.0d || baseValue == double.PositiveInfinity)
+ if (baseValue is 0.0d or double.PositiveInfinity)
+ {
return value.IsOne ? 0 : double.NaN;
+ }
- if (value._data == null)
+ if (value._data is null)
+ {
return double.NegativeInfinity;
+ }
var length = value._data.Length - 1;
var bitCount = -1;
@@ -3379,7 +4016,7 @@ public static double Log(BigInteger value, double baseValue)
{
if ((value._data[length] & (1 << curBit)) != 0)
{
- bitCount = curBit + length * 32;
+ bitCount = curBit + (length * 32);
break;
}
}
@@ -3391,19 +4028,24 @@ public static double Log(BigInteger value, double baseValue)
var tempBitlen = bitlen;
while (tempBitlen > int.MaxValue)
{
- testBit = testBit << int.MaxValue;
+ testBit <<= int.MaxValue;
tempBitlen -= int.MaxValue;
}
- testBit = testBit << (int)tempBitlen;
+
+ testBit <<= (int)tempBitlen;
for (var curbit = bitlen; curbit >= 0; --curbit)
{
if ((value & testBit)._sign != 0)
+ {
c += d;
+ }
+
d *= 0.5;
- testBit = testBit >> 1;
+ testBit >>= 1;
}
- return (Math.Log(c) + Math.Log(2) * bitlen) / Math.Log(baseValue);
+
+ return (Math.Log(c) + (Math.Log(2) * bitlen)) / Math.Log(baseValue);
}
///
@@ -3432,35 +4074,24 @@ public static double Log10(BigInteger value)
return Log(value, 10);
}
- ///
- /// Returns a value that indicates whether the current instance and an unsigned 64-bit integer have the same value.
- ///
- /// The unsigned 64-bit integer to compare.
- ///
- /// true if the current instance and the unsigned 64-bit integer have the same value; otherwise, false.
- ///
- [CLSCompliant(false)]
- public bool Equals(ulong other)
- {
- return CompareTo(other) == 0;
- }
-
///
/// Returns the hash code for the current object.
///
///
/// A 32-bit signed integer hash code.
///
- public override int GetHashCode()
+ public override readonly int GetHashCode()
{
- var hash = (uint)(_sign * 0x01010101u);
+ var hash = (uint) (_sign * 0x01010101u);
if (_data != null)
{
foreach (var bit in _data)
+ {
hash ^= bit;
+ }
}
- return (int)hash;
+ return (int) hash;
}
///
@@ -3568,15 +4199,19 @@ public static BigInteger Negate(BigInteger value)
///
///
/// is not a .
- public int CompareTo(object obj)
+ public readonly int CompareTo(object obj)
{
- if (obj == null)
+ if (obj is null)
+ {
return 1;
+ }
- if (!(obj is BigInteger))
+ if (obj is not BigInteger other)
+ {
return -1;
+ }
- return Compare(this, (BigInteger)obj);
+ return Compare(this, other);
}
///
@@ -3606,7 +4241,7 @@ public int CompareTo(object obj)
///
///
///
- public int CompareTo(BigInteger other)
+ public readonly int CompareTo(BigInteger other)
{
return Compare(this, other);
}
@@ -3639,15 +4274,22 @@ public int CompareTo(BigInteger other)
///
///
[CLSCompliant(false)]
- public int CompareTo(ulong other)
+ public readonly int CompareTo(ulong other)
{
if (_sign < 0)
+ {
return -1;
+ }
+
if (_sign == 0)
+ {
return other == 0 ? 0 : -1;
+ }
if (_data.Length > 2)
+ {
return 1;
+ }
var high = (uint)(other >> 32);
var low = (uint)other;
@@ -3655,27 +4297,6 @@ public int CompareTo(ulong other)
return LongCompare(low, high);
}
- private int LongCompare(uint low, uint high)
- {
- uint h = 0;
- if (_data.Length > 1)
- h = _data[1];
-
- if (h > high)
- return 1;
- if (h < high)
- return -1;
-
- var l = _data[0];
-
- if (l > low)
- return 1;
- if (l < low)
- return -1;
-
- return 0;
- }
-
///
/// Compares this instance to a signed 64-bit integer and returns an integer that indicates whether the value of this
/// instance is less than, equal to, or greater than the value of the signed 64-bit integer.
@@ -3703,32 +4324,77 @@ private int LongCompare(uint low, uint high)
///
///
///
- public int CompareTo(long other)
+ public readonly int CompareTo(long other)
{
int ls = _sign;
var rs = Math.Sign(other);
if (ls != rs)
+ {
return ls > rs ? 1 : -1;
+ }
if (ls == 0)
+ {
return 0;
+ }
if (_data.Length > 2)
+ {
return _sign;
+ }
if (other < 0)
+ {
other = -other;
- var low = (uint)other;
- var high = (uint)((ulong)other >> 32);
+ }
+
+ var low = (uint) other;
+ var high = (uint) ((ulong) other >> 32);
var r = LongCompare(low, high);
if (ls == -1)
+ {
r = -r;
+ }
return r;
}
+ private readonly int LongCompare(uint low, uint high)
+ {
+ uint h = 0;
+
+ if (_data.Length > 1)
+ {
+ h = _data[1];
+ }
+
+ if (h > high)
+ {
+ return 1;
+ }
+
+ if (h < high)
+ {
+ return -1;
+ }
+
+ var l = _data[0];
+
+ if (l > low)
+ {
+ return 1;
+ }
+
+ if (l < low)
+ {
+ return -1;
+ }
+
+ return 0;
+ }
+
///
/// Compares two values and returns an integer that indicates whether the first value is less than, equal to, or greater than the second value.
///
@@ -3761,11 +4427,16 @@ public static int Compare(BigInteger left, BigInteger right)
int rs = right._sign;
if (ls != rs)
+ {
return ls > rs ? 1 : -1;
+ }
var r = CoreCompare(left._data, right._data);
if (ls < 0)
+ {
r = -r;
+ }
+
return r;
}
@@ -3774,22 +4445,38 @@ private static int TopByte(uint x)
if ((x & 0xFFFF0000u) != 0)
{
if ((x & 0xFF000000u) != 0)
+ {
return 4;
+ }
+
return 3;
}
+
if ((x & 0xFF00u) != 0)
+ {
return 2;
+ }
+
return 1;
}
private static int FirstNonFfByte(uint word)
{
if ((word & 0xFF000000u) != 0xFF000000u)
+ {
return 4;
+ }
+
if ((word & 0xFF0000u) != 0xFF0000u)
+ {
return 3;
+ }
+
if ((word & 0xFF00u) != 0xFF00u)
+ {
return 2;
+ }
+
return 1;
}
@@ -3799,19 +4486,21 @@ private static int FirstNonFfByte(uint word)
///
/// The value of the current object converted to an array of bytes.
///
- public byte[] ToByteArray()
+ public readonly byte[] ToByteArray()
{
if (_sign == 0)
+ {
return new byte[1];
+ }
- //number of bytes not counting upper word
+ // number of bytes not counting upper word
var bytes = (_data.Length - 1) * 4;
var needExtraZero = false;
var topWord = _data[_data.Length - 1];
int extra;
- //if the topmost bit is set we need an extra
+ // if the topmost bit is set we need an extra
if (_sign == 1)
{
extra = TopByte(topWord);
@@ -3840,6 +4529,7 @@ public byte[] ToByteArray()
res[j++] = (byte)(word >> 16);
res[j++] = (byte)(word >> 24);
}
+
while (extra-- > 0)
{
res[j++] = (byte)topWord;
@@ -3866,25 +4556,32 @@ public byte[] ToByteArray()
res[j++] = (byte)(word >> 24);
}
- add = (ulong)~topWord + (carry);
+ add = (ulong)~topWord + carry;
word = (uint)add;
carry = (uint)(add >> 32);
if (carry == 0)
{
var ex = FirstNonFfByte(word);
- var needExtra = (word & (1 << (ex * 8 - 1))) == 0;
+ var needExtra = (word & (1 << ((ex * 8) - 1))) == 0;
var to = ex + (needExtra ? 1 : 0);
if (to != extra)
+ {
Array.Resize(ref res, bytes + to);
+ }
while (ex-- > 0)
{
res[j++] = (byte)word;
word >>= 8;
}
+
if (needExtra)
+ {
+#pragma warning disable S1854 // Unused assignments should be removed
res[j++] = 0xFF;
+#pragma warning restore S1854 // Unused assignments should be removed
+ }
}
else
{
@@ -3893,7 +4590,9 @@ public byte[] ToByteArray()
res[j++] = (byte)(word >> 8);
res[j++] = (byte)(word >> 16);
res[j++] = (byte)(word >> 24);
+#pragma warning disable S1854 // Unused assignments should be removed
res[j++] = 0xFF;
+#pragma warning restore S1854 // Unused assignments should be removed
}
}
@@ -3926,7 +4625,7 @@ private static uint[] CoreAdd(uint[] a, uint[] b)
for (; i < bl; i++)
{
- sum = sum + a[i];
+ sum += a[i];
res[i] = (uint)sum;
sum >>= 32;
}
@@ -3940,6 +4639,29 @@ private static uint[] CoreAdd(uint[] a, uint[] b)
return res;
}
+ private static uint[] CoreAdd(uint[] a, uint b)
+ {
+ var len = a.Length;
+ var res = new uint[len];
+
+ ulong sum = b;
+ int i;
+ for (i = 0; i < len; i++)
+ {
+ sum += a[i];
+ res[i] = (uint) sum;
+ sum >>= 32;
+ }
+
+ if (sum != 0)
+ {
+ Array.Resize(ref res, len + 1);
+ res[i] = (uint) sum;
+ }
+
+ return res;
+ }
+
/*invariant a > b*/
private static uint[] CoreSub(uint[] a, uint[] b)
{
@@ -3965,32 +4687,15 @@ private static uint[] CoreSub(uint[] a, uint[] b)
borrow = (borrow >> 32) & 0x1;
}
- //remove extra zeroes
- for (i = bl - 1; i >= 0 && res[i] == 0; --i) ;
- if (i < bl - 1)
- Array.Resize(ref res, i + 1);
-
- return res;
- }
-
- private static uint[] CoreAdd(uint[] a, uint b)
- {
- var len = a.Length;
- var res = new uint[len];
-
- ulong sum = b;
- int i;
- for (i = 0; i < len; i++)
+ // remove extra zeroes
+ for (i = bl - 1; i >= 0 && res[i] == 0; --i)
{
- sum = sum + a[i];
- res[i] = (uint)sum;
- sum >>= 32;
+ // Intentionally empty block
}
- if (sum != 0)
+ if (i < bl - 1)
{
- Array.Resize(ref res, len + 1);
- res[i] = (uint)sum;
+ Array.Resize(ref res, i + 1);
}
return res;
@@ -4010,10 +4715,16 @@ private static uint[] CoreSub(uint[] a, uint b)
borrow = (borrow >> 32) & 0x1;
}
- //remove extra zeroes
- for (i = len - 1; i >= 0 && res[i] == 0; --i) ;
+ // Remove extra zeroes
+ for (i = len - 1; i >= 0 && res[i] == 0; --i)
+ {
+ // Intentionally empty block
+ }
+
if (i < len - 1)
+ {
Array.Resize(ref res, i + 1);
+ }
return res;
}
@@ -4024,19 +4735,30 @@ private static int CoreCompare(uint[] a, uint[] b)
var bl = b != null ? b.Length : 0;
if (al > bl)
+ {
return 1;
+ }
+
if (bl > al)
+ {
return -1;
+ }
for (var i = al - 1; i >= 0; --i)
{
var ai = a[i];
var bi = b[i];
if (ai > bi)
+ {
return 1;
+ }
+
if (ai < bi)
+ {
return -1;
+ }
}
+
return 0;
}
@@ -4044,11 +4766,37 @@ private static int GetNormalizeShift(uint value)
{
var shift = 0;
- if ((value & 0xFFFF0000) == 0) { value <<= 16; shift += 16; }
- if ((value & 0xFF000000) == 0) { value <<= 8; shift += 8; }
- if ((value & 0xF0000000) == 0) { value <<= 4; shift += 4; }
- if ((value & 0xC0000000) == 0) { value <<= 2; shift += 2; }
- if ((value & 0x80000000) == 0) { value <<= 1; shift += 1; }
+ if ((value & 0xFFFF0000) == 0)
+ {
+ value <<= 16;
+ shift += 16;
+ }
+
+ if ((value & 0xFF000000) == 0)
+ {
+ value <<= 8;
+ shift += 8;
+ }
+
+ if ((value & 0xF0000000) == 0)
+ {
+ value <<= 4;
+ shift += 4;
+ }
+
+ if ((value & 0xC0000000) == 0)
+ {
+ value <<= 2;
+ shift += 2;
+ }
+
+ if ((value & 0x80000000) == 0)
+ {
+#pragma warning disable IDE0059 // Unnecessary assignment of a value
+ value <<= 1;
+#pragma warning restore IDE0059 // Unnecessary assignment of a value
+ shift += 1;
+ }
return shift;
}
@@ -4099,7 +4847,7 @@ private static void Unnormalize(uint[] un, out uint[] r, int shift)
{
var uni = un[i];
r[i] = (uni >> shift) | carry;
- carry = (uni << lshift);
+ carry = uni << lshift;
}
}
else
@@ -4118,8 +4866,7 @@ private static void DivModUnsigned(uint[] u, uint[] v, out uint[] q, out uint[]
if (n <= 1)
{
- // Divide by single digit
- //
+ // Divide by single digit
ulong rem = 0;
var v0 = v[0];
q = new uint[m];
@@ -4134,7 +4881,8 @@ private static void DivModUnsigned(uint[] u, uint[] v, out uint[] q, out uint[]
rem -= div * v0;
q[j] = (uint)div;
}
- r[0] = (uint)rem;
+
+ r[0] = (uint) rem;
}
else if (m >= n)
{
@@ -4147,37 +4895,35 @@ private static void DivModUnsigned(uint[] u, uint[] v, out uint[] q, out uint[]
Normalize(v, n, vn, shift);
q = new uint[m - n + 1];
- r = null;
- // Main division loop
- //
+ // Main division loop
for (var j = m - n; j >= 0; j--)
{
int i;
- var rr = Base * un[j + n] + un[j + n - 1];
+ var rr = (Base * un[j + n]) + un[j + n - 1];
var qq = rr / vn[n - 1];
rr -= qq * vn[n - 1];
- for (;;)
+ for (; ; )
{
// Estimate too big ?
- //
- if ((qq >= Base) || (qq * vn[n - 2] > (rr * Base + un[j + n - 2])))
+ if ((qq >= Base) || (qq * vn[n - 2] > ((rr * Base) + un[j + n - 2])))
{
qq--;
rr += (ulong)vn[n - 1];
if (rr < Base)
+ {
continue;
+ }
}
+
break;
}
-
- // Multiply and subtract
- //
+ // Multiply and subtract
long b = 0;
- long t = 0;
+ long t;
for (i = 0; i < n; i++)
{
var p = vn[i] * qq;
@@ -4187,15 +4933,14 @@ private static void DivModUnsigned(uint[] u, uint[] v, out uint[] q, out uint[]
t >>= 32;
b = (long)p - t;
}
+
t = (long)un[j + n] - b;
un[j + n] = (uint)t;
- // Store the calculated value
- //
+ // Store the calculated value
q[j] = (uint)qq;
- // Add back vn[0..n] to un[j..j+n]
- //
+ // Add back vn[0..n] to un[j..j+n]
if (t < 0)
{
q[j]--;
@@ -4206,6 +4951,7 @@ private static void DivModUnsigned(uint[] u, uint[] v, out uint[] q, out uint[]
un[j + i] = (uint)c;
c >>= 32;
}
+
c += (ulong)un[j + n];
un[j + n] = (uint)c;
}
diff --git a/src/Renci.SshNet/Common/ChannelDataEventArgs.cs b/src/Renci.SshNet/Common/ChannelDataEventArgs.cs
index 6b47eb6ed..dbc20b5be 100644
--- a/src/Renci.SshNet/Common/ChannelDataEventArgs.cs
+++ b/src/Renci.SshNet/Common/ChannelDataEventArgs.cs
@@ -1,24 +1,32 @@
-namespace Renci.SshNet.Common
+using System;
+
+namespace Renci.SshNet.Common
{
///
- /// Provides data for event.
+ /// Provides data for event.
///
internal class ChannelDataEventArgs : ChannelEventArgs
{
- ///
- /// Gets channel data.
- ///
- public byte[] Data { get; private set; }
-
///
/// Initializes a new instance of the class.
///
/// Channel number.
/// Channel data.
+ /// is .
public ChannelDataEventArgs(uint channelNumber, byte[] data)
: base(channelNumber)
{
+ if (data is null)
+ {
+ throw new ArgumentNullException(nameof(data));
+ }
+
Data = data;
}
+
+ ///
+ /// Gets channel data.
+ ///
+ public byte[] Data { get; }
}
}
diff --git a/src/Renci.SshNet/Common/ChannelEventArgs.cs b/src/Renci.SshNet/Common/ChannelEventArgs.cs
index a8e4549ce..ef514fd29 100644
--- a/src/Renci.SshNet/Common/ChannelEventArgs.cs
+++ b/src/Renci.SshNet/Common/ChannelEventArgs.cs
@@ -7,11 +7,6 @@ namespace Renci.SshNet.Common
///
internal class ChannelEventArgs : EventArgs
{
- ///
- /// Gets the channel number.
- ///
- public uint ChannelNumber { get; private set; }
-
///
/// Initializes a new instance of the class.
///
@@ -20,5 +15,13 @@ public ChannelEventArgs(uint channelNumber)
{
ChannelNumber = channelNumber;
}
+
+ ///
+ /// Gets the channel number.
+ ///
+ ///
+ /// The channel number.
+ ///
+ public uint ChannelNumber { get; }
}
}
diff --git a/src/Renci.SshNet/Common/ChannelExtendedDataEventArgs.cs b/src/Renci.SshNet/Common/ChannelExtendedDataEventArgs.cs
index 9098d6b1b..e67ccb901 100644
--- a/src/Renci.SshNet/Common/ChannelExtendedDataEventArgs.cs
+++ b/src/Renci.SshNet/Common/ChannelExtendedDataEventArgs.cs
@@ -1,9 +1,9 @@
namespace Renci.SshNet.Common
{
///
- /// Provides data for events.
+ /// Provides data for events.
///
- internal class ChannelExtendedDataEventArgs : ChannelDataEventArgs
+ internal sealed class ChannelExtendedDataEventArgs : ChannelDataEventArgs
{
///
/// Initializes a new instance of the class.
@@ -11,7 +11,8 @@ internal class ChannelExtendedDataEventArgs : ChannelDataEventArgs
/// Channel number.
/// Channel data.
/// Channel data type code.
- public ChannelExtendedDataEventArgs(uint channelNumber, byte[] data, uint dataTypeCode) : base(channelNumber, data)
+ public ChannelExtendedDataEventArgs(uint channelNumber, byte[] data, uint dataTypeCode)
+ : base(channelNumber, data)
{
DataTypeCode = dataTypeCode;
}
@@ -19,6 +20,9 @@ public ChannelExtendedDataEventArgs(uint channelNumber, byte[] data, uint dataTy
///
/// Gets the data type code.
///
- public uint DataTypeCode { get; private set; }
+ ///
+ /// The data type code.
+ ///
+ public uint DataTypeCode { get; }
}
}
diff --git a/src/Renci.SshNet/Common/ChannelOpenConfirmedEventArgs.cs b/src/Renci.SshNet/Common/ChannelOpenConfirmedEventArgs.cs
index bd10d8258..78cd9cd6b 100644
--- a/src/Renci.SshNet/Common/ChannelOpenConfirmedEventArgs.cs
+++ b/src/Renci.SshNet/Common/ChannelOpenConfirmedEventArgs.cs
@@ -1,9 +1,9 @@
namespace Renci.SshNet.Common
{
///
- /// Provides data for event.
+ /// Provides data for event.
///
- internal class ChannelOpenConfirmedEventArgs : ChannelEventArgs
+ internal sealed class ChannelOpenConfirmedEventArgs : ChannelEventArgs
{
///
/// Initializes a new instance of the class.
@@ -24,7 +24,7 @@ public ChannelOpenConfirmedEventArgs(uint remoteChannelNumber, uint initialWindo
///
/// The initial size of the window.
///
- public uint InitialWindowSize { get; private set; }
+ public uint InitialWindowSize { get; }
///
/// Gets the maximum size of the packet.
@@ -32,6 +32,6 @@ public ChannelOpenConfirmedEventArgs(uint remoteChannelNumber, uint initialWindo
///
/// The maximum size of the packet.
///
- public uint MaximumPacketSize { get; private set; }
+ public uint MaximumPacketSize { get; }
}
}
diff --git a/src/Renci.SshNet/Common/ChannelOpenFailedEventArgs.cs b/src/Renci.SshNet/Common/ChannelOpenFailedEventArgs.cs
index f130a59eb..291e9d7a6 100644
--- a/src/Renci.SshNet/Common/ChannelOpenFailedEventArgs.cs
+++ b/src/Renci.SshNet/Common/ChannelOpenFailedEventArgs.cs
@@ -1,25 +1,10 @@
namespace Renci.SshNet.Common
{
///
- /// Provides data for event.
+ /// Provides data for event.
///
- internal class ChannelOpenFailedEventArgs : ChannelEventArgs
+ internal sealed class ChannelOpenFailedEventArgs : ChannelEventArgs
{
- ///
- /// Gets failure reason code.
- ///
- public uint ReasonCode { get; private set; }
-
- ///
- /// Gets failure description.
- ///
- public string Description { get; private set; }
-
- ///
- /// Gets failure language.
- ///
- public string Language { get; private set; }
-
///
/// Initializes a new instance of the class.
///
@@ -34,5 +19,20 @@ public ChannelOpenFailedEventArgs(uint channelNumber, uint reasonCode, string de
Description = description;
Language = language;
}
+
+ ///
+ /// Gets failure reason code.
+ ///
+ public uint ReasonCode { get; }
+
+ ///
+ /// Gets failure description.
+ ///
+ public string Description { get; }
+
+ ///
+ /// Gets failure language.
+ ///
+ public string Language { get; }
}
}
diff --git a/src/Renci.SshNet/Common/ChannelRequestEventArgs.cs b/src/Renci.SshNet/Common/ChannelRequestEventArgs.cs
index 0de905a83..95548194d 100644
--- a/src/Renci.SshNet/Common/ChannelRequestEventArgs.cs
+++ b/src/Renci.SshNet/Common/ChannelRequestEventArgs.cs
@@ -1,25 +1,35 @@
using System;
+
using Renci.SshNet.Messages.Connection;
namespace Renci.SshNet.Common
{
///
- /// Provides data for event.
+ /// Provides data for event.
///
- internal class ChannelRequestEventArgs : EventArgs
+ internal sealed class ChannelRequestEventArgs : EventArgs
{
- ///
- /// Gets request information.
- ///
- public RequestInfo Info { get; private set; }
-
///
/// Initializes a new instance of the class.
///
/// Request information.
+ /// is .
public ChannelRequestEventArgs(RequestInfo info)
{
+ if (info is null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+
Info = info;
}
+
+ ///
+ /// Gets the request information.
+ ///
+ ///
+ /// The request information.
+ ///
+ public RequestInfo Info { get; }
}
}
diff --git a/src/Renci.SshNet/Common/CountdownEvent.cs b/src/Renci.SshNet/Common/CountdownEvent.cs
deleted file mode 100644
index 7387a786f..000000000
--- a/src/Renci.SshNet/Common/CountdownEvent.cs
+++ /dev/null
@@ -1,171 +0,0 @@
-#if !FEATURE_THREAD_COUNTDOWNEVENT
-
-using System;
-using System.Threading;
-
-namespace Renci.SshNet.Common
-{
- ///
- /// Represents a synchronization primitive that is signaled when its count reaches zero.
- ///
- internal class CountdownEvent : IDisposable
- {
- private int _count;
- private ManualResetEvent _event;
- private bool _disposed;
-
- ///
- /// Initializes a new instance of class with the specified count.
- ///
- /// The number of signals initially required to set the .
- /// is less than zero.
- ///
- /// If is zero, the event is created in a signaled state.
- ///
- public CountdownEvent(int initialCount)
- {
- if (initialCount < 0)
- {
- throw new ArgumentOutOfRangeException("initialCount");
- }
-
- _count = initialCount;
-
- var initialState = _count == 0;
- _event = new ManualResetEvent(initialState);
- }
-
- ///
- /// Gets the number of remaining signals required to set the event.
- ///
- ///
- /// The number of remaining signals required to set the event.
- ///
- public int CurrentCount
- {
- get { return _count; }
- }
-
- ///
- /// Indicates whether the 's current count has reached zero.
- ///
- ///
- /// true if the current count is zero; otherwise, false.
- ///
- public bool IsSet
- {
- get { return _count == 0; }
- }
-
- ///
- /// Gets a that is used to wait for the event to be set.
- ///
- ///
- /// A that is used to wait for the event to be set.
- ///
- /// The current instance has already been disposed.
- public WaitHandle WaitHandle
- {
- get
- {
- EnsureNotDisposed();
-
- return _event;
- }
- }
-
-
- ///
- /// Registers a signal with the , decrementing the value of .
- ///
- ///
- /// true if the signal caused the count to reach zero and the event was set; otherwise, false.
- ///
- /// The current instance has already been disposed.
- /// The current instance is already set.
- public bool Signal()
- {
- EnsureNotDisposed();
-
- if (_count <= 0)
- throw new InvalidOperationException("Invalid attempt made to decrement the event's count below zero.");
-
- var newCount = Interlocked.Decrement(ref _count);
- if (newCount == 0)
- {
- _event.Set();
- return true;
- }
-
- return false;
- }
-
- ///
- /// Increments the 's current count by one.
- ///
- /// The current instance has already been disposed.
- /// The current instance is already set.
- /// is equal to or greather than .
- public void AddCount()
- {
- EnsureNotDisposed();
-
- if (_count == int.MaxValue)
- throw new InvalidOperationException("TODO");
-
- Interlocked.Increment(ref _count);
- }
-
- ///
- /// Blocks the current thread until the is set, using a
- /// to measure the timeout.
- ///
- /// A that represents the number of milliseconds to wait, or a that represents -1 milliseconds to wait indefinitely.
- ///
- /// true if the was set; otherwise, false.
- ///
- /// The current instance has already been disposed.
- public bool Wait(TimeSpan timeout)
- {
- EnsureNotDisposed();
-
- return _event.WaitOne(timeout);
- }
-
- ///
- /// Releases all resources used by the current instance of the class.
- ///
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- ///
- /// Releases the unmanaged resources used by the , and optionally releases the managed resources.
- ///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- var theEvent = _event;
- if (theEvent != null)
- {
- _event = null;
- theEvent.Dispose();
- }
-
- _disposed = true;
- }
- }
-
- private void EnsureNotDisposed()
- {
- if (_disposed)
- throw new ObjectDisposedException(GetType().Name);
- }
- }
-}
-
-#endif // FEATURE_THREAD_COUNTDOWNEVENT
\ No newline at end of file
diff --git a/src/Renci.SshNet/Common/DerData.cs b/src/Renci.SshNet/Common/DerData.cs
index 35178798a..ba0a678dd 100644
--- a/src/Renci.SshNet/Common/DerData.cs
+++ b/src/Renci.SshNet/Common/DerData.cs
@@ -16,39 +16,17 @@ public class DerData
private const byte Octetstring = 0x04;
private const byte Null = 0x05;
private const byte Objectidentifier = 0x06;
- //private const byte EXTERNAL = 0x08;
- //private const byte ENUMERATED = 0x0a;
private const byte Sequence = 0x10;
- //private const byte SEQUENCEOF = 0x10; // for completeness
- //private const byte SET = 0x11;
- //private const byte SETOF = 0x11; // for completeness
-
- //private const byte NUMERICSTRING = 0x12;
- //private const byte PRINTABLESTRING = 0x13;
- //private const byte T61STRING = 0x14;
- //private const byte VIDEOTEXSTRING = 0x15;
- //private const byte IA5STRING = 0x16;
- //private const byte UTCTIME = 0x17;
- //private const byte GENERALIZEDTIME = 0x18;
- //private const byte GRAPHICSTRING = 0x19;
- //private const byte VISIBLESTRING = 0x1a;
- //private const byte GENERALSTRING = 0x1b;
- //private const byte UNIVERSALSTRING = 0x1c;
- //private const byte BMPSTRING = 0x1e;
- //private const byte UTF8STRING = 0x0c;
- //private const byte APPLICATION = 0x40;
- //private const byte TAGGED = 0x80;
private readonly List _data;
-
- private int _readerIndex;
private readonly int _lastIndex;
+ private int _readerIndex;
///
/// Gets a value indicating whether end of data is reached.
///
///
- /// true if end of data is reached; otherwise, false.
+ /// if end of data is reached; otherwise, .
///
public bool IsEndOfData
{
@@ -70,7 +48,7 @@ public DerData()
/// Initializes a new instance of the class.
///
/// DER encoded data.
- /// its a construct
+ /// its a construct.
public DerData(byte[] data, bool construct = false)
{
_data = new List(data);
@@ -80,7 +58,7 @@ public DerData(byte[] data, bool construct = false)
}
else
{
- ReadByte(); // skip dataType
+ _ = ReadByte(); // skip dataType
var length = ReadLength();
_lastIndex = _readerIndex + length;
}
@@ -109,7 +87,9 @@ public BigInteger ReadBigInteger()
{
var type = ReadByte();
if (type != Integer)
+ {
throw new InvalidOperationException(string.Format("Invalid data type, INTEGER(02) is expected, but was {0}", type.ToString("X2")));
+ }
var length = ReadLength();
@@ -126,14 +106,18 @@ public int ReadInteger()
{
var type = ReadByte();
if (type != Integer)
+ {
throw new InvalidOperationException(string.Format("Invalid data type, INTEGER(02) is expected, but was {0}", type.ToString("X2")));
+ }
var length = ReadLength();
var data = ReadBytes(length);
if (length > 4)
+ {
throw new InvalidOperationException("Integer type cannot occupy more then 4 bytes");
+ }
var result = 0;
var shift = (length - 1) * 8;
@@ -143,8 +127,6 @@ public int ReadInteger()
shift -= 8;
}
- //return (int)(data[0] << 56 | data[1] << 48 | data[2] << 40 | data[3] << 32 | data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
-
return result;
}
@@ -156,7 +138,9 @@ public byte[] ReadOctetString()
{
var type = ReadByte();
if (type != Octetstring)
+ {
throw new InvalidOperationException(string.Format("Invalid data type, OCTETSTRING(04) is expected, but was {0}", type.ToString("X2")));
+ }
var length = ReadLength();
var data = ReadBytes(length);
@@ -171,7 +155,9 @@ public byte[] ReadBitString()
{
var type = ReadByte();
if (type != BITSTRING)
+ {
throw new InvalidOperationException(string.Format("Invalid data type, BITSTRING(03) is expected, but was {0}", type.ToString("X2")));
+ }
var length = ReadLength();
var data = ReadBytes(length);
@@ -186,7 +172,9 @@ public byte[] ReadObject()
{
var type = ReadByte();
if (type != Objectidentifier)
+ {
throw new InvalidOperationException(string.Format("Invalid data type, OBJECT(06) is expected, but was {0}", type.ToString("X2")));
+ }
var length = ReadLength();
var data = ReadBytes(length);
@@ -242,18 +230,6 @@ public void Write(byte[] data)
WriteBytes(data);
}
- ///
- /// Writes BITSTRING data into internal buffer.
- ///
- /// The data.
- public void WriteBitstring(byte[] data)
- {
- _data.Add(BITSTRING);
- var length = GetLength(data.Length);
- WriteBytes(length);
- WriteBytes(data);
- }
-
///
/// Writes OBJECTIDENTIFIER data into internal buffer.
///
@@ -261,7 +237,7 @@ public void WriteBitstring(byte[] data)
public void Write(ObjectIdentifier identifier)
{
var temp = new ulong[identifier.Identifiers.Length - 1];
- temp[0] = identifier.Identifiers[0] * 40 + identifier.Identifiers[1];
+ temp[0] = (identifier.Identifiers[0] * 40) + identifier.Identifiers[1];
Buffer.BlockCopy(identifier.Identifiers, 2 * sizeof(ulong), temp, 1 * sizeof(ulong), (identifier.Identifiers.Length - 2) * sizeof(ulong));
var bytes = new List();
foreach (var subidentifier in temp)
@@ -275,7 +251,10 @@ public void Write(ObjectIdentifier identifier)
{
buffer[bufferIndex] = current;
if (bufferIndex < buffer.Length - 1)
+ {
buffer[bufferIndex] |= 0x80;
+ }
+
item >>= 7;
current = (byte)(item & 0x7F);
bufferIndex--;
@@ -294,6 +273,28 @@ public void Write(ObjectIdentifier identifier)
WriteBytes(bytes);
}
+ ///
+ /// Writes DerData data into internal buffer.
+ ///
+ /// DerData data to write.
+ public void Write(DerData data)
+ {
+ var bytes = data.Encode();
+ _data.AddRange(bytes);
+ }
+
+ ///
+ /// Writes BITSTRING data into internal buffer.
+ ///
+ /// The data.
+ public void WriteBitstring(byte[] data)
+ {
+ _data.Add(BITSTRING);
+ var length = GetLength(data.Length);
+ WriteBytes(length);
+ WriteBytes(data);
+ }
+
///
/// Writes OBJECTIDENTIFIER data into internal buffer.
///
@@ -315,17 +316,7 @@ public void WriteNull()
_data.Add(0);
}
- ///
- /// Writes DerData data into internal buffer.
- ///
- /// DerData data to write.
- public void Write(DerData data)
- {
- var bytes = data.Encode();
- _data.AddRange(bytes);
- }
-
- private static IEnumerable GetLength(int length)
+ private static byte[] GetLength(int length)
{
if (length > 127)
{
@@ -333,7 +324,9 @@ private static IEnumerable GetLength(int length)
var val = length;
while ((val >>= 8) != 0)
+ {
size++;
+ }
var data = new byte[size];
data[0] = (byte)(size | 0x80);
@@ -345,12 +338,16 @@ private static IEnumerable GetLength(int length)
return data;
}
- return new[] { (byte)length };
+
+ return new[] { (byte) length };
}
+
///
- /// Gets Data Length
+ /// Gets Data Length.
///
- /// length
+ ///
+ /// The length.
+ ///
public int ReadLength()
{
int length = ReadByte();
@@ -366,7 +363,9 @@ public int ReadLength()
// Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here
if (size > 4)
+ {
throw new InvalidOperationException(string.Format("DER length is '{0}' and cannot be more than 4 bytes.", size));
+ }
length = 0;
for (var i = 0; i < size; i++)
@@ -377,10 +376,9 @@ public int ReadLength()
}
if (length < 0)
+ {
throw new InvalidOperationException("Corrupted data - negative length found");
-
- //if (length >= limit) // after all we must have read at least 1 byte
- // throw new IOException("Corrupted stream - out of bounds length found");
+ }
}
return length;
@@ -389,6 +387,7 @@ public int ReadLength()
///
/// Write Byte data into internal buffer.
///
+ /// The data to write.
public void WriteBytes(IEnumerable data)
{
_data.AddRange(data);
@@ -397,11 +396,15 @@ public void WriteBytes(IEnumerable data)
///
/// Reads Byte data into internal buffer.
///
- /// data read
+ ///
+ /// The data read.
+ ///
public byte ReadByte()
{
if (_readerIndex > _data.Count)
+ {
throw new InvalidOperationException("Read out of boundaries.");
+ }
return _data[_readerIndex++];
}
@@ -409,12 +412,16 @@ public byte ReadByte()
///
/// Reads lengths Bytes data into internal buffer.
///
- /// data read
- /// amount of data to read.
+ ///
+ /// The data read.
+ ///
+ /// amount of data to read.
public byte[] ReadBytes(int length)
{
if (_readerIndex + length > _data.Count)
+ {
throw new InvalidOperationException("Read out of boundaries.");
+ }
var result = new byte[length];
_data.CopyTo(_readerIndex, result, 0, length);
@@ -422,4 +429,4 @@ public byte[] ReadBytes(int length)
return result;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Common/ExceptionEventArgs.cs b/src/Renci.SshNet/Common/ExceptionEventArgs.cs
index 0211be943..7e99def5a 100644
--- a/src/Renci.SshNet/Common/ExceptionEventArgs.cs
+++ b/src/Renci.SshNet/Common/ExceptionEventArgs.cs
@@ -7,11 +7,6 @@ namespace Renci.SshNet.Common
///
public class ExceptionEventArgs : EventArgs
{
- ///
- /// Gets the System.Exception that represents the error that occurred.
- ///
- public Exception Exception { get; private set; }
-
///
/// Initializes a new instance of the class.
///
@@ -20,5 +15,13 @@ public ExceptionEventArgs(Exception exception)
{
Exception = exception;
}
+
+ ///
+ /// Gets the that represents the error that occurred.
+ ///
+ ///
+ /// The that represents the error that occurred.
+ ///
+ public Exception Exception { get; }
}
}
diff --git a/src/Renci.SshNet/Common/Extensions.cs b/src/Renci.SshNet/Common/Extensions.cs
index 17d72d7fb..1d6ce3ca1 100644
--- a/src/Renci.SshNet/Common/Extensions.cs
+++ b/src/Renci.SshNet/Common/Extensions.cs
@@ -5,39 +5,16 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
-#if !FEATURE_WAITHANDLE_DISPOSE
-using System.Threading;
-#endif // !FEATURE_WAITHANDLE_DISPOSE
using Renci.SshNet.Abstractions;
using Renci.SshNet.Messages;
namespace Renci.SshNet.Common
{
///
- /// Collection of different extension method
+ /// Collection of different extension methods.
///
internal static partial class Extensions
{
- ///
- /// Determines whether the specified value is null or white space.
- ///
- /// The value.
- ///
- /// true if is null or white space; otherwise, false.
- ///
- public static bool IsNullOrWhiteSpace(this string value)
- {
- if (string.IsNullOrEmpty(value)) return true;
-
- for (var i = 0; i < value.Length; i++)
- {
- if (!char.IsWhiteSpace(value[i]))
- return false;
- }
-
- return true;
- }
-
internal static byte[] ToArray(this ServiceName serviceName)
{
switch (serviceName)
@@ -73,7 +50,7 @@ internal static BigInteger ToBigInteger(this byte[] data)
}
///
- /// Initializes a new instance of the structure using the SSH BigNum2 Format
+ /// Initializes a new instance of the structure using the SSH BigNum2 Format.
///
public static BigInteger ToBigInteger2(this byte[] data)
{
@@ -83,6 +60,7 @@ public static BigInteger ToBigInteger2(this byte[] data)
Buffer.BlockCopy(data, 0, buf, 1, data.Length);
data = buf;
}
+
return data.ToBigInteger();
}
@@ -100,7 +78,7 @@ internal static T[] Reverse(this T[] array)
}
///
- /// Prints out
+ /// Prints out the specified bytes.
///
/// The bytes.
internal static void DebugPrint(this IEnumerable bytes)
@@ -109,8 +87,9 @@ internal static void DebugPrint(this IEnumerable bytes)
foreach (var b in bytes)
{
- sb.AppendFormat(CultureInfo.CurrentCulture, "0x{0:x2}, ", b);
+ _ = sb.AppendFormat(CultureInfo.CurrentCulture, "0x{0:x2}, ", b);
}
+
Debug.WriteLine(sb.ToString());
}
@@ -120,32 +99,37 @@ internal static void DebugPrint(this IEnumerable bytes)
/// The type to create.
/// Type of the instance to create.
/// A reference to the newly created object.
- internal static T CreateInstance(this Type type) where T : class
+ internal static T CreateInstance(this Type type)
+ where T : class
{
- if (type == null)
+ if (type is null)
+ {
return null;
+ }
+
return Activator.CreateInstance(type) as T;
}
internal static void ValidatePort(this uint value, string argument)
{
if (value > IPEndPoint.MaxPort)
+ {
throw new ArgumentOutOfRangeException(argument,
- string.Format(CultureInfo.InvariantCulture, "Specified value cannot be greater than {0}.",
- IPEndPoint.MaxPort));
+ string.Format(CultureInfo.InvariantCulture, "Specified value cannot be greater than {0}.", IPEndPoint.MaxPort));
+ }
}
internal static void ValidatePort(this int value, string argument)
{
if (value < IPEndPoint.MinPort)
- throw new ArgumentOutOfRangeException(argument,
- string.Format(CultureInfo.InvariantCulture, "Specified value cannot be less than {0}.",
- IPEndPoint.MinPort));
+ {
+ throw new ArgumentOutOfRangeException(argument, string.Format(CultureInfo.InvariantCulture, "Specified value cannot be less than {0}.", IPEndPoint.MinPort));
+ }
if (value > IPEndPoint.MaxPort)
- throw new ArgumentOutOfRangeException(argument,
- string.Format(CultureInfo.InvariantCulture, "Specified value cannot be greater than {0}.",
- IPEndPoint.MaxPort));
+ {
+ throw new ArgumentOutOfRangeException(argument, string.Format(CultureInfo.InvariantCulture, "Specified value cannot be greater than {0}.", IPEndPoint.MaxPort));
+ }
}
///
@@ -158,21 +142,27 @@ internal static void ValidatePort(this int value, string argument)
/// A array that contains the specified number of bytes at the specified offset
/// of the input array.
///
- /// is null.
+ /// is .
///
/// When is zero and equals the length of ,
/// then is returned.
///
public static byte[] Take(this byte[] value, int offset, int count)
{
- if (value == null)
- throw new ArgumentNullException("value");
+ if (value is null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
if (count == 0)
- return Array.Empty;
+ {
+ return Array.Empty();
+ }
if (offset == 0 && value.Length == count)
+ {
return value;
+ }
var taken = new byte[count];
Buffer.BlockCopy(value, offset, taken, 0, count);
@@ -187,21 +177,27 @@ public static byte[] Take(this byte[] value, int offset, int count)
///
/// A array that contains the specified number of bytes at the start of the input array.
///
- /// is null.
+ /// is .
///
/// When equals the length of , then
/// is returned.
///
public static byte[] Take(this byte[] value, int count)
{
- if (value == null)
- throw new ArgumentNullException("value");
+ if (value is null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
if (count == 0)
- return Array.Empty;
+ {
+ return Array.Empty();
+ }
if (value.Length == count)
+ {
return value;
+ }
var taken = new byte[count];
Buffer.BlockCopy(value, 0, taken, 0, count);
@@ -210,24 +206,39 @@ public static byte[] Take(this byte[] value, int count)
public static bool IsEqualTo(this byte[] left, byte[] right)
{
- if (left == null)
- throw new ArgumentNullException("left");
- if (right == null)
- throw new ArgumentNullException("right");
+ if (left is null)
+ {
+ throw new ArgumentNullException(nameof(left));
+ }
+
+ if (right is null)
+ {
+ throw new ArgumentNullException(nameof(right));
+ }
if (left == right)
+ {
return true;
+ }
+#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
+ return left.AsSpan().SequenceEqual(right);
+#else
if (left.Length != right.Length)
+ {
return false;
+ }
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
+ {
return false;
+ }
}
return true;
+#endif
}
///
@@ -239,17 +250,23 @@ public static bool IsEqualTo(this byte[] left, byte[] right)
///
public static byte[] TrimLeadingZeros(this byte[] value)
{
- if (value == null)
- throw new ArgumentNullException("value");
+ if (value is null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
for (var i = 0; i < value.Length; i++)
{
if (value[i] == 0)
+ {
continue;
+ }
// if the first byte is non-zero, then we return the byte array as is
if (i == 0)
+ {
return value;
+ }
var remainingBytes = value.Length - i;
@@ -269,7 +286,10 @@ public static byte[] TrimLeadingZeros(this byte[] value)
public static byte[] Pad(this byte[] data, int length)
{
if (length <= data.Length)
+ {
return data;
+ }
+
var newData = new byte[length];
Buffer.BlockCopy(data, 0, newData, newData.Length - data.Length, data.Length);
return newData;
@@ -277,11 +297,15 @@ public static byte[] Pad(this byte[] data, int length)
public static byte[] Concat(this byte[] first, byte[] second)
{
- if (first == null || first.Length == 0)
+ if (first is null || first.Length == 0)
+ {
return second;
+ }
- if (second == null || second.Length == 0)
+ if (second is null || second.Length == 0)
+ {
return first;
+ }
var concat = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, concat, 0, first.Length);
@@ -301,66 +325,12 @@ internal static bool CanWrite(this Socket socket)
internal static bool IsConnected(this Socket socket)
{
- if (socket == null)
+ if (socket is null)
+ {
return false;
- return socket.Connected;
- }
-
-#if !FEATURE_SOCKET_DISPOSE
- ///
- /// Disposes the specified socket.
- ///
- /// The socket.
- [DebuggerNonUserCode]
- internal static void Dispose(this Socket socket)
- {
- if (socket == null)
- throw new NullReferenceException();
-
- socket.Close();
- }
-#endif // !FEATURE_SOCKET_DISPOSE
-
-#if !FEATURE_WAITHANDLE_DISPOSE
- ///
- /// Disposes the specified handle.
- ///
- /// The handle.
- [DebuggerNonUserCode]
- internal static void Dispose(this WaitHandle handle)
- {
- if (handle == null)
- throw new NullReferenceException();
-
- handle.Close();
- }
-#endif // !FEATURE_WAITHANDLE_DISPOSE
-
-#if !FEATURE_HASHALGORITHM_DISPOSE
- ///
- /// Disposes the specified algorithm.
- ///
- /// The algorithm.
- [DebuggerNonUserCode]
- internal static void Dispose(this System.Security.Cryptography.HashAlgorithm algorithm)
- {
- if (algorithm == null)
- throw new NullReferenceException();
-
- algorithm.Clear();
- }
-#endif // FEATURE_HASHALGORITHM_DISPOSE
+ }
-#if !FEATURE_STRINGBUILDER_CLEAR
- ///
- /// Clears the contents of the string builder.
- ///
- /// The to clear.
- public static void Clear(this StringBuilder value)
- {
- value.Length = 0;
- value.Capacity = 16;
+ return socket.Connected;
}
-#endif // !FEATURE_STRINGBUILDER_CLEAR
}
}
diff --git a/src/Renci.SshNet/Common/HostKeyEventArgs.cs b/src/Renci.SshNet/Common/HostKeyEventArgs.cs
index 7f0d6befc..acd38965a 100644
--- a/src/Renci.SshNet/Common/HostKeyEventArgs.cs
+++ b/src/Renci.SshNet/Common/HostKeyEventArgs.cs
@@ -1,4 +1,5 @@
using System;
+
using Renci.SshNet.Abstractions;
using Renci.SshNet.Security;
@@ -9,11 +10,15 @@ namespace Renci.SshNet.Common
///
public class HostKeyEventArgs : EventArgs
{
+ private readonly Lazy _lazyFingerPrint;
+ private readonly Lazy _lazyFingerPrintSHA256;
+ private readonly Lazy _lazyFingerPrintMD5;
+
///
/// Gets or sets a value indicating whether host key can be trusted.
///
///
- /// true if host key can be trusted; otherwise, false.
+ /// if host key can be trusted; otherwise, .
///
public bool CanTrust { get; set; }
@@ -25,12 +30,50 @@ public class HostKeyEventArgs : EventArgs
///
/// Gets the host key name.
///
- public string HostKeyName{ get; private set; }
+ public string HostKeyName { get; private set; }
///
- /// Gets the finger print.
+ /// Gets the MD5 fingerprint.
///
- public byte[] FingerPrint { get; private set; }
+ ///
+ /// MD5 fingerprint as byte array.
+ ///
+ public byte[] FingerPrint
+ {
+ get
+ {
+ return _lazyFingerPrint.Value;
+ }
+ }
+
+ ///
+ /// Gets the SHA256 fingerprint of the host key in the same format as the ssh command,
+ /// i.e. non-padded base64, but without the SHA256: prefix.
+ ///
+ /// ohD8VZEXGWo6Ez8GSEJQ9WpafgLFsOfLOtGGQCQo6Og.
+ ///
+ /// Base64 encoded SHA256 fingerprint with padding (equals sign) removed.
+ ///
+ public string FingerPrintSHA256
+ {
+ get
+ {
+ return _lazyFingerPrintSHA256.Value;
+ }
+ }
+
+ ///
+ /// Gets the MD5 fingerprint of the host key in the same format as the ssh command,
+ /// i.e. hexadecimal bytes separated by colons, but without the MD5: prefix.
+ ///
+ /// 97:70:33:82:fd:29:3a:73:39:af:6a:07:ad:f8:80:49.
+ public string FingerPrintMD5
+ {
+ get
+ {
+ return _lazyFingerPrintMD5.Value;
+ }
+ }
///
/// Gets the length of the key in bits.
@@ -44,20 +87,43 @@ public class HostKeyEventArgs : EventArgs
/// Initializes a new instance of the class.
///
/// The host.
+ /// is .
public HostKeyEventArgs(KeyHostAlgorithm host)
{
- CanTrust = true; // Set default value
+ if (host is null)
+ {
+ throw new ArgumentNullException(nameof(host));
+ }
+ CanTrust = true;
HostKey = host.Data;
-
HostKeyName = host.Name;
-
KeyLength = host.Key.KeyLength;
- using (var md5 = CryptoAbstraction.CreateMD5())
- {
- FingerPrint = md5.ComputeHash(host.Data);
- }
+ _lazyFingerPrint = new Lazy(() =>
+ {
+ using var md5 = CryptoAbstraction.CreateMD5();
+ return md5.ComputeHash(HostKey);
+ });
+
+ _lazyFingerPrintSHA256 = new Lazy(() =>
+ {
+ using var sha256 = CryptoAbstraction.CreateSHA256();
+
+ return Convert.ToBase64String(sha256.ComputeHash(HostKey))
+#if NET || NETSTANDARD2_1_OR_GREATER
+ .Replace("=", string.Empty, StringComparison.Ordinal);
+#else
+ .Replace("=", string.Empty);
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ });
+
+ _lazyFingerPrintMD5 = new Lazy(() =>
+ {
+#pragma warning disable CA1308 // Normalize strings to uppercase
+ return BitConverter.ToString(FingerPrint).Replace('-', ':').ToLowerInvariant();
+#pragma warning restore CA1308 // Normalize strings to uppercase
+ });
}
}
}
diff --git a/src/Renci.SshNet/Common/NetConfServerException.cs b/src/Renci.SshNet/Common/NetConfServerException.cs
index 86fbeabef..e8614bcb3 100644
--- a/src/Renci.SshNet/Common/NetConfServerException.cs
+++ b/src/Renci.SshNet/Common/NetConfServerException.cs
@@ -34,19 +34,19 @@ public NetConfServerException(string message)
///
/// The message.
/// The inner exception.
- public NetConfServerException(string message, Exception innerException) :
- base(message, innerException)
+ public NetConfServerException(string message, Exception innerException)
+ : base(message, innerException)
{
}
#if FEATURE_BINARY_SERIALIZATION
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The that holds the serialized object data about the exception being thrown.
/// The that contains contextual information about the source or destination.
- /// The parameter is null.
- /// The class name is null or is zero (0).
+ /// The parameter is .
+ /// The class name is or is zero (0).
protected NetConfServerException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
diff --git a/src/Renci.SshNet/Common/ObjectIdentifier.cs b/src/Renci.SshNet/Common/ObjectIdentifier.cs
index 3ff128bc6..5aa310a54 100644
--- a/src/Renci.SshNet/Common/ObjectIdentifier.cs
+++ b/src/Renci.SshNet/Common/ObjectIdentifier.cs
@@ -1,11 +1,15 @@
using System;
+using System.Linq;
+using System.Security.Cryptography;
namespace Renci.SshNet.Common
{
///
- /// Describes object identifier for DER encoding
+ /// Describes object identifier for DER encoding.
///
+#pragma warning disable CA1815 // Override equals and operator equals on value types
public struct ObjectIdentifier
+#pragma warning restore CA1815 // Override equals and operator equals on value types
{
///
/// Gets the object identifier.
@@ -13,16 +17,38 @@ public struct ObjectIdentifier
public ulong[] Identifiers { get; private set; }
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the struct.
///
/// The identifiers.
+ /// is .
+ /// has less than two elements.
public ObjectIdentifier(params ulong[] identifiers)
- : this()
{
+ if (identifiers is null)
+ {
+ throw new ArgumentNullException(nameof(identifiers));
+ }
+
if (identifiers.Length < 2)
- throw new ArgumentException("identifiers");
+ {
+ throw new ArgumentException("Must contain at least two elements.", nameof(identifiers));
+ }
Identifiers = identifiers;
}
+
+ internal static ObjectIdentifier FromHashAlgorithmName(HashAlgorithmName hashAlgorithmName)
+ {
+ var oid = CryptoConfig.MapNameToOID(hashAlgorithmName.Name);
+
+ if (oid is null)
+ {
+ throw new ArgumentException($"Could not map `{hashAlgorithmName}` to OID.", nameof(hashAlgorithmName));
+ }
+
+ var identifiers = oid.Split('.').Select(ulong.Parse).ToArray();
+
+ return new ObjectIdentifier(identifiers);
+ }
}
}
diff --git a/src/Renci.SshNet/Common/PacketDump.cs b/src/Renci.SshNet/Common/PacketDump.cs
index 7b50582cb..47329f6d0 100644
--- a/src/Renci.SshNet/Common/PacketDump.cs
+++ b/src/Renci.SshNet/Common/PacketDump.cs
@@ -5,7 +5,7 @@
namespace Renci.SshNet.Common
{
- internal class PacketDump
+ internal static class PacketDump
{
public static string Create(List data, int indentLevel)
{
@@ -14,10 +14,15 @@ public static string Create(List data, int indentLevel)
public static string Create(byte[] data, int indentLevel)
{
- if (data == null)
- throw new ArgumentNullException("data");
+ if (data is null)
+ {
+ throw new ArgumentNullException(nameof(data));
+ }
+
if (indentLevel < 0)
- throw new ArgumentOutOfRangeException("indentLevel", "Cannot be less than zero.");
+ {
+ throw new ArgumentOutOfRangeException(nameof(indentLevel), "Cannot be less than zero.");
+ }
const int lineWidth = 16;
@@ -31,12 +36,12 @@ public static string Create(byte[] data, int indentLevel)
if (result.Length > 0)
{
- result.Append(Environment.NewLine);
+ _ = result.Append(Environment.NewLine);
}
- result.Append(indentChars);
- result.Append(pos.ToString("X8"));
- result.Append(" ");
+ _ = result.Append(indentChars);
+ _ = result.Append(pos.ToString("X8"));
+ _ = result.Append(" ");
while (true)
{
@@ -48,10 +53,11 @@ public static string Create(byte[] data, int indentLevel)
}
}
- result.Append(AsHex(line, linePos));
- result.Append(" ");
- result.Append(AsAscii(line, linePos));
+ _ = result.Append(AsHex(line, linePos));
+ _ = result.Append(" ");
+ _ = result.Append(AsAscii(line, linePos));
}
+
return result.ToString();
}
@@ -63,15 +69,15 @@ private static string AsHex(byte[] data, int length)
{
if (i > 0)
{
- hex.Append(' ');
+ _ = hex.Append(' ');
}
- hex.Append(data[i].ToString("X2", CultureInfo.InvariantCulture));
+ _ = hex.Append(data[i].ToString("X2", CultureInfo.InvariantCulture));
}
if (length < data.Length)
{
- hex.Append(new string(' ', (data.Length - length) * 3));
+ _ = hex.Append(new string(' ', (data.Length - length) * 3));
}
return hex.ToString();
@@ -79,30 +85,26 @@ private static string AsHex(byte[] data, int length)
private static string AsAscii(byte[] data, int length)
{
-#if FEATURE_ENCODING_ASCII
- var encoding = Encoding.ASCII;
-#else
- var encoding = new ASCIIEncoding();
-#endif
+ var encoding = Encoding.ASCII;
- var ascii = new StringBuilder();
+ var ascii = new StringBuilder();
const char dot = '.';
for (var i = 0; i < length; i++)
{
var b = data[i];
- if (b < 32 || b >= 127)
+ if (b is < 32 or >= 127)
{
- ascii.Append(dot);
+ _ = ascii.Append(dot);
}
else
{
- ascii.Append(encoding.GetString(data, i, 1));
+ _ = ascii.Append(encoding.GetString(data, i, 1));
}
}
return ascii.ToString();
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Common/PipeStream.cs b/src/Renci.SshNet/Common/PipeStream.cs
index fac54fb62..da7b89cba 100644
--- a/src/Renci.SshNet/Common/PipeStream.cs
+++ b/src/Renci.SshNet/Common/PipeStream.cs
@@ -1,40 +1,36 @@
-namespace Renci.SshNet.Common
-{
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Threading;
- using System.Globalization;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Threading;
+namespace Renci.SshNet.Common
+{
///
- /// PipeStream is a thread-safe read/write data stream for use between two threads in a
+ /// PipeStream is a thread-safe read/write data stream for use between two threads in a
/// single-producer/single-consumer type problem.
///
- /// 2006/10/13 1.0
- /// Update on 2008/10/9 1.1 - uses Monitor instead of Manual Reset events for more elegant synchronicity.
///
- /// Copyright (c) 2006 James Kolpack (james dot kolpack at google mail)
- ///
- /// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
- /// associated documentation files (the "Software"), to deal in the Software without restriction,
- /// including without limitation the rights to use, copy, modify, merge, publish, distribute,
- /// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
- /// furnished to do so, subject to the following conditions:
- ///
- /// The above copyright notice and this permission notice shall be included in all copies or
- /// substantial portions of the Software.
- ///
- /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
- /// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
- /// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- /// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
- /// OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- /// OTHER DEALINGS IN THE SOFTWARE.
+ /// Copyright (c) 2006 James Kolpack (james dot kolpack at google mail)
+ ///
+ /// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+ /// associated documentation files (the "Software"), to deal in the Software without restriction,
+ /// including without limitation the rights to use, copy, modify, merge, publish, distribute,
+ /// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ /// furnished to do so, subject to the following conditions:
+ ///
+ /// The above copyright notice and this permission notice shall be included in all copies or
+ /// substantial portions of the Software.
+ ///
+ /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+ /// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+ /// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ /// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
+ /// OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ /// OTHER DEALINGS IN THE SOFTWARE.
///
public class PipeStream : Stream
{
- #region Private members
-
///
/// Queue of bytes provides the datastructure for transmitting from an
/// input stream to an output stream.
@@ -48,11 +44,6 @@ public class PipeStream : Stream
///
private bool _isFlushed;
- ///
- /// Maximum number of bytes to store in the buffer.
- ///
- private long _maxBufferLength = 200 * 1024 * 1024;
-
///
/// Setting this to true will cause Read() to block if it appears
/// that it will run out of data.
@@ -64,19 +55,11 @@ public class PipeStream : Stream
///
private bool _isDisposed;
- #endregion
-
- #region Public properties
-
///
/// Gets or sets the maximum number of bytes to store in the buffer.
///
/// The length of the max buffer.
- public long MaxBufferLength
- {
- get { return _maxBufferLength; }
- set { _maxBufferLength = value; }
- }
+ public long MaxBufferLength { get; set; } = 200 * 1024 * 1024;
///
/// Gets or sets a value indicating whether to block last read method before the buffer is empty.
@@ -87,36 +70,48 @@ public long MaxBufferLength
/// Setting to true will remove the possibility of ending a stream reader prematurely.
///
///
- /// true if block last read method before the buffer is empty; otherwise, false.
+ /// if block last read method before the buffer is empty; otherwise, .
///
/// Methods were called after the stream was closed.
public bool BlockLastReadBuffer
{
get
{
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_isDisposed, this);
+#else
if (_isDisposed)
+ {
throw CreateObjectDisposedException();
+ }
+#endif // NET7_0_OR_GREATER
return _canBlockLastRead;
}
set
{
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_isDisposed, this);
+#else
if (_isDisposed)
+ {
throw CreateObjectDisposedException();
+ }
+#endif // NET7_0_OR_GREATER
_canBlockLastRead = value;
// when turning off the block last read, signal Read() that it may now read the rest of the buffer.
if (!_canBlockLastRead)
+ {
lock (_buffer)
+ {
Monitor.Pulse(_buffer);
+ }
+ }
}
}
- #endregion
-
- #region Stream overide methods
-
///
/// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
///
@@ -128,8 +123,14 @@ public bool BlockLastReadBuffer
///
public override void Flush()
{
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_isDisposed, this);
+#else
if (_isDisposed)
+ {
throw CreateObjectDisposedException();
+ }
+#endif // NET7_0_OR_GREATER
_isFlushed = true;
lock (_buffer)
@@ -163,37 +164,61 @@ public override void SetLength(long value)
throw new NotSupportedException();
}
- ///
- ///When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
- ///
- ///
- ///The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the stream is closed or end of the stream has been reached.
- ///
- ///The zero-based byte offset in buffer at which to begin storing the data read from the current stream.
- ///The maximum number of bytes to be read from the current stream.
- ///An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.
- ///The sum of offset and count is larger than the buffer length.
- ///Methods were called after the stream was closed.
- ///The stream does not support reading.
- /// is null.
- ///An I/O error occurs.
- ///offset or count is negative.
+ ///
+ /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
+ ///
+ ///
+ /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the stream is closed or end of the stream has been reached.
+ ///
+ /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.
+ /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream.
+ /// The maximum number of bytes to be read from the current stream.
+ /// The sum of offset and count is larger than the buffer length.
+ /// Methods were called after the stream was closed.
+ /// The stream does not support reading.
+ /// is .
+ /// An I/O error occurs.
+ /// offset or count is negative.
public override int Read(byte[] buffer, int offset, int count)
{
if (offset != 0)
+ {
throw new NotSupportedException("Offsets with value of non-zero are not supported");
- if (buffer == null)
- throw new ArgumentNullException("buffer");
+ }
+
+ if (buffer is null)
+ {
+ throw new ArgumentNullException(nameof(buffer));
+ }
+
if (offset + count > buffer.Length)
+ {
throw new ArgumentException("The sum of offset and count is greater than the buffer length.");
+ }
+
if (offset < 0 || count < 0)
- throw new ArgumentOutOfRangeException("offset", "offset or count is negative.");
- if (BlockLastReadBuffer && count >= _maxBufferLength)
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "count({0}) > mMaxBufferLength({1})", count, _maxBufferLength));
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset), "offset or count is negative.");
+ }
+
+ if (BlockLastReadBuffer && count >= MaxBufferLength)
+ {
+ throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "count({0}) > mMaxBufferLength({1})", count, MaxBufferLength));
+ }
+
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_isDisposed, this);
+#else
if (_isDisposed)
+ {
throw CreateObjectDisposedException();
+ }
+#endif // NET7_0_OR_GREATER
+
if (count == 0)
+ {
return 0;
+ }
var readLength = 0;
@@ -201,7 +226,7 @@ public override int Read(byte[] buffer, int offset, int count)
{
while (!_isDisposed && !ReadAvailable(count))
{
- Monitor.Wait(_buffer);
+ _ = Monitor.Wait(_buffer);
}
// return zero when the read is interrupted by a close/dispose of the stream
@@ -223,46 +248,68 @@ public override int Read(byte[] buffer, int offset, int count)
}
///
- /// Returns true if there are
+ /// Returns a value indicating whether data is available.
///
/// The count.
- /// True if data available; otherwisefalse.
+ ///
+ /// if data is available; otherwise, .
+ ///
private bool ReadAvailable(int count)
{
var length = Length;
return (_isFlushed || length >= count) && (length >= (count + 1) || !BlockLastReadBuffer);
}
- ///
- ///When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
- ///
- ///The zero-based byte offset in buffer at which to begin copying bytes to the current stream.
- ///The number of bytes to be written to the current stream.
- ///An array of bytes. This method copies count bytes from buffer to the current stream.
- ///An I/O error occurs.
- ///The stream does not support writing.
- ///Methods were called after the stream was closed.
- /// is null.
- ///The sum of offset and count is greater than the buffer length.
- ///offset or count is negative.
+ ///
+ /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
+ ///
+ /// An array of bytes. This method copies count bytes from buffer to the current stream.
+ /// The zero-based byte offset in buffer at which to begin copying bytes to the current stream.
+ /// The number of bytes to be written to the current stream.
+ /// An I/O error occurs.
+ /// The stream does not support writing.
+ /// Methods were called after the stream was closed.
+ /// is .
+ /// The sum of offset and count is greater than the buffer length.
+ /// offset or count is negative.
public override void Write(byte[] buffer, int offset, int count)
{
- if (buffer == null)
- throw new ArgumentNullException("buffer");
+ if (buffer is null)
+ {
+ throw new ArgumentNullException(nameof(buffer));
+ }
+
if (offset + count > buffer.Length)
+ {
throw new ArgumentException("The sum of offset and count is greater than the buffer length.");
+ }
+
if (offset < 0 || count < 0)
- throw new ArgumentOutOfRangeException("offset", "offset or count is negative.");
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset), "offset or count is negative.");
+ }
+
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_isDisposed, this);
+#else
if (_isDisposed)
+ {
throw CreateObjectDisposedException();
+ }
+#endif // NET7_0_OR_GREATER
+
if (count == 0)
+ {
return;
+ }
lock (_buffer)
{
// wait until the buffer isn't full
- while (Length >= _maxBufferLength)
- Monitor.Wait(_buffer);
+ while (Length >= MaxBufferLength)
+ {
+ _ = Monitor.Wait(_buffer);
+ }
_isFlushed = false; // if it were flushed before, it soon will not be.
@@ -279,7 +326,7 @@ public override void Write(byte[] buffer, int offset, int count)
///
/// Releases the unmanaged resources used by the Stream and optionally releases the managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
///
/// Disposing a will interrupt blocking read and write operations.
///
@@ -297,33 +344,33 @@ protected override void Dispose(bool disposing)
}
}
- ///
- ///When overridden in a derived class, gets a value indicating whether the current stream supports reading.
- ///
- ///
- ///true if the stream supports reading; otherwise, false.
- ///
+ ///
+ /// Gets a value indicating whether the current stream supports reading.
+ ///
+ ///
+ /// true if the stream supports reading; otherwise, false.
+ ///
public override bool CanRead
{
get { return !_isDisposed; }
}
///
- /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
+ /// Gets a value indicating whether the current stream supports seeking.
///
///
- /// true if the stream supports seeking; otherwise, false.
- ///
+ /// if the stream supports seeking; otherwise, .
+ ///
public override bool CanSeek
{
get { return false; }
}
///
- /// When overridden in a derived class, gets a value indicating whether the current stream supports writing.
+ /// Gets a value indicating whether the current stream supports writing.
///
///
- /// true if the stream supports writing; otherwise, false.
+ /// if the stream supports writing; otherwise, .
///
public override bool CanWrite
{
@@ -331,7 +378,7 @@ public override bool CanWrite
}
///
- /// When overridden in a derived class, gets the length in bytes of the stream.
+ /// Gets the length in bytes of the stream.
///
///
/// A long value representing the length of the stream in bytes.
@@ -342,15 +389,21 @@ public override long Length
{
get
{
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_isDisposed, this);
+#else
if (_isDisposed)
+ {
throw CreateObjectDisposedException();
+ }
+#endif // NET7_0_OR_GREATER
return _buffer.Count;
}
}
///
- /// When overridden in a derived class, gets or sets the position within the current stream.
+ /// Gets or sets the position within the current stream.
///
///
/// The current position within the stream.
@@ -362,11 +415,11 @@ public override long Position
set { throw new NotSupportedException(); }
}
- #endregion
-
+#if !NET7_0_OR_GREATER
private ObjectDisposedException CreateObjectDisposedException()
{
return new ObjectDisposedException(GetType().FullName);
}
+#endif // !NET7_0_OR_GREATER
}
}
diff --git a/src/Renci.SshNet/Common/PortForwardEventArgs.cs b/src/Renci.SshNet/Common/PortForwardEventArgs.cs
index 96a7f8255..41a3e9fb4 100644
--- a/src/Renci.SshNet/Common/PortForwardEventArgs.cs
+++ b/src/Renci.SshNet/Common/PortForwardEventArgs.cs
@@ -1,37 +1,41 @@
using System;
+using System.Net;
namespace Renci.SshNet.Common
{
///
- /// Provides data for event.
+ /// Provides data for event.
///
public class PortForwardEventArgs : EventArgs
{
- ///
- /// Gets request originator host.
- ///
- public string OriginatorHost { get; private set; }
-
- ///
- /// Gets request originator port.
- ///
- public uint OriginatorPort { get; private set; }
-
///
/// Initializes a new instance of the class.
///
/// The host.
/// The port.
- /// is null.
- /// is not within and .
+ /// is .
+ /// is not within and .
internal PortForwardEventArgs(string host, uint port)
{
- if (host == null)
- throw new ArgumentNullException("host");
+ if (host is null)
+ {
+ throw new ArgumentNullException(nameof(host));
+ }
+
port.ValidatePort("port");
OriginatorHost = host;
OriginatorPort = port;
}
+
+ ///
+ /// Gets request originator host.
+ ///
+ public string OriginatorHost { get; }
+
+ ///
+ /// Gets request originator port.
+ ///
+ public uint OriginatorPort { get; }
}
}
diff --git a/src/Renci.SshNet/Common/PosixPath.cs b/src/Renci.SshNet/Common/PosixPath.cs
index 465916b3a..67b83a564 100644
--- a/src/Renci.SshNet/Common/PosixPath.cs
+++ b/src/Renci.SshNet/Common/PosixPath.cs
@@ -2,16 +2,45 @@
namespace Renci.SshNet.Common
{
- internal class PosixPath
+ ///
+ /// Represents a POSIX path.
+ ///
+ internal sealed class PosixPath
{
+ private PosixPath()
+ {
+ }
+
+ ///
+ /// Gets the directory of the path.
+ ///
+ ///
+ /// The directory of the path.
+ ///
public string Directory { get; private set; }
+
+ ///
+ /// Gets the file part of the path.
+ ///
+ ///
+ /// The file part of the path, or if the path represents a directory.
+ ///
public string File { get; private set; }
+ ///
+ /// Create a from the specified path.
+ ///
+ /// The path.
+ ///
+ /// A created from the specified path.
+ ///
+ /// is .
+ /// is empty ("").
public static PosixPath CreateAbsoluteOrRelativeFilePath(string path)
{
- if (path == null)
+ if (path is null)
{
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
}
var posixPath = new PosixPath();
@@ -21,7 +50,7 @@ public static PosixPath CreateAbsoluteOrRelativeFilePath(string path)
{
if (path.Length == 0)
{
- throw new ArgumentException("The path is a zero-length string.", "path");
+ throw new ArgumentException("The path is a zero-length string.", nameof(path));
}
posixPath.Directory = ".";
@@ -54,7 +83,7 @@ public static PosixPath CreateAbsoluteOrRelativeFilePath(string path)
///
/// The file name part of .
///
- /// is null.
+ /// is .
///
///
/// If contains no forward slash, then
@@ -66,14 +95,22 @@ public static PosixPath CreateAbsoluteOrRelativeFilePath(string path)
///
public static string GetFileName(string path)
{
- if (path == null)
- throw new ArgumentNullException("path");
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
var pathEnd = path.LastIndexOf('/');
if (pathEnd == -1)
+ {
return path;
+ }
+
if (pathEnd == path.Length - 1)
+ {
return string.Empty;
+ }
+
return path.Substring(pathEnd + 1);
}
@@ -85,19 +122,30 @@ public static string GetFileName(string path)
/// The directory part of the specified , or . if
/// does not contain any directory information.
///
- /// is null.
+ /// is .
public static string GetDirectoryName(string path)
{
- if (path == null)
- throw new ArgumentNullException("path");
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
var pathEnd = path.LastIndexOf('/');
if (pathEnd == -1)
+ {
return ".";
+ }
+
if (pathEnd == 0)
+ {
return "/";
+ }
+
if (pathEnd == path.Length - 1)
+ {
return path.Substring(0, pathEnd);
+ }
+
return path.Substring(0, pathEnd);
}
}
diff --git a/src/Renci.SshNet/Common/ProxyException.cs b/src/Renci.SshNet/Common/ProxyException.cs
index efb387b45..457cec53b 100644
--- a/src/Renci.SshNet/Common/ProxyException.cs
+++ b/src/Renci.SshNet/Common/ProxyException.cs
@@ -14,14 +14,14 @@ namespace Renci.SshNet.Common
public class ProxyException : SshException
{
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
public ProxyException()
{
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The message.
public ProxyException(string message)
@@ -30,12 +30,12 @@ public ProxyException(string message)
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The message.
/// The inner exception.
- public ProxyException(string message, Exception innerException) :
- base(message, innerException)
+ public ProxyException(string message, Exception innerException)
+ : base(message, innerException)
{
}
@@ -45,8 +45,8 @@ public ProxyException(string message, Exception innerException) :
///
/// The that holds the serialized object data about the exception being thrown.
/// The that contains contextual information about the source or destination.
- /// The parameter is null.
- /// The class name is null or is zero (0).
+ /// The parameter is .
+ /// The class name is or is zero (0).
protected ProxyException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
diff --git a/src/Renci.SshNet/Common/ScpDownloadEventArgs.cs b/src/Renci.SshNet/Common/ScpDownloadEventArgs.cs
index 95ddcd638..59c6312af 100644
--- a/src/Renci.SshNet/Common/ScpDownloadEventArgs.cs
+++ b/src/Renci.SshNet/Common/ScpDownloadEventArgs.cs
@@ -7,21 +7,6 @@ namespace Renci.SshNet.Common
///
public class ScpDownloadEventArgs : EventArgs
{
- ///
- /// Gets the downloaded filename.
- ///
- public string Filename { get; private set; }
-
- ///
- /// Gets the downloaded file size.
- ///
- public long Size { get; private set; }
-
- ///
- /// Gets number of downloaded bytes so far.
- ///
- public long Downloaded { get; private set; }
-
///
/// Initializes a new instance of the class.
///
@@ -34,5 +19,20 @@ public ScpDownloadEventArgs(string filename, long size, long downloaded)
Size = size;
Downloaded = downloaded;
}
+
+ ///
+ /// Gets the downloaded filename.
+ ///
+ public string Filename { get; }
+
+ ///
+ /// Gets the downloaded file size.
+ ///
+ public long Size { get; }
+
+ ///
+ /// Gets number of downloaded bytes so far.
+ ///
+ public long Downloaded { get; }
}
}
diff --git a/src/Renci.SshNet/Common/ScpException.cs b/src/Renci.SshNet/Common/ScpException.cs
index e98bc688d..26a7bdd85 100644
--- a/src/Renci.SshNet/Common/ScpException.cs
+++ b/src/Renci.SshNet/Common/ScpException.cs
@@ -34,8 +34,8 @@ public ScpException(string message)
///
/// The message.
/// The inner exception.
- public ScpException(string message, Exception innerException) :
- base(message, innerException)
+ public ScpException(string message, Exception innerException)
+ : base(message, innerException)
{
}
@@ -45,8 +45,8 @@ public ScpException(string message, Exception innerException) :
///
/// The that holds the serialized object data about the exception being thrown.
/// The that contains contextual information about the source or destination.
- /// The parameter is null.
- /// The class name is null or is zero (0).
+ /// The parameter is .
+ /// The class name is or is zero (0).
protected ScpException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
diff --git a/src/Renci.SshNet/Common/ScpUploadEventArgs.cs b/src/Renci.SshNet/Common/ScpUploadEventArgs.cs
index 555bdc07c..ca8514e9b 100644
--- a/src/Renci.SshNet/Common/ScpUploadEventArgs.cs
+++ b/src/Renci.SshNet/Common/ScpUploadEventArgs.cs
@@ -7,21 +7,6 @@ namespace Renci.SshNet.Common
///
public class ScpUploadEventArgs : EventArgs
{
- ///
- /// Gets the uploaded filename.
- ///
- public string Filename { get; private set; }
-
- ///
- /// Gets the uploaded file size.
- ///
- public long Size { get; private set; }
-
- ///
- /// Gets number of uploaded bytes so far.
- ///
- public long Uploaded { get; private set; }
-
///
/// Initializes a new instance of the class.
///
@@ -34,5 +19,20 @@ public ScpUploadEventArgs(string filename, long size, long uploaded)
Size = size;
Uploaded = uploaded;
}
+
+ ///
+ /// Gets the uploaded filename.
+ ///
+ public string Filename { get; }
+
+ ///
+ /// Gets the uploaded file size.
+ ///
+ public long Size { get; }
+
+ ///
+ /// Gets number of uploaded bytes so far.
+ ///
+ public long Uploaded { get; }
}
}
diff --git a/src/Renci.SshNet/Common/SemaphoreLight.cs b/src/Renci.SshNet/Common/SemaphoreLight.cs
deleted file mode 100644
index 55e4a840a..000000000
--- a/src/Renci.SshNet/Common/SemaphoreLight.cs
+++ /dev/null
@@ -1,240 +0,0 @@
-using System;
-using System.Threading;
-
-namespace Renci.SshNet.Common
-{
- ///
- /// Light implementation of SemaphoreSlim.
- ///
- public class SemaphoreLight : IDisposable
- {
- private readonly object _lock = new object();
- private ManualResetEvent _waitHandle;
-
- private int _currentCount;
-
- ///
- /// Initializes a new instance of the class, specifying
- /// the initial number of requests that can be granted concurrently.
- ///
- /// The initial number of requests for the semaphore that can be granted concurrently.
- /// is a negative number.
- public SemaphoreLight(int initialCount)
- {
- if (initialCount < 0 )
- throw new ArgumentOutOfRangeException("initialCount", "The value cannot be negative.");
-
- _currentCount = initialCount;
- }
-
- ///
- /// Gets the current count of the .
- ///
- public int CurrentCount { get { return _currentCount; } }
-
- ///
- /// Returns a that can be used to wait on the semaphore.
- ///
- ///
- /// A that can be used to wait on the semaphore.
- ///
- ///
- /// A successful wait on the does not imply a successful
- /// wait on the itself. It should be followed by a true wait
- /// on the semaphore.
- ///
- public WaitHandle AvailableWaitHandle
- {
- get
- {
- if (_waitHandle == null)
- {
- lock (_lock)
- {
- if (_waitHandle == null)
- {
- _waitHandle = new ManualResetEvent(_currentCount > 0);
- }
- }
- }
-
- return _waitHandle;
- }
- }
-
- ///
- /// Exits the once.
- ///
- /// The previous count of the .
- public int Release()
- {
- return Release(1);
- }
-
- ///
- /// Exits the a specified number of times.
- ///
- /// The number of times to exit the semaphore.
- ///
- /// The previous count of the .
- ///
- public int Release(int releaseCount)
- {
- lock (_lock)
- {
- var oldCount = _currentCount;
-
- _currentCount += releaseCount;
-
- // signal waithandle when the original semaphore count was zero
- if (_waitHandle != null && oldCount == 0)
- {
- _waitHandle.Set();
- }
-
- Monitor.PulseAll(_lock);
-
- return oldCount;
- }
- }
-
- ///
- /// Blocks the current thread until it can enter the .
- ///
- public void Wait()
- {
- lock (_lock)
- {
- while (_currentCount < 1)
- {
- Monitor.Wait(_lock);
- }
-
- _currentCount--;
-
- // unsignal waithandle when the semaphore count reaches zero
- if (_waitHandle != null && _currentCount == 0)
- {
- _waitHandle.Reset();
- }
-
- Monitor.PulseAll(_lock);
- }
- }
-
- ///
- /// Blocks the current thread until it can enter the , using a 32-bit signed
- /// integer that specifies the timeout.
- ///
- /// The number of milliseconds to wait, or Infinite(-1) to wait indefinitely.
- ///
- /// true if the current thread successfully entered the ; otherwise, false.
- ///
- public bool Wait(int millisecondsTimeout)
- {
- if (millisecondsTimeout < -1)
- throw new ArgumentOutOfRangeException("millisecondsTimeout", "The timeout must represent a value between -1 and Int32.MaxValue, inclusive.");
-
- return WaitWithTimeout(millisecondsTimeout);
- }
-
- ///
- /// Blocks the current thread until it can enter the , using a
- /// to specify the timeout.
- ///
- /// A that represents the number of milliseconds to wait, or a that represents -1 milliseconds to wait indefinitely.
- ///
- /// true if the current thread successfully entered the ; otherwise, false.
- ///
- public bool Wait(TimeSpan timeout)
- {
- var timeoutInMilliseconds = timeout.TotalMilliseconds;
- if (timeoutInMilliseconds < -1d || timeoutInMilliseconds > int.MaxValue)
- throw new ArgumentOutOfRangeException("timeout", "The timeout must represent a value between -1 and Int32.MaxValue, inclusive.");
-
- return WaitWithTimeout((int) timeoutInMilliseconds);
- }
-
- private bool WaitWithTimeout(int timeoutInMilliseconds)
- {
- lock (_lock)
- {
- if (timeoutInMilliseconds == Session.Infinite)
- {
- while (_currentCount < 1)
- Monitor.Wait(_lock);
- }
- else
- {
- if (_currentCount < 1)
- {
- if (timeoutInMilliseconds > 0)
- return false;
-
- var remainingTimeInMilliseconds = timeoutInMilliseconds;
- var startTicks = Environment.TickCount;
-
- while (_currentCount < 1)
- {
- if (!Monitor.Wait(_lock, remainingTimeInMilliseconds))
- {
- return false;
- }
-
- var elapsed = Environment.TickCount - startTicks;
- remainingTimeInMilliseconds -= elapsed;
- if (remainingTimeInMilliseconds < 0)
- return false;
- }
- }
- }
-
- _currentCount--;
-
- // unsignal waithandle when the semaphore count is zero
- if (_waitHandle != null && _currentCount == 0)
- {
- _waitHandle.Reset();
- }
-
- Monitor.PulseAll(_lock);
-
- return true;
- }
- }
-
- ///
- /// Finalizes the current .
- ///
- ~SemaphoreLight()
- {
- Dispose(false);
- }
-
- ///
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- ///
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- ///
- /// Releases unmanaged and - optionally - managed resources
- ///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
- protected void Dispose(bool disposing)
- {
- if (disposing)
- {
- var waitHandle = _waitHandle;
- if (waitHandle != null)
- {
- waitHandle.Dispose();
- _waitHandle = null;
- }
- }
- }
- }
-}
diff --git a/src/Renci.SshNet/Common/SftpPathNotFoundException.cs b/src/Renci.SshNet/Common/SftpPathNotFoundException.cs
index 681a4fe5f..61af3b2fe 100644
--- a/src/Renci.SshNet/Common/SftpPathNotFoundException.cs
+++ b/src/Renci.SshNet/Common/SftpPathNotFoundException.cs
@@ -34,8 +34,8 @@ public SftpPathNotFoundException(string message)
///
/// The message.
/// The inner exception.
- public SftpPathNotFoundException(string message, Exception innerException) :
- base(message, innerException)
+ public SftpPathNotFoundException(string message, Exception innerException)
+ : base(message, innerException)
{
}
@@ -45,8 +45,8 @@ public SftpPathNotFoundException(string message, Exception innerException) :
///
/// The that holds the serialized object data about the exception being thrown.
/// The that contains contextual information about the source or destination.
- /// The parameter is null.
- /// The class name is null or is zero (0).
+ /// The parameter is .
+ /// The class name is or is zero (0).
protected SftpPathNotFoundException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
diff --git a/src/Renci.SshNet/Common/SftpPermissionDeniedException.cs b/src/Renci.SshNet/Common/SftpPermissionDeniedException.cs
index 559c98cf3..b040417ff 100644
--- a/src/Renci.SshNet/Common/SftpPermissionDeniedException.cs
+++ b/src/Renci.SshNet/Common/SftpPermissionDeniedException.cs
@@ -34,8 +34,8 @@ public SftpPermissionDeniedException(string message)
///
/// The message.
/// The inner exception.
- public SftpPermissionDeniedException(string message, Exception innerException) :
- base(message, innerException)
+ public SftpPermissionDeniedException(string message, Exception innerException)
+ : base(message, innerException)
{
}
@@ -45,8 +45,8 @@ public SftpPermissionDeniedException(string message, Exception innerException) :
///
/// The that holds the serialized object data about the exception being thrown.
/// The that contains contextual information about the source or destination.
- /// The parameter is null.
- /// The class name is null or is zero (0).
+ /// The parameter is .
+ /// The class name is or is zero (0).
protected SftpPermissionDeniedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
diff --git a/src/Renci.SshNet/Common/ShellDataEventArgs.cs b/src/Renci.SshNet/Common/ShellDataEventArgs.cs
index 34fea8b46..e99913d22 100644
--- a/src/Renci.SshNet/Common/ShellDataEventArgs.cs
+++ b/src/Renci.SshNet/Common/ShellDataEventArgs.cs
@@ -3,20 +3,10 @@
namespace Renci.SshNet.Common
{
///
- /// Provides data for Shell DataReceived event
+ /// Provides data for Shell DataReceived event.
///
public class ShellDataEventArgs : EventArgs
{
- ///
- /// Gets the data.
- ///
- public byte[] Data { get; private set; }
-
- ///
- /// Gets the line data.
- ///
- public string Line { get; private set; }
-
///
/// Initializes a new instance of the class.
///
@@ -34,5 +24,15 @@ public ShellDataEventArgs(string line)
{
Line = line;
}
+
+ ///
+ /// Gets the data.
+ ///
+ public byte[] Data { get; }
+
+ ///
+ /// Gets the line data.
+ ///
+ public string Line { get; }
}
}
diff --git a/src/Renci.SshNet/Common/SshAuthenticationException.cs b/src/Renci.SshNet/Common/SshAuthenticationException.cs
index 4c6f72546..e2909bddb 100644
--- a/src/Renci.SshNet/Common/SshAuthenticationException.cs
+++ b/src/Renci.SshNet/Common/SshAuthenticationException.cs
@@ -18,7 +18,6 @@ public class SshAuthenticationException : SshException
///
public SshAuthenticationException()
{
-
}
///
@@ -28,7 +27,6 @@ public SshAuthenticationException()
public SshAuthenticationException(string message)
: base(message)
{
-
}
///
@@ -36,8 +34,8 @@ public SshAuthenticationException(string message)
///
/// The message.
/// The inner exception.
- public SshAuthenticationException(string message, Exception innerException) :
- base(message, innerException)
+ public SshAuthenticationException(string message, Exception innerException)
+ : base(message, innerException)
{
}
@@ -47,8 +45,8 @@ public SshAuthenticationException(string message, Exception innerException) :
///
/// The that holds the serialized object data about the exception being thrown.
/// The that contains contextual information about the source or destination.
- /// The parameter is null.
- /// The class name is null or is zero (0).
+ /// The parameter is .
+ /// The class name is or is zero (0).
protected SshAuthenticationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
diff --git a/src/Renci.SshNet/Common/SshConnectionException.cs b/src/Renci.SshNet/Common/SshConnectionException.cs
index 75997600e..a5c227b8e 100644
--- a/src/Renci.SshNet/Common/SshConnectionException.cs
+++ b/src/Renci.SshNet/Common/SshConnectionException.cs
@@ -47,6 +47,17 @@ public SshConnectionException(string message, DisconnectReason disconnectReasonC
DisconnectReason = disconnectReasonCode;
}
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The message.
+ /// The inner.
+ public SshConnectionException(string message, Exception inner)
+ : base(message, inner)
+ {
+ DisconnectReason = DisconnectReason.None;
+ }
+
///
/// Initializes a new instance of the class.
///
@@ -65,8 +76,8 @@ public SshConnectionException(string message, DisconnectReason disconnectReasonC
///
/// The that holds the serialized object data about the exception being thrown.
/// The that contains contextual information about the source or destination.
- /// The parameter is null.
- /// The class name is null or is zero (0).
+ /// The parameter is .
+ /// The class name is or is zero (0).
protected SshConnectionException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
diff --git a/src/Renci.SshNet/Common/SshData.cs b/src/Renci.SshNet/Common/SshData.cs
index 8e4eca406..578edb8c5 100644
--- a/src/Renci.SshNet/Common/SshData.cs
+++ b/src/Renci.SshNet/Common/SshData.cs
@@ -5,17 +5,16 @@
namespace Renci.SshNet.Common
{
///
- /// Base ssh data serialization type
+ /// Base ssh data serialization type.
///
+#pragma warning disable CA1001 // Types that own disposable fields should be disposable
public abstract class SshData
+#pragma warning restore CA1001 // Types that own disposable fields should be disposable
{
internal const int DefaultCapacity = 64;
-#if FEATURE_ENCODING_ASCII
internal static readonly Encoding Ascii = Encoding.ASCII;
-#else
- internal static readonly Encoding Ascii = new ASCIIEncoding();
-#endif
+
internal static readonly Encoding Utf8 = Encoding.UTF8;
private SshDataStream _stream;
@@ -35,7 +34,7 @@ protected SshDataStream DataStream
/// Gets a value indicating whether all data from the buffer has been read.
///
///
- /// true if this instance is end of data; otherwise, false.
+ /// if this instance is end of data; otherwise, .
///
protected bool IsEndOfData
{
@@ -60,15 +59,18 @@ protected virtual int BufferCapacity
/// Gets data bytes array.
///
///
- /// A array representation of data structure.
+ /// A array representation of data structure.
///
public byte[] GetBytes()
{
var messageLength = BufferCapacity;
var capacity = messageLength != -1 ? messageLength : DefaultCapacity;
- var dataStream = new SshDataStream(capacity);
- WriteBytes(dataStream);
- return dataStream.ToArray();
+
+ using (var dataStream = new SshDataStream(capacity))
+ {
+ WriteBytes(dataStream);
+ return dataStream.ToArray();
+ }
}
///
@@ -85,11 +87,13 @@ protected virtual void WriteBytes(SshDataStream stream)
/// Loads data from specified bytes.
///
/// Bytes array.
- /// is null.
+ /// is .
public void Load(byte[] data)
{
- if (data == null)
- throw new ArgumentNullException("data");
+ if (data is null)
+ {
+ throw new ArgumentNullException(nameof(data));
+ }
LoadInternal(data, 0, data.Length);
}
@@ -100,11 +104,13 @@ public void Load(byte[] data)
/// Bytes array.
/// The zero-based offset in at which to begin reading SSH data.
/// The number of bytes to load.
- /// is null.
+ /// is .
public void Load(byte[] data, int offset, int count)
{
- if (data == null)
- throw new ArgumentNullException("data");
+ if (data is null)
+ {
+ throw new ArgumentNullException(nameof(data));
+ }
LoadInternal(data, offset, count);
}
@@ -128,12 +134,14 @@ private void LoadInternal(byte[] value, int offset, int count)
///
/// Reads all data left in internal buffer at current position.
///
- /// An array of bytes containing the remaining data in the internal buffer.
+ ///
+ /// An array of bytes containing the remaining data in the internal buffer.
+ ///
protected byte[] ReadBytes()
{
var bytesLength = (int) (_stream.Length - _stream.Position);
var data = new byte[bytesLength];
- _stream.Read(data, 0, bytesLength);
+ _ = _stream.Read(data, 0, bytesLength);
return data;
}
@@ -141,78 +149,89 @@ protected byte[] ReadBytes()
/// Reads next specified number of bytes data type from internal buffer.
///
/// Number of bytes to read.
- /// An array of bytes that was read from the internal buffer.
- /// is greater than the internal buffer size.
+ ///
+ /// An array of bytes that was read from the internal buffer.
+ ///
+ /// is greater than the number of bytes available to be read.
protected byte[] ReadBytes(int length)
{
- // Note that this also prevents allocating non-relevant lengths, such as if length is greater than _data.Count but less than int.MaxValue.
- // For the nerds, the condition translates to: if (length > data.Count && length < int.MaxValue)
- // Which probably would cause all sorts of exception, most notably OutOfMemoryException.
-
- var data = new byte[length];
- var bytesRead = _stream.Read(data, 0, length);
-
- if (bytesRead < length)
- throw new ArgumentOutOfRangeException("length");
-
- return data;
+ return _stream.ReadBytes(length);
}
///
/// Reads next byte data type from internal buffer.
///
- /// Byte read.
+ ///
+ /// The read.
+ ///
+ /// Attempt to read past the end of the stream.
protected byte ReadByte()
{
var byteRead = _stream.ReadByte();
if (byteRead == -1)
+ {
throw new InvalidOperationException("Attempt to read past the end of the SSH data stream.");
+ }
+
return (byte) byteRead;
}
///
- /// Reads next boolean data type from internal buffer.
+ /// Reads the next from the internal buffer.
///
- /// Boolean read.
+ ///
+ /// The that was read.
+ ///
+ /// Attempt to read past the end of the stream.
protected bool ReadBoolean()
{
return ReadByte() != 0;
}
///
- /// Reads next uint16 data type from internal buffer.
+ /// Reads the next from the internal buffer.
///
- /// uint16 read
+ ///
+ /// The that was read.
+ ///
+ /// Attempt to read past the end of the stream.
protected ushort ReadUInt16()
{
- return Pack.BigEndianToUInt16(ReadBytes(2));
+ return _stream.ReadUInt16();
}
///
- /// Reads next uint32 data type from internal buffer.
+ /// Reads the next from the internal buffer.
///
- /// uint32 read
+ ///
+ /// The that was read.
+ ///
+ /// Attempt to read past the end of the stream.
protected uint ReadUInt32()
{
- return Pack.BigEndianToUInt32(ReadBytes(4));
+ return _stream.ReadUInt32();
}
///
- /// Reads next uint64 data type from internal buffer.
+ /// Reads the next from the internal buffer.
///
- /// uint64 read
+ ///
+ /// The that was read.
+ ///
+ /// Attempt to read past the end of the stream.
protected ulong ReadUInt64()
{
- return Pack.BigEndianToUInt64(ReadBytes(8));
+ return _stream.ReadUInt64();
}
///
- /// Reads next string data type from internal buffer using the specific encoding.
+ /// Reads the next from the internal buffer using the specified encoding.
///
+ /// The character encoding to use.
///
- /// The read.
+ /// The that was read.
///
- protected string ReadString(Encoding encoding)
+ protected string ReadString(Encoding encoding = null)
{
return _stream.ReadString(encoding);
}
@@ -243,16 +262,20 @@ protected string[] ReadNamesList()
///
/// Reads next extension-pair data type from internal buffer.
///
- /// Extensions pair dictionary.
- protected IDictionary ReadExtensionPair()
+ ///
+ /// Extensions pair dictionary.
+ ///
+ protected Dictionary ReadExtensionPair()
{
var result = new Dictionary();
+
while (!IsEndOfData)
{
var extensionName = ReadString(Ascii);
var extensionData = ReadString(Ascii);
result.Add(extensionName, extensionData);
}
+
return result;
}
@@ -260,7 +283,7 @@ protected IDictionary ReadExtensionPair()
/// Writes bytes array data into internal buffer.
///
/// Byte array data to write.
- /// is null.
+ /// is .
protected void Write(byte[] data)
{
_stream.Write(data);
@@ -273,7 +296,7 @@ protected void Write(byte[] data)
/// An array of bytes. This method write bytes from buffer to the current SSH data stream.
/// The zero-based offset in at which to begin writing bytes to the SSH data stream.
/// The number of bytes to be written to the current SSH data stream.
- /// is null.
+ /// is .
/// The sum of and is greater than the buffer length.
/// or is negative.
protected void Write(byte[] buffer, int offset, int count)
@@ -321,7 +344,7 @@ protected void Write(ulong data)
/// Writes data into internal buffer using default encoding.
///
/// data to write.
- /// is null.
+ /// is .
protected void Write(string data)
{
Write(data, Utf8);
@@ -332,37 +355,13 @@ protected void Write(string data)
///
/// data to write.
/// The character encoding to use.
- /// is null.
- /// is null.
+ /// is .
+ /// is .
protected void Write(string data, Encoding encoding)
{
_stream.Write(data, encoding);
}
- ///
- /// Writes data into internal buffer.
- ///
- /// The data to write.
- /// is null.
- protected void WriteBinaryString(byte[] buffer)
- {
- _stream.WriteBinary(buffer);
- }
-
- ///
- /// Writes data into internal buffer.
- ///
- /// An array of bytes. This method write bytes from buffer to the current SSH data stream.
- /// The zero-based byte offset in at which to begin writing bytes to the SSH data stream.
- /// The number of bytes to be written to the current SSH data stream.
- /// is null.
- /// The sum of and is greater than the buffer length.
- /// or is negative.
- protected void WriteBinary(byte[] buffer, int offset, int count)
- {
- _stream.WriteBinary(buffer, offset, count);
- }
-
///
/// Writes mpint data into internal buffer.
///
@@ -378,7 +377,11 @@ protected void Write(BigInteger data)
/// name-list data to write.
protected void Write(string[] data)
{
+#if NET || NETSTANDARD2_1_OR_GREATER
+ Write(string.Join(',', data), Ascii);
+#else
Write(string.Join(",", data), Ascii);
+#endif // NET || NETSTANDARD2_1_OR_GREATER
}
///
@@ -393,5 +396,29 @@ protected void Write(IDictionary data)
Write(item.Value, Ascii);
}
}
+
+ ///
+ /// Writes data into internal buffer.
+ ///
+ /// The data to write.
+ /// is .
+ protected void WriteBinaryString(byte[] buffer)
+ {
+ _stream.WriteBinary(buffer);
+ }
+
+ ///
+ /// Writes data into internal buffer.
+ ///
+ /// An array of bytes. This method write bytes from buffer to the current SSH data stream.
+ /// The zero-based byte offset in at which to begin writing bytes to the SSH data stream.
+ /// The number of bytes to be written to the current SSH data stream.
+ /// is .
+ /// The sum of and is greater than the buffer length.
+ /// or is negative.
+ protected void WriteBinary(byte[] buffer, int offset, int count)
+ {
+ _stream.WriteBinary(buffer, offset, count);
+ }
}
}
diff --git a/src/Renci.SshNet/Common/SshDataStream.cs b/src/Renci.SshNet/Common/SshDataStream.cs
index 010800c3e..9e2a28051 100644
--- a/src/Renci.SshNet/Common/SshDataStream.cs
+++ b/src/Renci.SshNet/Common/SshDataStream.cs
@@ -21,22 +21,22 @@ public SshDataStream(int capacity)
}
///
- /// Initializes a new non-resizable instance of the class based on the specified byte array.
+ /// Initializes a new instance of the class for the specified byte array.
///
/// The array of unsigned bytes from which to create the current stream.
- /// is null.
+ /// is .
public SshDataStream(byte[] buffer)
: base(buffer)
{
}
///
- /// Initializes a new non-resizable instance of the class based on the specified byte array.
+ /// Initializes a new instance of the class for the specified byte array.
///
/// The array of unsigned bytes from which to create the current stream.
/// The zero-based offset in at which to begin reading SSH data.
/// The number of bytes to load.
- /// is null.
+ /// is .
public SshDataStream(byte[] buffer, int offset, int count)
: base(buffer, offset, count)
{
@@ -46,7 +46,7 @@ public SshDataStream(byte[] buffer, int offset, int count)
/// Gets a value indicating whether all data from the SSH data stream has been read.
///
///
- /// true if this instance is end of data; otherwise, false.
+ /// if this instance is end of data; otherwise, .
///
public bool IsEndOfData
{
@@ -62,8 +62,14 @@ public bool IsEndOfData
/// data to write.
public void Write(uint value)
{
+#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
+ Span bytes = stackalloc byte[4];
+ System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(bytes, value);
+ Write(bytes);
+#else
var bytes = Pack.UInt32ToBigEndian(value);
Write(bytes, 0, bytes.Length);
+#endif
}
///
@@ -72,8 +78,14 @@ public void Write(uint value)
/// data to write.
public void Write(ulong value)
{
+#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
+ Span bytes = stackalloc byte[8];
+ System.Buffers.Binary.BinaryPrimitives.WriteUInt64BigEndian(bytes, value);
+ Write(bytes);
+#else
var bytes = Pack.UInt64ToBigEndian(value);
Write(bytes, 0, bytes.Length);
+#endif
}
///
@@ -90,15 +102,35 @@ public void Write(BigInteger data)
/// Writes bytes array data into the SSH data stream.
///
/// Byte array data to write.
- /// is null.
+ /// is .
public void Write(byte[] data)
{
- if (data == null)
- throw new ArgumentNullException("data");
+ if (data is null)
+ {
+ throw new ArgumentNullException(nameof(data));
+ }
Write(data, 0, data.Length);
}
+ ///
+ /// Writes string data to the SSH data stream using the specified encoding.
+ ///
+ /// The string data to write.
+ /// The character encoding to use.
+ /// is .
+ /// is .
+ public void Write(string s, Encoding encoding)
+ {
+ if (encoding is null)
+ {
+ throw new ArgumentNullException(nameof(encoding));
+ }
+
+ var bytes = encoding.GetBytes(s);
+ WriteBinary(bytes, 0, bytes.Length);
+ }
+
///
/// Reads a byte array from the SSH data stream.
///
@@ -121,11 +153,13 @@ public byte[] ReadBinary()
/// Writes a buffer preceded by its length into the SSH data stream.
///
/// The data to write.
- /// is null.
+ /// is .
public void WriteBinary(byte[] buffer)
{
- if (buffer == null)
- throw new ArgumentNullException("buffer");
+ if (buffer is null)
+ {
+ throw new ArgumentNullException(nameof(buffer));
+ }
WriteBinary(buffer, 0, buffer.Length);
}
@@ -136,7 +170,7 @@ public void WriteBinary(byte[] buffer)
/// An array of bytes. This method write bytes from buffer to the current SSH data stream.
/// The zero-based byte offset in at which to begin writing bytes to the SSH data stream.
/// The number of bytes to be written to the current SSH data stream.
- /// is null.
+ /// is .
/// The sum of and is greater than the buffer length.
/// or is negative.
public void WriteBinary(byte[] buffer, int offset, int count)
@@ -145,22 +179,6 @@ public void WriteBinary(byte[] buffer, int offset, int count)
Write(buffer, offset, count);
}
- ///
- /// Writes string data to the SSH data stream using the specified encoding.
- ///
- /// The string data to write.
- /// The character encoding to use.
- /// is null.
- /// is null.
- public void Write(string s, Encoding encoding)
- {
- if (encoding == null)
- throw new ArgumentNullException("encoding");
-
- var bytes = encoding.GetBytes(s);
- WriteBinary(bytes, 0, bytes.Length);
- }
-
///
/// Reads a from the SSH datastream.
///
@@ -174,6 +192,24 @@ public BigInteger ReadBigInt()
return new BigInteger(data.Reverse());
}
+ ///
+ /// Reads the next data type from the SSH data stream.
+ ///
+ ///
+ /// The read from the SSH data stream.
+ ///
+ public ushort ReadUInt16()
+ {
+#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
+ Span bytes = stackalloc byte[2];
+ ReadBytes(bytes);
+ return System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(bytes);
+#else
+ var data = ReadBytes(2);
+ return Pack.BigEndianToUInt16(data);
+#endif
+ }
+
///
/// Reads the next data type from the SSH data stream.
///
@@ -182,8 +218,14 @@ public BigInteger ReadBigInt()
///
public uint ReadUInt32()
{
+#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
+ Span span = stackalloc byte[4];
+ ReadBytes(span);
+ return System.Buffers.Binary.BinaryPrimitives.ReadUInt32BigEndian(span);
+#else
var data = ReadBytes(4);
return Pack.BigEndianToUInt32(data);
+#endif // NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
}
///
@@ -194,18 +236,27 @@ public uint ReadUInt32()
///
public ulong ReadUInt64()
{
+#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
+ Span span = stackalloc byte[8];
+ ReadBytes(span);
+ return System.Buffers.Binary.BinaryPrimitives.ReadUInt64BigEndian(span);
+#else
var data = ReadBytes(8);
return Pack.BigEndianToUInt64(data);
+#endif // NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
}
///
/// Reads the next data type from the SSH data stream.
///
+ /// The character encoding to use. Defaults to .
///
/// The read from the SSH data stream.
///
- public string ReadString(Encoding encoding)
+ public string ReadString(Encoding encoding = null)
{
+ encoding ??= Encoding.UTF8;
+
var length = ReadUInt32();
if (length > int.MaxValue)
@@ -217,6 +268,26 @@ public string ReadString(Encoding encoding)
return encoding.GetString(bytes, 0, bytes.Length);
}
+ ///
+ /// Writes the stream contents to a byte array, regardless of the .
+ ///
+ ///
+ /// This method returns the contents of the as a byte array.
+ ///
+ ///
+ /// If the current instance was constructed on a provided byte array, a copy of the section of the array
+ /// to which this instance has access is returned.
+ ///
+ public override byte[] ToArray()
+ {
+ if (Capacity == Length)
+ {
+ return GetBuffer();
+ }
+
+ return base.ToArray();
+ }
+
///
/// Reads next specified number of bytes data type from internal buffer.
///
@@ -225,42 +296,32 @@ public string ReadString(Encoding encoding)
/// An array of bytes that was read from the internal buffer.
///
/// is greater than the internal buffer size.
- private byte[] ReadBytes(int length)
+ internal byte[] ReadBytes(int length)
{
var data = new byte[length];
var bytesRead = Read(data, 0, length);
-
if (bytesRead < length)
- throw new ArgumentOutOfRangeException("length",
- string.Format(CultureInfo.InvariantCulture,
- "The requested length ({0}) is greater than the actual number of bytes read ({1}).", length, bytesRead));
+ {
+ throw new ArgumentOutOfRangeException(nameof(length), string.Format(CultureInfo.InvariantCulture, "The requested length ({0}) is greater than the actual number of bytes read ({1}).", length, bytesRead));
+ }
return data;
}
+#if NETSTANDARD2_1 || NET6_0_OR_GREATER
///
- /// Writes the stream contents to a byte array, regardless of the .
+ /// Reads data into the specified .
///
- ///
- /// This method returns the contents of the as a byte array.
- ///
- ///
- /// If the current instance was constructed on a provided byte array, a copy of the section of the array
- /// to which this instance has access is returned.
- ///
- public override byte[] ToArray()
+ /// The buffer to read into.
+ /// is larger than the total of bytes available.
+ private void ReadBytes(Span buffer)
{
- if (Capacity == Length)
+ var bytesRead = Read(buffer);
+ if (bytesRead < buffer.Length)
{
-#if FEATURE_MEMORYSTREAM_GETBUFFER
- return GetBuffer();
-#elif FEATURE_MEMORYSTREAM_TRYGETBUFFER
- ArraySegment buffer;
- if (TryGetBuffer(out buffer))
- return buffer.Array;
-#endif
+ throw new ArgumentOutOfRangeException(nameof(buffer), string.Format(CultureInfo.InvariantCulture, "The requested length ({0}) is greater than the actual number of bytes read ({1}).", buffer.Length, bytesRead));
}
- return base.ToArray();
}
+#endif // NETSTANDARD2_1 || NET6_0_OR_GREATER
}
}
diff --git a/src/Renci.SshNet/Common/SshException.cs b/src/Renci.SshNet/Common/SshException.cs
index ed0d4db42..a2f721ee3 100644
--- a/src/Renci.SshNet/Common/SshException.cs
+++ b/src/Renci.SshNet/Common/SshException.cs
@@ -45,8 +45,8 @@ public SshException(string message, Exception inner)
///
/// The that holds the serialized object data about the exception being thrown.
/// The that contains contextual information about the source or destination.
- /// The parameter is null.
- /// The class name is null or is zero (0).
+ /// The parameter is .
+ /// The class name is or is zero (0).
protected SshException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
diff --git a/src/Renci.SshNet/Common/SshIdentificationEventArgs.cs b/src/Renci.SshNet/Common/SshIdentificationEventArgs.cs
new file mode 100644
index 000000000..f618112bd
--- /dev/null
+++ b/src/Renci.SshNet/Common/SshIdentificationEventArgs.cs
@@ -0,0 +1,26 @@
+using System;
+
+using Renci.SshNet.Connection;
+
+namespace Renci.SshNet.Common
+{
+ ///
+ /// Provides data for the ServerIdentificationReceived events.
+ ///
+ public class SshIdentificationEventArgs : EventArgs
+ {
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The SSH identification.
+ public SshIdentificationEventArgs(SshIdentification sshIdentification)
+ {
+ SshIdentification = sshIdentification;
+ }
+
+ ///
+ /// Gets the SSH identification.
+ ///
+ public SshIdentification SshIdentification { get; private set; }
+ }
+}
diff --git a/src/Renci.SshNet/Common/SshOperationTimeoutException.cs b/src/Renci.SshNet/Common/SshOperationTimeoutException.cs
index 7dff901f6..f81318872 100644
--- a/src/Renci.SshNet/Common/SshOperationTimeoutException.cs
+++ b/src/Renci.SshNet/Common/SshOperationTimeoutException.cs
@@ -34,8 +34,8 @@ public SshOperationTimeoutException(string message)
///
/// The message.
/// The inner exception.
- public SshOperationTimeoutException(string message, Exception innerException) :
- base(message, innerException)
+ public SshOperationTimeoutException(string message, Exception innerException)
+ : base(message, innerException)
{
}
@@ -45,8 +45,8 @@ public SshOperationTimeoutException(string message, Exception innerException) :
///
/// The that holds the serialized object data about the exception being thrown.
/// The that contains contextual information about the source or destination.
- /// The parameter is null.
- /// The class name is null or is zero (0).
+ /// The parameter is .
+ /// The class name is or is zero (0).
protected SshOperationTimeoutException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
diff --git a/src/Renci.SshNet/Common/SshPassPhraseNullOrEmptyException.cs b/src/Renci.SshNet/Common/SshPassPhraseNullOrEmptyException.cs
index 1aa0f0d9d..1ddc19193 100644
--- a/src/Renci.SshNet/Common/SshPassPhraseNullOrEmptyException.cs
+++ b/src/Renci.SshNet/Common/SshPassPhraseNullOrEmptyException.cs
@@ -6,7 +6,7 @@
namespace Renci.SshNet.Common
{
///
- /// The exception that is thrown when pass phrase for key file is empty or null
+ /// The exception that is thrown when pass phrase for key file is empty or .
///
#if FEATURE_BINARY_SERIALIZATION
[Serializable]
@@ -18,7 +18,6 @@ public class SshPassPhraseNullOrEmptyException : SshException
///
public SshPassPhraseNullOrEmptyException()
{
-
}
///
@@ -28,7 +27,6 @@ public SshPassPhraseNullOrEmptyException()
public SshPassPhraseNullOrEmptyException(string message)
: base(message)
{
-
}
///
@@ -36,8 +34,8 @@ public SshPassPhraseNullOrEmptyException(string message)
///
/// The message.
/// The inner exception.
- public SshPassPhraseNullOrEmptyException(string message, Exception innerException) :
- base(message, innerException)
+ public SshPassPhraseNullOrEmptyException(string message, Exception innerException)
+ : base(message, innerException)
{
}
@@ -47,8 +45,8 @@ public SshPassPhraseNullOrEmptyException(string message, Exception innerExceptio
///
/// The that holds the serialized object data about the exception being thrown.
/// The that contains contextual information about the source or destination.
- /// The parameter is null.
- /// The class name is null or is zero (0).
+ /// The parameter is .
+ /// The class name is or is zero (0).
protected SshPassPhraseNullOrEmptyException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
diff --git a/src/Renci.SshNet/Common/TerminalModes.cs b/src/Renci.SshNet/Common/TerminalModes.cs
index 98c7b8fe5..6b813837a 100644
--- a/src/Renci.SshNet/Common/TerminalModes.cs
+++ b/src/Renci.SshNet/Common/TerminalModes.cs
@@ -1,27 +1,30 @@
namespace Renci.SshNet.Common
{
///
- /// Specifies the initial assignments of the opcode values that are used in the 'encoded terminal modes' valu
+ /// Specifies the initial assignments of the opcode values that are used in the 'encoded terminal modes' value.
///
+#pragma warning disable CA1028 // Enum Storage should be Int32
public enum TerminalModes : byte
+#pragma warning restore CA1028 // Enum Storage should be Int32
{
+#pragma warning disable CA1707 // Identifiers should not contain underscores
///
/// Indicates end of options.
- ///
+ ///
TTY_OP_END = 0,
-
+
///
/// Interrupt character; 255 if none. Similarly for the other characters. Not all of these characters are supported on all systems.
- ///
+ ///
VINTR = 1,
///
/// The quit character (sends SIGQUIT signal on POSIX systems).
- ///
+ ///
VQUIT = 2,
-
+
///
- /// Erase the character to left of the cursor.
+ /// Erase the character to left of the cursor.
///
VERASE = 3,
@@ -34,32 +37,32 @@ public enum TerminalModes : byte
/// End-of-file character (sends EOF from the terminal).
///
VEOF = 5,
-
+
///
/// End-of-line character in addition to carriage return and/or linefeed.
///
VEOL = 6,
-
+
///
/// Additional end-of-line character.
///
VEOL2 = 7,
-
+
///
/// Continues paused output (normally control-Q).
///
VSTART = 8,
-
+
///
/// Pauses output (normally control-S).
///
VSTOP = 9,
-
+
///
/// Suspends the current program.
///
VSUSP = 10,
-
+
///
/// Another suspend character.
///
@@ -76,7 +79,7 @@ public enum TerminalModes : byte
VWERASE = 13,
///
- /// Enter the next character typed literally, even if it is a special character
+ /// Enter the next character typed literally, even if it is a special character.
///
VLNEXT = 14,
@@ -289,5 +292,6 @@ public enum TerminalModes : byte
/// Specifies the output baud rate in bits per second.
///
TTY_OP_OSPEED = 129,
+#pragma warning restore CA1707 // Identifiers should not contain underscores
}
}
diff --git a/src/Renci.SshNet/Compression/CompressionMode.cs b/src/Renci.SshNet/Compression/CompressionMode.cs
index 1577e0bc8..b0b6f6b94 100644
--- a/src/Renci.SshNet/Compression/CompressionMode.cs
+++ b/src/Renci.SshNet/Compression/CompressionMode.cs
@@ -1,7 +1,7 @@
namespace Renci.SshNet.Compression
{
///
- /// Specifies compression modes
+ /// Specifies compression modes.
///
public enum CompressionMode
{
diff --git a/src/Renci.SshNet/Compression/Compressor.cs b/src/Renci.SshNet/Compression/Compressor.cs
index 5d06c781f..63eb3e336 100644
--- a/src/Renci.SshNet/Compression/Compressor.cs
+++ b/src/Renci.SshNet/Compression/Compressor.cs
@@ -1,25 +1,26 @@
-using Renci.SshNet.Security;
+using System;
using System.IO;
-using System;
+
+using Renci.SshNet.Security;
namespace Renci.SshNet.Compression
{
///
- /// Represents base class for compression algorithm implementation
+ /// Represents base class for compression algorithm implementation.
///
public abstract class Compressor : Algorithm, IDisposable
{
private readonly ZlibStream _compressor;
private readonly ZlibStream _decompressor;
-
private MemoryStream _compressorStream;
private MemoryStream _decompressorStream;
+ private bool _isDisposed;
///
/// Gets or sets a value indicating whether compression is active.
///
///
- /// true if compression is active; otherwise, false.
+ /// if compression is active; otherwise, .
///
protected bool IsActive { get; set; }
@@ -41,7 +42,7 @@ protected Compressor()
}
///
- /// Initializes the algorithm
+ /// Initializes the algorithm.
///
/// The session.
public virtual void Init(Session session)
@@ -53,7 +54,9 @@ public virtual void Init(Session session)
/// Compresses the specified data.
///
/// Data to compress.
- /// Compressed data
+ ///
+ /// The compressed data.
+ ///
public virtual byte[] Compress(byte[] data)
{
return Compress(data, 0, data.Length);
@@ -73,7 +76,9 @@ public virtual byte[] Compress(byte[] data, int offset, int length)
if (!IsActive)
{
if (offset == 0 && length == data.Length)
+ {
return data;
+ }
var buffer = new byte[length];
Buffer.BlockCopy(data, offset, buffer, 0, length);
@@ -113,7 +118,9 @@ public virtual byte[] Decompress(byte[] data, int offset, int length)
if (!IsActive)
{
if (offset == 0 && length == data.Length)
+ {
return data;
+ }
var buffer = new byte[length];
Buffer.BlockCopy(data, offset, buffer, 0, length);
@@ -127,27 +134,25 @@ public virtual byte[] Decompress(byte[] data, int offset, int length)
return _decompressorStream.ToArray();
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -175,9 +180,7 @@ protected virtual void Dispose(bool disposing)
///
~Compressor()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/Compression/Zlib.cs b/src/Renci.SshNet/Compression/Zlib.cs
index b518717a4..504697fd7 100644
--- a/src/Renci.SshNet/Compression/Zlib.cs
+++ b/src/Renci.SshNet/Compression/Zlib.cs
@@ -1,9 +1,9 @@
namespace Renci.SshNet.Compression
{
///
- /// Represents "zlib" compression implementation
+ /// Represents "zlib" compression implementation.
///
- internal class Zlib : Compressor
+ internal sealed class Zlib : Compressor
{
///
/// Gets algorithm name.
@@ -14,13 +14,14 @@ public override string Name
}
///
- /// Initializes the algorithm
+ /// Initializes the algorithm.
///
/// The session.
public override void Init(Session session)
{
base.Init(session);
+
IsActive = true;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Compression/ZlibOpenSsh.cs b/src/Renci.SshNet/Compression/ZlibOpenSsh.cs
index 177d76b49..45bf1165f 100644
--- a/src/Renci.SshNet/Compression/ZlibOpenSsh.cs
+++ b/src/Renci.SshNet/Compression/ZlibOpenSsh.cs
@@ -3,7 +3,7 @@
namespace Renci.SshNet.Compression
{
///
- /// Represents "zlib@openssh.org" compression implementation
+ /// Represents "zlib@openssh.org" compression implementation.
///
public class ZlibOpenSsh : Compressor
{
@@ -16,7 +16,7 @@ public override string Name
}
///
- /// Initializes the algorithm
+ /// Initializes the algorithm.
///
/// The session.
public override void Init(Session session)
@@ -32,4 +32,4 @@ private void Session_UserAuthenticationSuccessReceived(object sender, MessageEve
Session.UserAuthenticationSuccessReceived -= Session_UserAuthenticationSuccessReceived;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Compression/ZlibStream.cs b/src/Renci.SshNet/Compression/ZlibStream.cs
index e12996943..e09244992 100644
--- a/src/Renci.SshNet/Compression/ZlibStream.cs
+++ b/src/Renci.SshNet/Compression/ZlibStream.cs
@@ -1,11 +1,16 @@
using System.IO;
+#pragma warning disable S125 // Sections of code should not be commented out
+#pragma warning disable SA1005 // Single line comments should begin with single space
+
namespace Renci.SshNet.Compression
{
///
/// Implements Zlib compression algorithm.
///
+#pragma warning disable CA1711 // Identifiers should not have incorrect suffix
public class ZlibStream
+#pragma warning restore CA1711 // Identifiers should not have incorrect suffix
{
//private readonly Ionic.Zlib.ZlibStream _baseStream;
@@ -14,7 +19,9 @@ public class ZlibStream
///
/// The stream.
/// The mode.
+#pragma warning disable IDE0060 // Remove unused parameter
public ZlibStream(Stream stream, CompressionMode mode)
+#pragma warning restore IDE0060 // Remove unused parameter
{
//switch (mode)
//{
@@ -37,9 +44,15 @@ public ZlibStream(Stream stream, CompressionMode mode)
/// The buffer.
/// The offset.
/// The count.
+#pragma warning disable IDE0060 // Remove unused parameter
public void Write(byte[] buffer, int offset, int count)
+#pragma warning restore IDE0060 // Remove unused parameter
{
//this._baseStream.Write(buffer, offset, count);
}
+#pragma warning restore SA1005 // Single line comments should begin with single space
}
}
+
+#pragma warning restore SA1005 // Single line comments should begin with single space
+#pragma warning restore S125 // Sections of code should not be commented out
diff --git a/src/Renci.SshNet/Connection/ConnectorBase.cs b/src/Renci.SshNet/Connection/ConnectorBase.cs
index 6e9bed7af..58b45960a 100644
--- a/src/Renci.SshNet/Connection/ConnectorBase.cs
+++ b/src/Renci.SshNet/Connection/ConnectorBase.cs
@@ -1,9 +1,12 @@
-using Renci.SshNet.Abstractions;
-using Renci.SshNet.Common;
-using Renci.SshNet.Messages.Transport;
-using System;
+using System;
using System.Net;
using System.Net.Sockets;
+using System.Threading;
+using System.Threading.Tasks;
+
+using Renci.SshNet.Abstractions;
+using Renci.SshNet.Common;
+using Renci.SshNet.Messages.Transport;
namespace Renci.SshNet.Connection
{
@@ -11,8 +14,10 @@ internal abstract class ConnectorBase : IConnector
{
protected ConnectorBase(ISocketFactory socketFactory)
{
- if (socketFactory == null)
- throw new ArgumentNullException("socketFactory");
+ if (socketFactory is null)
+ {
+ throw new ArgumentNullException(nameof(socketFactory));
+ }
SocketFactory = socketFactory;
}
@@ -21,6 +26,8 @@ protected ConnectorBase(ISocketFactory socketFactory)
public abstract Socket Connect(IConnectionInfo connectionInfo);
+ public abstract Task ConnectAsync(IConnectionInfo connectionInfo, CancellationToken cancellationToken);
+
///
/// Establishes a socket connection to the specified host and port.
///
@@ -42,6 +49,40 @@ protected Socket SocketConnect(string host, int port, TimeSpan timeout)
{
SocketAbstraction.Connect(socket, ep, timeout);
+ const int socketBufferSize = 10 * Session.MaximumSshPacketSize;
+ socket.SendBufferSize = socketBufferSize;
+ socket.ReceiveBufferSize = socketBufferSize;
+ return socket;
+ }
+ catch (Exception)
+ {
+ socket.Dispose();
+ throw;
+ }
+ }
+
+ ///
+ /// Establishes a socket connection to the specified host and port.
+ ///
+ /// The host name of the server to connect to.
+ /// The port to connect to.
+ /// The cancellation token to observe.
+ /// The connection failed to establish within the configured .
+ /// An error occurred trying to establish the connection.
+ protected async Task SocketConnectAsync(string host, int port, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var ipAddress = (await DnsAbstraction.GetHostAddressesAsync(host).ConfigureAwait(false))[0];
+ var ep = new IPEndPoint(ipAddress, port);
+
+ DiagnosticAbstraction.Log(string.Format("Initiating connection to '{0}:{1}'.", host, port));
+
+ var socket = SocketFactory.Create(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
+ try
+ {
+ await SocketAbstraction.ConnectAsync(socket, ep, cancellationToken).ConfigureAwait(false);
+
const int socketBufferSize = 2 * Session.MaximumSshPacketSize;
socket.SendBufferSize = socketBufferSize;
socket.ReceiveBufferSize = socketBufferSize;
@@ -57,14 +98,14 @@ protected Socket SocketConnect(string host, int port, TimeSpan timeout)
protected static byte SocketReadByte(Socket socket)
{
var buffer = new byte[1];
- SocketRead(socket, buffer, 0, 1, Session.InfiniteTimeSpan);
+ _ = SocketRead(socket, buffer, 0, 1, Session.InfiniteTimeSpan);
return buffer[0];
}
protected static byte SocketReadByte(Socket socket, TimeSpan readTimeout)
{
var buffer = new byte[1];
- SocketRead(socket, buffer, 0, 1, readTimeout);
+ _ = SocketRead(socket, buffer, 0, 1, readTimeout);
return buffer[0];
}
@@ -107,6 +148,7 @@ protected static int SocketRead(Socket socket, byte[] buffer, int offset, int le
throw new SshConnectionException("An established connection was aborted by the server.",
DisconnectReason.ConnectionLost);
}
+
return bytesRead;
}
}
diff --git a/src/Renci.SshNet/Connection/DirectConnector.cs b/src/Renci.SshNet/Connection/DirectConnector.cs
index ec8464505..f0b1d6d62 100644
--- a/src/Renci.SshNet/Connection/DirectConnector.cs
+++ b/src/Renci.SshNet/Connection/DirectConnector.cs
@@ -1,10 +1,12 @@
using System.Net.Sockets;
+using System.Threading;
namespace Renci.SshNet.Connection
{
- internal class DirectConnector : ConnectorBase
+ internal sealed class DirectConnector : ConnectorBase
{
- public DirectConnector(ISocketFactory socketFactory) : base(socketFactory)
+ public DirectConnector(ISocketFactory socketFactory)
+ : base(socketFactory)
{
}
@@ -12,5 +14,10 @@ public override Socket Connect(IConnectionInfo connectionInfo)
{
return SocketConnect(connectionInfo.Host, connectionInfo.Port, connectionInfo.Timeout);
}
+
+ public override System.Threading.Tasks.Task ConnectAsync(IConnectionInfo connectionInfo, CancellationToken cancellationToken)
+ {
+ return SocketConnectAsync(connectionInfo.Host, connectionInfo.Port, cancellationToken);
+ }
}
}
diff --git a/src/Renci.SshNet/Connection/HttpConnector.cs b/src/Renci.SshNet/Connection/HttpConnector.cs
index b77f07345..afbaf0f01 100644
--- a/src/Renci.SshNet/Connection/HttpConnector.cs
+++ b/src/Renci.SshNet/Connection/HttpConnector.cs
@@ -1,11 +1,13 @@
-using Renci.SshNet.Abstractions;
-using Renci.SshNet.Common;
-using System;
+using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
+using Renci.SshNet.Abstractions;
+using Renci.SshNet.Common;
+
namespace Renci.SshNet.Connection
{
///
@@ -27,42 +29,29 @@ namespace Renci.SshNet.Connection
///
///
///
- internal class HttpConnector : ConnectorBase
+ internal sealed class HttpConnector : ProxyConnector
{
- public HttpConnector(ISocketFactory socketFactory) : base(socketFactory)
+ public HttpConnector(ISocketFactory socketFactory)
+ : base(socketFactory)
{
}
- public override Socket Connect(IConnectionInfo connectionInfo)
- {
- var socket = SocketConnect(connectionInfo.ProxyHost, connectionInfo.ProxyPort, connectionInfo.Timeout);
-
- try
- {
- HandleProxyConnect(connectionInfo, socket);
- return socket;
- }
- catch (Exception)
- {
- socket.Shutdown(SocketShutdown.Both);
- socket.Dispose();
-
- throw;
- }
- }
-
- private void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
+ protected override void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
{
var httpResponseRe = new Regex(@"HTTP/(?\d[.]\d) (?\d{3}) (?.+)$");
var httpHeaderRe = new Regex(@"(?[^\[\]()<>@,;:\""/?={} \t]+):(?.+)?");
- SocketAbstraction.Send(socket, SshData.Ascii.GetBytes(string.Format("CONNECT {0}:{1} HTTP/1.0\r\n", connectionInfo.Host, connectionInfo.Port)));
+ SocketAbstraction.Send(socket, SshData.Ascii.GetBytes(string.Format(CultureInfo.InvariantCulture,
+ "CONNECT {0}:{1} HTTP/1.0\r\n",
+ connectionInfo.Host,
+ connectionInfo.Port)));
- // Sent proxy authorization if specified
+ // Send proxy authorization if specified
if (!string.IsNullOrEmpty(connectionInfo.ProxyUsername))
{
- var authorization = string.Format("Proxy-Authorization: Basic {0}\r\n",
- Convert.ToBase64String(SshData.Ascii.GetBytes(string.Format("{0}:{1}", connectionInfo.ProxyUsername, connectionInfo.ProxyPassword))));
+ var authorization = string.Format(CultureInfo.InvariantCulture,
+ "Proxy-Authorization: Basic {0}\r\n",
+ Convert.ToBase64String(SshData.Ascii.GetBytes($"{connectionInfo.ProxyUsername}:{connectionInfo.ProxyPassword}")));
SocketAbstraction.Send(socket, SshData.Ascii.GetBytes(authorization));
}
@@ -74,24 +63,22 @@ private void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
while (true)
{
var response = SocketReadLine(socket, connectionInfo.Timeout);
- if (response == null)
+ if (response is null)
{
// server shut down socket
break;
}
- if (statusCode == null)
+ if (statusCode is null)
{
var statusMatch = httpResponseRe.Match(response);
if (statusMatch.Success)
{
var httpStatusCode = statusMatch.Result("${statusCode}");
- statusCode = (HttpStatusCode)int.Parse(httpStatusCode);
+ statusCode = (HttpStatusCode) int.Parse(httpStatusCode, CultureInfo.InvariantCulture);
if (statusCode != HttpStatusCode.OK)
{
- throw new ProxyException(string.Format("HTTP: Status code {0}, \"{1}\"",
- httpStatusCode,
- statusMatch.Result("${reasonPhrase}")));
+ throw new ProxyException($"HTTP: Status code {httpStatusCode}, \"{statusMatch.Result("${reasonPhrase}")}\"");
}
}
@@ -105,25 +92,27 @@ private void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
var fieldName = headerMatch.Result("${fieldName}");
if (fieldName.Equals("Content-Length", StringComparison.OrdinalIgnoreCase))
{
- contentLength = int.Parse(headerMatch.Result("${fieldValue}"));
+ contentLength = int.Parse(headerMatch.Result("${fieldValue}"), CultureInfo.InvariantCulture);
}
+
continue;
}
// check if we've reached the CRLF which separates request line and headers from the message body
if (response.Length == 0)
{
- // read response body if specified
+ // read response body if specified
if (contentLength > 0)
{
var contentBody = new byte[contentLength];
- SocketRead(socket, contentBody, 0, contentLength, connectionInfo.Timeout);
+ _ = SocketRead(socket, contentBody, 0, contentLength, connectionInfo.Timeout);
}
+
break;
}
}
- if (statusCode == null)
+ if (statusCode is null)
{
throw new ProxyException("HTTP response does not contain status line.");
}
@@ -137,7 +126,7 @@ private void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
/// The read has timed-out.
/// An error occurred when trying to access the socket.
///
- /// The line read from the socket, or null when the remote server has shutdown and all data has been received.
+ /// The line read from the socket, or when the remote server has shutdown and all data has been received.
///
private static string SocketReadLine(Socket socket, TimeSpan readTimeout)
{
diff --git a/src/Renci.SshNet/Connection/IConnector.cs b/src/Renci.SshNet/Connection/IConnector.cs
index 7efc5c5fa..6ce454eb2 100644
--- a/src/Renci.SshNet/Connection/IConnector.cs
+++ b/src/Renci.SshNet/Connection/IConnector.cs
@@ -1,9 +1,30 @@
using System.Net.Sockets;
+using System.Threading;
namespace Renci.SshNet.Connection
{
+ ///
+ /// Represents a means to connect to a SSH endpoint.
+ ///
internal interface IConnector
{
+ ///
+ /// Connects to a SSH endpoint using the specified .
+ ///
+ /// The to use to establish a connection to a SSH endpoint.
+ ///
+ /// A connected to the SSH endpoint represented by the specified .
+ ///
Socket Connect(IConnectionInfo connectionInfo);
+
+ ///
+ /// Asynchronously connects to a SSH endpoint using the specified .
+ ///
+ /// The to use to establish a connection to a SSH endpoint.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A connected to the SSH endpoint represented by the specified .
+ ///
+ System.Threading.Tasks.Task ConnectAsync(IConnectionInfo connectionInfo, CancellationToken cancellationToken);
}
}
diff --git a/src/Renci.SshNet/Connection/IProtocolVersionExchange.cs b/src/Renci.SshNet/Connection/IProtocolVersionExchange.cs
index 77bcfbd33..1cbe3d7f2 100644
--- a/src/Renci.SshNet/Connection/IProtocolVersionExchange.cs
+++ b/src/Renci.SshNet/Connection/IProtocolVersionExchange.cs
@@ -1,5 +1,7 @@
using System;
using System.Net.Sockets;
+using System.Threading;
+using System.Threading.Tasks;
namespace Renci.SshNet.Connection
{
@@ -18,5 +20,17 @@ internal interface IProtocolVersionExchange
/// The SSH identification of the server.
///
SshIdentification Start(string clientVersion, Socket socket, TimeSpan timeout);
+
+ ///
+ /// Asynchronously performs the SSH protocol version exchange.
+ ///
+ /// The identification string of the SSH client.
+ /// A connected to the server.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the SSH protocol version exchange. The value of its
+ /// contains the SSH identification of the server.
+ ///
+ Task StartAsync(string clientVersion, Socket socket, CancellationToken cancellationToken);
}
}
diff --git a/src/Renci.SshNet/Connection/ISocketFactory.cs b/src/Renci.SshNet/Connection/ISocketFactory.cs
index 0d76eeb29..a12233182 100644
--- a/src/Renci.SshNet/Connection/ISocketFactory.cs
+++ b/src/Renci.SshNet/Connection/ISocketFactory.cs
@@ -2,8 +2,22 @@
namespace Renci.SshNet.Connection
{
+ ///
+ /// Represents a factory to create instances.
+ ///
internal interface ISocketFactory
{
+ ///
+ /// Creates a with the specified ,
+ /// and that does not use the
+ /// Nagle algorithm.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ ///
+ /// The .
+ ///
Socket Create(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType);
}
}
diff --git a/src/Renci.SshNet/Connection/ProtocolVersionExchange.cs b/src/Renci.SshNet/Connection/ProtocolVersionExchange.cs
index 1d529a6d1..bde732c06 100644
--- a/src/Renci.SshNet/Connection/ProtocolVersionExchange.cs
+++ b/src/Renci.SshNet/Connection/ProtocolVersionExchange.cs
@@ -1,12 +1,15 @@
-using Renci.SshNet.Abstractions;
-using Renci.SshNet.Common;
-using Renci.SshNet.Messages.Transport;
-using System;
+using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
+using System.Threading;
+using System.Threading.Tasks;
+
+using Renci.SshNet.Abstractions;
+using Renci.SshNet.Common;
+using Renci.SshNet.Messages.Transport;
namespace Renci.SshNet.Connection
{
@@ -14,17 +17,13 @@ namespace Renci.SshNet.Connection
/// Handles the SSH protocol version exchange.
///
///
- /// https://tools.ietf.org/html/rfc4253#section-4.2
+ /// https://tools.ietf.org/html/rfc4253#section-4.2.
///
- internal class ProtocolVersionExchange : IProtocolVersionExchange
+ internal sealed class ProtocolVersionExchange : IProtocolVersionExchange
{
private const byte Null = 0x00;
-#if FEATURE_REGEX_COMPILE
- private static readonly Regex ServerVersionRe = new Regex("^SSH-(?[^-]+)-(?.+?)([ ](?.+))?$", RegexOptions.Compiled);
-#else
- private static readonly Regex ServerVersionRe = new Regex("^SSH-(?[^-]+)-(?.+?)([ ](?.+))?$");
-#endif
+ private static readonly Regex ServerVersionRe = new Regex("^SSH-(?[^-]+)-(?.+?)([ ](?.+))?$", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
///
/// Performs the SSH protocol version exchange.
@@ -48,24 +47,57 @@ public SshIdentification Start(string clientVersion, Socket socket, TimeSpan tim
while (true)
{
var line = SocketReadLine(socket, timeout, bytesReceived);
- if (line == null)
+ if (line is null)
+ {
+ if (bytesReceived.Count == 0)
+ {
+ throw CreateConnectionLostException();
+ }
+
+ throw CreateServerResponseDoesNotContainIdentification(bytesReceived);
+ }
+
+ var identificationMatch = ServerVersionRe.Match(line);
+ if (identificationMatch.Success)
+ {
+ return new SshIdentification(GetGroupValue(identificationMatch, "protoversion"),
+ GetGroupValue(identificationMatch, "softwareversion"),
+ GetGroupValue(identificationMatch, "comments"));
+ }
+ }
+ }
+
+ ///
+ /// Asynchronously performs the SSH protocol version exchange.
+ ///
+ /// The identification string of the SSH client.
+ /// A connected to the server.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the SSH protocol version exchange. The value of its
+ /// contains the SSH identification of the server.
+ ///
+ public async Task StartAsync(string clientVersion, Socket socket, CancellationToken cancellationToken)
+ {
+ // Immediately send the identification string since the spec states both sides MUST send an identification string
+ // when the connection has been established
+ SocketAbstraction.Send(socket, Encoding.UTF8.GetBytes(clientVersion + "\x0D\x0A"));
+
+ var bytesReceived = new List();
+
+ // Get server version from the server,
+ // ignore text lines which are sent before if any
+ while (true)
+ {
+ var line = await SocketReadLineAsync(socket, bytesReceived, cancellationToken).ConfigureAwait(false);
+ if (line is null)
{
if (bytesReceived.Count == 0)
{
- throw new SshConnectionException(string.Format("The server response does not contain an SSH identification string.{0}" +
- "The connection to the remote server was closed before any data was received.{0}{0}" +
- "More information on the Protocol Version Exchange is available here:{0}" +
- "https://tools.ietf.org/html/rfc4253#section-4.2",
- Environment.NewLine),
- DisconnectReason.ConnectionLost);
+ throw CreateConnectionLostException();
}
- throw new SshConnectionException(string.Format("The server response does not contain an SSH identification string:{0}{0}{1}{0}{0}" +
- "More information on the Protocol Version Exchange is available here:{0}" +
- "https://tools.ietf.org/html/rfc4253#section-4.2",
- Environment.NewLine,
- PacketDump.Create(bytesReceived, 2)),
- DisconnectReason.ProtocolError);
+ throw CreateServerResponseDoesNotContainIdentification(bytesReceived);
}
var identificationMatch = ServerVersionRe.Match(line);
@@ -98,7 +130,7 @@ private static string GetGroupValue(Match match, string groupName)
/// The read has timed-out.
/// An error occurred when trying to access the socket.
///
- /// The line read from the socket, or null when the remote server has shutdown and all data has been received.
+ /// The line read from the socket, or when the remote server has shutdown and all data has been received.
///
private static string SocketReadLine(Socket socket, TimeSpan timeout, List buffer)
{
@@ -121,16 +153,9 @@ private static string SocketReadLine(Socket socket, TimeSpan timeout, List
buffer.Add(byteRead);
// The null character MUST NOT be sent
- if (byteRead == Null)
+ if (byteRead is Null)
{
- throw new SshConnectionException(string.Format(CultureInfo.InvariantCulture,
- "The server response contains a null character at position 0x{0:X8}:{1}{1}{2}{1}{1}" +
- "A server must not send a null character before the Protocol Version Exchange is complete.{1}{1}" +
- "More information is available here:{1}" +
- "https://tools.ietf.org/html/rfc4253#section-4.2",
- buffer.Count,
- Environment.NewLine,
- PacketDump.Create(buffer.ToArray(), 2)));
+ throw CreateServerResponseContainsNullCharacterException(buffer);
}
if (byteRead == Session.LineFeed)
@@ -140,18 +165,102 @@ private static string SocketReadLine(Socket socket, TimeSpan timeout, List
// Return current line without CRLF
return Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + 2));
}
- else
- {
- // Even though RFC4253 clearly indicates that the identification string should be terminated
- // by a CR LF we also support banners and identification strings that are terminated by a LF
- // Return current line without LF
- return Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + 1));
- }
+ // Even though RFC4253 clearly indicates that the identification string should be terminated
+ // by a CR LF we also support banners and identification strings that are terminated by a LF
+
+ // Return current line without LF
+ return Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + 1));
}
}
return null;
}
+
+ private static async Task SocketReadLineAsync(Socket socket, List buffer, CancellationToken cancellationToken)
+ {
+ var data = new byte[1];
+
+ var startPosition = buffer.Count;
+
+ // Read data one byte at a time to find end of line and leave any unhandled information in the buffer
+ // to be processed by subsequent invocations.
+ while (true)
+ {
+ var bytesRead = await SocketAbstraction.ReadAsync(socket, data, cancellationToken).ConfigureAwait(false);
+ if (bytesRead == 0)
+ {
+ throw new SshConnectionException("The connection was closed by the remote host.");
+ }
+
+ var byteRead = data[0];
+ buffer.Add(byteRead);
+
+ // The null character MUST NOT be sent
+ if (byteRead is Null)
+ {
+ throw CreateServerResponseContainsNullCharacterException(buffer);
+ }
+
+ if (byteRead == Session.LineFeed)
+ {
+ if (buffer.Count > startPosition + 1 && buffer[buffer.Count - 2] == Session.CarriageReturn)
+ {
+ // Return current line without CRLF
+ return Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + 2));
+ }
+
+ // Even though RFC4253 clearly indicates that the identification string should be terminated
+ // by a CR LF we also support banners and identification strings that are terminated by a LF
+
+ // Return current line without LF
+ return Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + 1));
+ }
+ }
+ }
+
+ private static SshConnectionException CreateConnectionLostException()
+ {
+#pragma warning disable SA1118 // Parameter should not span multiple lines
+ var message = string.Format(CultureInfo.InvariantCulture,
+ "The server response does not contain an SSH identification string.{0}" +
+ "The connection to the remote server was closed before any data was received.{0}{0}" +
+ "More information on the Protocol Version Exchange is available here:{0}" +
+ "https://tools.ietf.org/html/rfc4253#section-4.2",
+ Environment.NewLine);
+#pragma warning restore SA1118 // Parameter should not span multiple lines
+
+ return new SshConnectionException(message, DisconnectReason.ConnectionLost);
+ }
+
+ private static SshConnectionException CreateServerResponseContainsNullCharacterException(List buffer)
+ {
+#pragma warning disable SA1118 // Parameter should not span multiple lines
+ var message = string.Format(CultureInfo.InvariantCulture,
+ "The server response contains a null character at position 0x{0:X8}:{1}{1}{2}{1}{1}" +
+ "A server must not send a null character before the Protocol Version Exchange is complete.{1}{1}" +
+ "More information is available here:{1}" +
+ "https://tools.ietf.org/html/rfc4253#section-4.2",
+ buffer.Count,
+ Environment.NewLine,
+ PacketDump.Create(buffer.ToArray(), 2));
+#pragma warning restore SA1118 // Parameter should not span multiple lines
+
+ throw new SshConnectionException(message);
+ }
+
+ private static SshConnectionException CreateServerResponseDoesNotContainIdentification(List bytesReceived)
+ {
+#pragma warning disable SA1118 // Parameter should not span multiple lines
+ var message = string.Format(CultureInfo.InvariantCulture,
+ "The server response does not contain an SSH identification string:{0}{0}{1}{0}{0}" +
+ "More information on the Protocol Version Exchange is available here:{0}" +
+ "https://tools.ietf.org/html/rfc4253#section-4.2",
+ Environment.NewLine,
+ PacketDump.Create(bytesReceived, 2));
+#pragma warning restore SA1118 // Parameter should not span multiple lines
+
+ throw new SshConnectionException(message, DisconnectReason.ProtocolError);
+ }
}
}
diff --git a/src/Renci.SshNet/Connection/ProxyConnector.cs b/src/Renci.SshNet/Connection/ProxyConnector.cs
new file mode 100644
index 000000000..d8261e024
--- /dev/null
+++ b/src/Renci.SshNet/Connection/ProxyConnector.cs
@@ -0,0 +1,97 @@
+using System;
+using System.Net.Sockets;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Renci.SshNet.Connection
+{
+ ///
+ /// Represents a connector that uses a proxy server to establish a connection to a given SSH
+ /// endpoint.
+ ///
+ internal abstract class ProxyConnector : ConnectorBase
+ {
+ protected ProxyConnector(ISocketFactory socketFactory)
+ : base(socketFactory)
+ {
+ }
+
+ protected abstract void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket);
+
+ // ToDo: Performs async/sync fallback, true async version should be implemented in derived classes
+ protected virtual
+#if NET || NETSTANDARD2_1_OR_GREATER
+ async
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ Task HandleProxyConnectAsync(IConnectionInfo connectionInfo, Socket socket, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(o => ((Socket)o).Dispose(), socket, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(o => ((Socket) o).Dispose(), socket, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+#pragma warning disable MA0042 // Do not use blocking calls in an async method; false positive caused by https://github.com/meziantou/Meziantou.Analyzer/issues/613
+ HandleProxyConnect(connectionInfo, socket);
+#pragma warning restore MA0042 // Do not use blocking calls in an async method
+ }
+
+#if !NET && !NETSTANDARD2_1_OR_GREATER
+ return Task.CompletedTask;
+#endif // !NET && !NETSTANDARD2_1_OR_GREATER
+ }
+
+ ///
+ /// Connects to a SSH endpoint using the specified .
+ ///
+ /// The to use to establish a connection to a SSH endpoint.
+ ///
+ /// A connected to the SSH endpoint represented by the specified .
+ ///
+ public override Socket Connect(IConnectionInfo connectionInfo)
+ {
+ var socket = SocketConnect(connectionInfo.ProxyHost, connectionInfo.ProxyPort, connectionInfo.Timeout);
+
+ try
+ {
+ HandleProxyConnect(connectionInfo, socket);
+ return socket;
+ }
+ catch (Exception)
+ {
+ socket.Shutdown(SocketShutdown.Both);
+ socket.Dispose();
+
+ throw;
+ }
+ }
+
+ ///
+ /// Asynchronously connects to a SSH endpoint using the specified .
+ ///
+ /// The to use to establish a connection to a SSH endpoint.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A connected to the SSH endpoint represented by the specified .
+ ///
+ public override async Task ConnectAsync(IConnectionInfo connectionInfo, CancellationToken cancellationToken)
+ {
+ var socket = await SocketConnectAsync(connectionInfo.ProxyHost, connectionInfo.ProxyPort, cancellationToken).ConfigureAwait(false);
+
+ try
+ {
+ await HandleProxyConnectAsync(connectionInfo, socket, cancellationToken).ConfigureAwait(false);
+ return socket;
+ }
+ catch (Exception)
+ {
+ socket.Shutdown(SocketShutdown.Both);
+ socket.Dispose();
+
+ throw;
+ }
+ }
+ }
+}
diff --git a/src/Renci.SshNet/Connection/SocketFactory.cs b/src/Renci.SshNet/Connection/SocketFactory.cs
index 8c61b87c6..698634947 100644
--- a/src/Renci.SshNet/Connection/SocketFactory.cs
+++ b/src/Renci.SshNet/Connection/SocketFactory.cs
@@ -2,11 +2,25 @@
namespace Renci.SshNet.Connection
{
- internal class SocketFactory : ISocketFactory
+ ///
+ /// Represents a factory to create instances.
+ ///
+ internal sealed class SocketFactory : ISocketFactory
{
+ ///
+ /// Creates a with the specified ,
+ /// and that does not use the
+ /// Nagle algorithm.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ ///
+ /// The .
+ ///
public Socket Create(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
- return new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
+ return new Socket(addressFamily, socketType, protocolType) { NoDelay = true };
}
}
}
diff --git a/src/Renci.SshNet/Connection/Socks4Connector.cs b/src/Renci.SshNet/Connection/Socks4Connector.cs
index 9154240f8..d679c17a3 100644
--- a/src/Renci.SshNet/Connection/Socks4Connector.cs
+++ b/src/Renci.SshNet/Connection/Socks4Connector.cs
@@ -1,58 +1,42 @@
-using Renci.SshNet.Abstractions;
-using Renci.SshNet.Common;
-using System;
+using System;
using System.Net.Sockets;
using System.Text;
+using Renci.SshNet.Abstractions;
+using Renci.SshNet.Common;
+
namespace Renci.SshNet.Connection
{
///
/// Establishes a tunnel via a SOCKS4 proxy server.
///
///
- /// https://www.openssh.com/txt/socks4.protocol
+ /// https://www.openssh.com/txt/socks4.protocol.
///
- internal class Socks4Connector : ConnectorBase
+ internal sealed class Socks4Connector : ProxyConnector
{
- public Socks4Connector(ISocketFactory socketFactory) : base(socketFactory)
+ public Socks4Connector(ISocketFactory socketFactory)
+ : base(socketFactory)
{
}
- public override Socket Connect(IConnectionInfo connectionInfo)
- {
- var socket = SocketConnect(connectionInfo.ProxyHost, connectionInfo.ProxyPort, connectionInfo.Timeout);
-
- try
- {
- HandleProxyConnect(connectionInfo, socket);
- return socket;
- }
- catch (Exception)
- {
- socket.Shutdown(SocketShutdown.Both);
- socket.Dispose();
-
- throw;
- }
- }
-
///
/// Establishes a connection to the server via a SOCKS5 proxy.
///
/// The connection information.
/// The .
- private void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
+ protected override void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
{
var connectionRequest = CreateSocks4ConnectionRequest(connectionInfo.Host, (ushort)connectionInfo.Port, connectionInfo.ProxyUsername);
SocketAbstraction.Send(socket, connectionRequest);
- // Read reply version
+ // Read reply version
if (SocketReadByte(socket, connectionInfo.Timeout) != 0x00)
{
throw new ProxyException("SOCKS4: Null is expected.");
}
- // Read response code
+ // Read response code
var code = SocketReadByte(socket, connectionInfo.Timeout);
switch (code)
@@ -70,7 +54,7 @@ private void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
}
var destBuffer = new byte[6]; // destination port and IP address should be ignored
- SocketRead(socket, destBuffer, 0, destBuffer.Length, connectionInfo.Timeout);
+ _ = SocketRead(socket, destBuffer, 0, destBuffer.Length, connectionInfo.Timeout);
}
private static byte[] CreateSocks4ConnectionRequest(string hostname, ushort port, string username)
@@ -78,21 +62,23 @@ private static byte[] CreateSocks4ConnectionRequest(string hostname, ushort port
var addressBytes = GetSocks4DestinationAddress(hostname);
var proxyUserBytes = GetProxyUserBytes(username);
- var connectionRequest = new byte
- [
- // SOCKS version number
- 1 +
- // Command code
- 1 +
- // Port number
- 2 +
- // IP address
- addressBytes.Length +
- // Username
- proxyUserBytes.Length +
- // Null terminator
- 1
- ];
+ var connectionRequest = new byte[// SOCKS version number
+ 1 +
+
+ // Command code
+ 1 +
+
+ // Port number
+ 2 +
+
+ // IP address
+ addressBytes.Length +
+
+ // Username
+ proxyUserBytes.Length +
+
+ // Null terminator
+ 1];
var index = 0;
@@ -140,14 +126,10 @@ private static byte[] GetProxyUserBytes(string proxyUser)
{
if (proxyUser == null)
{
- return Array.Empty;
+ return Array.Empty();
}
-#if FEATURE_ENCODING_ASCII
return Encoding.ASCII.GetBytes(proxyUser);
-#else
- return new ASCIIEncoding().GetBytes(proxyUser);
-#endif
}
}
}
diff --git a/src/Renci.SshNet/Connection/Socks5Connector.cs b/src/Renci.SshNet/Connection/Socks5Connector.cs
index 720ac5004..a1ed5f751 100644
--- a/src/Renci.SshNet/Connection/Socks5Connector.cs
+++ b/src/Renci.SshNet/Connection/Socks5Connector.cs
@@ -1,55 +1,42 @@
-using Renci.SshNet.Abstractions;
-using Renci.SshNet.Common;
-using System;
+using System;
using System.Net.Sockets;
+using Renci.SshNet.Abstractions;
+using Renci.SshNet.Common;
+
namespace Renci.SshNet.Connection
{
///
/// Establishes a tunnel via a SOCKS5 proxy server.
///
///
- /// https://en.wikipedia.org/wiki/SOCKS#SOCKS5
+ /// https://en.wikipedia.org/wiki/SOCKS#SOCKS5.
///
- internal class Socks5Connector : ConnectorBase
+ internal sealed class Socks5Connector : ProxyConnector
{
- public Socks5Connector(ISocketFactory socketFactory) : base(socketFactory)
+ public Socks5Connector(ISocketFactory socketFactory)
+ : base(socketFactory)
{
}
- public override Socket Connect(IConnectionInfo connectionInfo)
- {
- var socket = SocketConnect(connectionInfo.ProxyHost, connectionInfo.ProxyPort, connectionInfo.Timeout);
-
- try
- {
- HandleProxyConnect(connectionInfo, socket);
- return socket;
- }
- catch (Exception)
- {
- socket.Shutdown(SocketShutdown.Both);
- socket.Dispose();
-
- throw;
- }
- }
-
///
/// Establishes a connection to the server via a SOCKS5 proxy.
///
/// The connection information.
/// The .
- private void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
+ protected override void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
{
var greeting = new byte[]
{
// SOCKS version number
0x05,
+
// Number of supported authentication methods
0x02,
+
// No authentication
0x00,
+
// Username/Password authentication
0x02
};
@@ -65,34 +52,45 @@ private void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
switch (authenticationMethod)
{
case 0x00:
+ // No authentication
break;
case 0x02:
// Create username/password authentication request
var authenticationRequest = CreateSocks5UserNameAndPasswordAuthenticationRequest(connectionInfo.ProxyUsername, connectionInfo.ProxyPassword);
+
// Send authentication request
SocketAbstraction.Send(socket, authenticationRequest);
+
// Read authentication result
var authenticationResult = SocketAbstraction.Read(socket, 2, connectionInfo.Timeout);
if (authenticationResult[0] != 0x01)
+ {
throw new ProxyException("SOCKS5: Server authentication version is not valid.");
+ }
+
if (authenticationResult[1] != 0x00)
+ {
throw new ProxyException("SOCKS5: Username/Password authentication failed.");
+ }
+
break;
case 0xFF:
throw new ProxyException("SOCKS5: No acceptable authentication methods were offered.");
+ default:
+ throw new ProxyException($"SOCKS5: Chosen authentication method '0x{authenticationMethod:x2}' is not supported.");
}
var connectionRequest = CreateSocks5ConnectionRequest(connectionInfo.Host, (ushort) connectionInfo.Port);
SocketAbstraction.Send(socket, connectionRequest);
- // Read Server SOCKS5 version
+ // Read Server SOCKS5 version
if (SocketReadByte(socket) != 5)
{
throw new ProxyException("SOCKS5: Version 5 is expected.");
}
- // Read response code
+ // Read response code
var status = SocketReadByte(socket);
switch (status)
@@ -119,7 +117,7 @@ private void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
throw new ProxyException("SOCKS5: Not valid response.");
}
- // Read reserved byte
+ // Read reserved byte
if (SocketReadByte(socket) != 0)
{
throw new ProxyException("SOCKS5: 0 byte is expected.");
@@ -130,11 +128,11 @@ private void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
{
case 0x01:
var ipv4 = new byte[4];
- SocketRead(socket, ipv4, 0, 4);
+ _ = SocketRead(socket, ipv4, 0, 4);
break;
case 0x04:
var ipv6 = new byte[16];
- SocketRead(socket, ipv6, 0, 16);
+ _ =SocketRead(socket, ipv6, 0, 16);
break;
default:
throw new ProxyException(string.Format("Address type '{0}' is not supported.", addressType));
@@ -142,33 +140,39 @@ private void HandleProxyConnect(IConnectionInfo connectionInfo, Socket socket)
var port = new byte[2];
- // Read 2 bytes to be ignored
- SocketRead(socket, port, 0, 2);
+ // Read 2 bytes to be ignored
+ _ = SocketRead(socket, port, 0, 2);
}
///
- /// https://tools.ietf.org/html/rfc1929
+ /// https://tools.ietf.org/html/rfc1929.
///
private static byte[] CreateSocks5UserNameAndPasswordAuthenticationRequest(string username, string password)
{
if (username.Length > byte.MaxValue)
+ {
throw new ProxyException("Proxy username is too long.");
+ }
+
if (password.Length > byte.MaxValue)
+ {
throw new ProxyException("Proxy password is too long.");
+ }
+
+ var authenticationRequest = new byte[// Version of the negotiation
+ 1 +
- var authenticationRequest = new byte
- [
- // Version of the negotiation
- 1 +
- // Length of the username
- 1 +
- // Username
- username.Length +
- // Length of the password
- 1 +
- // Password
- password.Length
- ];
+ // Length of the username
+ 1 +
+
+ // Username
+ username.Length +
+
+ // Length of the password
+ 1 +
+
+ // Password
+ password.Length];
var index = 0;
@@ -179,38 +183,39 @@ private static byte[] CreateSocks5UserNameAndPasswordAuthenticationRequest(strin
authenticationRequest[index++] = (byte) username.Length;
// Username
- SshData.Ascii.GetBytes(username, 0, username.Length, authenticationRequest, index);
+ _ = SshData.Ascii.GetBytes(username, 0, username.Length, authenticationRequest, index);
index += username.Length;
// Length of the password
authenticationRequest[index++] = (byte) password.Length;
// Password
- SshData.Ascii.GetBytes(password, 0, password.Length, authenticationRequest, index);
+ _ =SshData.Ascii.GetBytes(password, 0, password.Length, authenticationRequest, index);
return authenticationRequest;
}
private static byte[] CreateSocks5ConnectionRequest(string hostname, ushort port)
{
- byte addressType;
- var addressBytes = GetSocks5DestinationAddress(hostname, out addressType);
+ var addressBytes = GetSocks5DestinationAddress(hostname, out var addressType);
- var connectionRequest = new byte
- [
- // SOCKS version number
- 1 +
- // Command code
- 1 +
- // Reserved
- 1 +
- // Address type
- 1 +
- // Address
- addressBytes.Length +
- // Port number
- 2
- ];
+ var connectionRequest = new byte[// SOCKS version number
+ 1 +
+
+ // Command code
+ 1 +
+
+ // Reserved
+ 1 +
+
+ // Address type
+ 1 +
+
+ // Address
+ addressBytes.Length +
+
+ // Port number
+ 2];
var index = 0;
@@ -242,6 +247,7 @@ private static byte[] GetSocks5DestinationAddress(string hostname, out byte addr
byte[] address;
+#pragma warning disable IDE0010 // Add missing cases
switch (ip.AddressFamily)
{
case AddressFamily.InterNetwork:
@@ -255,6 +261,7 @@ private static byte[] GetSocks5DestinationAddress(string hostname, out byte addr
default:
throw new ProxyException(string.Format("SOCKS5: IP address '{0}' is not supported.", ip));
}
+#pragma warning restore IDE0010 // Add missing cases
return address;
}
diff --git a/src/Renci.SshNet/Connection/SshIdentification.cs b/src/Renci.SshNet/Connection/SshIdentification.cs
index 90c00fe9f..727cc4d94 100644
--- a/src/Renci.SshNet/Connection/SshIdentification.cs
+++ b/src/Renci.SshNet/Connection/SshIdentification.cs
@@ -5,36 +5,41 @@ namespace Renci.SshNet.Connection
///
/// Represents an SSH identification.
///
- internal class SshIdentification
+ public sealed class SshIdentification
{
///
- /// Initializes a new instance with the specified protocol version
+ /// Initializes a new instance of the class with the specified protocol version
/// and software version.
///
/// The SSH protocol version.
- /// The software version of the implementation
+ /// The software version of the implementation.
/// is .
/// is .
public SshIdentification(string protocolVersion, string softwareVersion)
- : this(protocolVersion, softwareVersion, null)
+ : this(protocolVersion, softwareVersion, comments: null)
{
}
///
- /// Initializes a new instance with the specified protocol version,
+ /// Initializes a new instance of the class with the specified protocol version,
/// software version and comments.
///
/// The SSH protocol version.
- /// The software version of the implementation
+ /// The software version of the implementation.
/// The comments.
/// is .
/// is .
public SshIdentification(string protocolVersion, string softwareVersion, string comments)
{
- if (protocolVersion == null)
- throw new ArgumentNullException("protocolVersion");
- if (softwareVersion == null)
- throw new ArgumentNullException("softwareVersion");
+ if (protocolVersion is null)
+ {
+ throw new ArgumentNullException(nameof(protocolVersion));
+ }
+
+ if (softwareVersion is null)
+ {
+ throw new ArgumentNullException(nameof(softwareVersion));
+ }
ProtocolVersion = protocolVersion;
SoftwareVersion = softwareVersion;
@@ -42,7 +47,7 @@ public SshIdentification(string protocolVersion, string softwareVersion, string
}
///
- /// Gets or sets the software version of the implementation.
+ /// Gets the software version of the implementation.
///
///
/// The software version of the implementation.
@@ -51,18 +56,18 @@ public SshIdentification(string protocolVersion, string softwareVersion, string
/// This is primarily used to trigger compatibility extensions and to indicate
/// the capabilities of an implementation.
///
- public string SoftwareVersion { get; private set; }
+ public string SoftwareVersion { get; }
///
- /// Gets or sets the SSH protocol version.
+ /// Gets the SSH protocol version.
///
///
/// The SSH protocol version.
///
- public string ProtocolVersion { get; private set; }
+ public string ProtocolVersion { get; }
///
- /// Gets or sets the comments.
+ /// Gets the comments.
///
///
/// The comments, or if there are no comments.
@@ -71,7 +76,7 @@ public SshIdentification(string protocolVersion, string softwareVersion, string
/// should contain additional information that might be useful
/// in solving user problems.
///
- public string Comments { get; private set; }
+ public string Comments { get; }
///
/// Returns the SSH identification string.
@@ -82,10 +87,12 @@ public SshIdentification(string protocolVersion, string softwareVersion, string
public override string ToString()
{
var identificationString = "SSH-" + ProtocolVersion + "-" + SoftwareVersion;
+
if (Comments != null)
{
identificationString += " " + Comments;
}
+
return identificationString;
}
}
diff --git a/src/Renci.SshNet/ConnectionInfo.cs b/src/Renci.SshNet/ConnectionInfo.cs
index af8e1ca5c..721a45762 100644
--- a/src/Renci.SshNet/ConnectionInfo.cs
+++ b/src/Renci.SshNet/ConnectionInfo.cs
@@ -1,14 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Net;
+using System.Security.Cryptography;
using System.Text;
+
using Renci.SshNet.Abstractions;
-using Renci.SshNet.Security;
-using Renci.SshNet.Messages.Connection;
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Authentication;
-using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
+using Renci.SshNet.Messages.Connection;
+using Renci.SshNet.Security;
+using Renci.SshNet.Security.Cryptography;
using Renci.SshNet.Security.Cryptography.Ciphers;
+using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
namespace Renci.SshNet
{
@@ -21,7 +25,7 @@ namespace Renci.SshNet
///
public class ConnectionInfo : IConnectionInfoInternal
{
- internal static int DefaultPort = 22;
+ internal const int DefaultPort = 22;
///
/// The default connection timeout.
@@ -81,7 +85,7 @@ public class ConnectionInfo : IConnectionInfoInternal
/// Gets a value indicating whether connection is authenticated.
///
///
- /// true if connection is authenticated; otherwise, false.
+ /// if connection is authenticated; otherwise, .
///
public bool IsAuthenticated { get; private set; }
@@ -140,9 +144,6 @@ public class ConnectionInfo : IConnectionInfoInternal
///
/// The connection timeout. The default value is 30 seconds.
///
- ///
- ///
- ///
public TimeSpan Timeout { get; set; }
///
@@ -161,7 +162,7 @@ public class ConnectionInfo : IConnectionInfoInternal
/// Gets or sets the character encoding.
///
///
- /// The character encoding. The default is .
+ /// The character encoding. The default is .
///
public Encoding Encoding { get; set; }
@@ -186,9 +187,6 @@ public class ConnectionInfo : IConnectionInfoInternal
///
/// Occurs when authentication banner is sent by the server.
///
- ///
- ///
- ///
public event EventHandler AuthenticationBanner;
///
@@ -232,7 +230,7 @@ public class ConnectionInfo : IConnectionInfoInternal
public string ServerVersion { get; internal set; }
///
- /// Get the client version.
+ /// Gets the client version.
///
public string ClientVersion { get; internal set; }
@@ -247,13 +245,13 @@ public class ConnectionInfo : IConnectionInfoInternal
/// The host.
/// The username.
/// The authentication methods.
- /// is null.
+ /// is .
/// is a zero-length string.
- /// is null, a zero-length string or contains only whitespace characters.
- /// is null.
+ /// is , a zero-length string or contains only whitespace characters.
+ /// is .
/// No specified.
public ConnectionInfo(string host, string username, params AuthenticationMethod[] authenticationMethods)
- : this(host, DefaultPort, username, ProxyTypes.None, null, 0, null, null, authenticationMethods)
+ : this(host, DefaultPort, username, ProxyTypes.None, proxyHost: null, 0, proxyUsername: null, proxyPassword: null, authenticationMethods)
{
}
@@ -264,13 +262,13 @@ public ConnectionInfo(string host, string username, params AuthenticationMethod[
/// The port.
/// The username.
/// The authentication methods.
- /// is null.
- /// is null, a zero-length string or contains only whitespace characters.
- /// is not within and .
- /// is null.
+ /// is .
+ /// is , a zero-length string or contains only whitespace characters.
+ /// is not within and .
+ /// is .
/// No specified.
public ConnectionInfo(string host, int port, string username, params AuthenticationMethod[] authenticationMethods)
- : this(host, port, username, ProxyTypes.None, null, 0, null, null, authenticationMethods)
+ : this(host, port, username, ProxyTypes.None, proxyHost: null, 0, proxyUsername: null, proxyPassword: null, authenticationMethods)
{
}
@@ -286,37 +284,53 @@ public ConnectionInfo(string host, int port, string username, params Authenticat
/// The proxy username.
/// The proxy password.
/// The authentication methods.
- /// is null.
- /// is null, a zero-length string or contains only whitespace characters.
- /// is not within and .
- /// is not and is null.
- /// is not and is not within and .
- /// is null.
+ /// is .
+ /// is , a zero-length string or contains only whitespace characters.
+ /// is not within and .
+ /// is not and is .
+ /// is not and is not within and .
+ /// is .
/// No specified.
public ConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, params AuthenticationMethod[] authenticationMethods)
{
- if (host == null)
- throw new ArgumentNullException("host");
+ if (host is null)
+ {
+ throw new ArgumentNullException(nameof(host));
+ }
+
port.ValidatePort("port");
- if (username == null)
- throw new ArgumentNullException("username");
+ if (username is null)
+ {
+ throw new ArgumentNullException(nameof(username));
+ }
+
if (username.All(char.IsWhiteSpace))
- throw new ArgumentException("Cannot be empty or contain only whitespace.", "username");
+ {
+ throw new ArgumentException("Cannot be empty or contain only whitespace.", nameof(username));
+ }
if (proxyType != ProxyTypes.None)
{
- if (proxyHost == null)
- throw new ArgumentNullException("proxyHost");
+ if (proxyHost is null)
+ {
+ throw new ArgumentNullException(nameof(proxyHost));
+ }
+
proxyPort.ValidatePort("proxyPort");
}
- if (authenticationMethods == null)
- throw new ArgumentNullException("authenticationMethods");
+ if (authenticationMethods is null)
+ {
+ throw new ArgumentNullException(nameof(authenticationMethods));
+ }
+
if (authenticationMethods.Length == 0)
- throw new ArgumentException("At least one authentication method should be specified.", "authenticationMethods");
+ {
+ throw new ArgumentException("At least one authentication method should be specified.", nameof(authenticationMethods));
+ }
- // Set default connection values
+ // Set default connection values
Timeout = DefaultTimeout;
ChannelCloseTimeout = DefaultChannelCloseTimeout;
RetryAttempts = 10;
@@ -325,100 +339,89 @@ public ConnectionInfo(string host, int port, string username, ProxyTypes proxyTy
KeyExchangeAlgorithms = new Dictionary
{
- {"curve25519-sha256", typeof(KeyExchangeECCurve25519)},
- {"curve25519-sha256@libssh.org", typeof(KeyExchangeECCurve25519)},
- {"ecdh-sha2-nistp256", typeof(KeyExchangeECDH256)},
- {"ecdh-sha2-nistp384", typeof(KeyExchangeECDH384)},
- {"ecdh-sha2-nistp521", typeof(KeyExchangeECDH521)},
- {"diffie-hellman-group-exchange-sha256", typeof (KeyExchangeDiffieHellmanGroupExchangeSha256)},
- {"diffie-hellman-group-exchange-sha1", typeof (KeyExchangeDiffieHellmanGroupExchangeSha1)},
- {"diffie-hellman-group16-sha512", typeof(KeyExchangeDiffieHellmanGroup16Sha512)},
- {"diffie-hellman-group14-sha256", typeof (KeyExchangeDiffieHellmanGroup14Sha256)},
- {"diffie-hellman-group14-sha1", typeof (KeyExchangeDiffieHellmanGroup14Sha1)},
- {"diffie-hellman-group1-sha1", typeof (KeyExchangeDiffieHellmanGroup1Sha1)},
+ { "curve25519-sha256", typeof(KeyExchangeECCurve25519) },
+ { "curve25519-sha256@libssh.org", typeof(KeyExchangeECCurve25519) },
+ { "ecdh-sha2-nistp256", typeof(KeyExchangeECDH256) },
+ { "ecdh-sha2-nistp384", typeof(KeyExchangeECDH384) },
+ { "ecdh-sha2-nistp521", typeof(KeyExchangeECDH521) },
+ { "diffie-hellman-group-exchange-sha256", typeof(KeyExchangeDiffieHellmanGroupExchangeSha256) },
+ { "diffie-hellman-group-exchange-sha1", typeof(KeyExchangeDiffieHellmanGroupExchangeSha1) },
+ { "diffie-hellman-group16-sha512", typeof(KeyExchangeDiffieHellmanGroup16Sha512) },
+ { "diffie-hellman-group14-sha256", typeof(KeyExchangeDiffieHellmanGroup14Sha256) },
+ { "diffie-hellman-group14-sha1", typeof(KeyExchangeDiffieHellmanGroup14Sha1) },
+ { "diffie-hellman-group1-sha1", typeof(KeyExchangeDiffieHellmanGroup1Sha1) },
};
Encryptions = new Dictionary
{
- {"aes256-ctr", new CipherInfo(256, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null))},
- {"3des-cbc", new CipherInfo(192, (key, iv) => new TripleDesCipher(key, new CbcCipherMode(iv), null))},
- {"aes128-cbc", new CipherInfo(128, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null))},
- {"aes192-cbc", new CipherInfo(192, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null))},
- {"aes256-cbc", new CipherInfo(256, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null))},
- {"blowfish-cbc", new CipherInfo(128, (key, iv) => new BlowfishCipher(key, new CbcCipherMode(iv), null))},
- {"twofish-cbc", new CipherInfo(256, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
- {"twofish192-cbc", new CipherInfo(192, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
- {"twofish128-cbc", new CipherInfo(128, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
- {"twofish256-cbc", new CipherInfo(256, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null))},
- ////{"serpent256-cbc", typeof(CipherSerpent256CBC)},
- ////{"serpent192-cbc", typeof(...)},
- ////{"serpent128-cbc", typeof(...)},
- {"arcfour", new CipherInfo(128, (key, iv) => new Arc4Cipher(key, false))},
- {"arcfour128", new CipherInfo(128, (key, iv) => new Arc4Cipher(key, true))},
- {"arcfour256", new CipherInfo(256, (key, iv) => new Arc4Cipher(key, true))},
- ////{"idea-cbc", typeof(...)},
- {"cast128-cbc", new CipherInfo(128, (key, iv) => new CastCipher(key, new CbcCipherMode(iv), null))},
- ////{"rijndael-cbc@lysator.liu.se", typeof(...)},
- {"aes128-ctr", new CipherInfo(128, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null))},
- {"aes192-ctr", new CipherInfo(192, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null))},
+ { "aes128-ctr", new CipherInfo(128, (key, iv) => new AesCipher(key, iv, AesCipherMode.CTR, pkcs7Padding: false)) },
+ { "aes192-ctr", new CipherInfo(192, (key, iv) => new AesCipher(key, iv, AesCipherMode.CTR, pkcs7Padding: false)) },
+ { "aes256-ctr", new CipherInfo(256, (key, iv) => new AesCipher(key, iv, AesCipherMode.CTR, pkcs7Padding: false)) },
+ { "aes128-cbc", new CipherInfo(128, (key, iv) => new AesCipher(key, iv, AesCipherMode.CBC, pkcs7Padding: false)) },
+ { "aes192-cbc", new CipherInfo(192, (key, iv) => new AesCipher(key, iv, AesCipherMode.CBC, pkcs7Padding: false)) },
+ { "aes256-cbc", new CipherInfo(256, (key, iv) => new AesCipher(key, iv, AesCipherMode.CBC, pkcs7Padding: false)) },
+ { "3des-cbc", new CipherInfo(192, (key, iv) => new TripleDesCipher(key, new CbcCipherMode(iv), padding: null)) },
+ { "blowfish-cbc", new CipherInfo(128, (key, iv) => new BlowfishCipher(key, new CbcCipherMode(iv), padding: null)) },
+ { "twofish-cbc", new CipherInfo(256, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), padding: null)) },
+ { "twofish192-cbc", new CipherInfo(192, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), padding: null)) },
+ { "twofish128-cbc", new CipherInfo(128, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), padding: null)) },
+ { "twofish256-cbc", new CipherInfo(256, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), padding: null)) },
+ { "arcfour", new CipherInfo(128, (key, iv) => new Arc4Cipher(key, dischargeFirstBytes: false)) },
+ { "arcfour128", new CipherInfo(128, (key, iv) => new Arc4Cipher(key, dischargeFirstBytes: true)) },
+ { "arcfour256", new CipherInfo(256, (key, iv) => new Arc4Cipher(key, dischargeFirstBytes: true)) },
+ { "cast128-cbc", new CipherInfo(128, (key, iv) => new CastCipher(key, new CbcCipherMode(iv), padding: null)) },
};
+#pragma warning disable IDE0200 // Remove unnecessary lambda expression; We want to prevent instantiating the HashAlgorithm objects.
HmacAlgorithms = new Dictionary
{
- {"hmac-md5", new HashInfo(16*8, CryptoAbstraction.CreateHMACMD5)},
- {"hmac-md5-96", new HashInfo(16*8, key => CryptoAbstraction.CreateHMACMD5(key, 96))},
- {"hmac-sha1", new HashInfo(20*8, CryptoAbstraction.CreateHMACSHA1)},
- {"hmac-sha1-96", new HashInfo(20*8, key => CryptoAbstraction.CreateHMACSHA1(key, 96))},
- {"hmac-sha2-256", new HashInfo(32*8, CryptoAbstraction.CreateHMACSHA256)},
- {"hmac-sha2-256-96", new HashInfo(32*8, key => CryptoAbstraction.CreateHMACSHA256(key, 96))},
- {"hmac-sha2-512", new HashInfo(64 * 8, CryptoAbstraction.CreateHMACSHA512)},
- {"hmac-sha2-512-96", new HashInfo(64 * 8, key => CryptoAbstraction.CreateHMACSHA512(key, 96))},
- //{"umac-64@openssh.com", typeof(HMacSha1)},
- {"hmac-ripemd160", new HashInfo(160, CryptoAbstraction.CreateHMACRIPEMD160)},
- {"hmac-ripemd160@openssh.com", new HashInfo(160, CryptoAbstraction.CreateHMACRIPEMD160)},
- //{"none", typeof(...)},
+ { "hmac-sha2-256", new HashInfo(32*8, key => CryptoAbstraction.CreateHMACSHA256(key)) },
+ { "hmac-sha2-512", new HashInfo(64 * 8, key => CryptoAbstraction.CreateHMACSHA512(key)) },
+ { "hmac-sha2-512-96", new HashInfo(64 * 8, key => CryptoAbstraction.CreateHMACSHA512(key, 96)) },
+ { "hmac-sha2-256-96", new HashInfo(32*8, key => CryptoAbstraction.CreateHMACSHA256(key, 96)) },
+ { "hmac-ripemd160", new HashInfo(160, key => CryptoAbstraction.CreateHMACRIPEMD160(key)) },
+ { "hmac-ripemd160@openssh.com", new HashInfo(160, key => CryptoAbstraction.CreateHMACRIPEMD160(key)) },
+ { "hmac-sha1", new HashInfo(20*8, key => CryptoAbstraction.CreateHMACSHA1(key)) },
+ { "hmac-sha1-96", new HashInfo(20*8, key => CryptoAbstraction.CreateHMACSHA1(key, 96)) },
+ { "hmac-md5", new HashInfo(16*8, key => CryptoAbstraction.CreateHMACMD5(key)) },
+ { "hmac-md5-96", new HashInfo(16*8, key => CryptoAbstraction.CreateHMACMD5(key, 96)) },
};
+#pragma warning restore IDE0200 // Remove unnecessary lambda expression
HostKeyAlgorithms = new Dictionary>
{
- {"ssh-ed25519", data => new KeyHostAlgorithm("ssh-ed25519", new ED25519Key(), data)},
-#if FEATURE_ECDSA
- {"ecdsa-sha2-nistp256", data => new KeyHostAlgorithm("ecdsa-sha2-nistp256", new EcdsaKey(), data)},
- {"ecdsa-sha2-nistp384", data => new KeyHostAlgorithm("ecdsa-sha2-nistp384", new EcdsaKey(), data)},
- {"ecdsa-sha2-nistp521", data => new KeyHostAlgorithm("ecdsa-sha2-nistp521", new EcdsaKey(), data)},
-#endif
- {"ssh-rsa", data => new KeyHostAlgorithm("ssh-rsa", new RsaKey(), data)},
- {"ssh-dss", data => new KeyHostAlgorithm("ssh-dss", new DsaKey(), data)},
- //{"x509v3-sign-rsa", () => { ... },
- //{"x509v3-sign-dss", () => { ... },
- //{"spki-sign-rsa", () => { ... },
- //{"spki-sign-dss", () => { ... },
- //{"pgp-sign-rsa", () => { ... },
- //{"pgp-sign-dss", () => { ... },
+ { "ssh-ed25519", data => new KeyHostAlgorithm("ssh-ed25519", new ED25519Key(new SshKeyData(data))) },
+ { "ecdsa-sha2-nistp256", data => new KeyHostAlgorithm("ecdsa-sha2-nistp256", new EcdsaKey(new SshKeyData(data))) },
+ { "ecdsa-sha2-nistp384", data => new KeyHostAlgorithm("ecdsa-sha2-nistp384", new EcdsaKey(new SshKeyData(data))) },
+ { "ecdsa-sha2-nistp521", data => new KeyHostAlgorithm("ecdsa-sha2-nistp521", new EcdsaKey(new SshKeyData(data))) },
+#pragma warning disable SA1107 // Code should not contain multiple statements on one line
+ { "rsa-sha2-512", data => { var key = new RsaKey(new SshKeyData(data)); return new KeyHostAlgorithm("rsa-sha2-512", key, new RsaDigitalSignature(key, HashAlgorithmName.SHA512)); } },
+ { "rsa-sha2-256", data => { var key = new RsaKey(new SshKeyData(data)); return new KeyHostAlgorithm("rsa-sha2-256", key, new RsaDigitalSignature(key, HashAlgorithmName.SHA256)); } },
+#pragma warning restore SA1107 // Code should not contain multiple statements on one line
+ { "ssh-rsa", data => new KeyHostAlgorithm("ssh-rsa", new RsaKey(new SshKeyData(data))) },
+ { "ssh-dss", data => new KeyHostAlgorithm("ssh-dss", new DsaKey(new SshKeyData(data))) },
};
CompressionAlgorithms = new Dictionary
{
- //{"zlib@openssh.com", typeof(ZlibOpenSsh)},
- //{"zlib", typeof(Zlib)},
- {"none", null},
+ { "none", null },
};
ChannelRequests = new Dictionary
{
- {EnvironmentVariableRequestInfo.Name, new EnvironmentVariableRequestInfo()},
- {ExecRequestInfo.Name, new ExecRequestInfo()},
- {ExitSignalRequestInfo.Name, new ExitSignalRequestInfo()},
- {ExitStatusRequestInfo.Name, new ExitStatusRequestInfo()},
- {PseudoTerminalRequestInfo.Name, new PseudoTerminalRequestInfo()},
- {ShellRequestInfo.Name, new ShellRequestInfo()},
- {SignalRequestInfo.Name, new SignalRequestInfo()},
- {SubsystemRequestInfo.Name, new SubsystemRequestInfo()},
- {WindowChangeRequestInfo.Name, new WindowChangeRequestInfo()},
- {X11ForwardingRequestInfo.Name, new X11ForwardingRequestInfo()},
- {XonXoffRequestInfo.Name, new XonXoffRequestInfo()},
- {EndOfWriteRequestInfo.Name, new EndOfWriteRequestInfo()},
- {KeepAliveRequestInfo.Name, new KeepAliveRequestInfo()},
+ { EnvironmentVariableRequestInfo.Name, new EnvironmentVariableRequestInfo() },
+ { ExecRequestInfo.Name, new ExecRequestInfo() },
+ { ExitSignalRequestInfo.Name, new ExitSignalRequestInfo() },
+ { ExitStatusRequestInfo.Name, new ExitStatusRequestInfo() },
+ { PseudoTerminalRequestInfo.Name, new PseudoTerminalRequestInfo() },
+ { ShellRequestInfo.Name, new ShellRequestInfo() },
+ { SignalRequestInfo.Name, new SignalRequestInfo() },
+ { SubsystemRequestInfo.Name, new SubsystemRequestInfo() },
+ { WindowChangeRequestInfo.Name, new WindowChangeRequestInfo() },
+ { X11ForwardingRequestInfo.Name, new X11ForwardingRequestInfo() },
+ { XonXoffRequestInfo.Name, new XonXoffRequestInfo() },
+ { EndOfWriteRequestInfo.Name, new EndOfWriteRequestInfo() },
+ { KeepAliveRequestInfo.Name, new KeepAliveRequestInfo() },
};
Host = host;
@@ -439,13 +442,15 @@ public ConnectionInfo(string host, int port, string username, ProxyTypes proxyTy
///
/// The session to be authenticated.
/// The factory to use for creating new services.
- /// is null.
- /// is null.
+ /// is .
+ /// is .
/// No suitable authentication method found to complete authentication, or permission denied.
internal void Authenticate(ISession session, IServiceFactory serviceFactory)
{
- if (serviceFactory == null)
- throw new ArgumentNullException("serviceFactory");
+ if (serviceFactory is null)
+ {
+ throw new ArgumentNullException(nameof(serviceFactory));
+ }
IsAuthenticated = false;
var clientAuthentication = serviceFactory.CreateClientAuthentication();
@@ -457,25 +462,34 @@ internal void Authenticate(ISession session, IServiceFactory serviceFactory)
/// Signals that an authentication banner message was received from the server.
///
/// The session in which the banner message was received.
- /// The banner message.{
+ /// The banner message.
void IConnectionInfoInternal.UserAuthenticationBannerReceived(object sender, MessageEventArgs e)
{
- var authenticationBanner = AuthenticationBanner;
- if (authenticationBanner != null)
- {
- authenticationBanner(this,
- new AuthenticationBannerEventArgs(Username, e.Message.Message, e.Message.Language));
- }
+ AuthenticationBanner?.Invoke(this, new AuthenticationBannerEventArgs(Username, e.Message.Message, e.Message.Language));
}
+ ///
+ /// Creates a none authentication method.
+ ///
+ ///
+ /// A none authentication method.
+ ///
IAuthenticationMethod IConnectionInfoInternal.CreateNoneAuthenticationMethod()
{
return new NoneAuthenticationMethod(Username);
}
+ ///
+ /// Gets the supported authentication methods for this connection.
+ ///
+ ///
+ /// The supported authentication methods for this connection.
+ ///
IList IConnectionInfoInternal.AuthenticationMethods
{
+#pragma warning disable S2365 // Properties should not make collection or array copies
get { return AuthenticationMethods.Cast().ToList(); }
+#pragma warning restore S2365 // Properties should not make collection or array copies
}
}
}
diff --git a/src/Renci.SshNet/ExpectAction.cs b/src/Renci.SshNet/ExpectAction.cs
index c2ff3a6a1..8657d5933 100644
--- a/src/Renci.SshNet/ExpectAction.cs
+++ b/src/Renci.SshNet/ExpectAction.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet
{
///
- /// Specifies behavior for expected expression
+ /// Specifies behavior for expected expression.
///
public class ExpectAction
{
@@ -23,14 +23,18 @@ public class ExpectAction
///
/// The expect regular expression.
/// The action to perform.
- /// or is null.
+ /// or is .
public ExpectAction(Regex expect, Action action)
{
- if (expect == null)
- throw new ArgumentNullException("expect");
+ if (expect is null)
+ {
+ throw new ArgumentNullException(nameof(expect));
+ }
- if (action == null)
- throw new ArgumentNullException("action");
+ if (action is null)
+ {
+ throw new ArgumentNullException(nameof(action));
+ }
Expect = expect;
Action = action;
@@ -41,14 +45,18 @@ public ExpectAction(Regex expect, Action action)
///
/// The expect expression.
/// The action to perform.
- /// or is null.
+ /// or is .
public ExpectAction(string expect, Action action)
{
- if (expect == null)
- throw new ArgumentNullException("expect");
+ if (expect is null)
+ {
+ throw new ArgumentNullException(nameof(expect));
+ }
- if (action == null)
- throw new ArgumentNullException("action");
+ if (action is null)
+ {
+ throw new ArgumentNullException(nameof(action));
+ }
Expect = new Regex(Regex.Escape(expect));
Action = action;
diff --git a/src/Renci.SshNet/ExpectAsyncResult.cs b/src/Renci.SshNet/ExpectAsyncResult.cs
index 0f911c0b8..f83d32f75 100644
--- a/src/Renci.SshNet/ExpectAsyncResult.cs
+++ b/src/Renci.SshNet/ExpectAsyncResult.cs
@@ -1,10 +1,11 @@
-using Renci.SshNet.Common;
-using System;
+using System;
+
+using Renci.SshNet.Common;
namespace Renci.SshNet
{
///
- /// Provides additional information for asynchronous command execution
+ /// Provides additional information for asynchronous command execution.
///
public class ExpectAsyncResult : AsyncResult
{
@@ -13,7 +14,7 @@ public class ExpectAsyncResult : AsyncResult
///
/// The async callback.
/// The state.
- internal ExpectAsyncResult(AsyncCallback asyncCallback, Object state)
+ internal ExpectAsyncResult(AsyncCallback asyncCallback, object state)
: base(asyncCallback, state)
{
}
diff --git a/src/Renci.SshNet/ForwardedPort.cs b/src/Renci.SshNet/ForwardedPort.cs
index 26baaa1db..50157e1c1 100644
--- a/src/Renci.SshNet/ForwardedPort.cs
+++ b/src/Renci.SshNet/ForwardedPort.cs
@@ -1,4 +1,5 @@
using System;
+
using Renci.SshNet.Common;
namespace Renci.SshNet
@@ -16,28 +17,19 @@ public abstract class ForwardedPort : IForwardedPort
///
internal ISession Session { get; set; }
- ///
- /// The event occurs as the forwarded port is being stopped.
- ///
- internal event EventHandler Closing;
-
- ///
- /// The event occurs as the forwarded port is being stopped.
- ///
- event EventHandler IForwardedPort.Closing
- {
- add { Closing += value; }
- remove { Closing -= value; }
- }
-
///
/// Gets a value indicating whether port forwarding is started.
///
///
- /// true if port forwarding is started; otherwise, false.
+ /// if port forwarding is started; otherwise, .
///
public abstract bool IsStarted { get; }
+ ///
+ /// The event occurs as the forwarded port is being stopped.
+ ///
+ public event EventHandler Closing;
+
///
/// Occurs when an exception is thrown.
///
@@ -51,16 +43,26 @@ event EventHandler IForwardedPort.Closing
///
/// Starts port forwarding.
///
+ /// The current is already started -or- is not linked to a SSH session.
+ /// The client is not connected.
public virtual void Start()
{
CheckDisposed();
if (IsStarted)
+ {
throw new InvalidOperationException("Forwarded port is already started.");
- if (Session == null)
+ }
+
+ if (Session is null)
+ {
throw new InvalidOperationException("Forwarded port is not added to a client.");
+ }
+
if (!Session.IsConnected)
+ {
throw new SshConnectionException("Client not connected.");
+ }
Session.ErrorOccured += Session_ErrorOccured;
StartPort();
@@ -69,7 +71,9 @@ public virtual void Start()
///
/// Stops port forwarding.
///
+#pragma warning disable CA1716 // Identifiers should not match keywords
public virtual void Stop()
+#pragma warning restore CA1716 // Identifiers should not match keywords
{
if (IsStarted)
{
@@ -77,6 +81,15 @@ public virtual void Stop()
}
}
+ ///
+ /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
+ ///
+ public void Dispose()
+ {
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
+ }
+
///
/// Starts port forwarding.
///
@@ -92,22 +105,22 @@ protected virtual void StopPort(TimeSpan timeout)
RaiseClosing();
var session = Session;
- if (session != null)
+ if (session is not null)
{
session.ErrorOccured -= Session_ErrorOccured;
}
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
var session = Session;
- if (session != null)
+ if (session is not null)
{
StopPort(session.ConnectionInfo.Timeout);
Session = null;
@@ -127,11 +140,7 @@ protected virtual void Dispose(bool disposing)
/// The exception.
protected void RaiseExceptionEvent(Exception exception)
{
- var handlers = Exception;
- if (handlers != null)
- {
- handlers(this, new ExceptionEventArgs(exception));
- }
+ Exception?.Invoke(this, new ExceptionEventArgs(exception));
}
///
@@ -141,11 +150,7 @@ protected void RaiseExceptionEvent(Exception exception)
/// Request originator port.
protected void RaiseRequestReceived(string host, uint port)
{
- var handlers = RequestReceived;
- if (handlers != null)
- {
- handlers(this, new PortForwardEventArgs(host, port));
- }
+ RequestReceived?.Invoke(this, new PortForwardEventArgs(host, port));
}
///
@@ -153,11 +158,7 @@ protected void RaiseRequestReceived(string host, uint port)
///
private void RaiseClosing()
{
- var handlers = Closing;
- if (handlers != null)
- {
- handlers(this, EventArgs.Empty);
- }
+ Closing?.Invoke(this, EventArgs.Empty);
}
///
diff --git a/src/Renci.SshNet/ForwardedPortDynamic.NET.cs b/src/Renci.SshNet/ForwardedPortDynamic.NET.cs
deleted file mode 100644
index 36a804558..000000000
--- a/src/Renci.SshNet/ForwardedPortDynamic.NET.cs
+++ /dev/null
@@ -1,593 +0,0 @@
-using System;
-using System.Linq;
-using System.Text;
-using System.Net;
-using System.Net.Sockets;
-using System.Threading;
-using Renci.SshNet.Abstractions;
-using Renci.SshNet.Channels;
-using Renci.SshNet.Common;
-
-namespace Renci.SshNet
-{
- public partial class ForwardedPortDynamic
- {
- private Socket _listener;
- private CountdownEvent _pendingChannelCountdown;
-
- partial void InternalStart()
- {
- InitializePendingChannelCountdown();
-
- var ip = IPAddress.Any;
- if (!string.IsNullOrEmpty(BoundHost))
- {
- ip = DnsAbstraction.GetHostAddresses(BoundHost)[0];
- }
-
- var ep = new IPEndPoint(ip, (int) BoundPort);
-
- _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp) {NoDelay = true};
- _listener.Bind(ep);
- _listener.Listen(5);
-
- Session.ErrorOccured += Session_ErrorOccured;
- Session.Disconnected += Session_Disconnected;
-
- // consider port started when we're listening for inbound connections
- _status = ForwardedPortStatus.Started;
-
- StartAccept(null);
- }
-
- private void StartAccept(SocketAsyncEventArgs e)
- {
- if (e == null)
- {
- e = new SocketAsyncEventArgs();
- e.Completed += AcceptCompleted;
- }
- else
- {
- // clear the socket as we're reusing the context object
- e.AcceptSocket = null;
- }
-
- // only accept new connections while we are started
- if (IsStarted)
- {
- try
- {
- if (!_listener.AcceptAsync(e))
- {
- AcceptCompleted(null, e);
- }
- }
- catch (ObjectDisposedException)
- {
- if (_status == ForwardedPortStatus.Stopped || _status == ForwardedPortStatus.Stopped)
- {
- // ignore ObjectDisposedException while stopping or stopped
- return;
- }
-
- throw;
- }
- }
- }
-
- private void AcceptCompleted(object sender, SocketAsyncEventArgs e)
- {
- if (e.SocketError == SocketError.OperationAborted || e.SocketError == SocketError.NotSocket)
- {
- // server was stopped
- return;
- }
-
- // capture client socket
- var clientSocket = e.AcceptSocket;
-
- if (e.SocketError != SocketError.Success)
- {
- // accept new connection
- StartAccept(e);
- // dispose broken client socket
- CloseClientSocket(clientSocket);
- return;
- }
-
- // accept new connection
- StartAccept(e);
- // process connection
- ProcessAccept(clientSocket);
- }
-
- private void ProcessAccept(Socket clientSocket)
- {
- // close the client socket if we're no longer accepting new connections
- if (!IsStarted)
- {
- CloseClientSocket(clientSocket);
- return;
- }
-
- // capture the countdown event that we're adding a count to, as we need to make sure that we'll be signaling
- // that same instance; the instance field for the countdown event is re-initialized when the port is restarted
- // and at that time there may still be pending requests
- var pendingChannelCountdown = _pendingChannelCountdown;
-
- pendingChannelCountdown.AddCount();
-
- try
- {
- using (var channel = Session.CreateChannelDirectTcpip())
- {
- channel.Exception += Channel_Exception;
-
- if (!HandleSocks(channel, clientSocket, Session.ConnectionInfo.Timeout))
- {
- CloseClientSocket(clientSocket);
- return;
- }
-
- // start receiving from client socket (and sending to server)
- channel.Bind();
- }
- }
- catch (Exception exp)
- {
- RaiseExceptionEvent(exp);
- CloseClientSocket(clientSocket);
- }
- finally
- {
- // take into account that CountdownEvent has since been disposed; when stopping the port we
- // wait for a given time for the channels to close, but once that timeout period has elapsed
- // the CountdownEvent will be disposed
- try
- {
- pendingChannelCountdown.Signal();
- }
- catch (ObjectDisposedException)
- {
- }
- }
- }
-
- ///
- /// Initializes the .
- ///
- ///
- ///
- /// When the port is started for the first time, a is created with an initial count
- /// of 1.
- ///
- ///
- /// On subsequent (re)starts, we'll dispose the current and create a new one with
- /// initial count of 1.
- ///
- ///
- private void InitializePendingChannelCountdown()
- {
- var original = Interlocked.Exchange(ref _pendingChannelCountdown, new CountdownEvent(1));
- if (original != null)
- {
- original.Dispose();
- }
- }
-
- private bool HandleSocks(IChannelDirectTcpip channel, Socket clientSocket, TimeSpan timeout)
- {
- // create eventhandler which is to be invoked to interrupt a blocking receive
- // when we're closing the forwarded port
- EventHandler closeClientSocket = (_, args) => CloseClientSocket(clientSocket);
-
- Closing += closeClientSocket;
-
- try
- {
- var version = SocketAbstraction.ReadByte(clientSocket, timeout);
- switch (version)
- {
- case -1:
- // SOCKS client closed connection
- return false;
- case 4:
- return HandleSocks4(clientSocket, channel, timeout);
- case 5:
- return HandleSocks5(clientSocket, channel, timeout);
- default:
- throw new NotSupportedException(string.Format("SOCKS version {0} is not supported.", version));
- }
- }
- catch (SocketException ex)
- {
- // ignore exception thrown by interrupting the blocking receive as part of closing
- // the forwarded port
- if (ex.SocketErrorCode != SocketError.Interrupted)
- {
- RaiseExceptionEvent(ex);
- }
- return false;
- }
- finally
- {
- // interrupt of blocking receive is now handled by channel (SOCKS4 and SOCKS5)
- // or no longer necessary
- Closing -= closeClientSocket;
- }
-
- }
-
- private static void CloseClientSocket(Socket clientSocket)
- {
- if (clientSocket.Connected)
- {
- try
- {
- clientSocket.Shutdown(SocketShutdown.Send);
- }
- catch (Exception)
- {
- // ignore exception when client socket was already closed
- }
- }
-
- clientSocket.Dispose();
- }
-
- ///
- /// Interrupts the listener, and unsubscribes from events.
- ///
- partial void StopListener()
- {
- // close listener socket
- var listener = _listener;
- if (listener != null)
- {
- listener.Dispose();
- }
-
- // unsubscribe from session events
- var session = Session;
- if (session != null)
- {
- session.ErrorOccured -= Session_ErrorOccured;
- session.Disconnected -= Session_Disconnected;
- }
- }
-
- ///
- /// Waits for pending channels to close.
- ///
- /// The maximum time to wait for the pending channels to close.
- partial void InternalStop(TimeSpan timeout)
- {
- _pendingChannelCountdown.Signal();
- if (!_pendingChannelCountdown.Wait(timeout))
- {
- // TODO: log as warning
- DiagnosticAbstraction.Log("Timeout waiting for pending channels in dynamic forwarded port to close.");
- }
-
- }
-
- partial void InternalDispose(bool disposing)
- {
- if (disposing)
- {
- var listener = _listener;
- if (listener != null)
- {
- _listener = null;
- listener.Dispose();
- }
-
- var pendingRequestsCountdown = _pendingChannelCountdown;
- if (pendingRequestsCountdown != null)
- {
- _pendingChannelCountdown = null;
- pendingRequestsCountdown.Dispose();
- }
- }
- }
-
- private void Session_Disconnected(object sender, EventArgs e)
- {
- var session = Session;
- if (session != null)
- {
- StopPort(session.ConnectionInfo.Timeout);
- }
- }
-
- private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
- {
- var session = Session;
- if (session != null)
- {
- StopPort(session.ConnectionInfo.Timeout);
- }
- }
-
- private void Channel_Exception(object sender, ExceptionEventArgs e)
- {
- RaiseExceptionEvent(e.Exception);
- }
-
- private bool HandleSocks4(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout)
- {
- var commandCode = SocketAbstraction.ReadByte(socket, timeout);
- if (commandCode == -1)
- {
- // SOCKS client closed connection
- return false;
- }
-
- // TODO: See what need to be done depends on the code
-
- var portBuffer = new byte[2];
- if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0)
- {
- // SOCKS client closed connection
- return false;
- }
-
- var port = Pack.BigEndianToUInt16(portBuffer);
-
- var ipBuffer = new byte[4];
- if (SocketAbstraction.Read(socket, ipBuffer, 0, ipBuffer.Length, timeout) == 0)
- {
- // SOCKS client closed connection
- return false;
- }
-
- var ipAddress = new IPAddress(ipBuffer);
-
- var username = ReadString(socket, timeout);
- if (username == null)
- {
- // SOCKS client closed connection
- return false;
- }
-
- var host = ipAddress.ToString();
-
- RaiseRequestReceived(host, port);
-
- channel.Open(host, port, this, socket);
-
- SocketAbstraction.SendByte(socket, 0x00);
-
- if (channel.IsOpen)
- {
- SocketAbstraction.SendByte(socket, 0x5a);
- SocketAbstraction.Send(socket, portBuffer, 0, portBuffer.Length);
- SocketAbstraction.Send(socket, ipBuffer, 0, ipBuffer.Length);
- return true;
- }
-
- // signal that request was rejected or failed
- SocketAbstraction.SendByte(socket, 0x5b);
- return false;
- }
-
- private bool HandleSocks5(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout)
- {
- var authenticationMethodsCount = SocketAbstraction.ReadByte(socket, timeout);
- if (authenticationMethodsCount == -1)
- {
- // SOCKS client closed connection
- return false;
- }
-
- var authenticationMethods = new byte[authenticationMethodsCount];
- if (SocketAbstraction.Read(socket, authenticationMethods, 0, authenticationMethods.Length, timeout) == 0)
- {
- // SOCKS client closed connection
- return false;
- }
-
- if (authenticationMethods.Min() == 0)
- {
- // no user authentication is one of the authentication methods supported
- // by the SOCKS client
- SocketAbstraction.Send(socket, new byte[] {0x05, 0x00}, 0, 2);
- }
- else
- {
- // the SOCKS client requires authentication, which we currently do not support
- SocketAbstraction.Send(socket, new byte[] {0x05, 0xFF}, 0, 2);
-
- // we continue business as usual but expect the client to close the connection
- // so one of the subsequent reads should return -1 signaling that the client
- // has effectively closed the connection
- }
-
- var version = SocketAbstraction.ReadByte(socket, timeout);
- if (version == -1)
- {
- // SOCKS client closed connection
- return false;
- }
-
- if (version != 5)
- throw new ProxyException("SOCKS5: Version 5 is expected.");
-
- var commandCode = SocketAbstraction.ReadByte(socket, timeout);
- if (commandCode == -1)
- {
- // SOCKS client closed connection
- return false;
- }
-
- var reserved = SocketAbstraction.ReadByte(socket, timeout);
- if (reserved == -1)
- {
- // SOCKS client closed connection
- return false;
- }
-
- if (reserved != 0)
- {
- throw new ProxyException("SOCKS5: 0 is expected for reserved byte.");
- }
-
- var addressType = SocketAbstraction.ReadByte(socket, timeout);
- if (addressType == -1)
- {
- // SOCKS client closed connection
- return false;
- }
-
- var host = GetSocks5Host(addressType, socket, timeout);
- if (host == null)
- {
- // SOCKS client closed connection
- return false;
- }
-
- var portBuffer = new byte[2];
- if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0)
- {
- // SOCKS client closed connection
- return false;
- }
-
- var port = Pack.BigEndianToUInt16(portBuffer);
-
- RaiseRequestReceived(host, port);
-
- channel.Open(host, port, this, socket);
-
- var socksReply = CreateSocks5Reply(channel.IsOpen);
-
- SocketAbstraction.Send(socket, socksReply, 0, socksReply.Length);
-
- return true;
- }
-
- private static string GetSocks5Host(int addressType, Socket socket, TimeSpan timeout)
- {
- switch (addressType)
- {
- case 0x01: // IPv4
- {
- var addressBuffer = new byte[4];
- if (SocketAbstraction.Read(socket, addressBuffer, 0, 4, timeout) == 0)
- {
- // SOCKS client closed connection
- return null;
- }
-
- var ipv4 = new IPAddress(addressBuffer);
- return ipv4.ToString();
- }
- case 0x03: // Domain name
- {
- var length = SocketAbstraction.ReadByte(socket, timeout);
- if (length == -1)
- {
- // SOCKS client closed connection
- return null;
- }
- var addressBuffer = new byte[length];
- if (SocketAbstraction.Read(socket, addressBuffer, 0, addressBuffer.Length, timeout) == 0)
- {
- // SOCKS client closed connection
- return null;
- }
-
- var hostName = SshData.Ascii.GetString(addressBuffer, 0, addressBuffer.Length);
- return hostName;
- }
- case 0x04: // IPv6
- {
- var addressBuffer = new byte[16];
- if (SocketAbstraction.Read(socket, addressBuffer, 0, 16, timeout) == 0)
- {
- // SOCKS client closed connection
- return null;
- }
-
- var ipv6 = new IPAddress(addressBuffer);
- return ipv6.ToString();
- }
- default:
- throw new ProxyException(string.Format("SOCKS5: Address type '{0}' is not supported.", addressType));
- }
- }
-
- private static byte[] CreateSocks5Reply(bool channelOpen)
- {
- var socksReply = new byte
- [
- // SOCKS version
- 1 +
- // Reply field
- 1 +
- // Reserved; fixed: 0x00
- 1 +
- // Address type; fixed: 0x01
- 1 +
- // IPv4 server bound address; fixed: {0x00, 0x00, 0x00, 0x00}
- 4 +
- // server bound port; fixed: {0x00, 0x00}
- 2
- ];
-
- socksReply[0] = 0x05;
-
- if (channelOpen)
- {
- socksReply[1] = 0x00; // succeeded
- }
- else
- {
- socksReply[1] = 0x01; // general SOCKS server failure
- }
-
- // reserved
- socksReply[2] = 0x00;
-
- // IPv4 address type
- socksReply[3] = 0x01;
-
- return socksReply;
- }
-
- ///
- /// Reads a null terminated string from a socket.
- ///
- /// The to read from.
- /// The timeout to apply to individual reads.
- ///
- /// The read, or null when the socket was closed.
- ///
- private static string ReadString(Socket socket, TimeSpan timeout)
- {
- var text = new StringBuilder();
- var buffer = new byte[1];
- while (true)
- {
- if (SocketAbstraction.Read(socket, buffer, 0, 1, timeout) == 0)
- {
- // SOCKS client closed connection
- return null;
- }
-
- var byteRead = buffer[0];
- if (byteRead == 0)
- {
- // end of the string
- break;
- }
-
- var c = (char) byteRead;
- text.Append(c);
- }
- return text.ToString();
- }
- }
-}
-
diff --git a/src/Renci.SshNet/ForwardedPortDynamic.cs b/src/Renci.SshNet/ForwardedPortDynamic.cs
index dbe9794db..21ab59a20 100644
--- a/src/Renci.SshNet/ForwardedPortDynamic.cs
+++ b/src/Renci.SshNet/ForwardedPortDynamic.cs
@@ -1,4 +1,14 @@
using System;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading;
+
+using Renci.SshNet.Abstractions;
+using Renci.SshNet.Channels;
+using Renci.SshNet.Common;
namespace Renci.SshNet
{
@@ -6,25 +16,36 @@ namespace Renci.SshNet
/// Provides functionality for forwarding connections from the client to destination servers via the SSH server,
/// also known as dynamic port forwarding.
///
- public partial class ForwardedPortDynamic : ForwardedPort
+ public class ForwardedPortDynamic : ForwardedPort
{
private ForwardedPortStatus _status;
+ ///
+ /// Holds a value indicating whether the current instance is disposed.
+ ///
+ ///
+ /// if the current instance is disposed; otherwise, .
+ ///
+ private bool _isDisposed;
+
///
/// Gets the bound host.
///
- public string BoundHost { get; private set; }
+ public string BoundHost { get; }
///
/// Gets the bound port.
///
- public uint BoundPort { get; private set; }
+ public uint BoundPort { get; }
+
+ private Socket _listener;
+ private CountdownEvent _pendingChannelCountdown;
///
/// Gets a value indicating whether port forwarding is started.
///
///
- /// true if port forwarding is started; otherwise, false.
+ /// if port forwarding is started; otherwise, .
///
public override bool IsStarted
{
@@ -35,7 +56,8 @@ public override bool IsStarted
/// Initializes a new instance of the class.
///
/// The port.
- public ForwardedPortDynamic(uint port) : this(string.Empty, port)
+ public ForwardedPortDynamic(uint port)
+ : this(string.Empty, port)
{
}
@@ -57,7 +79,9 @@ public ForwardedPortDynamic(string host, uint port)
protected override void StartPort()
{
if (!ForwardedPortStatus.ToStarting(ref _status))
+ {
return;
+ }
try
{
@@ -78,14 +102,19 @@ protected override void StartPort()
protected override void StopPort(TimeSpan timeout)
{
if (!ForwardedPortStatus.ToStopping(ref _status))
+ {
return;
+ }
// signal existing channels that the port is closing
base.StopPort(timeout);
+
// prevent new requests from getting processed
StopListener();
+
// wait for open channels to close
InternalStop(timeout);
+
// mark port stopped
_status = ForwardedPortStatus.Stopped;
}
@@ -96,68 +125,629 @@ protected override void StopPort(TimeSpan timeout)
/// The current instance is disposed.
protected override void CheckDisposed()
{
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_isDisposed, this);
+#else
if (_isDisposed)
+ {
throw new ObjectDisposedException(GetType().FullName);
+ }
+#endif // NET7_0_OR_GREATER
}
- partial void InternalStart();
-
///
- /// Stops the listener.
+ /// Releases unmanaged and - optionally - managed resources.
///
- partial void StopListener();
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
+ protected override void Dispose(bool disposing)
+ {
+ if (_isDisposed)
+ {
+ return;
+ }
+
+ base.Dispose(disposing);
+
+ InternalDispose(disposing);
+ _isDisposed = true;
+ }
+
+ private void InternalStart()
+ {
+ InitializePendingChannelCountdown();
+
+ var ip = IPAddress.Any;
+ if (!string.IsNullOrEmpty(BoundHost))
+ {
+ ip = DnsAbstraction.GetHostAddresses(BoundHost)[0];
+ }
+
+ var ep = new IPEndPoint(ip, (int) BoundPort);
+
+ _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
+ _listener.Bind(ep);
+ _listener.Listen(5);
+
+ Session.ErrorOccured += Session_ErrorOccured;
+ Session.Disconnected += Session_Disconnected;
+
+ // consider port started when we're listening for inbound connections
+ _status = ForwardedPortStatus.Started;
+
+ StartAccept(e: null);
+ }
+
+ private void StartAccept(SocketAsyncEventArgs e)
+ {
+ if (e is null)
+ {
+#pragma warning disable CA2000 // Dispose objects before losing scope
+ e = new SocketAsyncEventArgs();
+#pragma warning restore CA2000 // Dispose objects before losing scope
+ e.Completed += AcceptCompleted;
+ }
+ else
+ {
+ // clear the socket as we're reusing the context object
+ e.AcceptSocket = null;
+ }
+
+ // only accept new connections while we are started
+ if (IsStarted)
+ {
+ try
+ {
+ if (!_listener.AcceptAsync(e))
+ {
+ AcceptCompleted(sender: null, e);
+ }
+ }
+ catch (ObjectDisposedException)
+ {
+ if (_status == ForwardedPortStatus.Stopping || _status == ForwardedPortStatus.Stopped)
+ {
+ // ignore ObjectDisposedException while stopping or stopped
+ return;
+ }
+
+ throw;
+ }
+ }
+ }
+
+ private void AcceptCompleted(object sender, SocketAsyncEventArgs e)
+ {
+ if (e.SocketError is SocketError.OperationAborted or SocketError.NotSocket)
+ {
+ // server was stopped
+ return;
+ }
+
+ // capture client socket
+ var clientSocket = e.AcceptSocket;
+
+ if (e.SocketError != SocketError.Success)
+ {
+ // accept new connection
+ StartAccept(e);
+
+ // dispose broken client socket
+ CloseClientSocket(clientSocket);
+ return;
+ }
+
+ // accept new connection
+ StartAccept(e);
+
+ // process connection
+ ProcessAccept(clientSocket);
+ }
+
+ private void ProcessAccept(Socket clientSocket)
+ {
+ // close the client socket if we're no longer accepting new connections
+ if (!IsStarted)
+ {
+ CloseClientSocket(clientSocket);
+ return;
+ }
+
+ // capture the countdown event that we're adding a count to, as we need to make sure that we'll be signaling
+ // that same instance; the instance field for the countdown event is re-initialized when the port is restarted
+ // and at that time there may still be pending requests
+ var pendingChannelCountdown = _pendingChannelCountdown;
+
+ pendingChannelCountdown.AddCount();
+
+ try
+ {
+ using (var channel = Session.CreateChannelDirectTcpip())
+ {
+ channel.Exception += Channel_Exception;
+
+ if (!HandleSocks(channel, clientSocket, Session.ConnectionInfo.Timeout))
+ {
+ CloseClientSocket(clientSocket);
+ return;
+ }
+
+ // start receiving from client socket (and sending to server)
+ channel.Bind();
+ }
+ }
+ catch (Exception exp)
+ {
+ RaiseExceptionEvent(exp);
+ CloseClientSocket(clientSocket);
+ }
+ finally
+ {
+ // take into account that CountdownEvent has since been disposed; when stopping the port we
+ // wait for a given time for the channels to close, but once that timeout period has elapsed
+ // the CountdownEvent will be disposed
+ try
+ {
+ _ = pendingChannelCountdown.Signal();
+ }
+ catch (ObjectDisposedException)
+ {
+ // Ignore any ObjectDisposedException
+ }
+ }
+ }
///
- /// Waits for pending requests to finish, and channels to close.
+ /// Initializes the .
///
- /// The maximum time to wait for the forwarded port to stop.
- partial void InternalStop(TimeSpan timeout);
+ ///
+ ///
+ /// When the port is started for the first time, a is created with an initial count
+ /// of 1.
+ ///
+ ///
+ /// On subsequent (re)starts, we'll dispose the current and create a new one with
+ /// initial count of 1.
+ ///
+ ///
+ private void InitializePendingChannelCountdown()
+ {
+ var original = Interlocked.Exchange(ref _pendingChannelCountdown, new CountdownEvent(1));
+ original?.Dispose();
+ }
- #region IDisposable Members
+ private bool HandleSocks(IChannelDirectTcpip channel, Socket clientSocket, TimeSpan timeout)
+ {
+ Closing += closeClientSocket;
+
+ try
+ {
+ var version = SocketAbstraction.ReadByte(clientSocket, timeout);
+ switch (version)
+ {
+ case -1:
+ // SOCKS client closed connection
+ return false;
+ case 4:
+ return HandleSocks4(clientSocket, channel, timeout);
+ case 5:
+ return HandleSocks5(clientSocket, channel, timeout);
+ default:
+ throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "SOCKS version {0} is not supported.", version));
+ }
+ }
+ catch (SocketException ex)
+ {
+ // ignore exception thrown by interrupting the blocking receive as part of closing
+ // the forwarded port
+#if NETFRAMEWORK
+ if (ex.SocketErrorCode != SocketError.Interrupted)
+ {
+ RaiseExceptionEvent(ex);
+ }
+#else
+ // Since .NET 5 the exception has been changed.
+ // more info https://github.com/dotnet/runtime/issues/41585
+ if (ex.SocketErrorCode != SocketError.ConnectionAborted)
+ {
+ RaiseExceptionEvent(ex);
+ }
+#endif
+ return false;
+ }
+ finally
+ {
+ // interrupt of blocking receive is now handled by channel (SOCKS4 and SOCKS5)
+ // or no longer necessary
+ Closing -= closeClientSocket;
+ }
+
+#pragma warning disable SA1300 // Element should begin with upper-case letter
+ void closeClientSocket(object sender, EventArgs args)
+ {
+ CloseClientSocket(clientSocket);
+ }
+#pragma warning restore SA1300 // Element should begin with upper-case letter
+ }
+
+ private static void CloseClientSocket(Socket clientSocket)
+ {
+ if (clientSocket.Connected)
+ {
+ try
+ {
+ clientSocket.Shutdown(SocketShutdown.Send);
+ }
+ catch (Exception)
+ {
+ // ignore exception when client socket was already closed
+ }
+ }
+
+ clientSocket.Dispose();
+ }
///
- /// Holds a value indicating whether the current instance is disposed.
+ /// Interrupts the listener, and unsubscribes from events.
///
- ///
- /// true if the current instance is disposed; otherwise, false.
- ///
- private bool _isDisposed;
+ private void StopListener()
+ {
+ // close listener socket
+ _listener?.Dispose();
+
+ // unsubscribe from session events
+ var session = Session;
+ if (session is not null)
+ {
+ session.ErrorOccured -= Session_ErrorOccured;
+ session.Disconnected -= Session_Disconnected;
+ }
+ }
///
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
+ /// Waits for pending channels to close.
///
- public void Dispose()
+ /// The maximum time to wait for the pending channels to close.
+ private void InternalStop(TimeSpan timeout)
+ {
+ _ = _pendingChannelCountdown.Signal();
+
+ if (!_pendingChannelCountdown.Wait(timeout))
+ {
+ // TODO: log as warning
+ DiagnosticAbstraction.Log("Timeout waiting for pending channels in dynamic forwarded port to close.");
+ }
+ }
+
+ private void InternalDispose(bool disposing)
+ {
+ if (disposing)
+ {
+ var listener = _listener;
+ if (listener is not null)
+ {
+ _listener = null;
+ listener.Dispose();
+ }
+
+ var pendingRequestsCountdown = _pendingChannelCountdown;
+ if (pendingRequestsCountdown is not null)
+ {
+ _pendingChannelCountdown = null;
+ pendingRequestsCountdown.Dispose();
+ }
+ }
+ }
+
+ private void Session_Disconnected(object sender, EventArgs e)
+ {
+ var session = Session;
+ if (session is not null)
+ {
+ StopPort(session.ConnectionInfo.Timeout);
+ }
+ }
+
+ private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
+ {
+ var session = Session;
+ if (session is not null)
+ {
+ StopPort(session.ConnectionInfo.Timeout);
+ }
+ }
+
+ private void Channel_Exception(object sender, ExceptionEventArgs e)
+ {
+ RaiseExceptionEvent(e.Exception);
+ }
+
+ private bool HandleSocks4(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout)
+ {
+ var commandCode = SocketAbstraction.ReadByte(socket, timeout);
+ if (commandCode == -1)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ var portBuffer = new byte[2];
+ if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ var port = Pack.BigEndianToUInt16(portBuffer);
+
+ var ipBuffer = new byte[4];
+ if (SocketAbstraction.Read(socket, ipBuffer, 0, ipBuffer.Length, timeout) == 0)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ var ipAddress = new IPAddress(ipBuffer);
+
+ var username = ReadString(socket, timeout);
+ if (username is null)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ var host = ipAddress.ToString();
+
+ RaiseRequestReceived(host, port);
+
+ channel.Open(host, port, this, socket);
+
+ SocketAbstraction.SendByte(socket, 0x00);
+
+ if (channel.IsOpen)
+ {
+ SocketAbstraction.SendByte(socket, 0x5a);
+ SocketAbstraction.Send(socket, portBuffer, 0, portBuffer.Length);
+ SocketAbstraction.Send(socket, ipBuffer, 0, ipBuffer.Length);
+ return true;
+ }
+
+ // signal that request was rejected or failed
+ SocketAbstraction.SendByte(socket, 0x5b);
+ return false;
+ }
+
+ private bool HandleSocks5(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout)
+ {
+ var authenticationMethodsCount = SocketAbstraction.ReadByte(socket, timeout);
+ if (authenticationMethodsCount == -1)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ var authenticationMethods = new byte[authenticationMethodsCount];
+ if (SocketAbstraction.Read(socket, authenticationMethods, 0, authenticationMethods.Length, timeout) == 0)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ if (authenticationMethods.Min() == 0)
+ {
+ // no user authentication is one of the authentication methods supported
+ // by the SOCKS client
+ SocketAbstraction.Send(socket, new byte[] { 0x05, 0x00 }, 0, 2);
+ }
+ else
+ {
+ // the SOCKS client requires authentication, which we currently do not support
+ SocketAbstraction.Send(socket, new byte[] { 0x05, 0xFF }, 0, 2);
+
+ // we continue business as usual but expect the client to close the connection
+ // so one of the subsequent reads should return -1 signaling that the client
+ // has effectively closed the connection
+ }
+
+ var version = SocketAbstraction.ReadByte(socket, timeout);
+ if (version == -1)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ if (version != 5)
+ {
+ throw new ProxyException("SOCKS5: Version 5 is expected.");
+ }
+
+ var commandCode = SocketAbstraction.ReadByte(socket, timeout);
+ if (commandCode == -1)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ var reserved = SocketAbstraction.ReadByte(socket, timeout);
+ if (reserved == -1)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ if (reserved != 0)
+ {
+ throw new ProxyException("SOCKS5: 0 is expected for reserved byte.");
+ }
+
+ var addressType = SocketAbstraction.ReadByte(socket, timeout);
+ if (addressType == -1)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ var host = GetSocks5Host(addressType, socket, timeout);
+ if (host is null)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ var portBuffer = new byte[2];
+ if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0)
+ {
+ // SOCKS client closed connection
+ return false;
+ }
+
+ var port = Pack.BigEndianToUInt16(portBuffer);
+
+ RaiseRequestReceived(host, port);
+
+ channel.Open(host, port, this, socket);
+
+ var socksReply = CreateSocks5Reply(channel.IsOpen);
+
+ SocketAbstraction.Send(socket, socksReply, 0, socksReply.Length);
+
+ return true;
+ }
+
+ private static string GetSocks5Host(int addressType, Socket socket, TimeSpan timeout)
{
- Dispose(true);
- GC.SuppressFinalize(this);
+ switch (addressType)
+ {
+ case 0x01: // IPv4
+ {
+ var addressBuffer = new byte[4];
+ if (SocketAbstraction.Read(socket, addressBuffer, 0, 4, timeout) == 0)
+ {
+ // SOCKS client closed connection
+ return null;
+ }
+
+ var ipv4 = new IPAddress(addressBuffer);
+ return ipv4.ToString();
+ }
+
+ case 0x03: // Domain name
+ {
+ var length = SocketAbstraction.ReadByte(socket, timeout);
+ if (length == -1)
+ {
+ // SOCKS client closed connection
+ return null;
+ }
+
+ var addressBuffer = new byte[length];
+ if (SocketAbstraction.Read(socket, addressBuffer, 0, addressBuffer.Length, timeout) == 0)
+ {
+ // SOCKS client closed connection
+ return null;
+ }
+
+ var hostName = SshData.Ascii.GetString(addressBuffer, 0, addressBuffer.Length);
+ return hostName;
+ }
+
+ case 0x04: // IPv6
+ {
+ var addressBuffer = new byte[16];
+ if (SocketAbstraction.Read(socket, addressBuffer, 0, 16, timeout) == 0)
+ {
+ // SOCKS client closed connection
+ return null;
+ }
+
+ var ipv6 = new IPAddress(addressBuffer);
+ return ipv6.ToString();
+ }
+
+ default:
+ throw new ProxyException(string.Format(CultureInfo.InvariantCulture, "SOCKS5: Address type '{0}' is not supported.", addressType));
+ }
}
- partial void InternalDispose(bool disposing);
+ private static byte[] CreateSocks5Reply(bool channelOpen)
+ {
+ var socksReply = new byte[// SOCKS version
+ 1 +
+
+ // Reply field
+ 1 +
+
+ // Reserved; fixed: 0x00
+ 1 +
+
+ // Address type; fixed: 0x01
+ 1 +
+
+ // IPv4 server bound address; fixed: {0x00, 0x00, 0x00, 0x00}
+ 4 +
+
+ // server bound port; fixed: {0x00, 0x00}
+ 2];
+
+ socksReply[0] = 0x05;
+
+ if (channelOpen)
+ {
+ socksReply[1] = 0x00; // succeeded
+ }
+ else
+ {
+ socksReply[1] = 0x01; // general SOCKS server failure
+ }
+
+ // reserved
+ socksReply[2] = 0x00;
+
+ // IPv4 address type
+ socksReply[3] = 0x01;
+
+ return socksReply;
+ }
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Reads a null terminated string from a socket.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
- protected override void Dispose(bool disposing)
+ /// The to read from.
+ /// The timeout to apply to individual reads.
+ ///
+ /// The read, or when the socket was closed.
+ ///
+ private static string ReadString(Socket socket, TimeSpan timeout)
{
- if (_isDisposed)
- return;
+ var text = new StringBuilder();
+ var buffer = new byte[1];
- base.Dispose(disposing);
- InternalDispose(disposing);
+ while (true)
+ {
+ if (SocketAbstraction.Read(socket, buffer, 0, 1, timeout) == 0)
+ {
+ // SOCKS client closed connection
+ return null;
+ }
- _isDisposed = true;
+ var byteRead = buffer[0];
+ if (byteRead == 0)
+ {
+ // end of the string
+ break;
+ }
+
+ _ = text.Append((char) byteRead);
+ }
+
+ return text.ToString();
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~ForwardedPortDynamic()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/ForwardedPortLocal.NET.cs b/src/Renci.SshNet/ForwardedPortLocal.NET.cs
deleted file mode 100644
index ba01ddbd3..000000000
--- a/src/Renci.SshNet/ForwardedPortLocal.NET.cs
+++ /dev/null
@@ -1,267 +0,0 @@
-using System;
-using System.Net.Sockets;
-using System.Net;
-using System.Threading;
-using Renci.SshNet.Abstractions;
-using Renci.SshNet.Common;
-
-namespace Renci.SshNet
-{
- public partial class ForwardedPortLocal
- {
- private Socket _listener;
- private CountdownEvent _pendingChannelCountdown;
-
- partial void InternalStart()
- {
- var addr = DnsAbstraction.GetHostAddresses(BoundHost)[0];
- var ep = new IPEndPoint(addr, (int) BoundPort);
-
- _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp) {NoDelay = true};
- _listener.Bind(ep);
- _listener.Listen(5);
-
- // update bound port (in case original was passed as zero)
- BoundPort = (uint)((IPEndPoint)_listener.LocalEndPoint).Port;
-
- Session.ErrorOccured += Session_ErrorOccured;
- Session.Disconnected += Session_Disconnected;
-
- InitializePendingChannelCountdown();
-
- // consider port started when we're listening for inbound connections
- _status = ForwardedPortStatus.Started;
-
- StartAccept(null);
- }
-
- private void StartAccept(SocketAsyncEventArgs e)
- {
- if (e == null)
- {
- e = new SocketAsyncEventArgs();
- e.Completed += AcceptCompleted;
- }
- else
- {
- // clear the socket as we're reusing the context object
- e.AcceptSocket = null;
- }
-
- // only accept new connections while we are started
- if (IsStarted)
- {
- try
- {
- if (!_listener.AcceptAsync(e))
- {
- AcceptCompleted(null, e);
- }
- }
- catch (ObjectDisposedException)
- {
- if (_status == ForwardedPortStatus.Stopped || _status == ForwardedPortStatus.Stopped)
- {
- // ignore ObjectDisposedException while stopping or stopped
- return;
- }
-
- throw;
- }
- }
- }
-
- private void AcceptCompleted(object sender, SocketAsyncEventArgs e)
- {
- if (e.SocketError == SocketError.OperationAborted || e.SocketError == SocketError.NotSocket)
- {
- // server was stopped
- return;
- }
-
- // capture client socket
- var clientSocket = e.AcceptSocket;
-
- if (e.SocketError != SocketError.Success)
- {
- // accept new connection
- StartAccept(e);
- // dispose broken client socket
- CloseClientSocket(clientSocket);
- return;
- }
-
- // accept new connection
- StartAccept(e);
- // process connection
- ProcessAccept(clientSocket);
- }
-
- private void ProcessAccept(Socket clientSocket)
- {
- // close the client socket if we're no longer accepting new connections
- if (!IsStarted)
- {
- CloseClientSocket(clientSocket);
- return;
- }
-
- // capture the countdown event that we're adding a count to, as we need to make sure that we'll be signaling
- // that same instance; the instance field for the countdown event is re-initialized when the port is restarted
- // and at that time there may still be pending requests
- var pendingChannelCountdown = _pendingChannelCountdown;
-
- pendingChannelCountdown.AddCount();
-
- try
- {
- var originatorEndPoint = (IPEndPoint) clientSocket.RemoteEndPoint;
-
- RaiseRequestReceived(originatorEndPoint.Address.ToString(),
- (uint)originatorEndPoint.Port);
-
- using (var channel = Session.CreateChannelDirectTcpip())
- {
- channel.Exception += Channel_Exception;
- channel.Open(Host, Port, this, clientSocket);
- channel.Bind();
- }
- }
- catch (Exception exp)
- {
- RaiseExceptionEvent(exp);
- CloseClientSocket(clientSocket);
- }
- finally
- {
- // take into account that CountdownEvent has since been disposed; when stopping the port we
- // wait for a given time for the channels to close, but once that timeout period has elapsed
- // the CountdownEvent will be disposed
- try
- {
- pendingChannelCountdown.Signal();
- }
- catch (ObjectDisposedException)
- {
- }
- }
- }
-
- ///
- /// Initializes the .
- ///
- ///
- ///
- /// When the port is started for the first time, a is created with an initial count
- /// of 1.
- ///
- ///
- /// On subsequent (re)starts, we'll dispose the current and create a new one with
- /// initial count of 1.
- ///
- ///
- private void InitializePendingChannelCountdown()
- {
- var original = Interlocked.Exchange(ref _pendingChannelCountdown, new CountdownEvent(1));
- if (original != null)
- {
- original.Dispose();
- }
- }
-
- private static void CloseClientSocket(Socket clientSocket)
- {
- if (clientSocket.Connected)
- {
- try
- {
- clientSocket.Shutdown(SocketShutdown.Send);
- }
- catch (Exception)
- {
- // ignore exception when client socket was already closed
- }
- }
-
- clientSocket.Dispose();
- }
-
- ///
- /// Interrupts the listener, and unsubscribes from events.
- ///
- partial void StopListener()
- {
- // close listener socket
- var listener = _listener;
- if (listener != null)
- {
- listener.Dispose();
- }
-
- // unsubscribe from session events
- var session = Session;
- if (session != null)
- {
- session.ErrorOccured -= Session_ErrorOccured;
- session.Disconnected -= Session_Disconnected;
- }
- }
-
- ///
- /// Waits for pending channels to close.
- ///
- /// The maximum time to wait for the pending channels to close.
- partial void InternalStop(TimeSpan timeout)
- {
- _pendingChannelCountdown.Signal();
- if (!_pendingChannelCountdown.Wait(timeout))
- {
- // TODO: log as warning
- DiagnosticAbstraction.Log("Timeout waiting for pending channels in local forwarded port to close.");
- }
- }
-
- partial void InternalDispose(bool disposing)
- {
- if (disposing)
- {
- var listener = _listener;
- if (listener != null)
- {
- _listener = null;
- listener.Dispose();
- }
-
- var pendingRequestsCountdown = _pendingChannelCountdown;
- if (pendingRequestsCountdown != null)
- {
- _pendingChannelCountdown = null;
- pendingRequestsCountdown.Dispose();
- }
- }
- }
-
- private void Session_Disconnected(object sender, EventArgs e)
- {
- var session = Session;
- if (session != null)
- {
- StopPort(session.ConnectionInfo.Timeout);
- }
- }
-
- private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
- {
- var session = Session;
- if (session != null)
- {
- StopPort(session.ConnectionInfo.Timeout);
- }
- }
-
- private void Channel_Exception(object sender, ExceptionEventArgs e)
- {
- RaiseExceptionEvent(e.Exception);
- }
- }
-}
diff --git a/src/Renci.SshNet/ForwardedPortLocal.cs b/src/Renci.SshNet/ForwardedPortLocal.cs
index 79246bd73..72bf08dc7 100644
--- a/src/Renci.SshNet/ForwardedPortLocal.cs
+++ b/src/Renci.SshNet/ForwardedPortLocal.cs
@@ -1,14 +1,22 @@
using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+
+using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
namespace Renci.SshNet
{
///
- /// Provides functionality for local port forwarding
+ /// Provides functionality for local port forwarding.
///
- public partial class ForwardedPortLocal : ForwardedPort, IDisposable
+ public partial class ForwardedPortLocal : ForwardedPort
{
private ForwardedPortStatus _status;
+ private bool _isDisposed;
+ private Socket _listener;
+ private CountdownEvent _pendingChannelCountdown;
///
/// Gets the bound host.
@@ -34,7 +42,7 @@ public partial class ForwardedPortLocal : ForwardedPort, IDisposable
/// Gets a value indicating whether port forwarding is started.
///
///
- /// true if port forwarding is started; otherwise, false.
+ /// if port forwarding is started; otherwise, .
///
public override bool IsStarted
{
@@ -47,12 +55,9 @@ public override bool IsStarted
/// The bound port.
/// The host.
/// The port.
- /// is greater than .
- /// is null.
- /// is greater than .
- ///
- ///
- ///
+ /// is greater than .
+ /// is .
+ /// is greater than .
public ForwardedPortLocal(uint boundPort, string host, uint port)
: this(string.Empty, boundPort, host, port)
{
@@ -64,11 +69,11 @@ public ForwardedPortLocal(uint boundPort, string host, uint port)
/// The bound host.
/// The host.
/// The port.
- /// is null.
- /// is null.
- /// is greater than .
+ /// is .
+ /// is .
+ /// is greater than .
public ForwardedPortLocal(string boundHost, string host, uint port)
- : this(boundHost, 0, host, port)
+ : this(boundHost, 0, host, port)
{
}
@@ -79,17 +84,21 @@ public ForwardedPortLocal(string boundHost, string host, uint port)
/// The bound port.
/// The host.
/// The port.
- /// is null.
- /// is null.
- /// is greater than .
- /// is greater than .
+ /// is .
+ /// is .
+ /// is greater than .
+ /// is greater than .
public ForwardedPortLocal(string boundHost, uint boundPort, string host, uint port)
{
- if (boundHost == null)
- throw new ArgumentNullException("boundHost");
+ if (boundHost is null)
+ {
+ throw new ArgumentNullException(nameof(boundHost));
+ }
- if (host == null)
- throw new ArgumentNullException("host");
+ if (host is null)
+ {
+ throw new ArgumentNullException(nameof(host));
+ }
boundPort.ValidatePort("boundPort");
port.ValidatePort("port");
@@ -107,7 +116,9 @@ public ForwardedPortLocal(string boundHost, uint boundPort, string host, uint po
protected override void StartPort()
{
if (!ForwardedPortStatus.ToStarting(ref _status))
+ {
return;
+ }
try
{
@@ -128,14 +139,19 @@ protected override void StartPort()
protected override void StopPort(TimeSpan timeout)
{
if (!ForwardedPortStatus.ToStopping(ref _status))
+ {
return;
+ }
// signal existing channels that the port is closing
base.StopPort(timeout);
+
// prevent new requests from getting processed
StopListener();
+
// wait for open channels to close
InternalStop(timeout);
+
// mark port stopped
_status = ForwardedPortStatus.Stopped;
}
@@ -146,61 +162,289 @@ protected override void StopPort(TimeSpan timeout)
/// The current instance is disposed.
protected override void CheckDisposed()
{
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_isDisposed, this);
+#else
if (_isDisposed)
+ {
throw new ObjectDisposedException(GetType().FullName);
+ }
+#endif // NET7_0_OR_GREATER
}
- partial void InternalStart();
+ ///
+ /// Releases unmanaged and - optionally - managed resources.
+ ///
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
+ protected override void Dispose(bool disposing)
+ {
+ if (_isDisposed)
+ {
+ return;
+ }
+
+ base.Dispose(disposing);
+ InternalDispose(disposing);
+ _isDisposed = true;
+ }
///
- /// Interrupts the listener, and waits for the listener loop to finish.
+ /// Finalizes an instance of the class.
///
- ///
- /// When the forwarded port is stopped, then any further action is skipped.
- ///
- partial void StopListener();
+ ~ForwardedPortLocal()
+ {
+ Dispose(disposing: false);
+ }
- partial void InternalStop(TimeSpan timeout);
+ private void InternalStart()
+ {
+ var addr = DnsAbstraction.GetHostAddresses(BoundHost)[0];
+ var ep = new IPEndPoint(addr, (int) BoundPort);
- #region IDisposable Members
+ _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
+ _listener.Bind(ep);
+ _listener.Listen(5);
- private bool _isDisposed;
+ // update bound port (in case original was passed as zero)
+ BoundPort = (uint) ((IPEndPoint) _listener.LocalEndPoint).Port;
+
+ Session.ErrorOccured += Session_ErrorOccured;
+ Session.Disconnected += Session_Disconnected;
+
+ InitializePendingChannelCountdown();
+
+ // consider port started when we're listening for inbound connections
+ _status = ForwardedPortStatus.Started;
+
+ StartAccept(e: null);
+ }
+
+ private void StartAccept(SocketAsyncEventArgs e)
+ {
+ if (e is null)
+ {
+#pragma warning disable CA2000 // Dispose objects before losing scope
+ e = new SocketAsyncEventArgs();
+#pragma warning restore CA2000 // Dispose objects before losing scope
+ e.Completed += AcceptCompleted;
+ }
+ else
+ {
+ // clear the socket as we're reusing the context object
+ e.AcceptSocket = null;
+ }
+
+ // only accept new connections while we are started
+ if (IsStarted)
+ {
+ try
+ {
+ if (!_listener.AcceptAsync(e))
+ {
+ AcceptCompleted(sender: null, e);
+ }
+ }
+ catch (ObjectDisposedException)
+ {
+ if (_status == ForwardedPortStatus.Stopping || _status == ForwardedPortStatus.Stopped)
+ {
+ // ignore ObjectDisposedException while stopping or stopped
+ return;
+ }
+
+ throw;
+ }
+ }
+ }
+
+ private void AcceptCompleted(object sender, SocketAsyncEventArgs e)
+ {
+ if (e.SocketError is SocketError.OperationAborted or SocketError.NotSocket)
+ {
+ // server was stopped
+ return;
+ }
+
+ // capture client socket
+ var clientSocket = e.AcceptSocket;
+
+ if (e.SocketError != SocketError.Success)
+ {
+ // accept new connection
+ StartAccept(e);
+
+ // dispose broken client socket
+ CloseClientSocket(clientSocket);
+ return;
+ }
+
+ // accept new connection
+ StartAccept(e);
+
+ // process connection
+ ProcessAccept(clientSocket);
+ }
+
+ private void ProcessAccept(Socket clientSocket)
+ {
+ // close the client socket if we're no longer accepting new connections
+ if (!IsStarted)
+ {
+ CloseClientSocket(clientSocket);
+ return;
+ }
+
+ // capture the countdown event that we're adding a count to, as we need to make sure that we'll be signaling
+ // that same instance; the instance field for the countdown event is re-initialized when the port is restarted
+ // and at that time there may still be pending requests
+ var pendingChannelCountdown = _pendingChannelCountdown;
+
+ pendingChannelCountdown.AddCount();
+
+ try
+ {
+ var originatorEndPoint = (IPEndPoint) clientSocket.RemoteEndPoint;
+
+ RaiseRequestReceived(originatorEndPoint.Address.ToString(),
+ (uint) originatorEndPoint.Port);
+
+ using (var channel = Session.CreateChannelDirectTcpip())
+ {
+ channel.Exception += Channel_Exception;
+ channel.Open(Host, Port, this, clientSocket);
+ channel.Bind();
+ }
+ }
+ catch (Exception exp)
+ {
+ RaiseExceptionEvent(exp);
+ CloseClientSocket(clientSocket);
+ }
+ finally
+ {
+ // take into account that CountdownEvent has since been disposed; when stopping the port we
+ // wait for a given time for the channels to close, but once that timeout period has elapsed
+ // the CountdownEvent will be disposed
+ try
+ {
+ _ = pendingChannelCountdown.Signal();
+ }
+ catch (ObjectDisposedException)
+ {
+ // Ignore any ObjectDisposedException
+ }
+ }
+ }
///
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
+ /// Initializes the .
///
- public void Dispose()
+ ///
+ ///
+ /// When the port is started for the first time, a is created with an initial count
+ /// of 1.
+ ///
+ ///
+ /// On subsequent (re)starts, we'll dispose the current and create a new one with
+ /// initial count of 1.
+ ///
+ ///
+ private void InitializePendingChannelCountdown()
{
- Dispose(true);
- GC.SuppressFinalize(this);
+ var original = Interlocked.Exchange(ref _pendingChannelCountdown, new CountdownEvent(1));
+ original?.Dispose();
}
- partial void InternalDispose(bool disposing);
+ private static void CloseClientSocket(Socket clientSocket)
+ {
+ if (clientSocket.Connected)
+ {
+ try
+ {
+ clientSocket.Shutdown(SocketShutdown.Send);
+ }
+ catch (Exception)
+ {
+ // ignore exception when client socket was already closed
+ }
+ }
+
+ clientSocket.Dispose();
+ }
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Interrupts the listener, and unsubscribes from events.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
- protected override void Dispose(bool disposing)
+ private void StopListener()
{
- if (_isDisposed)
- return;
-
- base.Dispose(disposing);
- InternalDispose(disposing);
+ // close listener socket
+ _listener?.Dispose();
- _isDisposed = true;
+ // unsubscribe from session events
+ var session = Session;
+ if (session != null)
+ {
+ session.ErrorOccured -= Session_ErrorOccured;
+ session.Disconnected -= Session_Disconnected;
+ }
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Waits for pending channels to close.
///
- ~ForwardedPortLocal()
+ /// The maximum time to wait for the pending channels to close.
+ private void InternalStop(TimeSpan timeout)
+ {
+ _ = _pendingChannelCountdown.Signal();
+
+ if (!_pendingChannelCountdown.Wait(timeout))
+ {
+ // TODO: log as warning
+ DiagnosticAbstraction.Log("Timeout waiting for pending channels in local forwarded port to close.");
+ }
+ }
+
+ private void InternalDispose(bool disposing)
{
- Dispose(false);
+ if (disposing)
+ {
+ var listener = _listener;
+ if (listener is not null)
+ {
+ _listener = null;
+ listener.Dispose();
+ }
+
+ var pendingRequestsCountdown = _pendingChannelCountdown;
+ if (pendingRequestsCountdown is not null)
+ {
+ _pendingChannelCountdown = null;
+ pendingRequestsCountdown.Dispose();
+ }
+ }
+ }
+
+ private void Session_Disconnected(object sender, EventArgs e)
+ {
+ var session = Session;
+ if (session is not null)
+ {
+ StopPort(session.ConnectionInfo.Timeout);
+ }
}
- #endregion
+ private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
+ {
+ var session = Session;
+ if (session is not null)
+ {
+ StopPort(session.ConnectionInfo.Timeout);
+ }
+ }
+
+ private void Channel_Exception(object sender, ExceptionEventArgs e)
+ {
+ RaiseExceptionEvent(e.Exception);
+ }
}
}
diff --git a/src/Renci.SshNet/ForwardedPortRemote.cs b/src/Renci.SshNet/ForwardedPortRemote.cs
index b2ed15fe4..1b4a74eb4 100644
--- a/src/Renci.SshNet/ForwardedPortRemote.cs
+++ b/src/Renci.SshNet/ForwardedPortRemote.cs
@@ -1,29 +1,30 @@
using System;
-using System.Threading;
-using Renci.SshNet.Messages.Connection;
-using Renci.SshNet.Common;
using System.Globalization;
using System.Net;
+using System.Threading;
+
using Renci.SshNet.Abstractions;
+using Renci.SshNet.Common;
+using Renci.SshNet.Messages.Connection;
namespace Renci.SshNet
{
///
- /// Provides functionality for remote port forwarding
+ /// Provides functionality for remote port forwarding.
///
- public class ForwardedPortRemote : ForwardedPort, IDisposable
+ public class ForwardedPortRemote : ForwardedPort
{
private ForwardedPortStatus _status;
private bool _requestStatus;
-
- private EventWaitHandle _globalRequestResponse = new AutoResetEvent(false);
+ private EventWaitHandle _globalRequestResponse = new AutoResetEvent(initialState: false);
private CountdownEvent _pendingChannelCountdown;
+ private bool _isDisposed;
///
/// Gets a value indicating whether port forwarding is started.
///
///
- /// true if port forwarding is started; otherwise, false.
+ /// if port forwarding is started; otherwise, .
///
public override bool IsStarted
{
@@ -79,16 +80,21 @@ public string Host
/// The bound port.
/// The host address.
/// The port.
- /// is null.
- /// is null.
- /// is greater than .
- /// is greater than .
+ /// is .
+ /// is .
+ /// is greater than .
+ /// is greater than .
public ForwardedPortRemote(IPAddress boundHostAddress, uint boundPort, IPAddress hostAddress, uint port)
{
- if (boundHostAddress == null)
- throw new ArgumentNullException("boundHostAddress");
- if (hostAddress == null)
- throw new ArgumentNullException("hostAddress");
+ if (boundHostAddress is null)
+ {
+ throw new ArgumentNullException(nameof(boundHostAddress));
+ }
+
+ if (hostAddress is null)
+ {
+ throw new ArgumentNullException(nameof(hostAddress));
+ }
boundPort.ValidatePort("boundPort");
port.ValidatePort("port");
@@ -106,9 +112,6 @@ public ForwardedPortRemote(IPAddress boundHostAddress, uint boundPort, IPAddress
/// The bound port.
/// The host.
/// The port.
- ///
- ///
- ///
public ForwardedPortRemote(uint boundPort, string host, uint port)
: this(string.Empty, boundPort, host, port)
{
@@ -135,7 +138,9 @@ public ForwardedPortRemote(string boundHost, uint boundPort, string host, uint p
protected override void StartPort()
{
if (!ForwardedPortStatus.ToStarting(ref _status))
+ {
return;
+ }
InitializePendingChannelCountdown();
@@ -151,6 +156,7 @@ protected override void StartPort()
// send global request to start forwarding
Session.SendMessage(new TcpIpForwardGlobalRequestMessage(BoundHost, BoundPort));
+
// wat for response on global request to start direct tcpip
Session.WaitOnHandle(_globalRequestResponse);
@@ -183,15 +189,18 @@ protected override void StartPort()
protected override void StopPort(TimeSpan timeout)
{
if (!ForwardedPortStatus.ToStopping(ref _status))
+ {
return;
+ }
base.StopPort(timeout);
// send global request to cancel direct tcpip
Session.SendMessage(new CancelTcpIpForwardGlobalRequestMessage(BoundHost, BoundPort));
+
// wait for response on global request to cancel direct tcpip or completion of message
// listener loop (in which case response on global request can never be received)
- WaitHandle.WaitAny(new[] { _globalRequestResponse, Session.MessageListenerCompleted }, timeout);
+ _ = WaitHandle.WaitAny(new[] { _globalRequestResponse, Session.MessageListenerCompleted }, timeout);
// unsubscribe from session events as either the tcpip forward is cancelled at the
// server, or our session message loop has completed
@@ -200,8 +209,8 @@ protected override void StopPort(TimeSpan timeout)
Session.ChannelOpenReceived -= Session_ChannelOpening;
// wait for pending channels to close
- _pendingChannelCountdown.Signal();
-
+ _ = _pendingChannelCountdown.Signal();
+
if (!_pendingChannelCountdown.Wait(timeout))
{
// TODO: log as warning
@@ -217,22 +226,29 @@ protected override void StopPort(TimeSpan timeout)
/// The current instance is disposed.
protected override void CheckDisposed()
{
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_isDisposed, this);
+#else
if (_isDisposed)
+ {
throw new ObjectDisposedException(GetType().FullName);
+ }
+#endif // NET7_0_OR_GREATER
}
private void Session_ChannelOpening(object sender, MessageEventArgs e)
{
var channelOpenMessage = e.Message;
- var info = channelOpenMessage.Info as ForwardedTcpipChannelInfo;
- if (info != null)
+ if (channelOpenMessage.Info is ForwardedTcpipChannelInfo info)
{
- // Ensure this is the corresponding request
+ // Ensure this is the corresponding request
if (info.ConnectedAddress == BoundHost && info.ConnectedPort == BoundPort)
{
if (!IsStarted)
{
- Session.SendMessage(new ChannelOpenFailureMessage(channelOpenMessage.LocalChannelNumber, "", ChannelOpenFailureMessage.AdministrativelyProhibited));
+ Session.SendMessage(new ChannelOpenFailureMessage(channelOpenMessage.LocalChannelNumber,
+ string.Empty,
+ ChannelOpenFailureMessage.AdministrativelyProhibited));
return;
}
@@ -266,10 +282,11 @@ private void Session_ChannelOpening(object sender, MessageEventArgs e)
{
_requestStatus = true;
+
if (BoundPort == 0)
{
- BoundPort = (e.Message.BoundPort == null) ? 0 : e.Message.BoundPort.Value;
+ BoundPort = (e.Message.BoundPort is null) ? 0 : e.Message.BoundPort.Value;
}
- _globalRequestResponse.Set();
- }
-
- #region IDisposable Members
-
- private bool _isDisposed;
-
- ///
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- ///
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
+ _ = _globalRequestResponse.Set();
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected override void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
base.Dispose(disposing);
@@ -375,14 +379,11 @@ protected override void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~ForwardedPortRemote()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/ForwardedPortStatus.cs b/src/Renci.SshNet/ForwardedPortStatus.cs
index 7fce9ee7e..5695e28c7 100644
--- a/src/Renci.SshNet/ForwardedPortStatus.cs
+++ b/src/Renci.SshNet/ForwardedPortStatus.cs
@@ -3,44 +3,46 @@
namespace Renci.SshNet
{
- internal class ForwardedPortStatus
+ internal sealed class ForwardedPortStatus
{
- private readonly int _value;
- private readonly string _name;
-
public static readonly ForwardedPortStatus Stopped = new ForwardedPortStatus(1, "Stopped");
public static readonly ForwardedPortStatus Stopping = new ForwardedPortStatus(2, "Stopping");
public static readonly ForwardedPortStatus Started = new ForwardedPortStatus(3, "Started");
public static readonly ForwardedPortStatus Starting = new ForwardedPortStatus(4, "Starting");
+ private readonly int _value;
+ private readonly string _name;
+
private ForwardedPortStatus(int value, string name)
{
_value = value;
_name = name;
}
- public override bool Equals(object other)
+ public override bool Equals(object obj)
{
- if (ReferenceEquals(other, null))
- return false;
-
- if (ReferenceEquals(this, other))
+ if (ReferenceEquals(this, obj))
+ {
return true;
+ }
- var forwardedPortStatus = other as ForwardedPortStatus;
- if (forwardedPortStatus == null)
+ if (obj is not ForwardedPortStatus forwardedPortStatus)
+ {
return false;
+ }
return forwardedPortStatus._value == _value;
}
+#pragma warning disable S3875 // "operator==" should not be overloaded on reference types
public static bool operator ==(ForwardedPortStatus left, ForwardedPortStatus right)
+#pragma warning restore S3875 // "operator==" should not be overloaded on reference types
{
// check if lhs is null
- if (ReferenceEquals(left, null))
+ if (left is null)
{
// check if both lhs and rhs are null
- return (ReferenceEquals(right, null));
+ return right is null;
}
return left.Equals(right);
@@ -66,12 +68,12 @@ public override string ToString()
///
/// The status to transition from.
///
- /// true if has been changed to ; otherwise, false.
+ /// if has been changed to ; otherwise, .
///
/// Cannot transition to .
///
/// While a transition from to is not possible, this method will
- /// return false for any such attempts. This is related to concurrency.
+ /// return for any such attempts. This is related to concurrency.
///
public static bool ToStopping(ref ForwardedPortStatus status)
{
@@ -85,7 +87,9 @@ public static bool ToStopping(ref ForwardedPortStatus status)
// we've successfully transitioned from Started to Stopping
if (status == Stopping)
+ {
return true;
+ }
// attempt to transition from Starting to Stopping
previousStatus = Interlocked.CompareExchange(ref status, Stopping, Starting);
@@ -97,7 +101,9 @@ public static bool ToStopping(ref ForwardedPortStatus status)
// we've successfully transitioned from Starting to Stopping
if (status == Stopping)
+ {
return true;
+ }
// there's no valid transition from status to Stopping
throw new InvalidOperationException(string.Format("Forwarded port cannot transition from '{0}' to '{1}'.",
@@ -110,12 +116,12 @@ public static bool ToStopping(ref ForwardedPortStatus status)
///
/// The status to transition from.
///
- /// true if has been changed to ; otherwise, false.
+ /// if has been changed to ; otherwise, .
///
/// Cannot transition to .
///
/// While a transition from to is not possible, this method will
- /// return false for any such attempts. This is related to concurrency.
+ /// return for any such attempts. This is related to concurrency.
///
public static bool ToStarting(ref ForwardedPortStatus status)
{
@@ -129,7 +135,9 @@ public static bool ToStarting(ref ForwardedPortStatus status)
// we've successfully transitioned from Stopped to Starting
if (status == Starting)
+ {
return true;
+ }
// there's no valid transition from status to Starting
throw new InvalidOperationException(string.Format("Forwarded port cannot transition from '{0}' to '{1}'.",
diff --git a/src/Renci.SshNet/HashInfo.cs b/src/Renci.SshNet/HashInfo.cs
index 156c8456b..cbbbf5fe7 100644
--- a/src/Renci.SshNet/HashInfo.cs
+++ b/src/Renci.SshNet/HashInfo.cs
@@ -5,7 +5,7 @@
namespace Renci.SshNet
{
///
- /// Holds information about key size and cipher to use
+ /// Holds information about key size and cipher to use.
///
public class HashInfo
{
@@ -23,14 +23,14 @@ public class HashInfo
public Func HashAlgorithm { get; private set; }
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// Size of the key.
/// The hash algorithm to use for a given key.
public HashInfo(int keySize, Func hash)
{
KeySize = keySize;
- HashAlgorithm = key => (hash(key.Take(KeySize / 8)));
+ HashAlgorithm = key => hash(key.Take(KeySize / 8));
}
}
}
diff --git a/src/Renci.SshNet/IBaseClient.cs b/src/Renci.SshNet/IBaseClient.cs
new file mode 100644
index 000000000..c42df3426
--- /dev/null
+++ b/src/Renci.SshNet/IBaseClient.cs
@@ -0,0 +1,94 @@
+using System;
+using System.Net.Sockets;
+using System.Threading;
+using System.Threading.Tasks;
+
+using Renci.SshNet.Common;
+
+namespace Renci.SshNet
+{
+ ///
+ /// Serves as base class for client implementations, provides common client functionality.
+ ///
+ public interface IBaseClient : IDisposable
+ {
+ ///
+ /// Gets the connection info.
+ ///
+ ///
+ /// The connection info.
+ ///
+ /// The method was called after the client was disposed.
+ ConnectionInfo ConnectionInfo { get; }
+
+ ///
+ /// Gets a value indicating whether this client is connected to the server.
+ ///
+ ///
+ /// if this client is connected; otherwise, .
+ ///
+ /// The method was called after the client was disposed.
+ bool IsConnected { get; }
+
+ ///
+ /// Gets or sets the keep-alive interval.
+ ///
+ ///
+ /// The keep-alive interval. Specify negative one (-1) milliseconds to disable the
+ /// keep-alive. This is the default value.
+ ///
+ /// The method was called after the client was disposed.
+ TimeSpan KeepAliveInterval { get; set; }
+
+ ///
+ /// Occurs when an error occurred.
+ ///
+ event EventHandler ErrorOccurred;
+
+ ///
+ /// Occurs when host key received.
+ ///
+ event EventHandler HostKeyReceived;
+
+ ///
+ /// Connects client to the server.
+ ///
+ /// The client is already connected.
+ /// The method was called after the client was disposed.
+ /// Socket connection to the SSH server or proxy server could not be established, or an error occurred while resolving the hostname.
+ /// SSH session could not be established.
+ /// Authentication of SSH session failed.
+ /// Failed to establish proxy connection.
+ void Connect();
+
+ ///
+ /// Asynchronously connects client to the server.
+ ///
+ /// The to observe.
+ /// A that represents the asynchronous connect operation.
+ ///
+ /// The client is already connected.
+ /// The method was called after the client was disposed.
+ /// Socket connection to the SSH server or proxy server could not be established, or an error occurred while resolving the hostname.
+ /// SSH session could not be established.
+ /// Authentication of SSH session failed.
+ /// Failed to establish proxy connection.
+ Task ConnectAsync(CancellationToken cancellationToken);
+
+ ///
+ /// Disconnects client from the server.
+ ///
+ /// The method was called after the client was disposed.
+ void Disconnect();
+
+ ///
+ /// Sends a keep-alive message to the server.
+ ///
+ ///
+ /// Use to configure the client to send a keep-alive at regular
+ /// intervals.
+ ///
+ /// The method was called after the client was disposed.
+ void SendKeepAlive();
+ }
+}
diff --git a/src/Renci.SshNet/IClientAuthentication.cs b/src/Renci.SshNet/IClientAuthentication.cs
index 5dbfccc3e..15124fc79 100644
--- a/src/Renci.SshNet/IClientAuthentication.cs
+++ b/src/Renci.SshNet/IClientAuthentication.cs
@@ -1,7 +1,23 @@
-namespace Renci.SshNet
+using System;
+
+using Renci.SshNet.Common;
+
+namespace Renci.SshNet
{
+ ///
+ /// Represents a mechanism to authenticate a given client.
+ ///
internal interface IClientAuthentication
{
+ ///
+ /// Attempts to perform authentication for a given using the
+ /// of the specified
+ /// .
+ ///
+ /// A to use for authenticating.
+ /// The for which to perform authentication.
+ /// or is .
+ /// Failed to Authenticate the client.
void Authenticate(IConnectionInfoInternal connectionInfo, ISession session);
}
}
diff --git a/src/Renci.SshNet/IConnectionInfo.cs b/src/Renci.SshNet/IConnectionInfo.cs
index 22abefda2..35dabcc2f 100644
--- a/src/Renci.SshNet/IConnectionInfo.cs
+++ b/src/Renci.SshNet/IConnectionInfo.cs
@@ -1,47 +1,19 @@
using System;
using System.Collections.Generic;
using System.Text;
+
using Renci.SshNet.Common;
-using Renci.SshNet.Messages.Authentication;
using Renci.SshNet.Messages.Connection;
namespace Renci.SshNet
{
- internal interface IConnectionInfoInternal : IConnectionInfo
- {
- ///
- /// Signals that an authentication banner message was received from the server.
- ///
- /// The session in which the banner message was received.
- /// The banner message.{
- void UserAuthenticationBannerReceived(object sender, MessageEventArgs e);
-
- ///
- /// Gets the supported authentication methods for this connection.
- ///
- ///
- /// The supported authentication methods for this connection.
- ///
- IList AuthenticationMethods { get; }
-
- ///
- /// Creates a for the credentials represented
- /// by the current .
- ///
- ///
- /// A for the credentials represented by the
- /// current .
- ///
- IAuthenticationMethod CreateNoneAuthenticationMethod();
- }
-
///
/// Represents remote connection information.
///
internal interface IConnectionInfo
{
///
- /// Gets or sets the timeout to used when waiting for a server to acknowledge closing a channel.
+ /// Gets the timeout to used when waiting for a server to acknowledge closing a channel.
///
///
/// The channel close timeout. The default value is 1 second.
@@ -121,14 +93,11 @@ internal interface IConnectionInfo
int RetryAttempts { get; }
///
- /// Gets or sets connection timeout.
+ /// Gets the connection timeout.
///
///
/// The connection timeout. The default value is 30 seconds.
///
- ///
- ///
- ///
TimeSpan Timeout { get; }
///
diff --git a/src/Renci.SshNet/IConnectionInfoInternal.cs b/src/Renci.SshNet/IConnectionInfoInternal.cs
new file mode 100644
index 000000000..053e36dda
--- /dev/null
+++ b/src/Renci.SshNet/IConnectionInfoInternal.cs
@@ -0,0 +1,37 @@
+using System.Collections.Generic;
+
+using Renci.SshNet.Messages.Authentication;
+
+namespace Renci.SshNet
+{
+ ///
+ /// Represents remote connection information.
+ ///
+ internal interface IConnectionInfoInternal : IConnectionInfo
+ {
+ ///
+ /// Signals that an authentication banner message was received from the server.
+ ///
+ /// The session in which the banner message was received.
+ /// The banner message.
+ void UserAuthenticationBannerReceived(object sender, MessageEventArgs e);
+
+ ///
+ /// Gets the supported authentication methods for this connection.
+ ///
+ ///
+ /// The supported authentication methods for this connection.
+ ///
+ IList AuthenticationMethods { get; }
+
+ ///
+ /// Creates a for the credentials represented
+ /// by the current .
+ ///
+ ///
+ /// A for the credentials represented by the
+ /// current .
+ ///
+ IAuthenticationMethod CreateNoneAuthenticationMethod();
+ }
+}
diff --git a/src/Renci.SshNet/IForwardedPort.cs b/src/Renci.SshNet/IForwardedPort.cs
index e9a2bd56b..92e49ee3b 100644
--- a/src/Renci.SshNet/IForwardedPort.cs
+++ b/src/Renci.SshNet/IForwardedPort.cs
@@ -5,7 +5,7 @@ namespace Renci.SshNet
///
/// Supports port forwarding functionality.
///
- public interface IForwardedPort
+ public interface IForwardedPort : IDisposable
{
///
/// The event occurs as the forwarded port is being stopped.
diff --git a/src/Renci.SshNet/IPrivateKeySource.cs b/src/Renci.SshNet/IPrivateKeySource.cs
new file mode 100644
index 000000000..96ab4574f
--- /dev/null
+++ b/src/Renci.SshNet/IPrivateKeySource.cs
@@ -0,0 +1,21 @@
+using System.Collections.Generic;
+
+using Renci.SshNet.Security;
+
+namespace Renci.SshNet
+{
+ ///
+ /// Represents private key source interface.
+ ///
+ public interface IPrivateKeySource
+ {
+ ///
+ /// Gets the host keys algorithms.
+ ///
+ ///
+ /// In situations where there is a preferred order of usage of the host algorithms,
+ /// the collection should be ordered from most preferred to least.
+ ///
+ IReadOnlyCollection HostKeyAlgorithms { get; }
+ }
+}
diff --git a/src/Renci.SshNet/IRemotePathTransformation.cs b/src/Renci.SshNet/IRemotePathTransformation.cs
index 30c52421c..d139db5db 100644
--- a/src/Renci.SshNet/IRemotePathTransformation.cs
+++ b/src/Renci.SshNet/IRemotePathTransformation.cs
@@ -14,6 +14,4 @@ public interface IRemotePathTransformation
///
string Transform(string path);
}
-
-
}
diff --git a/src/Renci.SshNet/IServiceFactory.NET.cs b/src/Renci.SshNet/IServiceFactory.NET.cs
deleted file mode 100644
index 0a86e08eb..000000000
--- a/src/Renci.SshNet/IServiceFactory.NET.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-using Renci.SshNet.NetConf;
-
-namespace Renci.SshNet
-{
- internal partial interface IServiceFactory
- {
- ///
- /// Creates a new in a given
- /// and with the specified operation timeout.
- ///
- /// The to create the in.
- /// The number of milliseconds to wait for an operation to complete, or -1 to wait indefinitely.
- ///
- /// An .
- ///
- INetConfSession CreateNetConfSession(ISession session, int operationTimeout);
- }
-}
diff --git a/src/Renci.SshNet/IServiceFactory.cs b/src/Renci.SshNet/IServiceFactory.cs
index dad93e237..8b2c8650b 100644
--- a/src/Renci.SshNet/IServiceFactory.cs
+++ b/src/Renci.SshNet/IServiceFactory.cs
@@ -2,8 +2,10 @@
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
+
using Renci.SshNet.Common;
using Renci.SshNet.Connection;
+using Renci.SshNet.NetConf;
using Renci.SshNet.Security;
using Renci.SshNet.Sftp;
@@ -14,8 +16,25 @@ namespace Renci.SshNet
///
internal partial interface IServiceFactory
{
+ ///
+ /// Creates an .
+ ///
+ ///
+ /// An .
+ ///
IClientAuthentication CreateClientAuthentication();
+ ///
+ /// Creates a new in a given
+ /// and with the specified operation timeout.
+ ///
+ /// The to create the in.
+ /// The number of milliseconds to wait for an operation to complete, or -1 to wait indefinitely.
+ ///
+ /// An .
+ ///
+ INetConfSession CreateNetConfSession(ISession session, int operationTimeout);
+
///
/// Creates a new with the specified and
/// .
@@ -25,8 +44,8 @@ internal partial interface IServiceFactory
///
/// An for the specified .
///
- /// is null.
- /// is null.
+ /// is .
+ /// is .
ISession CreateSession(ConnectionInfo connectionInfo, ISocketFactory socketFactory);
///
@@ -34,7 +53,7 @@ internal partial interface IServiceFactory
/// the specified operation timeout and encoding.
///
/// The to create the in.
- /// The number of milliseconds to wait for an operation to complete, or -1 to wait indefinitely.
+ /// The number of milliseconds to wait for an operation to complete, or -1 to wait indefinitely.
/// The encoding.
/// The factory to use for creating SFTP messages.
///
@@ -59,13 +78,29 @@ internal partial interface IServiceFactory
///
/// A that was negotiated between client and server.
///
- /// is null.
- /// is null.
+ /// is .
+ /// is .
/// No key exchange algorithm is supported by both client and server.
IKeyExchange CreateKeyExchange(IDictionary clientAlgorithms, string[] serverAlgorithms);
+ ///
+ /// Creates an for the specified file and with the specified
+ /// buffer size.
+ ///
+ /// The file to read.
+ /// The SFTP session to use.
+ /// The size of buffer.
+ ///
+ /// An .
+ ///
ISftpFileReader CreateSftpFileReader(string fileName, ISftpSession sftpSession, uint bufferSize);
+ ///
+ /// Creates a new instance.
+ ///
+ ///
+ /// An .
+ ///
ISftpResponseFactory CreateSftpResponseFactory();
///
@@ -75,10 +110,10 @@ internal partial interface IServiceFactory
/// The TERM environment variable.
/// The terminal width in columns.
/// The terminal width in rows.
- /// The terminal height in pixels.
+ /// The terminal width in pixels.
/// The terminal height in pixels.
- /// Size of the buffer.
/// The terminal mode values.
+ /// Size of the buffer.
///
/// The created instance.
///
diff --git a/src/Renci.SshNet/ISession.cs b/src/Renci.SshNet/ISession.cs
index cd950da52..707d36805 100644
--- a/src/Renci.SshNet/ISession.cs
+++ b/src/Renci.SshNet/ISession.cs
@@ -1,6 +1,8 @@
using System;
using System.Net.Sockets;
using System.Threading;
+using System.Threading.Tasks;
+
using Renci.SshNet.Channels;
using Renci.SshNet.Common;
using Renci.SshNet.Messages;
@@ -15,7 +17,7 @@ namespace Renci.SshNet
internal interface ISession : IDisposable
{
///
- /// Gets or sets the connection info.
+ /// Gets the connection info.
///
/// The connection info.
IConnectionInfo ConnectionInfo { get; }
@@ -24,7 +26,7 @@ internal interface ISession : IDisposable
/// Gets a value indicating whether the session is connected.
///
///
- /// true if the session is connected; otherwise, false.
+ /// if the session is connected; otherwise, .
///
bool IsConnected { get; }
@@ -34,14 +36,14 @@ internal interface ISession : IDisposable
///
/// The session semaphore.
///
- SemaphoreLight SessionSemaphore { get; }
+ SemaphoreSlim SessionSemaphore { get; }
///
/// Gets a that can be used to wait for the message listener loop to complete.
///
///
/// A that can be used to wait for the message listener loop to complete, or
- /// null when the session has not been connected.
+ /// when the session has not been connected.
///
WaitHandle MessageListenerCompleted { get; }
@@ -54,6 +56,17 @@ internal interface ISession : IDisposable
/// Failed to establish proxy connection.
void Connect();
+ ///
+ /// Asynchronously connects to the server.
+ ///
+ /// The to observe.
+ /// A that represents the asynchronous connect operation.
+ /// Socket connection to the SSH server or proxy server could not be established, or an error occurred while resolving the hostname.
+ /// SSH session could not be established.
+ /// Authentication of SSH session failed.
+ /// Failed to establish proxy connection.
+ Task ConnectAsync(CancellationToken cancellationToken);
+
///
/// Create a new SSH session channel.
///
@@ -73,6 +86,9 @@ internal interface ISession : IDisposable
///
/// Creates a "forwarded-tcpip" SSH channel.
///
+ /// The number of the remote channel.
+ /// The window size of the remote channel.
+ /// The data packet size of the remote channel.
///
/// A new "forwarded-tcpip" SSH channel.
///
@@ -112,11 +128,11 @@ internal interface ISession : IDisposable
///
/// The message to send.
///
- /// true if the message was sent to the server; otherwise, false.
+ /// if the message was sent to the server; otherwise, .
///
/// The size of the packet exceeds the maximum size defined by the protocol.
///
- /// This methods returns false when the attempt to send the message results in a
+ /// This methods returns when the attempt to send the message results in a
/// or a .
///
bool TrySendMessage(Message message);
@@ -244,6 +260,11 @@ internal interface ISession : IDisposable
///
event EventHandler ErrorOccured;
+ ///
+ /// Occurs when server identification received.
+ ///
+ event EventHandler ServerIdentificationReceived;
+
///
/// Occurs when host key received.
///
diff --git a/src/Renci.SshNet/ISftpClient.cs b/src/Renci.SshNet/ISftpClient.cs
index b1212cfea..efbce934a 100644
--- a/src/Renci.SshNet/ISftpClient.cs
+++ b/src/Renci.SshNet/ISftpClient.cs
@@ -2,15 +2,18 @@
using System.Collections.Generic;
using System.IO;
using System.Text;
-using Renci.SshNet.Sftp;
+using System.Threading;
+using System.Threading.Tasks;
+
using Renci.SshNet.Common;
+using Renci.SshNet.Sftp;
namespace Renci.SshNet
{
///
/// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
///
- public interface ISftpClient
+ public interface ISftpClient : IBaseClient
{
///
/// Gets or sets the maximum size of the buffer in bytes.
@@ -37,7 +40,7 @@ public interface ISftpClient
/// SSH_FXP_DATA protocol fields.
///
///
- /// The size of the each indivual SSH_FXP_DATA message is limited to the
+ /// The size of the each individual SSH_FXP_DATA message is limited to the
/// local maximum packet size of the channel, which is set to 64 KB
/// for SSH.NET. However, the peer can limit this even further.
///
@@ -53,7 +56,7 @@ public interface ISftpClient
/// one (-1) milliseconds, which indicates an infinite timeout period.
///
/// The method was called after the client was disposed.
- /// represents a value that is less than -1 or greater than milliseconds.
+ /// represents a value that is less than -1 or greater than milliseconds.
TimeSpan OperationTimeout { get; set; }
///
@@ -75,12 +78,12 @@ public interface ISftpClient
///
/// The file to append the lines to. The file is created if it does not already exist.
/// The lines to append to the file.
- /// isnull -or- is null.
+ /// is . -or- is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
///
- /// The characters are written to the file using UTF-8 encoding without a Byte-Order Mark (BOM)
+ /// The characters are written to the file using UTF-8 encoding without a Byte-Order Mark (BOM).
///
void AppendAllLines(string path, IEnumerable contents);
@@ -90,7 +93,7 @@ public interface ISftpClient
/// The file to append the lines to. The file is created if it does not already exist.
/// The lines to append to the file.
/// The character encoding to use.
- /// is null. -or- is null. -or- is null.
+ /// is . -or- is . -or- is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -101,7 +104,7 @@ public interface ISftpClient
///
/// The file to append the specified string to.
/// The string to append to the file.
- /// is null. -or- is null.
+ /// is . -or- is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -116,7 +119,7 @@ public interface ISftpClient
/// The file to append the specified string to.
/// The string to append to the file.
/// The character encoding to use.
- /// is null. -or- is null. -or- is null.
+ /// is . -or- is . -or- is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -131,7 +134,7 @@ public interface ISftpClient
/// A that appends text to a file using UTF-8 encoding without a
/// Byte-Order Mark (BOM).
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -146,7 +149,7 @@ public interface ISftpClient
///
/// A that appends text to a file using the specified encoding.
///
- /// is null. -or- is null.
+ /// is . -or- is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -160,8 +163,8 @@ public interface ISftpClient
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to perform the operation was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -180,8 +183,8 @@ public interface ISftpClient
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to perform the operation was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -202,8 +205,8 @@ public interface ISftpClient
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// The method was called after the client was disposed.
///
/// Method calls made by this method to , may under certain conditions result in exceptions thrown by the stream.
@@ -234,8 +237,9 @@ public interface ISftpClient
///
/// An that represents the asynchronous directory synchronization.
///
- /// is null.
- /// is null or contains only whitespace.
+ /// is .
+ /// is or contains only whitespace.
+ /// If a problem occurs while copying the file.
IAsyncResult BeginSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, AsyncCallback asyncCallback, object state);
///
@@ -246,8 +250,8 @@ public interface ISftpClient
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to list the contents of the directory was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -271,8 +275,8 @@ public interface ISftpClient
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to list the contents of the directory was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -298,8 +302,8 @@ public interface ISftpClient
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to list the contents of the directory was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -326,16 +330,16 @@ public interface ISftpClient
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// The method was called after the client was disposed.
///
///
/// Method calls made by this method to , may under certain conditions result in exceptions thrown by the stream.
///
///
- /// When refers to an existing file, set to true to overwrite and truncate that file.
- /// If is false, the upload will fail and will throw an
+ /// When refers to an existing file, set to to overwrite and truncate that file.
+ /// If is , the upload will fail and will throw an
/// .
///
///
@@ -345,7 +349,7 @@ public interface ISftpClient
/// Changes remote directory to path.
///
/// New directory path.
- /// is null.
+ /// is .
/// Client is not connected.
/// Permission to change directory denied by remote host. -or- A SSH command was denied by the server.
/// was not found on the remote host.
@@ -358,7 +362,7 @@ public interface ISftpClient
///
/// File(s) path, may match multiple files.
/// The mode.
- /// is null.
+ /// is .
/// Client is not connected.
/// Permission to change permission on the path(s) was denied by the remote host. -or- A SSH command was denied by the server.
/// was not found on the remote host.
@@ -373,7 +377,7 @@ public interface ISftpClient
///
/// A that provides read/write access to the file specified in path.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -390,7 +394,7 @@ public interface ISftpClient
///
/// A that provides read/write access to the file specified in path.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -403,7 +407,7 @@ public interface ISftpClient
/// Creates remote directory specified by path.
///
/// Directory path to create.
- /// is null or contains only whitespace characters.
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to create the directory was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -418,7 +422,7 @@ public interface ISftpClient
/// A that writes text to a file using UTF-8 encoding without
/// a Byte-Order Mark (BOM).
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -440,7 +444,7 @@ public interface ISftpClient
///
/// A that writes to a file using the specified encoding.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -458,7 +462,7 @@ public interface ISftpClient
/// Deletes the specified file or directory.
///
/// The name of the file or directory to be deleted. Wildcard characters are not supported.
- /// is null.
+ /// is .
/// Client is not connected.
/// was not found on the remote host.
/// The method was called after the client was disposed.
@@ -468,7 +472,7 @@ public interface ISftpClient
/// Deletes remote directory specified by path.
///
/// Directory to be deleted path.
- /// is null or contains only whitespace characters.
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// was not found on the remote host.
/// Permission to delete the directory was denied by the remote host. -or- A SSH command was denied by the server.
@@ -480,7 +484,7 @@ public interface ISftpClient
/// Deletes remote file specified by path.
///
/// File to be deleted path.
- /// is null or contains only whitespace characters.
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// was not found on the remote host.
/// Permission to delete the file was denied by the remote host. -or- A SSH command was denied by the server.
@@ -488,17 +492,31 @@ public interface ISftpClient
/// The method was called after the client was disposed.
void DeleteFile(string path);
+ ///
+ /// Asynchronously deletes remote file specified by path.
+ ///
+ /// File to be deleted path.
+ /// The to observe.
+ /// A that represents the asynchronous delete operation.
+ /// is or contains only whitespace characters.
+ /// Client is not connected.
+ /// was not found on the remote host.
+ /// Permission to delete the file was denied by the remote host. -or- A SSH command was denied by the server.
+ /// A SSH error where is the message from the remote host.
+ /// The method was called after the client was disposed.
+ Task DeleteFileAsync(string path, CancellationToken cancellationToken);
+
///
/// Downloads remote file specified by the path into the stream.
///
/// File to download.
/// Stream to write the file into.
/// The download callback.
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to perform the operation was denied by the remote host. -or- A SSH command was denied by the server.
- /// was not found on the remote host.///
+ /// was not found on the remote host.///
/// A SSH error where is the message from the remote host.
/// The method was called after the client was disposed.
///
@@ -510,7 +528,7 @@ public interface ISftpClient
/// Ends an asynchronous file downloading into the stream.
///
/// The pending asynchronous SFTP request.
- /// The object did not come from the corresponding async method on this type.-or- was called multiple times with the same .
+ /// The object did not come from the corresponding async method on this type.-or- was called multiple times with the same .
/// Client is not connected.
/// Permission to perform the operation was denied by the remote host. -or- A SSH command was denied by the server.
/// The path was not found on the remote host.
@@ -524,8 +542,8 @@ public interface ISftpClient
///
/// A list of files.
///
- /// The object did not come from the corresponding async method on this type.-or- was called multiple times with the same .
- IEnumerable EndListDirectory(IAsyncResult asyncResult);
+ /// The object did not come from the corresponding async method on this type.-or- was called multiple times with the same .
+ IEnumerable EndListDirectory(IAsyncResult asyncResult);
///
/// Ends the synchronize directories.
@@ -534,7 +552,7 @@ public interface ISftpClient
///
/// A list of uploaded files.
///
- /// The object did not come from the corresponding async method on this type.-or- was called multiple times with the same .
+ /// The object did not come from the corresponding async method on this type.-or- was called multiple times with the same .
/// The destination path was not found on the remote host.
IEnumerable EndSynchronizeDirectories(IAsyncResult asyncResult);
@@ -542,7 +560,7 @@ public interface ISftpClient
/// Ends an asynchronous uploading the stream into remote file.
///
/// The pending asynchronous SFTP request.
- /// The object did not come from the corresponding async method on this type.-or- was called multiple times with the same .
+ /// The object did not come from the corresponding async method on this type.-or- was called multiple times with the same .
/// Client is not connected.
/// The directory of the file was not found on the remote host.
/// Permission to upload the file was denied by the remote host. -or- A SSH command was denied by the server.
@@ -550,13 +568,13 @@ public interface ISftpClient
void EndUploadFile(IAsyncResult asyncResult);
///
- /// Checks whether file or directory exists;
+ /// Checks whether file or directory exists.
///
/// The path.
///
- /// true if directory or file exists; otherwise false.
+ /// if directory or file exists; otherwise .
///
- /// is null or contains only whitespace characters.
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to perform the operation was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -568,13 +586,15 @@ public interface ISftpClient
///
/// The path.
///
- /// A reference to file object.
+ /// A reference to file object.
///
/// Client is not connected.
/// was not found on the remote host.
- /// is null.
+ /// is .
/// The method was called after the client was disposed.
- SftpFile Get(string path);
+#pragma warning disable CA1716 // Identifiers should not match keywords
+ ISftpFile Get(string path);
+#pragma warning restore CA1716 // Identifiers should not match keywords
///
/// Gets the of the file on the path.
@@ -583,7 +603,7 @@ public interface ISftpClient
///
/// The of the file on the path.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// was not found on the remote host.
/// The method was called after the client was disposed.
@@ -597,7 +617,7 @@ public interface ISftpClient
/// A structure set to the date and time that the specified file or directory was last accessed.
/// This value is expressed in local time.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
DateTime GetLastAccessTime(string path);
@@ -610,7 +630,7 @@ public interface ISftpClient
/// A structure set to the date and time that the specified file or directory was last accessed.
/// This value is expressed in UTC time.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
DateTime GetLastAccessTimeUtc(string path);
@@ -623,7 +643,7 @@ public interface ISftpClient
/// A structure set to the date and time that the specified file or directory was last written to.
/// This value is expressed in local time.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
DateTime GetLastWriteTime(string path);
@@ -636,7 +656,7 @@ public interface ISftpClient
/// A structure set to the date and time that the specified file or directory was last written to.
/// This value is expressed in UTC time.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
DateTime GetLastWriteTimeUtc(string path);
@@ -649,10 +669,24 @@ public interface ISftpClient
/// A instance that contains file status information.
///
/// Client is not connected.
- /// is null.
+ /// is .
/// The method was called after the client was disposed.
SftpFileSytemInformation GetStatus(string path);
+ ///
+ /// Asynchronously gets status using statvfs@openssh.com request.
+ ///
+ /// The path.
+ /// The to observe.
+ ///
+ /// A that represents the status operation.
+ /// The task result contains the instance that contains file status information.
+ ///
+ /// Client is not connected.
+ /// is .
+ /// The method was called after the client was disposed.
+ Task GetStatusAsync(string path, CancellationToken cancellationToken);
+
///
/// Retrieves list of files in remote directory.
///
@@ -661,12 +695,28 @@ public interface ISftpClient
///
/// A list of files.
///
- /// is null.
+ /// is .
+ /// Client is not connected.
+ /// Permission to list the contents of the directory was denied by the remote host. -or- A SSH command was denied by the server.
+ /// A SSH error where is the message from the remote host.
+ /// The method was called after the client was disposed.
+ IEnumerable ListDirectory(string path, Action listCallback = null);
+
+ ///
+ /// Asynchronously enumerates the files in remote directory.
+ ///
+ /// The path.
+ /// The to observe.
+ ///
+ /// An of that represents the asynchronous enumeration operation.
+ /// The enumeration contains an async stream of for the files in the directory specified by .
+ ///
+ /// is .
/// Client is not connected.
/// Permission to list the contents of the directory was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
/// The method was called after the client was disposed.
- IEnumerable ListDirectory(string path, Action listCallback = null);
+ IAsyncEnumerable ListDirectoryAsync(string path, CancellationToken cancellationToken);
///
/// Opens a on the specified path with read/write access.
@@ -676,7 +726,7 @@ public interface ISftpClient
///
/// An unshared that provides access to the specified file, with the specified mode and read/write access.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
SftpFileStream Open(string path, FileMode mode);
@@ -690,11 +740,27 @@ public interface ISftpClient
///
/// An unshared that provides access to the specified file, with the specified mode and access.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
SftpFileStream Open(string path, FileMode mode, FileAccess access);
+ ///
+ /// Asynchronously opens a on the specified path, with the specified mode and access.
+ ///
+ /// The file to open.
+ /// A value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.
+ /// A value that specifies the operations that can be performed on the file.
+ /// The to observe.
+ ///
+ /// A that represents the asynchronous open operation.
+ /// The task result contains the that provides access to the specified file, with the specified mode and access.
+ ///
+ /// is .
+ /// Client is not connected.
+ /// The method was called after the client was disposed.
+ Task OpenAsync(string path, FileMode mode, FileAccess access, CancellationToken cancellationToken);
+
///
/// Opens an existing file for reading.
///
@@ -702,7 +768,7 @@ public interface ISftpClient
///
/// A read-only on the specified path.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
SftpFileStream OpenRead(string path);
@@ -714,7 +780,7 @@ public interface ISftpClient
///
/// A on the specified path.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
StreamReader OpenText(string path);
@@ -726,7 +792,7 @@ public interface ISftpClient
///
/// An unshared object on the specified path with access.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
///
@@ -741,7 +807,7 @@ public interface ISftpClient
///
/// A byte array containing the contents of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
byte[] ReadAllBytes(string path);
@@ -753,7 +819,7 @@ public interface ISftpClient
///
/// A string array containing all lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
string[] ReadAllLines(string path);
@@ -766,7 +832,7 @@ public interface ISftpClient
///
/// A string array containing all lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
string[] ReadAllLines(string path, Encoding encoding);
@@ -778,7 +844,7 @@ public interface ISftpClient
///
/// A string containing all lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
string ReadAllText(string path);
@@ -791,7 +857,7 @@ public interface ISftpClient
///
/// A string containing all lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
string ReadAllText(string path, Encoding encoding);
@@ -803,7 +869,7 @@ public interface ISftpClient
///
/// The lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
IEnumerable ReadLines(string path);
@@ -816,7 +882,7 @@ public interface ISftpClient
///
/// The lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
IEnumerable ReadLines(string path, Encoding encoding);
@@ -826,7 +892,7 @@ public interface ISftpClient
///
/// Path to the old file location.
/// Path to the new file location.
- /// is null. -or- or is null.
+ /// is . -or- or is .
/// Client is not connected.
/// Permission to rename the file was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -838,20 +904,62 @@ public interface ISftpClient
///
/// Path to the old file location.
/// Path to the new file location.
- /// if set to true then perform a posix rename.
- /// is null. -or- or is null.
+ /// if set to then perform a posix rename.
+ /// is . -or- or is .
/// Client is not connected.
/// Permission to rename the file was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
/// The method was called after the client was disposed.
void RenameFile(string oldPath, string newPath, bool isPosix);
+ ///
+ /// Asynchronously renames remote file from old path to new path.
+ ///
+ /// Path to the old file location.
+ /// Path to the new file location.
+ /// The to observe.
+ /// A that represents the asynchronous rename operation.
+ /// is . -or- or is .
+ /// Client is not connected.
+ /// Permission to rename the file was denied by the remote host. -or- A SSH command was denied by the server.
+ /// A SSH error where is the message from the remote host.
+ /// The method was called after the client was disposed.
+ Task RenameFileAsync(string oldPath, string newPath, CancellationToken cancellationToken);
+
+ ///
+ /// Sets the date and time the specified file was last accessed.
+ ///
+ /// The file for which to set the access date and time information.
+ /// A containing the value to set for the last access date and time of path. This value is expressed in local time.
+ void SetLastAccessTime(string path, DateTime lastAccessTime);
+
+ ///
+ /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed.
+ ///
+ /// The file for which to set the access date and time information.
+ /// A containing the value to set for the last access date and time of path. This value is expressed in UTC time.
+ void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc);
+
+ ///
+ /// Sets the date and time that the specified file was last written to.
+ ///
+ /// The file for which to set the date and time information.
+ /// A containing the value to set for the last write date and time of path. This value is expressed in local time.
+ void SetLastWriteTime(string path, DateTime lastWriteTime);
+
+ ///
+ /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to.
+ ///
+ /// The file for which to set the date and time information.
+ /// A containing the value to set for the last write date and time of path. This value is expressed in UTC time.
+ void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc);
+
///
/// Sets the specified of the file on the specified path.
///
/// The path to the file.
/// The desired .
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
void SetAttributes(string path, SftpFileAttributes fileAttributes);
@@ -861,7 +969,7 @@ public interface ISftpClient
///
/// The old path.
/// The new path.
- /// is null. -or- is null or contains only whitespace characters.
+ /// is . -or- is or contains only whitespace characters.
/// Client is not connected.
/// Permission to create the symbolic link was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -877,9 +985,10 @@ public interface ISftpClient
///
/// A list of uploaded files.
///
- /// is null.
- /// is null or contains only whitespace.
+ /// is .
+ /// is or contains only whitespace.
/// was not found on the remote host.
+ /// If a problem occurs while copying the file.
IEnumerable SynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern);
///
@@ -888,8 +997,8 @@ public interface ISftpClient
/// Data input stream.
/// Remote file path.
/// The upload callback.
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to upload the file was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -904,10 +1013,10 @@ public interface ISftpClient
///
/// Data input stream.
/// Remote file path.
- /// if set to true then existing file will be overwritten.
+ /// if set to then existing file will be overwritten.
/// The upload callback.
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to upload the file was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -922,7 +1031,7 @@ public interface ISftpClient
///
/// The file to write to.
/// The bytes to write to the file.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -941,7 +1050,7 @@ public interface ISftpClient
///
/// The file to write to.
/// The lines to write to the file.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -964,7 +1073,7 @@ public interface ISftpClient
/// The file to write to.
/// The lines to write to the file.
/// The character encoding to use.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -983,7 +1092,7 @@ public interface ISftpClient
///
/// The file to write to.
/// The string array to write to the file.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1006,7 +1115,7 @@ public interface ISftpClient
/// The file to write to.
/// The string array to write to the file.
/// An object that represents the character encoding applied to the string array.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1025,7 +1134,7 @@ public interface ISftpClient
///
/// The file to write to.
/// The string to write to the file.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1048,7 +1157,7 @@ public interface ISftpClient
/// The file to write to.
/// The string to write to the file.
/// The encoding to apply to the string.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1062,4 +1171,4 @@ public interface ISftpClient
///
void WriteAllText(string path, string contents, Encoding encoding);
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/ISubsystemSession.cs b/src/Renci.SshNet/ISubsystemSession.cs
index 48f155b65..f1fe6f914 100644
--- a/src/Renci.SshNet/ISubsystemSession.cs
+++ b/src/Renci.SshNet/ISubsystemSession.cs
@@ -13,7 +13,7 @@ internal interface ISubsystemSession : IDisposable
/// Gets or set the number of seconds to wait for an operation to complete.
///
///
- /// The number of seconds to wait for an operation to complete, or -1 to wait indefinitely.
+ /// The number of seconds to wait for an operation to complete, or -1 to wait indefinitely.
///
int OperationTimeout { get; }
@@ -21,7 +21,7 @@ internal interface ISubsystemSession : IDisposable
/// Gets a value indicating whether this session is open.
///
///
- /// true if this session is open; otherwise, false.
+ /// if this session is open; otherwise, .
///
bool IsOpen { get; }
@@ -41,7 +41,7 @@ internal interface ISubsystemSession : IDisposable
/// Waits a specified time for a given to get signaled.
///
/// The handle to wait for.
- /// The number of millieseconds wait for to get signaled, or -1 to wait indefinitely.
+ /// The number of millieseconds wait for to get signaled, or -1 to wait indefinitely.
/// The connection was closed by the server.
/// The channel was closed.
/// The handle did not get signaled within the specified timeout.
@@ -52,10 +52,10 @@ internal interface ISubsystemSession : IDisposable
/// 32-bit signed integer to specify the time interval in milliseconds.
///
/// The handle to wait for.
- /// To number of milliseconds to wait for to get signaled, or -1 to wait indefinitely.
+ /// To number of milliseconds to wait for to get signaled, or -1 to wait indefinitely.
///
- /// true if received a signal within the specified timeout;
- /// otherwise, false.
+ /// if received a signal within the specified timeout;
+ /// otherwise, .
///
/// The connection was closed by the server.
/// The channel was closed.
@@ -72,7 +72,7 @@ internal interface ISubsystemSession : IDisposable
///
/// The first handle to wait for.
/// The second handle to wait for.
- /// To number of milliseconds to wait for a to get signaled, or -1 to wait indefinitely.
+ /// To number of milliseconds to wait for a to get signaled, or -1 to wait indefinitely.
///
/// 0 if received a signal within the specified timeout and 1
/// if received a signal within the specified timeout, or
@@ -98,7 +98,7 @@ internal interface ISubsystemSession : IDisposable
/// integer to specify the time interval.
///
/// A array - constructed using - containing the objects to wait for.
- /// To number of milliseconds to wait for a to get signaled, or -1 to wait indefinitely.
+ /// To number of milliseconds to wait for a to get signaled, or -1 to wait indefinitely.
///
/// The array index of the first non-system object that satisfied the wait.
///
diff --git a/src/Renci.SshNet/KeyboardInteractiveAuthenticationMethod.cs b/src/Renci.SshNet/KeyboardInteractiveAuthenticationMethod.cs
index f8c78cbf5..7169fabc0 100644
--- a/src/Renci.SshNet/KeyboardInteractiveAuthenticationMethod.cs
+++ b/src/Renci.SshNet/KeyboardInteractiveAuthenticationMethod.cs
@@ -1,10 +1,12 @@
using System;
using System.Linq;
+using System.Runtime.ExceptionServices;
using System.Threading;
+
using Renci.SshNet.Abstractions;
+using Renci.SshNet.Common;
using Renci.SshNet.Messages;
using Renci.SshNet.Messages.Authentication;
-using Renci.SshNet.Common;
namespace Renci.SshNet
{
@@ -13,16 +15,19 @@ namespace Renci.SshNet
///
public class KeyboardInteractiveAuthenticationMethod : AuthenticationMethod, IDisposable
{
+ private readonly RequestMessage _requestMessage;
private AuthenticationResult _authenticationResult = AuthenticationResult.Failure;
-
private Session _session;
- private EventWaitHandle _authenticationCompleted = new AutoResetEvent(false);
+ private EventWaitHandle _authenticationCompleted = new AutoResetEvent(initialState: false);
private Exception _exception;
- private readonly RequestMessage _requestMessage;
+ private bool _isDisposed;
///
- /// Gets authentication method name
+ /// Gets the name of the authentication method.
///
+ ///
+ /// The name of the authentication method.
+ ///
public override string Name
{
get { return _requestMessage.MethodName; }
@@ -37,7 +42,7 @@ public override string Name
/// Initializes a new instance of the class.
///
/// The username.
- /// is whitespace or null.
+ /// is whitespace or .
public KeyboardInteractiveAuthenticationMethod(string username)
: base(username)
{
@@ -73,7 +78,9 @@ public override AuthenticationResult Authenticate(Session session)
}
if (_exception != null)
- throw _exception;
+ {
+ ExceptionDispatchInfo.Capture(_exception).Throw();
+ }
return _authenticationResult;
}
@@ -81,20 +88,24 @@ public override AuthenticationResult Authenticate(Session session)
private void Session_UserAuthenticationSuccessReceived(object sender, MessageEventArgs e)
{
_authenticationResult = AuthenticationResult.Success;
- _authenticationCompleted.Set();
+ _ = _authenticationCompleted.Set();
}
private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs e)
{
if (e.Message.PartialSuccess)
+ {
_authenticationResult = AuthenticationResult.PartialSuccess;
+ }
else
+ {
_authenticationResult = AuthenticationResult.Failure;
+ }
// Copy allowed authentication methods
AllowedAuthentications = e.Message.AllowedAuthentications;
- _authenticationCompleted.Set();
+ _ = _authenticationCompleted.Set();
}
private void Session_UserAuthenticationInformationRequestReceived(object sender, MessageEventArgs e)
@@ -110,50 +121,55 @@ private void Session_UserAuthenticationInformationRequestReceived(object sender,
{
try
{
- if (AuthenticationPrompt != null)
- {
- AuthenticationPrompt(this, eventArgs);
- }
+ AuthenticationPrompt?.Invoke(this, eventArgs);
var informationResponse = new InformationResponseMessage();
- foreach (var response in from r in eventArgs.Prompts orderby r.Id ascending select r.Response)
+ foreach (var prompt in eventArgs.Prompts.OrderBy(r => r.Id))
{
- informationResponse.Responses.Add(response);
+ if (prompt.Response is null)
+ {
+ throw new SshAuthenticationException(
+ $"{nameof(AuthenticationPrompt)}.{nameof(prompt.Response)} is null for " +
+ $"prompt \"{prompt.Request}\". You can set this by subscribing to " +
+ $"{nameof(KeyboardInteractiveAuthenticationMethod)}.{nameof(AuthenticationPrompt)} " +
+ $"and inspecting the {nameof(AuthenticationPromptEventArgs.Prompts)} property " +
+ $"of the event args.");
+ }
+
+ informationResponse.Responses.Add(prompt.Response);
}
- // Send information response message
+ // Send information response message
_session.SendMessage(informationResponse);
}
catch (Exception exp)
{
_exception = exp;
- _authenticationCompleted.Set();
+ _ = _authenticationCompleted.Set();
}
});
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -169,14 +185,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~KeyboardInteractiveAuthenticationMethod()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/KeyboardInteractiveConnectionInfo.cs b/src/Renci.SshNet/KeyboardInteractiveConnectionInfo.cs
index d8780caa7..a2738796a 100644
--- a/src/Renci.SshNet/KeyboardInteractiveConnectionInfo.cs
+++ b/src/Renci.SshNet/KeyboardInteractiveConnectionInfo.cs
@@ -4,23 +4,17 @@
namespace Renci.SshNet
{
///
- /// Provides connection information when keyboard interactive authentication method is used
+ /// Provides connection information when keyboard interactive authentication method is used.
///
- ///
- ///
- ///
public class KeyboardInteractiveConnectionInfo : ConnectionInfo, IDisposable
{
+ private bool _isDisposed;
+
///
/// Occurs when server prompts for more authentication information.
///
- ///
- ///
- ///
public event EventHandler AuthenticationPrompt;
- // TODO: DOCS Add exception documentation for this class.
-
///
/// Initializes a new instance of the class.
///
@@ -29,7 +23,6 @@ public class KeyboardInteractiveConnectionInfo : ConnectionInfo, IDisposable
public KeyboardInteractiveConnectionInfo(string host, string username)
: this(host, DefaultPort, username, ProxyTypes.None, string.Empty, 0, string.Empty, string.Empty)
{
-
}
///
@@ -41,7 +34,6 @@ public KeyboardInteractiveConnectionInfo(string host, string username)
public KeyboardInteractiveConnectionInfo(string host, int port, string username)
: this(host, port, username, ProxyTypes.None, string.Empty, 0, string.Empty, string.Empty)
{
-
}
///
@@ -131,45 +123,39 @@ public KeyboardInteractiveConnectionInfo(string host, int port, string username,
{
foreach (var authenticationMethod in AuthenticationMethods)
{
- var kbdInteractive = authenticationMethod as KeyboardInteractiveAuthenticationMethod;
- if (kbdInteractive != null)
+ if (authenticationMethod is KeyboardInteractiveAuthenticationMethod kbdInteractive)
{
kbdInteractive.AuthenticationPrompt += AuthenticationMethod_AuthenticationPrompt;
}
}
-
}
private void AuthenticationMethod_AuthenticationPrompt(object sender, AuthenticationPromptEventArgs e)
{
- if (AuthenticationPrompt != null)
- {
- AuthenticationPrompt(sender, e);
- }
+#pragma warning disable MA0091 // Sender should be 'this' for instance events
+ AuthenticationPrompt?.Invoke(sender, e);
+#pragma warning restore MA0091 // Sender should be 'this' for instance events
}
-
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -177,8 +163,7 @@ protected virtual void Dispose(bool disposing)
{
foreach (var authenticationMethods in AuthenticationMethods)
{
- var disposable = authenticationMethods as IDisposable;
- if (disposable != null)
+ if (authenticationMethods is IDisposable disposable)
{
disposable.Dispose();
}
@@ -190,14 +175,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~KeyboardInteractiveConnectionInfo()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/MessageEventArgs.cs b/src/Renci.SshNet/MessageEventArgs.cs
index 216b8adae..be1700263 100644
--- a/src/Renci.SshNet/MessageEventArgs.cs
+++ b/src/Renci.SshNet/MessageEventArgs.cs
@@ -5,7 +5,7 @@ namespace Renci.SshNet
///
/// Provides data for message events.
///
- /// Message type
+ /// Message type.
public class MessageEventArgs : EventArgs
{
///
@@ -14,14 +14,16 @@ public class MessageEventArgs : EventArgs
public T Message { get; private set; }
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The message.
- /// is null.
+ /// is .
public MessageEventArgs(T message)
{
- if (message == null)
- throw new ArgumentNullException("message");
+ if (message is null)
+ {
+ throw new ArgumentNullException(nameof(message));
+ }
Message = message;
}
diff --git a/src/Renci.SshNet/Messages/Authentication/BannerMessage.cs b/src/Renci.SshNet/Messages/Authentication/BannerMessage.cs
index 90652a34f..15f46386b 100644
--- a/src/Renci.SshNet/Messages/Authentication/BannerMessage.cs
+++ b/src/Renci.SshNet/Messages/Authentication/BannerMessage.cs
@@ -3,12 +3,29 @@
///
/// Represents SSH_MSG_USERAUTH_BANNER message.
///
- [Message("SSH_MSG_USERAUTH_BANNER", 53)]
public class BannerMessage : Message
{
private byte[] _message;
private byte[] _language;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_USERAUTH_BANNER";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 53;
+ }
+ }
+
///
/// Gets banner message.
///
diff --git a/src/Renci.SshNet/Messages/Authentication/FailureMessage.cs b/src/Renci.SshNet/Messages/Authentication/FailureMessage.cs
index 040877f30..1904fa1de 100644
--- a/src/Renci.SshNet/Messages/Authentication/FailureMessage.cs
+++ b/src/Renci.SshNet/Messages/Authentication/FailureMessage.cs
@@ -5,9 +5,26 @@ namespace Renci.SshNet.Messages.Authentication
///
/// Represents SSH_MSG_USERAUTH_FAILURE message.
///
- [Message("SSH_MSG_USERAUTH_FAILURE", 51)]
public class FailureMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_USERAUTH_FAILURE";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 51;
+ }
+ }
+
///
/// Gets or sets the allowed authentications if available.
///
@@ -25,7 +42,7 @@ public class FailureMessage : Message
/// Gets a value indicating whether authentication is partially successful.
///
///
- /// true if partially successful; otherwise, false.
+ /// if partially successful; otherwise, .
///
public bool PartialSuccess { get; private set; }
@@ -38,7 +55,11 @@ protected override void LoadData()
PartialSuccess = ReadBoolean();
if (PartialSuccess)
{
+#if NET || NETSTANDARD2_1_OR_GREATER
+ Message = string.Join(',', AllowedAuthentications);
+#else
Message = string.Join(",", AllowedAuthentications);
+#endif // NET || NETSTANDARD2_1_OR_GREATER
}
}
@@ -47,12 +68,22 @@ protected override void LoadData()
///
protected override void SaveData()
{
+#pragma warning disable MA0025 // Implement the functionality instead of throwing NotImplementedException
throw new NotImplementedException();
+#pragma warning restore MA0025 // Implement the functionality instead of throwing NotImplementedException
}
internal override void Process(Session session)
{
session.OnUserAuthenticationFailureReceived(this);
}
+
+ ///
+ public override string ToString()
+ {
+#pragma warning disable MA0089 // Optimize string method usage
+ return $"SSH_MSG_USERAUTH_FAILURE {string.Join(",", AllowedAuthentications)} ({nameof(PartialSuccess)}:{PartialSuccess})";
+#pragma warning restore MA0089 // Optimize string method usage
+ }
}
}
diff --git a/src/Renci.SshNet/Messages/Authentication/InformationRequestMessage.cs b/src/Renci.SshNet/Messages/Authentication/InformationRequestMessage.cs
index 910a0f55e..9a45bcf2b 100644
--- a/src/Renci.SshNet/Messages/Authentication/InformationRequestMessage.cs
+++ b/src/Renci.SshNet/Messages/Authentication/InformationRequestMessage.cs
@@ -8,9 +8,26 @@ namespace Renci.SshNet.Messages.Authentication
///
/// Represents SSH_MSG_USERAUTH_INFO_REQUEST message.
///
- [Message("SSH_MSG_USERAUTH_INFO_REQUEST", 60)]
- internal class InformationRequestMessage : Message
+ internal sealed class InformationRequestMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_USERAUTH_INFO_REQUEST";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 60;
+ }
+ }
+
///
/// Gets information request name.
///
@@ -29,7 +46,7 @@ internal class InformationRequestMessage : Message
///
/// Gets information request prompts.
///
- public IEnumerable Prompts { get; private set; }
+ public IReadOnlyList Prompts { get; private set; }
///
/// Called when type specific data need to be loaded.
diff --git a/src/Renci.SshNet/Messages/Authentication/InformationResponseMessage.cs b/src/Renci.SshNet/Messages/Authentication/InformationResponseMessage.cs
index 5e0c352fb..27e4fe65b 100644
--- a/src/Renci.SshNet/Messages/Authentication/InformationResponseMessage.cs
+++ b/src/Renci.SshNet/Messages/Authentication/InformationResponseMessage.cs
@@ -6,13 +6,30 @@ namespace Renci.SshNet.Messages.Authentication
///
/// Represents SSH_MSG_USERAUTH_INFO_RESPONSE message.
///
- [Message("SSH_MSG_USERAUTH_INFO_RESPONSE", 61)]
- internal class InformationResponseMessage : Message
+ internal sealed class InformationResponseMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_USERAUTH_INFO_RESPONSE";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 61;
+ }
+ }
+
///
/// Gets authentication responses.
///
- public IList Responses { get; private set; }
+ public List Responses { get; private set; }
///
/// Gets the size of the message in bytes.
@@ -48,6 +65,7 @@ protected override void LoadData()
protected override void SaveData()
{
Write((uint) Responses.Count);
+
foreach (var response in Responses)
{
Write(response);
diff --git a/src/Renci.SshNet/Messages/Authentication/PasswordChangeRequiredMessage.cs b/src/Renci.SshNet/Messages/Authentication/PasswordChangeRequiredMessage.cs
index ac05dffa2..8cff4d1d7 100644
--- a/src/Renci.SshNet/Messages/Authentication/PasswordChangeRequiredMessage.cs
+++ b/src/Renci.SshNet/Messages/Authentication/PasswordChangeRequiredMessage.cs
@@ -3,9 +3,26 @@
///
/// Represents SSH_MSG_USERAUTH_PASSWD_CHANGEREQ message.
///
- [Message("SSH_MSG_USERAUTH_PASSWD_CHANGEREQ", 60)]
- internal class PasswordChangeRequiredMessage : Message
+ internal sealed class PasswordChangeRequiredMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_USERAUTH_PASSWD_CHANGEREQ";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 60;
+ }
+ }
+
///
/// Gets password change request message as UTF-8 encoded byte array.
///
diff --git a/src/Renci.SshNet/Messages/Authentication/PublicKeyMessage.cs b/src/Renci.SshNet/Messages/Authentication/PublicKeyMessage.cs
index 9658a2e05..491d1262c 100644
--- a/src/Renci.SshNet/Messages/Authentication/PublicKeyMessage.cs
+++ b/src/Renci.SshNet/Messages/Authentication/PublicKeyMessage.cs
@@ -3,9 +3,26 @@
///
/// Represents SSH_MSG_USERAUTH_PK_OK message.
///
- [Message("SSH_MSG_USERAUTH_PK_OK", 60)]
- internal class PublicKeyMessage : Message
+ internal sealed class PublicKeyMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_USERAUTH_PK_OK";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 60;
+ }
+ }
+
///
/// Gets the name of the public key algorithm as ASCII encoded byte array.
///
@@ -60,5 +77,11 @@ protected override void SaveData()
WriteBinaryString(PublicKeyAlgorithmName);
WriteBinaryString(PublicKeyData);
}
+
+ ///
+ public override string ToString()
+ {
+ return $"SSH_MSG_USERAUTH_PK_OK ({Ascii.GetString(PublicKeyAlgorithmName)})";
+ }
}
}
diff --git a/src/Renci.SshNet/Messages/Authentication/RequestMessage.cs b/src/Renci.SshNet/Messages/Authentication/RequestMessage.cs
index b535da224..58daa10fc 100644
--- a/src/Renci.SshNet/Messages/Authentication/RequestMessage.cs
+++ b/src/Renci.SshNet/Messages/Authentication/RequestMessage.cs
@@ -6,9 +6,26 @@ namespace Renci.SshNet.Messages.Authentication
///
/// Represents SSH_MSG_USERAUTH_REQUEST message. Server as a base message for other user authentication requests.
///
- [Message("SSH_MSG_USERAUTH_REQUEST", AuthenticationMessageCode)]
public abstract class RequestMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_USERAUTH_REQUEST";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return AuthenticationMessageCode;
+ }
+ }
+
///
/// Returns the authentication message code for SSH_MSG_USERAUTH_REQUEST.
///
@@ -106,6 +123,11 @@ internal override void Process(Session session)
{
throw new NotImplementedException();
}
+
+ ///
+ public override string ToString()
+ {
+ return $"SSH_MSG_USERAUTH_REQUEST ({MethodName})";
+ }
}
}
-
diff --git a/src/Renci.SshNet/Messages/Authentication/RequestMessageHost.cs b/src/Renci.SshNet/Messages/Authentication/RequestMessageHost.cs
index 5d5a22dce..ec9fd2047 100644
--- a/src/Renci.SshNet/Messages/Authentication/RequestMessageHost.cs
+++ b/src/Renci.SshNet/Messages/Authentication/RequestMessageHost.cs
@@ -3,44 +3,44 @@
///
/// Represents "hostbased" SSH_MSG_USERAUTH_REQUEST message.
///
- internal class RequestMessageHost : RequestMessage
+ internal sealed class RequestMessageHost : RequestMessage
{
///
/// Gets the public key algorithm for host key as ASCII encoded byte array.
///
- public byte[] PublicKeyAlgorithm { get; private set; }
+ public byte[] PublicKeyAlgorithm { get; }
///
- /// Gets or sets the public host key and certificates for client host.
+ /// Gets the public host key and certificates for client host.
///
///
/// The public host key.
///
- public byte[] PublicHostKey { get; private set; }
+ public byte[] PublicHostKey { get; }
///
- /// Gets or sets the name of the client host as ASCII encoded byte array.
+ /// Gets the name of the client host as ASCII encoded byte array.
///
///
/// The name of the client host.
///
- public byte[] ClientHostName { get; private set; }
+ public byte[] ClientHostName { get; }
///
- /// Gets or sets the client username on the client host as UTF-8 encoded byte array.
+ /// Gets the client username on the client host as UTF-8 encoded byte array.
///
///
/// The client username.
///
- public byte[] ClientUsername { get; private set; }
+ public byte[] ClientUsername { get; }
///
- /// Gets or sets the signature.
+ /// Gets the signature.
///
///
/// The signature.
///
- public byte[] Signature { get; private set; }
+ public byte[] Signature { get; }
///
/// Gets the size of the message in bytes.
diff --git a/src/Renci.SshNet/Messages/Authentication/RequestMessageKeyboardInteractive.cs b/src/Renci.SshNet/Messages/Authentication/RequestMessageKeyboardInteractive.cs
index 6961cb5a3..6175511ed 100644
--- a/src/Renci.SshNet/Messages/Authentication/RequestMessageKeyboardInteractive.cs
+++ b/src/Renci.SshNet/Messages/Authentication/RequestMessageKeyboardInteractive.cs
@@ -1,11 +1,11 @@
-using Renci.SshNet.Common;
+using System;
namespace Renci.SshNet.Messages.Authentication
{
///
/// Represents "keyboard-interactive" SSH_MSG_USERAUTH_REQUEST message.
///
- internal class RequestMessageKeyboardInteractive : RequestMessage
+ internal sealed class RequestMessageKeyboardInteractive : RequestMessage
{
///
/// Gets message language.
@@ -44,8 +44,8 @@ protected override int BufferCapacity
public RequestMessageKeyboardInteractive(ServiceName serviceName, string username)
: base(serviceName, username, "keyboard-interactive")
{
- Language = Array.Empty;
- SubMethods = Array.Empty;
+ Language = Array.Empty();
+ SubMethods = Array.Empty();
}
///
diff --git a/src/Renci.SshNet/Messages/Authentication/RequestMessageNone.cs b/src/Renci.SshNet/Messages/Authentication/RequestMessageNone.cs
index 77cc55f3a..1f84f4161 100644
--- a/src/Renci.SshNet/Messages/Authentication/RequestMessageNone.cs
+++ b/src/Renci.SshNet/Messages/Authentication/RequestMessageNone.cs
@@ -3,10 +3,10 @@
///
/// Represents "none" SSH_MSG_USERAUTH_REQUEST message.
///
- internal class RequestMessageNone : RequestMessage
+ internal sealed class RequestMessageNone : RequestMessage
{
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// Name of the service.
/// Authentication username.
diff --git a/src/Renci.SshNet/Messages/Authentication/RequestMessagePassword.cs b/src/Renci.SshNet/Messages/Authentication/RequestMessagePassword.cs
index 881617b85..603342c67 100644
--- a/src/Renci.SshNet/Messages/Authentication/RequestMessagePassword.cs
+++ b/src/Renci.SshNet/Messages/Authentication/RequestMessagePassword.cs
@@ -3,7 +3,7 @@
///
/// Represents "password" SSH_MSG_USERAUTH_REQUEST message.
///
- internal class RequestMessagePassword : RequestMessage
+ internal sealed class RequestMessagePassword : RequestMessage
{
///
/// Gets authentication password.
diff --git a/src/Renci.SshNet/Messages/Authentication/RequestMessagePublicKey.cs b/src/Renci.SshNet/Messages/Authentication/RequestMessagePublicKey.cs
index 9a888e295..a759ef20c 100644
--- a/src/Renci.SshNet/Messages/Authentication/RequestMessagePublicKey.cs
+++ b/src/Renci.SshNet/Messages/Authentication/RequestMessagePublicKey.cs
@@ -92,7 +92,15 @@ protected override void SaveData()
WriteBinaryString(PublicKeyAlgorithmName);
WriteBinaryString(PublicKeyData);
if (Signature != null)
+ {
WriteBinaryString(Signature);
+ }
+ }
+
+ ///
+ public override string ToString()
+ {
+ return $"{base.ToString()} {Ascii.GetString(PublicKeyAlgorithmName)} {(Signature != null ? "with" : "without")} signature.";
}
}
}
diff --git a/src/Renci.SshNet/Messages/Authentication/SuccessMessage.cs b/src/Renci.SshNet/Messages/Authentication/SuccessMessage.cs
index e21544211..03ed4a9a0 100644
--- a/src/Renci.SshNet/Messages/Authentication/SuccessMessage.cs
+++ b/src/Renci.SshNet/Messages/Authentication/SuccessMessage.cs
@@ -3,9 +3,26 @@
///
/// Represents SSH_MSG_USERAUTH_SUCCESS message.
///
- [Message("SSH_MSG_USERAUTH_SUCCESS", 52)]
public class SuccessMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_USERAUTH_SUCCESS";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 52;
+ }
+ }
+
///
/// Called when type specific data need to be loaded.
///
diff --git a/src/Renci.SshNet/Messages/Connection/CancelTcpIpForwardGlobalRequestMessage.cs b/src/Renci.SshNet/Messages/Connection/CancelTcpIpForwardGlobalRequestMessage.cs
index eaf8c6be2..0b3431c06 100644
--- a/src/Renci.SshNet/Messages/Connection/CancelTcpIpForwardGlobalRequestMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/CancelTcpIpForwardGlobalRequestMessage.cs
@@ -2,12 +2,12 @@
namespace Renci.SshNet.Messages.Connection
{
- internal class CancelTcpIpForwardGlobalRequestMessage : GlobalRequestMessage
+ internal sealed class CancelTcpIpForwardGlobalRequestMessage : GlobalRequestMessage
{
private byte[] _addressToBind;
public CancelTcpIpForwardGlobalRequestMessage(string addressToBind, uint portToBind)
- : base(Ascii.GetBytes("cancel-tcpip-forward"), true)
+ : base(Ascii.GetBytes("cancel-tcpip-forward"), wantReply: true)
{
AddressToBind = addressToBind;
PortToBind = portToBind;
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelCloseMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelCloseMessage.cs
index 09a6ba834..c66294a79 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelCloseMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelCloseMessage.cs
@@ -3,15 +3,31 @@
///
/// Represents SSH_MSG_CHANNEL_CLOSE message.
///
- [Message("SSH_MSG_CHANNEL_CLOSE", 97)]
public class ChannelCloseMessage : ChannelMessage
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_CHANNEL_CLOSE";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 97;
+ }
+ }
+
///
/// Initializes a new instance of the class.
///
public ChannelCloseMessage()
{
-
}
///
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelDataMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelDataMessage.cs
index 76c98f364..f387a7c36 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelDataMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelDataMessage.cs
@@ -5,13 +5,28 @@ namespace Renci.SshNet.Messages.Connection
///
/// Represents SSH_MSG_CHANNEL_DATA message.
///
- [Message("SSH_MSG_CHANNEL_DATA", MessageNumber)]
public class ChannelDataMessage : ChannelMessage
{
- internal const byte MessageNumber = 94;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_CHANNEL_DATA";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 94;
+ }
+ }
///
- /// Gets or sets message data.
+ /// Gets the message data.
///
///
/// The data.
@@ -27,7 +42,7 @@ public class ChannelDataMessage : ChannelMessage
///
/// The zero-based offset in at which the data begins.
///
- public int Offset { get; set; }
+ public int Offset { get; private set; }
///
/// Gets the number of bytes of to read or write.
@@ -35,7 +50,7 @@ public class ChannelDataMessage : ChannelMessage
///
/// The number of bytes of to read or write.
///
- public int Size { get; set; }
+ public int Size { get; private set; }
///
/// Gets the size of the message in bytes.
@@ -74,8 +89,10 @@ public ChannelDataMessage()
public ChannelDataMessage(uint localChannelNumber, byte[] data)
: base(localChannelNumber)
{
- if (data == null)
- throw new ArgumentNullException("data");
+ if (data is null)
+ {
+ throw new ArgumentNullException(nameof(data));
+ }
Data = data;
Offset = 0;
@@ -92,8 +109,10 @@ public ChannelDataMessage(uint localChannelNumber, byte[] data)
public ChannelDataMessage(uint localChannelNumber, byte[] data, int offset, int size)
: base(localChannelNumber)
{
- if (data == null)
- throw new ArgumentNullException("data");
+ if (data is null)
+ {
+ throw new ArgumentNullException(nameof(data));
+ }
Data = data;
Offset = offset;
@@ -106,6 +125,7 @@ public ChannelDataMessage(uint localChannelNumber, byte[] data, int offset, int
protected override void LoadData()
{
base.LoadData();
+
Data = ReadBinary();
Offset = 0;
Size = Data.Length;
@@ -117,6 +137,7 @@ protected override void LoadData()
protected override void SaveData()
{
base.SaveData();
+
WriteBinary(Data, Offset, Size);
}
}
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelEofMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelEofMessage.cs
index 469b7b60b..1a7ca9bce 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelEofMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelEofMessage.cs
@@ -3,15 +3,31 @@
///
/// Represents SSH_MSG_CHANNEL_EOF message.
///
- [Message("SSH_MSG_CHANNEL_EOF", 96)]
public class ChannelEofMessage : ChannelMessage
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_CHANNEL_EOF";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 96;
+ }
+ }
+
///
/// Initializes a new instance of the class.
///
public ChannelEofMessage()
{
-
}
///
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelExtendedDataMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelExtendedDataMessage.cs
index 4546a7343..c3788ff3a 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelExtendedDataMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelExtendedDataMessage.cs
@@ -3,9 +3,26 @@
///
/// Represents SSH_MSG_CHANNEL_EXTENDED_DATA message.
///
- [Message("SSH_MSG_CHANNEL_EXTENDED_DATA", 95)]
public class ChannelExtendedDataMessage : ChannelMessage
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_CHANNEL_EXTENDED_DATA";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 95;
+ }
+ }
+
///
/// Gets message data type code.
///
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelFailureMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelFailureMessage.cs
index f011f992a..a6b24d2da 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelFailureMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelFailureMessage.cs
@@ -3,15 +3,31 @@
///
/// Represents SSH_MSG_CHANNEL_FAILURE message.
///
- [Message("SSH_MSG_CHANNEL_FAILURE", 100)]
public class ChannelFailureMessage : ChannelMessage
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_CHANNEL_FAILURE";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 100;
+ }
+ }
+
///
/// Initializes a new instance of the class.
///
public ChannelFailureMessage()
{
-
}
///
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelMessage.cs
index b47852b95..e1d6ee995 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelMessage.cs
@@ -32,14 +32,14 @@ protected override int BufferCapacity
}
///
- /// Initializes a new .
+ /// Initializes a new instance of the class.
///
protected ChannelMessage()
{
}
///
- /// Initializes a new with the specified local channel number.
+ /// Initializes a new instance of the class with the specified local channel number.
///
/// The local channel number.
protected ChannelMessage(uint localChannelNumber)
@@ -64,10 +64,10 @@ protected override void SaveData()
}
///
- /// Returns a that represents this instance.
+ /// Returns a that represents this instance.
///
///
- /// A that represents this instance.
+ /// A that represents this instance.
///
public override string ToString()
{
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelOpen/ChannelOpenInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelOpen/ChannelOpenInfo.cs
index c9c334058..5c6e3c406 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelOpen/ChannelOpenInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelOpen/ChannelOpenInfo.cs
@@ -3,7 +3,7 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Base class for open channel messages
+ /// Base class for open channel messages.
///
public abstract class ChannelOpenInfo : SshData
{
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelOpen/ChannelOpenMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelOpen/ChannelOpenMessage.cs
index 1f8bb3e92..a45eda441 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelOpen/ChannelOpenMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelOpen/ChannelOpenMessage.cs
@@ -6,13 +6,28 @@ namespace Renci.SshNet.Messages.Connection
///
/// Represents SSH_MSG_CHANNEL_OPEN message.
///
- [Message("SSH_MSG_CHANNEL_OPEN", MessageNumber)]
public class ChannelOpenMessage : Message
{
- internal const byte MessageNumber = 90;
-
private byte[] _infoBytes;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_CHANNEL_OPEN";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 90;
+ }
+ }
+
///
/// Gets the type of the channel as ASCII encoded byte array.
///
@@ -76,7 +91,7 @@ protected override int BufferCapacity
///
public ChannelOpenMessage()
{
- // Required for dynamicly loading request type when it comes from the server
+ // Required for dynamicly loading request type when it comes from the server
}
///
@@ -86,11 +101,13 @@ public ChannelOpenMessage()
/// Initial size of the window.
/// Maximum size of the packet.
/// Information specific to the type of the channel to open.
- /// is null.
+ /// is .
public ChannelOpenMessage(uint channelNumber, uint initialWindowSize, uint maximumPacketSize, ChannelOpenInfo info)
{
if (info == null)
- throw new ArgumentNullException("info");
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
ChannelType = Ascii.GetBytes(info.ChannelType);
LocalChannelNumber = channelNumber;
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelOpen/DirectTcpipChannelInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelOpen/DirectTcpipChannelInfo.cs
index 8ad47fbb7..aefb316ad 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelOpen/DirectTcpipChannelInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelOpen/DirectTcpipChannelInfo.cs
@@ -3,15 +3,15 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Used to open "direct-tcpip" channel type
+ /// Used to open "direct-tcpip" channel type.
///
- internal class DirectTcpipChannelInfo : ChannelOpenInfo
+ internal sealed class DirectTcpipChannelInfo : ChannelOpenInfo
{
private byte[] _hostToConnect;
private byte[] _originatorAddress;
///
- /// Specifies channel open type
+ /// Specifies channel open type.
///
public const string NAME = "direct-tcpip";
@@ -79,7 +79,7 @@ protected override int BufferCapacity
/// Initializes a new instance of the class from the
/// specified data.
///
- /// is null.
+ /// is .
public DirectTcpipChannelInfo(byte[] data)
{
Load(data);
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelOpen/ForwardedTcpipChannelInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelOpen/ForwardedTcpipChannelInfo.cs
index 64d0ebba9..f8bb6742d 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelOpen/ForwardedTcpipChannelInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelOpen/ForwardedTcpipChannelInfo.cs
@@ -3,10 +3,15 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Used to open "forwarded-tcpip" channel type
+ /// Used to open "forwarded-tcpip" channel type.
///
- internal class ForwardedTcpipChannelInfo : ChannelOpenInfo
+ internal sealed class ForwardedTcpipChannelInfo : ChannelOpenInfo
{
+ ///
+ /// Specifies channel open type.
+ ///
+ public const string NAME = "forwarded-tcpip";
+
private byte[] _connectedAddress;
private byte[] _originatorAddress;
@@ -14,15 +19,15 @@ internal class ForwardedTcpipChannelInfo : ChannelOpenInfo
/// Initializes a new instance of the class from the
/// specified data.
///
- /// is null.
+ /// is .
public ForwardedTcpipChannelInfo(byte[] data)
{
Load(data);
}
///
- /// Initializes a new instance with the specified connector
- /// address and port, and originator address and port.
+ /// Initializes a new instance of the class with the
+ /// specified connector address and port, and originator address and port.
///
public ForwardedTcpipChannelInfo(string connectedAddress, uint connectedPort, string originatorAddress, uint originatorPort)
{
@@ -32,11 +37,6 @@ public ForwardedTcpipChannelInfo(string connectedAddress, uint connectedPort, st
OriginatorPort = originatorPort;
}
- ///
- /// Specifies channel open type
- ///
- public const string NAME = "forwarded-tcpip";
-
///
/// Gets the type of the channel to open.
///
@@ -51,6 +51,9 @@ public override string ChannelType
///
/// Gets the connected address.
///
+ ///
+ /// The connected address.
+ ///
public string ConnectedAddress
{
get { return Utf8.GetString(_connectedAddress, 0, _connectedAddress.Length); }
@@ -60,11 +63,17 @@ public string ConnectedAddress
///
/// Gets the connected port.
///
+ ///
+ /// The connected port.
+ ///
public uint ConnectedPort { get; private set; }
///
/// Gets the originator address.
///
+ ///
+ /// The originator address.
+ ///
public string OriginatorAddress
{
get { return Utf8.GetString(_originatorAddress, 0, _originatorAddress.Length); }
@@ -74,6 +83,9 @@ public string OriginatorAddress
///
/// Gets the originator port.
///
+ ///
+ /// The originator port.
+ ///
public uint OriginatorPort { get; private set; }
///
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelOpen/SessionChannelOpenInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelOpen/SessionChannelOpenInfo.cs
index bfe047688..f20df5833 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelOpen/SessionChannelOpenInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelOpen/SessionChannelOpenInfo.cs
@@ -3,12 +3,12 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Used to open "session" channel type
+ /// Used to open "session" channel type.
///
- internal class SessionChannelOpenInfo : ChannelOpenInfo
+ internal sealed class SessionChannelOpenInfo : ChannelOpenInfo
{
///
- /// Specifies channel open type
+ /// Specifies channel open type.
///
public const string Name = "session";
@@ -34,7 +34,7 @@ public SessionChannelOpenInfo()
/// Initializes a new instance of the class from the
/// specified data.
///
- /// is null.
+ /// is .
public SessionChannelOpenInfo(byte[] data)
{
Load(data);
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelOpen/X11ChannelOpenInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelOpen/X11ChannelOpenInfo.cs
index 6f62cfdaf..d071799c1 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelOpen/X11ChannelOpenInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelOpen/X11ChannelOpenInfo.cs
@@ -3,14 +3,14 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Used to open "x11" channel type
+ /// Used to open "x11" channel type.
///
- internal class X11ChannelOpenInfo : ChannelOpenInfo
+ internal sealed class X11ChannelOpenInfo : ChannelOpenInfo
{
private byte[] _originatorAddress;
///
- /// Specifies channel open type
+ /// Specifies channel open type.
///
public const string Name = "x11";
@@ -61,7 +61,7 @@ protected override int BufferCapacity
/// Initializes a new instance of the class from the
/// specified data.
///
- /// is null.
+ /// is .
public X11ChannelOpenInfo(byte[] data)
{
Load(data);
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelOpenConfirmationMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelOpenConfirmationMessage.cs
index 0213136df..ae6db2bf9 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelOpenConfirmationMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelOpenConfirmationMessage.cs
@@ -3,9 +3,26 @@
///
/// Represents SSH_MSG_CHANNEL_OPEN_CONFIRMATION message.
///
- [Message("SSH_MSG_CHANNEL_OPEN_CONFIRMATION", 91)]
public class ChannelOpenConfirmationMessage : ChannelMessage
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_CHANNEL_OPEN_CONFIRMATION";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 91;
+ }
+ }
+
///
/// Gets the remote channel number.
///
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelOpenFailureMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelOpenFailureMessage.cs
index 2a2888077..e68ab0358 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelOpenFailureMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelOpenFailureMessage.cs
@@ -3,7 +3,6 @@
///
/// Represents SSH_MSG_CHANNEL_OPEN_FAILURE message.
///
- [Message("SSH_MSG_CHANNEL_OPEN_FAILURE", 92)]
public class ChannelOpenFailureMessage : ChannelMessage
{
internal const uint AdministrativelyProhibited = 1;
@@ -14,6 +13,24 @@ public class ChannelOpenFailureMessage : ChannelMessage
private byte[] _description;
private byte[] _language;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_CHANNEL_OPEN_FAILURE";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 92;
+ }
+ }
+
///
/// Gets failure reason code.
///
@@ -62,7 +79,6 @@ protected override int BufferCapacity
///
public ChannelOpenFailureMessage()
{
-
}
///
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelOpenFailureReasons.cs b/src/Renci.SshNet/Messages/Connection/ChannelOpenFailureReasons.cs
index 94bbf8d33..0fbeaf4d3 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelOpenFailureReasons.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelOpenFailureReasons.cs
@@ -6,19 +6,22 @@
internal enum ChannelOpenFailureReasons : uint
{
///
- /// SSH_OPEN_ADMINISTRATIVELY_PROHIBITED
+ /// SSH_OPEN_ADMINISTRATIVELY_PROHIBITED.
///
AdministativelyProhibited = 1,
+
///
- /// SSH_OPEN_CONNECT_FAILED
+ /// SSH_OPEN_CONNECT_FAILED.
///
ConnectFailed = 2,
+
///
- /// SSH_OPEN_UNKNOWN_CHANNEL_TYPE
+ /// SSH_OPEN_UNKNOWN_CHANNEL_TYPE.
///
UnknownChannelType = 3,
+
///
- /// SSH_OPEN_RESOURCE_SHORTAGE
+ /// SSH_OPEN_RESOURCE_SHORTAGE.
///
ResourceShortage = 4
}
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/BreakRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/BreakRequestInfo.cs
index 0cadd6379..c36655e84 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/BreakRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/BreakRequestInfo.cs
@@ -1,12 +1,12 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "break" type channel request information
+ /// Represents "break" type channel request information.
///
- internal class BreakRequestInfo : RequestInfo
+ internal sealed class BreakRequestInfo : RequestInfo
{
///
- /// Channel request name
+ /// Channel request name.
///
public const string Name = "break";
@@ -43,7 +43,7 @@ protected override int BufferCapacity
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
public BreakRequestInfo()
{
@@ -51,7 +51,7 @@ public BreakRequestInfo()
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// Length of the break.
public BreakRequestInfo(uint breakLength)
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ChannelRequestMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ChannelRequestMessage.cs
index ab4d99e96..695c35b29 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ChannelRequestMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ChannelRequestMessage.cs
@@ -3,12 +3,29 @@
///
/// Represents SSH_MSG_CHANNEL_REQUEST message.
///
- [Message("SSH_MSG_CHANNEL_REQUEST", 98)]
public class ChannelRequestMessage : ChannelMessage
{
private string _requestName;
private byte[] _requestNameBytes;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_CHANNEL_REQUEST";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 98;
+ }
+ }
+
///
/// Gets the name of the request.
///
@@ -17,7 +34,10 @@ public class ChannelRequestMessage : ChannelMessage
///
public string RequestName
{
- get { return _requestName; }
+ get
+ {
+ return _requestName;
+ }
private set
{
_requestName = value;
@@ -53,7 +73,7 @@ protected override int BufferCapacity
///
public ChannelRequestMessage()
{
- // Required for dynamically loading request type when it comes from the server
+ // Required for dynamically loading request type when it comes from the server
}
///
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/EndOfWriteRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/EndOfWriteRequestInfo.cs
index e5e3735a0..ac4fc0ebc 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/EndOfWriteRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/EndOfWriteRequestInfo.cs
@@ -1,12 +1,12 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "eow@openssh.com" type channel request information
+ /// Represents "eow@openssh.com" type channel request information.
///
public class EndOfWriteRequestInfo : RequestInfo
{
///
- /// Channel request name
+ /// Channel request name.
///
public const string Name = "eow@openssh.com";
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/EnvironmentVariableRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/EnvironmentVariableRequestInfo.cs
index 7df594542..d04f80ef9 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/EnvironmentVariableRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/EnvironmentVariableRequestInfo.cs
@@ -1,15 +1,15 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "env" type channel request information
+ /// Represents "env" type channel request information.
///
- internal class EnvironmentVariableRequestInfo : RequestInfo
+ internal sealed class EnvironmentVariableRequestInfo : RequestInfo
{
private byte[] _variableName;
private byte[] _variableValue;
///
- /// Channel request name
+ /// Channel request name.
///
public const string Name = "env";
@@ -25,7 +25,7 @@ public override string RequestName
}
///
- /// Gets or sets the name of the variable.
+ /// Gets the name of the variable.
///
///
/// The name of the variable.
@@ -36,7 +36,7 @@ public string VariableName
}
///
- /// Gets or sets the variable value.
+ /// Gets the value of the variable.
///
///
/// The variable value.
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExecRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExecRequestInfo.cs
index 673f4c2bf..0f9f6eabb 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExecRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExecRequestInfo.cs
@@ -4,14 +4,14 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "exec" type channel request information
+ /// Represents "exec" type channel request information.
///
- internal class ExecRequestInfo : RequestInfo
+ internal sealed class ExecRequestInfo : RequestInfo
{
private byte[] _command;
///
- /// Channel request name
+ /// Channel request name.
///
public const string Name = "exec";
@@ -75,14 +75,19 @@ public ExecRequestInfo()
///
/// The command.
/// The character encoding to use.
- /// or is null.
+ /// or is .
public ExecRequestInfo(string command, Encoding encoding)
: this()
{
- if (command == null)
- throw new ArgumentNullException("command");
- if (encoding == null)
- throw new ArgumentNullException("encoding");
+ if (command is null)
+ {
+ throw new ArgumentNullException(nameof(command));
+ }
+
+ if (encoding is null)
+ {
+ throw new ArgumentNullException(nameof(encoding));
+ }
_command = encoding.GetBytes(command);
Encoding = encoding;
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExitSignalRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExitSignalRequestInfo.cs
index 512f3b97d..da17aee1d 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExitSignalRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExitSignalRequestInfo.cs
@@ -1,16 +1,16 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "exit-signal" type channel request information
+ /// Represents "exit-signal" type channel request information.
///
- internal class ExitSignalRequestInfo : RequestInfo
+ internal sealed class ExitSignalRequestInfo : RequestInfo
{
private byte[] _signalName;
private byte[] _errorMessage;
private byte[] _language;
///
- /// Channel request name
+ /// Channel request name.
///
public const string Name = "exit-signal";
@@ -41,7 +41,7 @@ public string SignalName
/// Gets a value indicating whether core is dumped.
///
///
- /// true if core is dumped; otherwise, false.
+ /// if core is dumped; otherwise, .
///
public bool CoreDumped { get; private set; }
@@ -91,7 +91,7 @@ public ExitSignalRequestInfo()
/// Initializes a new instance of the class.
///
/// Name of the signal.
- /// if set to true then core is dumped.
+ /// if set to then core is dumped.
/// The error message.
/// The language.
public ExitSignalRequestInfo(string signalName, bool coreDumped, string errorMessage, string language)
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExitStatusRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExitStatusRequestInfo.cs
index 96cc1d061..3d4651793 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExitStatusRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExitStatusRequestInfo.cs
@@ -1,9 +1,9 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "exit-status" type channel request information
+ /// Represents "exit-status" type channel request information.
///
- internal class ExitStatusRequestInfo : RequestInfo
+ internal sealed class ExitStatusRequestInfo : RequestInfo
{
///
/// Channel request name.
@@ -30,7 +30,7 @@ protected override int BufferCapacity
{
get
{
- var capacity = base.BufferCapacity;
+ var capacity = base.BufferCapacity;
capacity += 4; // ExitStatus
return capacity;
}
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/KeepAliveRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/KeepAliveRequestInfo.cs
index 9bf303d6e..75b88df84 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/KeepAliveRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/KeepAliveRequestInfo.cs
@@ -1,12 +1,12 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "keepalive@openssh.com" type channel request information
+ /// Represents "keepalive@openssh.com" type channel request information.
///
public class KeepAliveRequestInfo : RequestInfo
{
///
- /// Channel request name
+ /// Channel request name.
///
public const string Name = "keepalive@openssh.com";
@@ -22,7 +22,7 @@ public override string RequestName
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
public KeepAliveRequestInfo()
{
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/PseudoTerminalInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/PseudoTerminalRequestInfo.cs
similarity index 92%
rename from src/Renci.SshNet/Messages/Connection/ChannelRequest/PseudoTerminalInfo.cs
rename to src/Renci.SshNet/Messages/Connection/ChannelRequest/PseudoTerminalRequestInfo.cs
index 6fdc681cb..82df2712f 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/PseudoTerminalInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/PseudoTerminalRequestInfo.cs
@@ -1,15 +1,16 @@
-using Renci.SshNet.Common;
-using System.Collections.Generic;
+using System.Collections.Generic;
+
+using Renci.SshNet.Common;
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "pty-req" type channel request information
+ /// Represents "pty-req" type channel request information.
///
- internal class PseudoTerminalRequestInfo : RequestInfo
+ internal sealed class PseudoTerminalRequestInfo : RequestInfo
{
///
- /// Channel request name
+ /// Channel request name.
///
public const string Name = "pty-req";
@@ -98,7 +99,7 @@ public PseudoTerminalRequestInfo()
/// The TERM environment variable which a identifier for the text window’s capabilities.
/// The terminal width in columns.
/// The terminal width in rows.
- /// The terminal height in pixels.
+ /// The terminal width in pixels.
/// The terminal height in pixels.
/// The terminal mode values.
///
@@ -140,7 +141,7 @@ protected override void SaveData()
// write total length of encoded terminal modes, which is 1 bytes for the opcode / terminal mode
// and 4 bytes for the uint argument for each entry; the encoded terminal modes are terminated by
// opcode TTY_OP_END (which is 1 byte)
- Write((uint) TerminalModeValues.Count*(1 + 4) + 1);
+ Write(((uint) TerminalModeValues.Count*(1 + 4)) + 1);
foreach (var item in TerminalModeValues)
{
@@ -153,7 +154,7 @@ protected override void SaveData()
else
{
// when there are no terminal mode, the length of the string is zero
- Write((uint) 0);
+ Write(0u);
}
}
}
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/RequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/RequestInfo.cs
index 5512989cf..546f7ec6b 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/RequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/RequestInfo.cs
@@ -19,7 +19,7 @@ public abstract class RequestInfo : SshData
/// Gets or sets a value indicating whether reply message is needed.
///
///
- /// true if reply message is needed; otherwise, false.
+ /// if reply message is needed; otherwise, .
///
public bool WantReply { get; protected set; }
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ShellRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ShellRequestInfo.cs
index 4b570d708..92ed4fd6b 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ShellRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ShellRequestInfo.cs
@@ -1,12 +1,12 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "shell" type channel request information
+ /// Represents "shell" type channel request information.
///
- internal class ShellRequestInfo : RequestInfo
+ internal sealed class ShellRequestInfo : RequestInfo
{
///
- /// Channel request name
+ /// Channel request name.
///
public const string Name = "shell";
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/SignalRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/SignalRequestInfo.cs
index 493681b44..c16c842c8 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/SignalRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/SignalRequestInfo.cs
@@ -1,9 +1,9 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "signal" type channel request information
+ /// Represents "signal" type channel request information.
///
- internal class SignalRequestInfo : RequestInfo
+ internal sealed class SignalRequestInfo : RequestInfo
{
private byte[] _signalName;
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/SubsystemRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/SubsystemRequestInfo.cs
index 1af72be8e..0013792ca 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/SubsystemRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/SubsystemRequestInfo.cs
@@ -1,14 +1,14 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "subsystem" type channel request information
+ /// Represents "subsystem" type channel request information.
///
- internal class SubsystemRequestInfo : RequestInfo
+ internal sealed class SubsystemRequestInfo : RequestInfo
{
private byte[] _subsystemName;
///
- /// Channel request name
+ /// Channel request name.
///
public const string Name = "subsystem";
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/WindowChangeRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/WindowChangeRequestInfo.cs
index 4f0813bd8..34e4c2cb3 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/WindowChangeRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/WindowChangeRequestInfo.cs
@@ -1,12 +1,12 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "window-change" type channel request information
+ /// Represents "window-change" type channel request information.
///
- internal class WindowChangeRequestInfo : RequestInfo
+ internal sealed class WindowChangeRequestInfo : RequestInfo
{
///
- /// Channe request name
+ /// Channe request name.
///
public const string Name = "window-change";
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/X11ForwardingRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/X11ForwardingRequestInfo.cs
index 89ebfe4f9..c7f38c94f 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/X11ForwardingRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/X11ForwardingRequestInfo.cs
@@ -1,14 +1,14 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "x11-req" type channel request information
+ /// Represents "x11-req" type channel request information.
///
- internal class X11ForwardingRequestInfo : RequestInfo
+ internal sealed class X11ForwardingRequestInfo : RequestInfo
{
private byte[] _authenticationProtocol;
///
- /// Channel request name
+ /// Channel request name.
///
public const string Name = "x11-req";
@@ -27,12 +27,12 @@ public override string RequestName
/// Gets or sets a value indicating whether it is a single connection.
///
///
- /// true if it is a single connection; otherwise, false.
+ /// if it is a single connection; otherwise, .
///
public bool IsSingleConnection { get; set; }
///
- /// Gets or sets the authentication protocol.
+ /// Gets the authentication protocol.
///
///
/// The authentication protocol.
@@ -91,7 +91,7 @@ public X11ForwardingRequestInfo()
///
/// Initializes a new instance of the class.
///
- /// if set to true it is a single connection.
+ /// if set to it is a single connection.
/// The protocol.
/// The cookie.
/// The screen number.
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/XonXoffRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/XonXoffRequestInfo.cs
index ff10a73ab..2cf9a19c0 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/XonXoffRequestInfo.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/XonXoffRequestInfo.cs
@@ -1,12 +1,12 @@
namespace Renci.SshNet.Messages.Connection
{
///
- /// Represents "xon-xoff" type channel request information
+ /// Represents "xon-xoff" type channel request information.
///
- internal class XonXoffRequestInfo : RequestInfo
+ internal sealed class XonXoffRequestInfo : RequestInfo
{
///
- /// Channel request type
+ /// Channel request type.
///
public const string Name = "xon-xoff";
@@ -25,7 +25,7 @@ public override string RequestName
/// Gets or sets a value indicating whether client can do.
///
///
- /// true if client can do; otherwise, false.
+ /// if client can do; otherwise, .
///
public bool ClientCanDo { get; set; }
@@ -56,7 +56,7 @@ public XonXoffRequestInfo()
///
/// Initializes a new instance of the class.
///
- /// if set to true [client can do].
+ /// if set to [client can do].
public XonXoffRequestInfo(bool clientCanDo)
: this()
{
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelSuccessMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelSuccessMessage.cs
index d6f21e9a5..c554f32e9 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelSuccessMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelSuccessMessage.cs
@@ -3,7 +3,6 @@
///
/// Represents SSH_MSG_CHANNEL_SUCCESS message.
///
- [Message("SSH_MSG_CHANNEL_SUCCESS", 99)]
public class ChannelSuccessMessage : ChannelMessage
{
///
@@ -11,7 +10,6 @@ public class ChannelSuccessMessage : ChannelMessage
///
public ChannelSuccessMessage()
{
-
}
///
@@ -23,6 +21,24 @@ public ChannelSuccessMessage(uint localChannelNumber)
{
}
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_CHANNEL_SUCCESS";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 99;
+ }
+ }
+
internal override void Process(Session session)
{
session.OnChannelSuccessReceived(this);
diff --git a/src/Renci.SshNet/Messages/Connection/ChannelWindowAdjustMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelWindowAdjustMessage.cs
index 364b81300..3e6ad90d1 100644
--- a/src/Renci.SshNet/Messages/Connection/ChannelWindowAdjustMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/ChannelWindowAdjustMessage.cs
@@ -3,9 +3,26 @@
///
/// Represents SSH_MSG_CHANNEL_SUCCESS message.
///
- [Message("SSH_MSG_CHANNEL_WINDOW_ADJUST", 93)]
public class ChannelWindowAdjustMessage : ChannelMessage
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_CHANNEL_WINDOW_ADJUST";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 93;
+ }
+ }
+
///
/// Gets number of bytes to add to the window.
///
@@ -32,7 +49,6 @@ protected override int BufferCapacity
///
public ChannelWindowAdjustMessage()
{
-
}
///
@@ -52,6 +68,7 @@ public ChannelWindowAdjustMessage(uint localChannelNumber, uint bytesToAdd)
protected override void LoadData()
{
base.LoadData();
+
BytesToAdd = ReadUInt32();
}
@@ -61,6 +78,7 @@ protected override void LoadData()
protected override void SaveData()
{
base.SaveData();
+
Write(BytesToAdd);
}
diff --git a/src/Renci.SshNet/Messages/Connection/GlobalRequestMessage.cs b/src/Renci.SshNet/Messages/Connection/GlobalRequestMessage.cs
index 250f73566..d34778e54 100644
--- a/src/Renci.SshNet/Messages/Connection/GlobalRequestMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/GlobalRequestMessage.cs
@@ -3,11 +3,28 @@
///
/// Represents SSH_MSG_GLOBAL_REQUEST message.
///
- [Message("SSH_MSG_GLOBAL_REQUEST", 80)]
public class GlobalRequestMessage : Message
{
private byte[] _requestName;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_GLOBAL_REQUEST";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 80;
+ }
+ }
+
///
/// Gets the name of the request.
///
@@ -23,7 +40,7 @@ public string RequestName
/// Gets a value indicating whether message reply should be sent..
///
///
- /// true if message reply should be sent; otherwise, false.
+ /// if message reply should be sent; otherwise, .
///
public bool WantReply { get; private set; }
@@ -56,7 +73,7 @@ public GlobalRequestMessage()
/// Initializes a new instance of the class.
///
/// Name of the request.
- /// if set to true [want reply].
+ /// if set to [want reply].
internal GlobalRequestMessage(byte[] requestName, bool wantReply)
{
_requestName = requestName;
diff --git a/src/Renci.SshNet/Messages/Connection/GlobalRequestName.cs b/src/Renci.SshNet/Messages/Connection/GlobalRequestName.cs
index 6a1d0e279..263278c0a 100644
--- a/src/Renci.SshNet/Messages/Connection/GlobalRequestName.cs
+++ b/src/Renci.SshNet/Messages/Connection/GlobalRequestName.cs
@@ -6,11 +6,12 @@
public enum GlobalRequestName
{
///
- /// tcpip-forward
+ /// tcpip-forward.
///
TcpIpForward,
+
///
- /// cancel-tcpip-forward
+ /// cancel-tcpip-forward.
///
CancelTcpIpForward,
}
diff --git a/src/Renci.SshNet/Messages/Connection/RequestFailureMessage.cs b/src/Renci.SshNet/Messages/Connection/RequestFailureMessage.cs
index af9df7501..8602f5089 100644
--- a/src/Renci.SshNet/Messages/Connection/RequestFailureMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/RequestFailureMessage.cs
@@ -1,12 +1,28 @@
-
-namespace Renci.SshNet.Messages.Connection
+namespace Renci.SshNet.Messages.Connection
{
///
/// Represents SSH_MSG_REQUEST_FAILURE message.
///
- [Message("SSH_MSG_REQUEST_FAILURE", 82)]
public class RequestFailureMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_REQUEST_FAILURE";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 82;
+ }
+ }
+
///
/// Called when type specific data need to be loaded.
///
diff --git a/src/Renci.SshNet/Messages/Connection/RequestSuccessMessage.cs b/src/Renci.SshNet/Messages/Connection/RequestSuccessMessage.cs
index b456efe85..68f5a2f84 100644
--- a/src/Renci.SshNet/Messages/Connection/RequestSuccessMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/RequestSuccessMessage.cs
@@ -3,9 +3,26 @@
///
/// Represents SSH_MSG_REQUEST_SUCCESS message.
///
- [Message("SSH_MSG_REQUEST_SUCCESS", 81)]
public class RequestSuccessMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_REQUEST_SUCCESS";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 81;
+ }
+ }
+
///
/// Gets the bound port.
///
@@ -22,8 +39,12 @@ protected override int BufferCapacity
get
{
var capacity = base.BufferCapacity;
+
if (BoundPort.HasValue)
+ {
capacity += 4; // BoundPort
+ }
+
return capacity;
}
}
@@ -33,7 +54,6 @@ protected override int BufferCapacity
///
public RequestSuccessMessage()
{
-
}
///
@@ -51,7 +71,9 @@ public RequestSuccessMessage(uint boundPort)
protected override void LoadData()
{
if (!IsEndOfData)
+ {
BoundPort = ReadUInt32();
+ }
}
///
@@ -60,7 +82,9 @@ protected override void LoadData()
protected override void SaveData()
{
if (BoundPort.HasValue)
+ {
Write(BoundPort.Value);
+ }
}
internal override void Process(Session session)
diff --git a/src/Renci.SshNet/Messages/Connection/TcpIpForwardGlobalRequestMessage.cs b/src/Renci.SshNet/Messages/Connection/TcpIpForwardGlobalRequestMessage.cs
index 83d0b013c..edddcb567 100644
--- a/src/Renci.SshNet/Messages/Connection/TcpIpForwardGlobalRequestMessage.cs
+++ b/src/Renci.SshNet/Messages/Connection/TcpIpForwardGlobalRequestMessage.cs
@@ -2,12 +2,12 @@
namespace Renci.SshNet.Messages.Connection
{
- internal class TcpIpForwardGlobalRequestMessage : GlobalRequestMessage
+ internal sealed class TcpIpForwardGlobalRequestMessage : GlobalRequestMessage
{
private byte[] _addressToBind;
public TcpIpForwardGlobalRequestMessage(string addressToBind, uint portToBind)
- : base(Ascii.GetBytes("tcpip-forward"), true)
+ : base(Ascii.GetBytes("tcpip-forward"), wantReply: true)
{
AddressToBind = addressToBind;
PortToBind = portToBind;
diff --git a/src/Renci.SshNet/Messages/Message.cs b/src/Renci.SshNet/Messages/Message.cs
index 2bbfb7b9e..eab59815d 100644
--- a/src/Renci.SshNet/Messages/Message.cs
+++ b/src/Renci.SshNet/Messages/Message.cs
@@ -1,22 +1,27 @@
using System.IO;
-using Renci.SshNet.Common;
-using System.Globalization;
+
using Renci.SshNet.Abstractions;
+using Renci.SshNet.Common;
using Renci.SshNet.Compression;
namespace Renci.SshNet.Messages
{
///
- /// Base class for all SSH protocol messages
+ /// Base class for all SSH protocol messages.
///
public abstract class Message : SshData
{
///
- /// Gets the size of the message in bytes.
+ /// Gets the message name as defined in RFC 4250.
+ ///
+ public abstract string MessageName { get; }
+
+ ///
+ /// Gets the message number as defined in RFC 4250.
///
- ///
- /// The size of the messages in bytes.
- ///
+ public abstract byte MessageNumber { get; }
+
+ ///
protected override int BufferCapacity
{
get
@@ -25,27 +30,11 @@ protected override int BufferCapacity
}
}
- ///
- /// Writes the message to the specified .
- ///
+ ///
protected override void WriteBytes(SshDataStream stream)
{
- var enumerator = GetType().GetCustomAttributes(true).GetEnumerator();
- try
- {
- if (!enumerator.MoveNext())
- {
- throw new SshException(string.Format(CultureInfo.CurrentCulture, "Type '{0}' is not a valid message type.", GetType().AssemblyQualifiedName));
- }
-
- var messageAttribute = enumerator.Current;
- stream.WriteByte(messageAttribute.Number);
- base.WriteBytes(stream);
- }
- finally
- {
- enumerator.Dispose();
- }
+ stream.WriteByte(MessageNumber);
+ base.WriteBytes(stream);
}
internal byte[] GetPacket(byte paddingMultiplier, Compressor compressor)
@@ -54,58 +43,61 @@ internal byte[] GetPacket(byte paddingMultiplier, Compressor compressor)
var messageLength = BufferCapacity;
- SshDataStream sshDataStream;
-
if (messageLength == -1 || compressor != null)
{
- sshDataStream = new SshDataStream(DefaultCapacity);
+ using (var sshDataStream = new SshDataStream(DefaultCapacity))
+ {
+ // skip:
+ // * 4 bytes for the outbound packet sequence
+ // * 4 bytes for the packet data length
+ // * one byte for the packet padding length
+ _ = sshDataStream.Seek(outboundPacketSequenceSize + 4 + 1, SeekOrigin.Begin);
- // skip:
- // * 4 bytes for the outbound packet sequence
- // * 4 bytes for the packet data length
- // * one byte for the packet padding length
- sshDataStream.Seek(outboundPacketSequenceSize + 4 + 1, SeekOrigin.Begin);
+ if (compressor != null)
+ {
+ // obtain uncompressed message payload
+ using (var uncompressedDataStream = new SshDataStream(messageLength != -1 ? messageLength : DefaultCapacity))
+ {
+ WriteBytes(uncompressedDataStream);
- if (compressor != null)
- {
- // obtain uncompressed message payload
- var uncompressedDataStream = new SshDataStream(messageLength != -1 ? messageLength : DefaultCapacity);
- WriteBytes(uncompressedDataStream);
+ // compress message payload
+ var compressedMessageData = compressor.Compress(uncompressedDataStream.ToArray());
- // compress message payload
- var compressedMessageData = compressor.Compress(uncompressedDataStream.ToArray());
+ // add compressed message payload
+ sshDataStream.Write(compressedMessageData, 0, compressedMessageData.Length);
+ }
+ }
+ else
+ {
+ // add message payload
+ WriteBytes(sshDataStream);
+ }
- // add compressed message payload
- sshDataStream.Write(compressedMessageData, 0, compressedMessageData.Length);
- }
- else
- {
- // add message payload
- WriteBytes(sshDataStream);
- }
+ messageLength = (int) sshDataStream.Length - (outboundPacketSequenceSize + 4 + 1);
- messageLength = (int) sshDataStream.Length - (outboundPacketSequenceSize + 4 + 1);
+ var packetLength = messageLength + 4 + 1;
- var packetLength = messageLength + 4 + 1;
+ // determine the padding length
+ var paddingLength = GetPaddingLength(paddingMultiplier, packetLength);
- // determine the padding length
- var paddingLength = GetPaddingLength(paddingMultiplier, packetLength);
+ // add padding bytes
+ var paddingBytes = new byte[paddingLength];
+ CryptoAbstraction.GenerateRandom(paddingBytes);
+ sshDataStream.Write(paddingBytes, 0, paddingLength);
- // add padding bytes
- var paddingBytes = new byte[paddingLength];
- CryptoAbstraction.GenerateRandom(paddingBytes);
- sshDataStream.Write(paddingBytes, 0, paddingLength);
+ var packetDataLength = GetPacketDataLength(messageLength, paddingLength);
- var packetDataLength = GetPacketDataLength(messageLength, paddingLength);
+ // skip bytes for outbound packet sequence
+ _ = sshDataStream.Seek(outboundPacketSequenceSize, SeekOrigin.Begin);
- // skip bytes for outbound packet sequence
- sshDataStream.Seek(outboundPacketSequenceSize, SeekOrigin.Begin);
+ // add packet data length
+ sshDataStream.Write(packetDataLength);
- // add packet data length
- sshDataStream.Write(packetDataLength);
+ // add packet padding length
+ sshDataStream.WriteByte(paddingLength);
- // add packet padding length
- sshDataStream.WriteByte(paddingLength);
+ return sshDataStream.ToArray();
+ }
}
else
{
@@ -117,27 +109,28 @@ internal byte[] GetPacket(byte paddingMultiplier, Compressor compressor)
var packetDataLength = GetPacketDataLength(messageLength, paddingLength);
// lets construct an SSH data stream of the exact size required
- sshDataStream = new SshDataStream(packetLength + paddingLength + outboundPacketSequenceSize);
+ using (var sshDataStream = new SshDataStream(packetLength + paddingLength + outboundPacketSequenceSize))
+ {
+ // skip bytes for outbound packet sequenceSize
+ _ = sshDataStream.Seek(outboundPacketSequenceSize, SeekOrigin.Begin);
- // skip bytes for outbound packet sequenceSize
- sshDataStream.Seek(outboundPacketSequenceSize, SeekOrigin.Begin);
+ // add packet data length
+ sshDataStream.Write(packetDataLength);
- // add packet data length
- sshDataStream.Write(packetDataLength);
+ // add packet padding length
+ sshDataStream.WriteByte(paddingLength);
- // add packet padding length
- sshDataStream.WriteByte(paddingLength);
+ // add message payload
+ WriteBytes(sshDataStream);
- // add message payload
- WriteBytes(sshDataStream);
+ // add padding bytes
+ var paddingBytes = new byte[paddingLength];
+ CryptoAbstraction.GenerateRandom(paddingBytes);
+ sshDataStream.Write(paddingBytes, 0, paddingLength);
- // add padding bytes
- var paddingBytes = new byte[paddingLength];
- CryptoAbstraction.GenerateRandom(paddingBytes);
- sshDataStream.Write(paddingBytes, 0, paddingLength);
+ return sshDataStream.ToArray();
+ }
}
-
- return sshDataStream.ToArray();
}
private static uint GetPacketDataLength(int messageLength, byte paddingLength)
@@ -148,35 +141,19 @@ private static uint GetPacketDataLength(int messageLength, byte paddingLength)
private static byte GetPaddingLength(byte paddingMultiplier, long packetLength)
{
var paddingLength = (byte)((-packetLength) & (paddingMultiplier - 1));
+
if (paddingLength < paddingMultiplier)
{
paddingLength += paddingMultiplier;
}
+
return paddingLength;
}
- ///
- /// Returns a that represents this instance.
- ///
- ///
- /// A that represents this instance.
- ///
+ ///
public override string ToString()
{
- var enumerator = GetType().GetCustomAttributes(true).GetEnumerator();
- try
- {
- if (!enumerator.MoveNext())
- {
- return string.Format(CultureInfo.CurrentCulture, "'{0}' without Message attribute.", GetType().FullName);
- }
-
- return enumerator.Current.Name;
- }
- finally
- {
- enumerator.Dispose();
- }
+ return MessageName;
}
///
@@ -185,4 +162,4 @@ public override string ToString()
/// The for which to process the current message.
internal abstract void Process(Session session);
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Messages/MessageAttribute.cs b/src/Renci.SshNet/Messages/MessageAttribute.cs
deleted file mode 100644
index 10c0cdef0..000000000
--- a/src/Renci.SshNet/Messages/MessageAttribute.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using System;
-
-namespace Renci.SshNet.Messages
-{
-
- ///
- /// Indicates that a class represents SSH message. This class cannot be inherited.
- ///
- [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
- public sealed class MessageAttribute : Attribute
- {
- ///
- /// Gets or sets message name as defined in RFC 4250.
- ///
- ///
- /// The name.
- ///
- public string Name { get; set; }
-
- ///
- /// Gets or sets message number as defined in RFC 4250.
- ///
- ///
- /// The number.
- ///
- public byte Number { get; set; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The name.
- /// The number.
- public MessageAttribute(string name, byte number)
- {
- Name = name;
- Number = number;
- }
- }
-}
diff --git a/src/Renci.SshNet/Messages/ServiceName.cs b/src/Renci.SshNet/Messages/ServiceName.cs
index 1c63ddbed..bfd6644cd 100644
--- a/src/Renci.SshNet/Messages/ServiceName.cs
+++ b/src/Renci.SshNet/Messages/ServiceName.cs
@@ -1,17 +1,17 @@
namespace Renci.SshNet.Messages
{
///
- /// Specifies list of supported services
+ /// Specifies list of supported services.
///
public enum ServiceName
{
///
- /// ssh-userauth
+ /// ssh-userauth.
///
UserAuthentication,
///
- /// ssh-connection
+ /// ssh-connection.
///
Connection
}
diff --git a/src/Renci.SshNet/Messages/Transport/DebugMessage.cs b/src/Renci.SshNet/Messages/Transport/DebugMessage.cs
index b762bf41d..0331107d9 100644
--- a/src/Renci.SshNet/Messages/Transport/DebugMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/DebugMessage.cs
@@ -3,17 +3,34 @@
///
/// Represents SSH_MSG_DEBUG message.
///
- [Message("SSH_MSG_DEBUG", 4)]
public class DebugMessage : Message
{
private byte[] _message;
private byte[] _language;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_DEBUG";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 4;
+ }
+ }
+
///
/// Gets a value indicating whether the message to be always displayed.
///
///
- /// true if the message always to be displayed; otherwise, false.
+ /// if the message always to be displayed; otherwise, .
///
public bool IsAlwaysDisplay { get; private set; }
diff --git a/src/Renci.SshNet/Messages/Transport/DisconnectMessage.cs b/src/Renci.SshNet/Messages/Transport/DisconnectMessage.cs
index b5f43adfc..88ad5a01a 100644
--- a/src/Renci.SshNet/Messages/Transport/DisconnectMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/DisconnectMessage.cs
@@ -3,12 +3,29 @@
///
/// Represents SSH_MSG_DISCONNECT message.
///
- [Message("SSH_MSG_DISCONNECT", 1)]
public class DisconnectMessage : Message, IKeyExchangedAllowed
{
private byte[] _description;
private byte[] _language;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_DISCONNECT";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 1;
+ }
+ }
+
///
/// Gets disconnect reason code.
///
diff --git a/src/Renci.SshNet/Messages/Transport/DisconnectReason.cs b/src/Renci.SshNet/Messages/Transport/DisconnectReason.cs
index 35c6f885a..cf4119ba9 100644
--- a/src/Renci.SshNet/Messages/Transport/DisconnectReason.cs
+++ b/src/Renci.SshNet/Messages/Transport/DisconnectReason.cs
@@ -9,65 +9,82 @@ public enum DisconnectReason
/// Disconnect reason is not provided.
///
None = 0,
+
///
- /// SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT
+ /// SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT.
///
HostNotAllowedToConnect = 1,
+
///
- /// SSH_DISCONNECT_PROTOCOL_ERROR
+ /// SSH_DISCONNECT_PROTOCOL_ERROR.
///
ProtocolError = 2,
+
///
- /// SSH_DISCONNECT_KEY_EXCHANGE_FAILED
+ /// SSH_DISCONNECT_KEY_EXCHANGE_FAILED.
///
KeyExchangeFailed = 3,
+
///
- /// SSH_DISCONNECT_RESERVED
+ /// SSH_DISCONNECT_RESERVED.
///
+#pragma warning disable CA1700 // Do not name enum values 'Reserved'
Reserved = 4,
+#pragma warning restore CA1700 // Do not name enum values 'Reserved'
+
///
- /// SSH_DISCONNECT_MAC_ERROR
+ /// SSH_DISCONNECT_MAC_ERROR.
///
MacError = 5,
+
///
- /// SSH_DISCONNECT_COMPRESSION_ERROR
+ /// SSH_DISCONNECT_COMPRESSION_ERROR.
///
CompressionError = 6,
+
///
- /// SSH_DISCONNECT_SERVICE_NOT_AVAILABLE
+ /// SSH_DISCONNECT_SERVICE_NOT_AVAILABLE.
///
ServiceNotAvailable = 7,
+
///
- /// SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED
+ /// SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED.
///
ProtocolVersionNotSupported = 8,
+
///
- /// SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE
+ /// SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE.
///
HostKeyNotVerifiable = 9,
+
///
- /// SSH_DISCONNECT_CONNECTION_LOST
+ /// SSH_DISCONNECT_CONNECTION_LOST.
///
ConnectionLost = 10,
+
///
- /// SSH_DISCONNECT_BY_APPLICATION
+ /// SSH_DISCONNECT_BY_APPLICATION.
///
ByApplication = 11,
+
///
- /// SSH_DISCONNECT_TOO_MANY_CONNECTIONS
+ /// SSH_DISCONNECT_TOO_MANY_CONNECTIONS.
///
TooManyConnections = 12,
+
///
- /// SSH_DISCONNECT_AUTH_CANCELLED_BY_USER
+ /// SSH_DISCONNECT_AUTH_CANCELLED_BY_USER.
///
AuthenticationCanceledByUser = 13,
+
///
- /// SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE
+ /// SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE.
///
NoMoreAuthenticationMethodsAvailable = 14,
+
///
- /// SSH_DISCONNECT_ILLEGAL_USER_NAME
+ /// SSH_DISCONNECT_ILLEGAL_USER_NAME.
///
- IllegalUserName = 15,
+ IllegalUserName = 15
}
}
diff --git a/src/Renci.SshNet/Messages/Transport/IKeyExchangedAllowed.cs b/src/Renci.SshNet/Messages/Transport/IKeyExchangedAllowed.cs
index b53a09e40..1f06aeb31 100644
--- a/src/Renci.SshNet/Messages/Transport/IKeyExchangedAllowed.cs
+++ b/src/Renci.SshNet/Messages/Transport/IKeyExchangedAllowed.cs
@@ -1,9 +1,11 @@
namespace Renci.SshNet.Messages.Transport
{
///
- /// Indicates that message that implement this interface is allowed during key exchange phase
+ /// Indicates that message that implement this interface is allowed during key exchange phase.
///
+#pragma warning disable CA1040 // Avoid empty interfaces
public interface IKeyExchangedAllowed
+#pragma warning restore CA1040 // Avoid empty interfaces
{
}
}
diff --git a/src/Renci.SshNet/Messages/Transport/IgnoreMessage.cs b/src/Renci.SshNet/Messages/Transport/IgnoreMessage.cs
index 580cd3b21..b71b28788 100644
--- a/src/Renci.SshNet/Messages/Transport/IgnoreMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/IgnoreMessage.cs
@@ -1,29 +1,56 @@
using System;
-using System.Globalization;
-using Renci.SshNet.Abstractions;
-using Renci.SshNet.Common;
namespace Renci.SshNet.Messages.Transport
{
///
/// Represents SSH_MSG_IGNORE message.
///
- [Message("SSH_MSG_IGNORE", MessageNumber)]
public class IgnoreMessage : Message
{
- internal const byte MessageNumber = 2;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_IGNORE";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 2;
+ }
+ }
///
- /// Gets ignore message data if any.
+ /// Gets ignore message data if this message has been initialised
+ /// with data to be sent. Otherwise, returns an empty array.
///
public byte[] Data { get; private set; }
///
- /// Initializes a new instance of the class
+ /// Initializes a new instance of the class.
///
public IgnoreMessage()
{
- Data = Array.Empty;
+ Data = Array.Empty();
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The data.
+ public IgnoreMessage(byte[] data)
+ {
+ if (data is null)
+ {
+ throw new ArgumentNullException(nameof(data));
+ }
+
+ Data = data;
}
///
@@ -43,38 +70,12 @@ protected override int BufferCapacity
}
}
- ///
- /// Initializes a new instance of the class.
- ///
- /// The data.
- public IgnoreMessage(byte[] data)
- {
- if (data == null)
- throw new ArgumentNullException("data");
-
- Data = data;
- }
-
///
/// Called when type specific data need to be loaded.
///
protected override void LoadData()
{
- var dataLength = ReadUInt32();
- if (dataLength > int.MaxValue)
- {
- throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Data longer than {0} is not supported.", int.MaxValue));
- }
-
- if (dataLength > (DataStream.Length - DataStream.Position))
- {
- DiagnosticAbstraction.Log("SSH_MSG_IGNORE: Length exceeds data bytes, data ignored.");
- Data = Array.Empty;
- }
- else
- {
- Data = ReadBytes((int) dataLength);
- }
+ // Do nothing - this data is supposed to be ignored.
}
///
diff --git a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeGroup.cs b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeGroup.cs
index 6fe1c76ff..a17c23e33 100644
--- a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeGroup.cs
+++ b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeGroup.cs
@@ -5,16 +5,31 @@ namespace Renci.SshNet.Messages.Transport
///
/// Represents SSH_MSG_KEX_DH_GEX_GROUP message.
///
- [Message("SSH_MSG_KEX_DH_GEX_GROUP", MessageNumber)]
public class KeyExchangeDhGroupExchangeGroup : Message
{
- internal const byte MessageNumber = 31;
-
private byte[] _safePrime;
private byte[] _subGroup;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_KEX_DH_GEX_GROUP";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 31;
+ }
+ }
+
///
- /// Gets or sets the safe prime.
+ /// Gets the safe prime.
///
///
/// The safe prime.
@@ -25,7 +40,7 @@ public BigInteger SafePrime
}
///
- /// Gets or sets the generator for subgroup in GF(p).
+ /// Gets the generator for subgroup in GF(p).
///
///
/// The sub group.
diff --git a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeInit.cs b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeInit.cs
index c8af4724d..c63484739 100644
--- a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeInit.cs
+++ b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeInit.cs
@@ -3,9 +3,26 @@
///
/// Represents SSH_MSG_KEX_DH_GEX_INIT message.
///
- [Message("SSH_MSG_KEX_DH_GEX_INIT", 32)]
- internal class KeyExchangeDhGroupExchangeInit : Message, IKeyExchangedAllowed
+ internal sealed class KeyExchangeDhGroupExchangeInit : Message, IKeyExchangedAllowed
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_KEX_DH_GEX_INIT";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 32;
+ }
+ }
+
///
/// Gets the E value.
///
diff --git a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeReply.cs b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeReply.cs
index 88bad74e2..090dd71ab 100644
--- a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeReply.cs
+++ b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeReply.cs
@@ -1,19 +1,34 @@
-using Renci.SshNet.Common;
-
-namespace Renci.SshNet.Messages.Transport
+namespace Renci.SshNet.Messages.Transport
{
///
/// Represents SSH_MSG_KEX_DH_GEX_REPLY message.
///
- [Message("SSH_MSG_KEX_DH_GEX_REPLY", MessageNumber)]
- internal class KeyExchangeDhGroupExchangeReply : Message
+ internal sealed class KeyExchangeDhGroupExchangeReply : Message
{
- internal const byte MessageNumber = 33;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_KEX_DH_GEX_REPLY";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 33;
+ }
+ }
///
- /// Gets server public host key and certificates
+ /// Gets server public host key and certificates.
///
- /// The host key.
+ ///
+ /// The host key.
+ ///
public byte[] HostKey { get; private set; }
///
diff --git a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeRequest.cs b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeRequest.cs
index d31335910..1ad967c8e 100644
--- a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeRequest.cs
+++ b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhGroupExchangeRequest.cs
@@ -3,13 +3,28 @@
///
/// Represents SSH_MSG_KEX_DH_GEX_REQUEST message.
///
- [Message("SSH_MSG_KEX_DH_GEX_REQUEST", MessageNumber)]
- internal class KeyExchangeDhGroupExchangeRequest : Message, IKeyExchangedAllowed
+ internal sealed class KeyExchangeDhGroupExchangeRequest : Message, IKeyExchangedAllowed
{
- internal const byte MessageNumber = 34;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_KEX_DH_GEX_REQUEST";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 34;
+ }
+ }
///
- /// Gets or sets the minimal size in bits of an acceptable group.
+ /// Gets the minimum size, in bits, of an acceptable group.
///
///
/// The minimum.
@@ -17,7 +32,7 @@ internal class KeyExchangeDhGroupExchangeRequest : Message, IKeyExchangedAllowed
public uint Minimum { get; private set; }
///
- /// Gets or sets the preferred size in bits of the group the server will send.
+ /// Gets the preferred size, in bits, of the group the server will send.
///
///
/// The preferred.
@@ -25,7 +40,7 @@ internal class KeyExchangeDhGroupExchangeRequest : Message, IKeyExchangedAllowed
public uint Preferred { get; private set; }
///
- /// Gets or sets the maximal size in bits of an acceptable group.
+ /// Gets the maximum size, in bits, of an acceptable group.
///
///
/// The maximum.
diff --git a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhInitMessage.cs b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhInitMessage.cs
index 9d1d76850..3ce030c8d 100644
--- a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhInitMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhInitMessage.cs
@@ -3,9 +3,26 @@
///
/// Represents SSH_MSG_KEXDH_INIT message.
///
- [Message("SSH_MSG_KEXDH_INIT", 30)]
- internal class KeyExchangeDhInitMessage : Message, IKeyExchangedAllowed
+ internal sealed class KeyExchangeDhInitMessage : Message, IKeyExchangedAllowed
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_KEXDH_INIT";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 30;
+ }
+ }
+
///
/// Gets the E value.
///
diff --git a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhReplyMessage.cs b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhReplyMessage.cs
index 105e5797c..efc280183 100644
--- a/src/Renci.SshNet/Messages/Transport/KeyExchangeDhReplyMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/KeyExchangeDhReplyMessage.cs
@@ -3,11 +3,28 @@
///
/// Represents SSH_MSG_KEXDH_REPLY message.
///
- [Message("SSH_MSG_KEXDH_REPLY", 31)]
public class KeyExchangeDhReplyMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_KEXDH_REPLY";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 31;
+ }
+ }
+
///
- /// Gets server public host key and certificates
+ /// Gets server public host key and certificates.
///
/// The host key.
public byte[] HostKey { get; private set; }
diff --git a/src/Renci.SshNet/Messages/Transport/KeyExchangeEcdhInitMessage.cs b/src/Renci.SshNet/Messages/Transport/KeyExchangeEcdhInitMessage.cs
index ddcf03f19..ab5bc1c85 100644
--- a/src/Renci.SshNet/Messages/Transport/KeyExchangeEcdhInitMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/KeyExchangeEcdhInitMessage.cs
@@ -6,11 +6,28 @@ namespace Renci.SshNet.Messages.Transport
///
/// Represents SSH_MSG_KEXECDH_INIT message.
///
- [Message("SSH_MSG_KEX_ECDH_INIT", 30)]
- internal class KeyExchangeEcdhInitMessage : Message, IKeyExchangedAllowed
+ internal sealed class KeyExchangeEcdhInitMessage : Message, IKeyExchangedAllowed
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_KEX_ECDH_INIT";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 30;
+ }
+ }
+
///
- /// Gets the client's ephemeral contribution to the ECDH exchange, encoded as an octet string
+ /// Gets the client's ephemeral contribution to the ECDH exchange, encoded as an octet string.
///
public byte[] QC { get; private set; }
@@ -75,4 +92,4 @@ internal override void Process(Session session)
throw new NotImplementedException();
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Messages/Transport/KeyExchangeEcdhReplyMessage.cs b/src/Renci.SshNet/Messages/Transport/KeyExchangeEcdhReplyMessage.cs
index a194caf1e..70ed96c00 100644
--- a/src/Renci.SshNet/Messages/Transport/KeyExchangeEcdhReplyMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/KeyExchangeEcdhReplyMessage.cs
@@ -3,11 +3,28 @@
///
/// Represents SSH_MSG_KEXECDH_REPLY message.
///
- [Message("SSH_MSG_KEX_ECDH_REPLY", 31)]
public class KeyExchangeEcdhReplyMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_KEX_ECDH_REPLY";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 31;
+ }
+ }
+
///
- /// Gets a string encoding an X.509v3 certificate containing the server's ECDSA public host key
+ /// Gets a string encoding an X.509v3 certificate containing the server's ECDSA public host key.
///
/// The host key.
public byte[] KS { get; private set; }
@@ -69,4 +86,4 @@ internal override void Process(Session session)
session.OnKeyExchangeEcdhReplyMessageReceived(this);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Messages/Transport/KeyExchangeInitMessage.cs b/src/Renci.SshNet/Messages/Transport/KeyExchangeInitMessage.cs
index 8e9daff95..7bfce46dc 100644
--- a/src/Renci.SshNet/Messages/Transport/KeyExchangeInitMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/KeyExchangeInitMessage.cs
@@ -5,7 +5,6 @@ namespace Renci.SshNet.Messages.Transport
///
/// Represents SSH_MSG_KEXINIT message.
///
- [Message("SSH_MSG_KEXINIT", 20)]
public class KeyExchangeInitMessage : Message, IKeyExchangedAllowed
{
///
@@ -20,6 +19,24 @@ public KeyExchangeInitMessage()
#region Message Properties
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_KEXINIT";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 20;
+ }
+ }
+
///
/// Gets session cookie.
///
@@ -109,7 +126,7 @@ public KeyExchangeInitMessage()
/// Gets or sets a value indicating whether first key exchange packet follows.
///
///
- /// true if first key exchange packet follows; otherwise, false.
+ /// if first key exchange packet follows; otherwise, .
///
public bool FirstKexPacketFollows { get; set; }
diff --git a/src/Renci.SshNet/Messages/Transport/NewKeysMessage.cs b/src/Renci.SshNet/Messages/Transport/NewKeysMessage.cs
index 838d4373b..ea0f6b754 100644
--- a/src/Renci.SshNet/Messages/Transport/NewKeysMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/NewKeysMessage.cs
@@ -3,9 +3,26 @@
///
/// Represents SSH_MSG_NEWKEYS message.
///
- [Message("SSH_MSG_NEWKEYS", 21)]
public class NewKeysMessage : Message, IKeyExchangedAllowed
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_NEWKEYS";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 21;
+ }
+ }
+
///
/// Called when type specific data need to be loaded.
///
diff --git a/src/Renci.SshNet/Messages/Transport/ServiceAcceptMessage.cs b/src/Renci.SshNet/Messages/Transport/ServiceAcceptMessage.cs
index a7c2a8c6f..ce16d9fd4 100644
--- a/src/Renci.SshNet/Messages/Transport/ServiceAcceptMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/ServiceAcceptMessage.cs
@@ -6,10 +6,25 @@ namespace Renci.SshNet.Messages.Transport
///
/// Represents SSH_MSG_SERVICE_ACCEPT message.
///
- [Message("SSH_MSG_SERVICE_ACCEPT", MessageNumber)]
public class ServiceAcceptMessage : Message
{
- internal const byte MessageNumber = 6;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_SERVICE_ACCEPT";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 6;
+ }
+ }
///
/// Gets the name of the service.
diff --git a/src/Renci.SshNet/Messages/Transport/ServiceRequestMessage.cs b/src/Renci.SshNet/Messages/Transport/ServiceRequestMessage.cs
index c41a4f904..c7b6a6cbf 100644
--- a/src/Renci.SshNet/Messages/Transport/ServiceRequestMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/ServiceRequestMessage.cs
@@ -6,11 +6,28 @@ namespace Renci.SshNet.Messages.Transport
///
/// Represents SSH_MSG_SERVICE_REQUEST message.
///
- [Message("SSH_MSG_SERVICE_REQUEST", 5)]
public class ServiceRequestMessage : Message
{
private readonly byte[] _serviceName;
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_SERVICE_REQUEST";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 5;
+ }
+ }
+
///
/// Gets the name of the service.
///
diff --git a/src/Renci.SshNet/Messages/Transport/UnimplementedMessage.cs b/src/Renci.SshNet/Messages/Transport/UnimplementedMessage.cs
index 323a01439..761156408 100644
--- a/src/Renci.SshNet/Messages/Transport/UnimplementedMessage.cs
+++ b/src/Renci.SshNet/Messages/Transport/UnimplementedMessage.cs
@@ -5,9 +5,26 @@ namespace Renci.SshNet.Messages.Transport
///
/// Represents SSH_MSG_UNIMPLEMENTED message.
///
- [Message("SSH_MSG_UNIMPLEMENTED", 3)]
public class UnimplementedMessage : Message
{
+ ///
+ public override string MessageName
+ {
+ get
+ {
+ return "SSH_MSG_UNIMPLEMENTED";
+ }
+ }
+
+ ///
+ public override byte MessageNumber
+ {
+ get
+ {
+ return 3;
+ }
+ }
+
///
/// Called when type specific data need to be loaded.
///
diff --git a/src/Renci.SshNet/NetConfClient.cs b/src/Renci.SshNet/NetConfClient.cs
index b1877c601..09cff7609 100644
--- a/src/Renci.SshNet/NetConfClient.cs
+++ b/src/Renci.SshNet/NetConfClient.cs
@@ -1,13 +1,13 @@
using System;
-using Renci.SshNet.Common;
-using Renci.SshNet.NetConf;
-using System.Xml;
using System.Diagnostics.CodeAnalysis;
using System.Net;
+using System.Xml;
+
+using Renci.SshNet.Common;
+using Renci.SshNet.NetConf;
namespace Renci.SshNet
{
- // TODO: Please help with documentation here, as I don't know the details, specially for the methods not documented.
///
/// Contains operation for working with NetConf server.
///
@@ -16,7 +16,7 @@ public class NetConfClient : BaseClient
private int _operationTimeout;
///
- /// Holds instance that used to communicate to the server
+ /// Holds instance that used to communicate to the server.
///
private INetConfSession _netConfSession;
@@ -27,14 +27,20 @@ public class NetConfClient : BaseClient
/// The timeout to wait until an operation completes. The default value is negative
/// one (-1) milliseconds, which indicates an infinite time-out period.
///
- /// represents a value that is less than -1 or greater than milliseconds.
- public TimeSpan OperationTimeout {
- get { return TimeSpan.FromMilliseconds(_operationTimeout); }
+ /// represents a value that is less than -1 or greater than milliseconds.
+ public TimeSpan OperationTimeout
+ {
+ get
+ {
+ return TimeSpan.FromMilliseconds(_operationTimeout);
+ }
set
{
var timeoutInMilliseconds = value.TotalMilliseconds;
- if (timeoutInMilliseconds < -1d || timeoutInMilliseconds > int.MaxValue)
- throw new ArgumentOutOfRangeException("value", "The timeout must represent a value between -1 and Int32.MaxValue, inclusive.");
+ if (timeoutInMilliseconds is < -1d or > int.MaxValue)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), "The timeout must represent a value between -1 and Int32.MaxValue, inclusive.");
+ }
_operationTimeout = (int) timeoutInMilliseconds;
}
@@ -51,15 +57,13 @@ internal INetConfSession NetConfSession
get { return _netConfSession; }
}
- #region Constructors
-
///
/// Initializes a new instance of the class.
///
/// The connection info.
- /// is null.
+ /// is .
public NetConfClient(ConnectionInfo connectionInfo)
- : this(connectionInfo, false)
+ : this(connectionInfo, ownsConnectionInfo: false)
{
}
@@ -70,12 +74,12 @@ public NetConfClient(ConnectionInfo connectionInfo)
/// Connection port.
/// Authentication username.
/// Authentication password.
- /// is null.
- /// is invalid, or is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, or is or contains only whitespace characters.
/// is not within and .
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
public NetConfClient(string host, int port, string username, string password)
- : this(new PasswordConnectionInfo(host, port, username, password), true)
+ : this(new PasswordConnectionInfo(host, port, username, password), ownsConnectionInfo: true)
{
}
@@ -85,8 +89,8 @@ public NetConfClient(string host, int port, string username, string password)
/// Connection host.
/// Authentication username.
/// Authentication password.
- /// is null.
- /// is invalid, or is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, or is or contains only whitespace characters.
public NetConfClient(string host, string username, string password)
: this(host, ConnectionInfo.DefaultPort, username, password)
{
@@ -99,12 +103,12 @@ public NetConfClient(string host, string username, string password)
/// Connection port.
/// Authentication username.
/// Authentication private key file(s) .
- /// is null.
- /// is invalid, -or- is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, -or- is or contains only whitespace characters.
/// is not within and .
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
- public NetConfClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)
- : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), true)
+ public NetConfClient(string host, int port, string username, params IPrivateKeySource[] keyFiles)
+ : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), ownsConnectionInfo: true)
{
}
@@ -114,9 +118,9 @@ public NetConfClient(string host, int port, string username, params PrivateKeyFi
/// Connection host.
/// Authentication username.
/// Authentication private key file(s) .
- /// is null.
- /// is invalid, -or- is null or contains only whitespace characters.
- public NetConfClient(string host, string username, params PrivateKeyFile[] keyFiles)
+ /// is .
+ /// is invalid, -or- is or contains only whitespace characters.
+ public NetConfClient(string host, string username, params IPrivateKeySource[] keyFiles)
: this(host, ConnectionInfo.DefaultPort, username, keyFiles)
{
}
@@ -126,9 +130,9 @@ public NetConfClient(string host, string username, params PrivateKeyFile[] keyFi
///
/// The connection info.
/// Specified whether this instance owns the connection info.
- /// is null.
+ /// is .
///
- /// If is true, then the
+ /// If is , then the
/// connection info will be disposed when this instance is disposed.
///
private NetConfClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
@@ -142,10 +146,10 @@ private NetConfClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
/// The connection info.
/// Specified whether this instance owns the connection info.
/// The factory to use for creating new services.
- /// is null.
- /// is null.
+ /// is .
+ /// is .
///
- /// If is true, then the
+ /// If is , then the
/// connection info will be disposed when this instance is disposed.
///
internal NetConfClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
@@ -155,15 +159,13 @@ internal NetConfClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, I
AutomaticMessageIdHandling = true;
}
- #endregion
-
///
/// Gets the NetConf server capabilities.
///
///
/// The NetConf server capabilities.
///
- public XmlDocument ServerCapabilities
+ public XmlDocument ServerCapabilities
{
get { return _netConfSession.ServerCapabilities; }
}
@@ -184,8 +186,8 @@ public XmlDocument ClientCapabilities
/// enabled.
///
///
- /// true if automatic message id handling is enabled; otherwise, false.
- /// The default value is true.
+ /// if automatic message id handling is enabled; otherwise, .
+ /// The default value is .
///
public bool AutomaticMessageIdHandling { get; set; }
@@ -193,7 +195,9 @@ public XmlDocument ClientCapabilities
/// Sends the receive RPC.
///
/// The RPC.
- /// Reply message to RPC request
+ ///
+ /// Reply message to RPC request.
+ ///
/// Client is not connected.
public XmlDocument SendReceiveRpc(XmlDocument rpc)
{
@@ -204,7 +208,9 @@ public XmlDocument SendReceiveRpc(XmlDocument rpc)
/// Sends the receive RPC.
///
/// The XML.
- /// Reply message to RPC request
+ ///
+ /// Reply message to RPC request.
+ ///
public XmlDocument SendReceiveRpc(string xml)
{
var rpc = new XmlDocument();
@@ -215,7 +221,9 @@ public XmlDocument SendReceiveRpc(string xml)
///
/// Sends the close RPC.
///
- /// Reply message to closing RPC request
+ ///
+ /// Reply message to closing RPC request.
+ ///
/// Client is not connected.
public XmlDocument SendCloseRpc()
{
@@ -245,9 +253,9 @@ protected override void OnDisconnecting()
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
diff --git a/src/Renci.SshNet/Netconf/INetConfSession.cs b/src/Renci.SshNet/Netconf/INetConfSession.cs
index 4dd3e24d4..223cd3e0d 100644
--- a/src/Renci.SshNet/Netconf/INetConfSession.cs
+++ b/src/Renci.SshNet/Netconf/INetConfSession.cs
@@ -1,25 +1,39 @@
using System.Xml;
+using Renci.SshNet.Common;
+
namespace Renci.SshNet.NetConf
{
+ ///
+ /// Represents a NETCONF session.
+ ///
internal interface INetConfSession : ISubsystemSession
{
///
- /// Gets the NetConf server capabilities.
+ /// Gets the NETCONF server capabilities.
///
///
- /// The NetConf server capabilities.
+ /// The NETCONF server capabilities.
///
XmlDocument ServerCapabilities { get; }
///
- /// Gets the NetConf client capabilities.
+ /// Gets the NETCONF client capabilities.
///
///
- /// The NetConf client capabilities.
+ /// The NETCONF client capabilities.
///
XmlDocument ClientCapabilities { get; }
+ ///
+ /// Sends the specified RPC request and returns the reply sent by the NETCONF server.
+ ///
+ /// The RPC request.
+ /// to automatically increment the message id and verify the message id of the RPC reply.
+ ///
+ /// The RPC reply.
+ ///
+ /// is and the message id in the RPC reply does not match the message id of the RPC request.
XmlDocument SendReceiveRpc(XmlDocument rpc, bool automaticMessageIdHandling);
}
}
diff --git a/src/Renci.SshNet/Netconf/NetConfSession.cs b/src/Renci.SshNet/Netconf/NetConfSession.cs
index 14ba00a6e..317b99c1c 100644
--- a/src/Renci.SshNet/Netconf/NetConfSession.cs
+++ b/src/Renci.SshNet/Netconf/NetConfSession.cs
@@ -1,21 +1,22 @@
using System;
using System.Globalization;
using System.Text;
+using System.Text.RegularExpressions;
using System.Threading;
-using Renci.SshNet.Common;
using System.Xml;
-using System.Text.RegularExpressions;
+
+using Renci.SshNet.Common;
namespace Renci.SshNet.NetConf
{
- internal class NetConfSession : SubsystemSession, INetConfSession
+ internal sealed class NetConfSession : SubsystemSession, INetConfSession
{
private const string Prompt = "]]>]]>";
private readonly StringBuilder _data = new StringBuilder();
private bool _usingFramingProtocol;
- private EventWaitHandle _serverCapabilitiesConfirmed = new AutoResetEvent(false);
- private EventWaitHandle _rpcReplyReceived = new AutoResetEvent(false);
+ private EventWaitHandle _serverCapabilitiesConfirmed = new AutoResetEvent(initialState: false);
+ private EventWaitHandle _rpcReplyReceived = new AutoResetEvent(initialState: false);
private StringBuilder _rpcReply = new StringBuilder();
private int _messageId;
@@ -46,12 +47,11 @@ public NetConfSession(ISession session, int operationTimeout)
"" +
"" +
"");
-
}
public XmlDocument SendReceiveRpc(XmlDocument rpc, bool automaticMessageIdHandling)
{
- _data.Clear();
+ _ = _data.Clear();
XmlNamespaceManager nsMgr = null;
if (automaticMessageIdHandling)
@@ -61,15 +61,16 @@ public XmlDocument SendReceiveRpc(XmlDocument rpc, bool automaticMessageIdHandli
nsMgr.AddNamespace("nc", "urn:ietf:params:xml:ns:netconf:base:1.0");
rpc.SelectSingleNode("/nc:rpc/@message-id", nsMgr).Value = _messageId.ToString(CultureInfo.InvariantCulture);
}
+
_rpcReply = new StringBuilder();
- _rpcReplyReceived.Reset();
+ _ = _rpcReplyReceived.Reset();
var reply = new XmlDocument();
if (_usingFramingProtocol)
{
var command = new StringBuilder(rpc.InnerXml.Length + 10);
- command.AppendFormat("\n#{0}\n", rpc.InnerXml.Length);
- command.Append(rpc.InnerXml);
- command.Append("\n##\n");
+ _ = command.AppendFormat(CultureInfo.InvariantCulture, "\n#{0}\n", rpc.InnerXml.Length);
+ _ = command.Append(rpc.InnerXml);
+ _ = command.Append("\n##\n");
SendData(Encoding.UTF8.GetBytes(command.ToString()));
WaitOnHandle(_rpcReplyReceived, OperationTimeout);
@@ -81,6 +82,7 @@ public XmlDocument SendReceiveRpc(XmlDocument rpc, bool automaticMessageIdHandli
WaitOnHandle(_rpcReplyReceived, OperationTimeout);
reply.LoadXml(_rpcReply.ToString());
}
+
if (automaticMessageIdHandling)
{
var replyId = rpc.SelectSingleNode("/nc:rpc/@message-id", nsMgr).Value;
@@ -89,14 +91,15 @@ public XmlDocument SendReceiveRpc(XmlDocument rpc, bool automaticMessageIdHandli
throw new NetConfServerException("The rpc message id does not match the rpc-reply message id.");
}
}
+
return reply;
}
protected override void OnChannelOpen()
{
- _data.Clear();
+ _ = _data.Clear();
- var message = string.Format("{0}{1}", ClientCapabilities.InnerXml, Prompt);
+ var message = string.Concat(ClientCapabilities.InnerXml, Prompt);
SendData(Encoding.UTF8.GetBytes(message));
@@ -107,21 +110,22 @@ protected override void OnDataReceived(byte[] data)
{
var chunk = Encoding.UTF8.GetString(data);
- if (ServerCapabilities == null) // This must be server capabilities, old protocol
+ if (ServerCapabilities is null)
{
- _data.Append(chunk);
+ _ = _data.Append(chunk);
if (!chunk.Contains(Prompt))
{
return;
}
+
try
{
- chunk = _data.ToString();
- _data.Clear();
+ chunk = _data.ToString();
+ _ = _data.Clear();
ServerCapabilities = new XmlDocument();
- ServerCapabilities.LoadXml(chunk.Replace(Prompt, ""));
+ ServerCapabilities.LoadXml(chunk.Replace(Prompt, string.Empty));
}
catch (XmlException e)
{
@@ -131,9 +135,9 @@ protected override void OnDataReceived(byte[] data)
var nsMgr = new XmlNamespaceManager(ServerCapabilities.NameTable);
nsMgr.AddNamespace("nc", "urn:ietf:params:xml:ns:netconf:base:1.0");
- _usingFramingProtocol = (ServerCapabilities.SelectSingleNode("/nc:hello/nc:capabilities/nc:capability[text()='urn:ietf:params:netconf:base:1.1']", nsMgr) != null);
+ _usingFramingProtocol = ServerCapabilities.SelectSingleNode("/nc:hello/nc:capabilities/nc:capability[text()='urn:ietf:params:netconf:base:1.1']", nsMgr) != null;
- _serverCapabilitiesConfirmed.Set();
+ _ = _serverCapabilitiesConfirmed.Set();
}
else if (_usingFramingProtocol)
{
@@ -146,30 +150,35 @@ protected override void OnDataReceived(byte[] data)
{
break;
}
- var fractionLength = Convert.ToInt32(match.Groups["length"].Value);
- _rpcReply.Append(chunk, position + match.Index + match.Length, fractionLength);
+
+ var fractionLength = Convert.ToInt32(match.Groups["length"].Value, CultureInfo.InvariantCulture);
+ _ = _rpcReply.Append(chunk, position + match.Index + match.Length, fractionLength);
position += match.Index + match.Length + fractionLength;
}
+
+#if NET7_0_OR_GREATER
+ if (Regex.IsMatch(chunk.AsSpan(position), @"\n##\n"))
+#else
if (Regex.IsMatch(chunk.Substring(position), @"\n##\n"))
+#endif // NET7_0_OR_GREATER
{
- _rpcReplyReceived.Set();
+ _ = _rpcReplyReceived.Set();
}
}
- else // Old protocol
+ else
{
- _data.Append(chunk);
+ _ = _data.Append(chunk);
if (!chunk.Contains(Prompt))
{
return;
- //throw new NetConfServerException("Server XML message does not end with the prompt " + _prompt);
}
-
+
chunk = _data.ToString();
- _data.Clear();
+ _ = _data.Clear();
- _rpcReply.Append(chunk.Replace(Prompt, ""));
- _rpcReplyReceived.Set();
+ _ = _rpcReply.Append(chunk.Replace(Prompt, string.Empty));
+ _ = _rpcReplyReceived.Set();
}
}
diff --git a/src/Renci.SshNet/NoneAuthenticationMethod.cs b/src/Renci.SshNet/NoneAuthenticationMethod.cs
index a5d842fd7..3969f1b29 100644
--- a/src/Renci.SshNet/NoneAuthenticationMethod.cs
+++ b/src/Renci.SshNet/NoneAuthenticationMethod.cs
@@ -1,23 +1,22 @@
using System;
using System.Threading;
-#if !FEATURE_WAITHANDLE_DISPOSE
-using Renci.SshNet.Common;
-#endif // !FEATURE_WAITHANDLE_DISPOSE
-using Renci.SshNet.Messages.Authentication;
+
using Renci.SshNet.Messages;
+using Renci.SshNet.Messages.Authentication;
namespace Renci.SshNet
{
///
- /// Provides functionality for "none" authentication method
+ /// Provides functionality for "none" authentication method.
///
public class NoneAuthenticationMethod : AuthenticationMethod, IDisposable
{
private AuthenticationResult _authenticationResult = AuthenticationResult.Failure;
- private EventWaitHandle _authenticationCompleted = new AutoResetEvent(false);
+ private EventWaitHandle _authenticationCompleted = new AutoResetEvent(initialState: false);
+ private bool _isDisposed;
///
- /// Gets connection name
+ /// Gets the name of the authentication method.
///
public override string Name
{
@@ -28,7 +27,7 @@ public override string Name
/// Initializes a new instance of the class.
///
/// The username.
- /// is whitespace or null.
+ /// is whitespace or .
public NoneAuthenticationMethod(string username)
: base(username)
{
@@ -41,11 +40,13 @@ public NoneAuthenticationMethod(string username)
///
/// Result of authentication process.
///
- /// is null.
+ /// is .
public override AuthenticationResult Authenticate(Session session)
{
- if (session == null)
- throw new ArgumentNullException("session");
+ if (session is null)
+ {
+ throw new ArgumentNullException(nameof(session));
+ }
session.UserAuthenticationSuccessReceived += Session_UserAuthenticationSuccessReceived;
session.UserAuthenticationFailureReceived += Session_UserAuthenticationFailureReceived;
@@ -68,43 +69,45 @@ private void Session_UserAuthenticationSuccessReceived(object sender, MessageEve
{
_authenticationResult = AuthenticationResult.Success;
- _authenticationCompleted.Set();
+ _ = _authenticationCompleted.Set();
}
private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs e)
{
if (e.Message.PartialSuccess)
+ {
_authenticationResult = AuthenticationResult.PartialSuccess;
+ }
else
+ {
_authenticationResult = AuthenticationResult.Failure;
+ }
// Copy allowed authentication methods
AllowedAuthentications = e.Message.AllowedAuthentications;
- _authenticationCompleted.Set();
+ _ = _authenticationCompleted.Set();
}
-
- #region IDisposable Members
-
- private bool _isDisposed;
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -120,15 +123,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~NoneAuthenticationMethod()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
-
}
}
diff --git a/src/Renci.SshNet/PasswordAuthenticationMethod.cs b/src/Renci.SshNet/PasswordAuthenticationMethod.cs
index 48e46bef3..f53016240 100644
--- a/src/Renci.SshNet/PasswordAuthenticationMethod.cs
+++ b/src/Renci.SshNet/PasswordAuthenticationMethod.cs
@@ -1,10 +1,12 @@
using System;
+using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
+
using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
-using Renci.SshNet.Messages.Authentication;
using Renci.SshNet.Messages;
+using Renci.SshNet.Messages.Authentication;
namespace Renci.SshNet
{
@@ -13,15 +15,16 @@ namespace Renci.SshNet
///
public class PasswordAuthenticationMethod : AuthenticationMethod, IDisposable
{
+ private readonly RequestMessage _requestMessage;
+ private readonly byte[] _password;
private AuthenticationResult _authenticationResult = AuthenticationResult.Failure;
private Session _session;
- private EventWaitHandle _authenticationCompleted = new AutoResetEvent(false);
+ private EventWaitHandle _authenticationCompleted = new AutoResetEvent(initialState: false);
private Exception _exception;
- private readonly RequestMessage _requestMessage;
- private readonly byte[] _password;
+ private bool _isDisposed;
///
- /// Gets authentication method name
+ /// Gets the name of the authentication method.
///
public override string Name
{
@@ -49,8 +52,8 @@ internal byte[] Password
///
/// The username.
/// The password.
- /// is whitespace or null.
- /// is null.
+ /// is whitespace or .
+ /// is .
public PasswordAuthenticationMethod(string username, string password)
: this(username, Encoding.UTF8.GetBytes(password))
{
@@ -61,13 +64,15 @@ public PasswordAuthenticationMethod(string username, string password)
///
/// The username.
/// The password.
- /// is whitespace or null.
- /// is null.
+ /// is whitespace or .
+ /// is .
public PasswordAuthenticationMethod(string username, byte[] password)
: base(username)
{
- if (password == null)
- throw new ArgumentNullException("password");
+ if (password is null)
+ {
+ throw new ArgumentNullException(nameof(password));
+ }
_password = password;
_requestMessage = new RequestMessagePassword(ServiceName.Connection, Username, _password);
@@ -80,11 +85,13 @@ public PasswordAuthenticationMethod(string username, byte[] password)
///
/// Result of authentication process.
///
- /// is null.
+ /// is .
public override AuthenticationResult Authenticate(Session session)
{
- if (session == null)
- throw new ArgumentNullException("session");
+ if (session is null)
+ {
+ throw new ArgumentNullException(nameof(session));
+ }
_session = session;
@@ -98,7 +105,7 @@ public override AuthenticationResult Authenticate(Session session)
session.SendMessage(_requestMessage);
session.WaitOnHandle(_authenticationCompleted);
}
- finally
+ finally
{
session.UnRegisterMessage("SSH_MSG_USERAUTH_PASSWD_CHANGEREQ");
session.UserAuthenticationSuccessReceived -= Session_UserAuthenticationSuccessReceived;
@@ -107,7 +114,9 @@ public override AuthenticationResult Authenticate(Session session)
}
if (_exception != null)
- throw _exception;
+ {
+ ExceptionDispatchInfo.Capture(_exception).Throw();
+ }
return _authenticationResult;
}
@@ -116,20 +125,24 @@ private void Session_UserAuthenticationSuccessReceived(object sender, MessageEve
{
_authenticationResult = AuthenticationResult.Success;
- _authenticationCompleted.Set();
+ _ = _authenticationCompleted.Set();
}
private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs e)
{
if (e.Message.PartialSuccess)
+ {
_authenticationResult = AuthenticationResult.PartialSuccess;
+ }
else
+ {
_authenticationResult = AuthenticationResult.Failure;
+ }
- // Copy allowed authentication methods
+ // Copy allowed authentication methods
AllowedAuthentications = e.Message.AllowedAuthentications;
- _authenticationCompleted.Set();
+ _ = _authenticationCompleted.Set();
}
private void Session_UserAuthenticationPasswordChangeRequiredReceived(object sender, MessageEventArgs e)
@@ -142,45 +155,40 @@ private void Session_UserAuthenticationPasswordChangeRequiredReceived(object sen
{
var eventArgs = new AuthenticationPasswordChangeEventArgs(Username);
- // Raise an event to allow user to supply a new password
- if (PasswordExpired != null)
- {
- PasswordExpired(this, eventArgs);
- }
+ // Raise an event to allow user to supply a new password
+ PasswordExpired?.Invoke(this, eventArgs);
- // Send new authentication request with new password
+ // Send new authentication request with new password
_session.SendMessage(new RequestMessagePassword(ServiceName.Connection, Username, _password, eventArgs.NewPassword));
}
catch (Exception exp)
{
_exception = exp;
- _authenticationCompleted.Set();
+ _ = _authenticationCompleted.Set();
}
});
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
-
+ }
+
if (disposing)
{
var authenticationCompleted = _authenticationCompleted;
@@ -195,14 +203,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~PasswordAuthenticationMethod()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/PasswordConnectionInfo.cs b/src/Renci.SshNet/PasswordConnectionInfo.cs
index d42ff5094..072b32147 100644
--- a/src/Renci.SshNet/PasswordConnectionInfo.cs
+++ b/src/Renci.SshNet/PasswordConnectionInfo.cs
@@ -6,21 +6,15 @@
namespace Renci.SshNet
{
///
- /// Provides connection information when password authentication method is used
+ /// Provides connection information when password authentication method is used.
///
- ///
- ///
- ///
- ///
- ///
public class PasswordConnectionInfo : ConnectionInfo, IDisposable
{
+ private bool _isDisposed;
+
///
/// Occurs when user's password has expired and needs to be changed.
///
- ///
- ///
- ///
public event EventHandler PasswordExpired;
///
@@ -29,11 +23,8 @@ public class PasswordConnectionInfo : ConnectionInfo, IDisposable
/// Connection host.
/// Connection username.
/// Connection password.
- ///
- ///
- ///
- /// is null.
- /// is invalid, or is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, or is or contains only whitespace characters.
public PasswordConnectionInfo(string host, string username, string password)
: this(host, DefaultPort, username, Encoding.UTF8.GetBytes(password))
{
@@ -46,8 +37,8 @@ public PasswordConnectionInfo(string host, string username, string password)
/// Connection port.
/// Connection username.
/// Connection password.
- /// is null.
- /// is invalid, or is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, or is or contains only whitespace characters.
/// is not within and .
public PasswordConnectionInfo(string host, int port, string username, string password)
: this(host, port, username, Encoding.UTF8.GetBytes(password), ProxyTypes.None, string.Empty, 0, string.Empty, string.Empty)
@@ -148,8 +139,8 @@ public PasswordConnectionInfo(string host, string username, byte[] password)
/// Connection port.
/// Connection username.
/// Connection password.
- /// is null.
- /// is invalid, or is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, or is or contains only whitespace characters.
/// is not within and .
public PasswordConnectionInfo(string host, int port, string username, byte[] password)
: this(host, port, username, password, ProxyTypes.None, string.Empty, 0, string.Empty, string.Empty)
@@ -249,8 +240,7 @@ public PasswordConnectionInfo(string host, int port, string username, byte[] pas
{
foreach (var authenticationMethod in AuthenticationMethods)
{
- var pwdAuthentication = authenticationMethod as PasswordAuthenticationMethod;
- if (pwdAuthentication != null)
+ if (authenticationMethod is PasswordAuthenticationMethod pwdAuthentication)
{
pwdAuthentication.PasswordExpired += AuthenticationMethod_PasswordExpired;
}
@@ -259,33 +249,30 @@ public PasswordConnectionInfo(string host, int port, string username, byte[] pas
private void AuthenticationMethod_PasswordExpired(object sender, AuthenticationPasswordChangeEventArgs e)
{
- if (PasswordExpired != null)
- {
- PasswordExpired(sender, e);
- }
+#pragma warning disable MA0091 // Sender should be 'this' for instance events
+ PasswordExpired?.Invoke(sender, e);
+#pragma warning restore MA0091 // Sender should be 'this' for instance events
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -293,8 +280,7 @@ protected virtual void Dispose(bool disposing)
{
foreach (var authenticationMethod in AuthenticationMethods)
{
- var disposable = authenticationMethod as IDisposable;
- if (disposable != null)
+ if (authenticationMethod is IDisposable disposable)
{
disposable.Dispose();
}
@@ -306,17 +292,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~PasswordConnectionInfo()
{
- // Do not re-create Dispose clean-up code here.
- // Calling Dispose(false) is optimal in terms of
- // readability and maintainability.
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/PrivateKeyAuthenticationMethod.cs b/src/Renci.SshNet/PrivateKeyAuthenticationMethod.cs
index 93ebbe19d..a8f7f4bd3 100644
--- a/src/Renci.SshNet/PrivateKeyAuthenticationMethod.cs
+++ b/src/Renci.SshNet/PrivateKeyAuthenticationMethod.cs
@@ -1,11 +1,13 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
-using Renci.SshNet.Messages.Authentication;
-using Renci.SshNet.Messages;
-using Renci.SshNet.Common;
+using System.Linq;
using System.Threading;
+using Renci.SshNet.Common;
+using Renci.SshNet.Messages;
+using Renci.SshNet.Messages.Authentication;
+
namespace Renci.SshNet
{
///
@@ -14,11 +16,14 @@ namespace Renci.SshNet
public class PrivateKeyAuthenticationMethod : AuthenticationMethod, IDisposable
{
private AuthenticationResult _authenticationResult = AuthenticationResult.Failure;
- private EventWaitHandle _authenticationCompleted = new ManualResetEvent(false);
+ private EventWaitHandle _authenticationCompleted = new ManualResetEvent(initialState: false);
+#pragma warning disable S1450 // Private fields only used as local variables in methods should become local variables
private bool _isSignatureRequired;
+#pragma warning restore S1450 // Private fields only used as local variables in methods should become local variables
+ private bool _isDisposed;
///
- /// Gets authentication method name
+ /// Gets the name of the authentication method.
///
public override string Name
{
@@ -28,21 +33,23 @@ public override string Name
///
/// Gets the key files used for authentication.
///
- public ICollection KeyFiles { get; private set; }
+ public ICollection KeyFiles { get; private set; }
///
/// Initializes a new instance of the class.
///
/// The username.
/// The key files.
- /// is whitespace or null.
- public PrivateKeyAuthenticationMethod(string username, params PrivateKeyFile[] keyFiles)
+ /// is whitespace or .
+ public PrivateKeyAuthenticationMethod(string username, params IPrivateKeySource[] keyFiles)
: base(username)
{
- if (keyFiles == null)
- throw new ArgumentNullException("keyFiles");
+ if (keyFiles is null)
+ {
+ throw new ArgumentNullException(nameof(keyFiles));
+ }
- KeyFiles = new Collection(keyFiles);
+ KeyFiles = new Collection(keyFiles);
}
///
@@ -60,51 +67,53 @@ public override AuthenticationResult Authenticate(Session session)
session.RegisterMessage("SSH_MSG_USERAUTH_PK_OK");
+ var hostAlgorithms = KeyFiles.SelectMany(x => x.HostKeyAlgorithms).ToList();
+
try
{
- foreach (var keyFile in KeyFiles)
+ foreach (var hostAlgorithm in hostAlgorithms)
{
- _authenticationCompleted.Reset();
+ _ = _authenticationCompleted.Reset();
_isSignatureRequired = false;
var message = new RequestMessagePublicKey(ServiceName.Connection,
Username,
- keyFile.HostKey.Name,
- keyFile.HostKey.Data);
+ hostAlgorithm.Name,
+ hostAlgorithm.Data);
- if (KeyFiles.Count < 2)
+ if (hostAlgorithms.Count == 1)
{
- // If only one key file provided then send signature for very first request
+ // If only one key file provided then send signature for very first request
var signatureData = new SignatureData(message, session.SessionId).GetBytes();
- message.Signature = keyFile.HostKey.Sign(signatureData);
+ message.Signature = hostAlgorithm.Sign(signatureData);
}
- // Send public key authentication request
+ // Send public key authentication request
session.SendMessage(message);
session.WaitOnHandle(_authenticationCompleted);
if (_isSignatureRequired)
{
- _authenticationCompleted.Reset();
+ _ = _authenticationCompleted.Reset();
var signatureMessage = new RequestMessagePublicKey(ServiceName.Connection,
Username,
- keyFile.HostKey.Name,
- keyFile.HostKey.Data);
+ hostAlgorithm.Name,
+ hostAlgorithm.Data);
var signatureData = new SignatureData(message, session.SessionId).GetBytes();
- signatureMessage.Signature = keyFile.HostKey.Sign(signatureData);
+ signatureMessage.Signature = hostAlgorithm.Sign(signatureData);
- // Send public key authentication request with signature
+ // Send public key authentication request with signature
session.SendMessage(signatureMessage);
}
session.WaitOnHandle(_authenticationCompleted);
- if (_authenticationResult == AuthenticationResult.Success)
+ if (_authenticationResult is AuthenticationResult.Success or AuthenticationResult.PartialSuccess)
{
break;
}
@@ -125,49 +134,51 @@ private void Session_UserAuthenticationSuccessReceived(object sender, MessageEve
{
_authenticationResult = AuthenticationResult.Success;
- _authenticationCompleted.Set();
+ _ = _authenticationCompleted.Set();
}
private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs e)
{
if (e.Message.PartialSuccess)
+ {
_authenticationResult = AuthenticationResult.PartialSuccess;
+ }
else
+ {
_authenticationResult = AuthenticationResult.Failure;
+ }
- // Copy allowed authentication methods
+ // Copy allowed authentication methods
AllowedAuthentications = e.Message.AllowedAuthentications;
- _authenticationCompleted.Set();
+ _ = _authenticationCompleted.Set();
}
private void Session_UserAuthenticationPublicKeyReceived(object sender, MessageEventArgs e)
{
_isSignatureRequired = true;
- _authenticationCompleted.Set();
+ _ = _authenticationCompleted.Set();
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -183,17 +194,14 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~PrivateKeyAuthenticationMethod()
{
- Dispose(false);
+ Dispose(disposing: false);
}
- #endregion
-
- private class SignatureData : SshData
+ private sealed class SignatureData : SshData
{
private readonly RequestMessagePublicKey _message;
diff --git a/src/Renci.SshNet/PrivateKeyConnectionInfo.cs b/src/Renci.SshNet/PrivateKeyConnectionInfo.cs
index 7f0c4f658..dacfc36b1 100644
--- a/src/Renci.SshNet/PrivateKeyConnectionInfo.cs
+++ b/src/Renci.SshNet/PrivateKeyConnectionInfo.cs
@@ -5,17 +5,16 @@
namespace Renci.SshNet
{
///
- /// Provides connection information when private key authentication method is used
+ /// Provides connection information when private key authentication method is used.
///
- ///
- ///
- ///
public class PrivateKeyConnectionInfo : ConnectionInfo, IDisposable
{
+ private bool _isDisposed;
+
///
/// Gets the key files used for authentication.
///
- public ICollection KeyFiles { get; private set; }
+ public ICollection KeyFiles { get; private set; }
///
/// Initializes a new instance of the class.
@@ -23,14 +22,9 @@ public class PrivateKeyConnectionInfo : ConnectionInfo, IDisposable
/// Connection host.
/// Connection username.
/// Connection key files.
- ///
- ///
- ///
- ///
public PrivateKeyConnectionInfo(string host, string username, params PrivateKeyFile[] keyFiles)
: this(host, DefaultPort, username, ProxyTypes.None, string.Empty, 0, string.Empty, string.Empty, keyFiles)
{
-
}
///
@@ -40,13 +34,13 @@ public PrivateKeyConnectionInfo(string host, string username, params PrivateKeyF
/// Connection port.
/// Connection username.
/// Connection key files.
- public PrivateKeyConnectionInfo(string host, int port, string username, params PrivateKeyFile[] keyFiles)
+ public PrivateKeyConnectionInfo(string host, int port, string username, params IPrivateKeySource[] keyFiles)
: this(host, port, username, ProxyTypes.None, string.Empty, 0, string.Empty, string.Empty, keyFiles)
{
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// Connection host.
/// The port.
@@ -55,13 +49,13 @@ public PrivateKeyConnectionInfo(string host, int port, string username, params P
/// The proxy host.
/// The proxy port.
/// The key files.
- public PrivateKeyConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, params PrivateKeyFile[] keyFiles)
+ public PrivateKeyConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, params IPrivateKeySource[] keyFiles)
: this(host, port, username, proxyType, proxyHost, proxyPort, string.Empty, string.Empty, keyFiles)
{
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// Connection host.
/// The port.
@@ -71,13 +65,13 @@ public PrivateKeyConnectionInfo(string host, int port, string username, ProxyTyp
/// The proxy port.
/// The proxy username.
/// The key files.
- public PrivateKeyConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, params PrivateKeyFile[] keyFiles)
+ public PrivateKeyConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, params IPrivateKeySource[] keyFiles)
: this(host, port, username, proxyType, proxyHost, proxyPort, proxyUsername, string.Empty, keyFiles)
{
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// Connection host.
/// Connection username.
@@ -85,13 +79,13 @@ public PrivateKeyConnectionInfo(string host, int port, string username, ProxyTyp
/// The proxy host.
/// The proxy port.
/// The key files.
- public PrivateKeyConnectionInfo(string host, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, params PrivateKeyFile[] keyFiles)
+ public PrivateKeyConnectionInfo(string host, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, params IPrivateKeySource[] keyFiles)
: this(host, DefaultPort, username, proxyType, proxyHost, proxyPort, string.Empty, string.Empty, keyFiles)
{
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// Connection host.
/// Connection username.
@@ -100,13 +94,13 @@ public PrivateKeyConnectionInfo(string host, string username, ProxyTypes proxyTy
/// The proxy port.
/// The proxy username.
/// The key files.
- public PrivateKeyConnectionInfo(string host, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, params PrivateKeyFile[] keyFiles)
+ public PrivateKeyConnectionInfo(string host, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, params IPrivateKeySource[] keyFiles)
: this(host, DefaultPort, username, proxyType, proxyHost, proxyPort, proxyUsername, string.Empty, keyFiles)
{
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// Connection host.
/// Connection username.
@@ -116,13 +110,13 @@ public PrivateKeyConnectionInfo(string host, string username, ProxyTypes proxyTy
/// The proxy username.
/// The proxy password.
/// The key files.
- public PrivateKeyConnectionInfo(string host, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, params PrivateKeyFile[] keyFiles)
+ public PrivateKeyConnectionInfo(string host, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, params IPrivateKeySource[] keyFiles)
: this(host, DefaultPort, username, proxyType, proxyHost, proxyPort, proxyUsername, proxyPassword, keyFiles)
{
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// Connection host.
/// The port.
@@ -133,33 +127,31 @@ public PrivateKeyConnectionInfo(string host, string username, ProxyTypes proxyTy
/// The proxy username.
/// The proxy password.
/// The key files.
- public PrivateKeyConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, params PrivateKeyFile[] keyFiles)
+ public PrivateKeyConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, params IPrivateKeySource[] keyFiles)
: base(host, port, username, proxyType, proxyHost, proxyPort, proxyUsername, proxyPassword, new PrivateKeyAuthenticationMethod(username, keyFiles))
{
- KeyFiles = new Collection(keyFiles);
+ KeyFiles = new Collection(keyFiles);
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -168,8 +160,7 @@ protected virtual void Dispose(bool disposing)
{
foreach (var authenticationMethod in AuthenticationMethods)
{
- var disposable = authenticationMethod as IDisposable;
- if (disposable != null)
+ if (authenticationMethod is IDisposable disposable)
{
disposable.Dispose();
}
@@ -181,17 +172,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~PrivateKeyConnectionInfo()
{
- // Do not re-create Dispose clean-up code here.
- // Calling Dispose(false) is optimal in terms of
- // readability and maintainability.
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/PrivateKeyFile.cs b/src/Renci.SshNet/PrivateKeyFile.cs
index 31fac7db4..d42594583 100644
--- a/src/Renci.SshNet/PrivateKeyFile.cs
+++ b/src/Renci.SshNet/PrivateKeyFile.cs
@@ -1,38 +1,37 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
using System.IO;
+using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
+
using Renci.SshNet.Abstractions;
-using Renci.SshNet.Security;
using Renci.SshNet.Common;
-using System.Globalization;
+using Renci.SshNet.Security;
+using Renci.SshNet.Security.Cryptography;
using Renci.SshNet.Security.Cryptography.Ciphers;
using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
using Renci.SshNet.Security.Cryptography.Ciphers.Paddings;
-using System.Diagnostics.CodeAnalysis;
-using Renci.SshNet.Security.Cryptography;
namespace Renci.SshNet
{
///
/// Represents private key information.
///
- ///
- ///
- ///
///
///
/// The following private keys are supported:
///
/// -
- /// RSA in OpenSSL PEM and ssh.com format
+ /// RSA in OpenSSL PEM, ssh.com and OpenSSH key format
///
/// -
/// DSA in OpenSSL PEM and ssh.com format
///
/// -
- /// ECDSA 256/384/521 in OpenSSL PEM format
+ /// ECDSA 256/384/521 in OpenSSL PEM and OpenSSH key format
///
/// -
/// ED25519 in OpenSSH key format
@@ -63,21 +62,46 @@ namespace Renci.SshNet
///
///
///
- public class PrivateKeyFile : IDisposable
+ public class PrivateKeyFile : IPrivateKeySource, IDisposable
{
private static readonly Regex PrivateKeyRegex = new Regex(@"^-+ *BEGIN (?\w+( \w+)*) PRIVATE KEY *-+\r?\n((Proc-Type: 4,ENCRYPTED\r?\nDEK-Info: (?[A-Z0-9-]+),(?[A-F0-9]+)\r?\n\r?\n)|(Comment: ""?[^\r\n]*""?\r?\n))?(?([a-zA-Z0-9/+=]{1,80}\r?\n)+)-+ *END \k PRIVATE KEY *-+",
-#if FEATURE_REGEX_COMPILE
- RegexOptions.Compiled | RegexOptions.Multiline);
-#else
- RegexOptions.Multiline);
-#endif
+ RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.ExplicitCapture);
+ private readonly List _hostAlgorithms = new List();
private Key _key;
+ private bool _isDisposed;
+
+ ///
+ /// Gets the supported host algorithms for this key file.
+ ///
+ public IReadOnlyCollection HostKeyAlgorithms
+ {
+ get
+ {
+ return _hostAlgorithms;
+ }
+ }
///
- /// Gets the host key.
+ /// Gets the key.
///
- public HostAlgorithm HostKey { get; private set; }
+ public Key Key
+ {
+ get
+ {
+ return _key;
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The key.
+ public PrivateKeyFile(Key key)
+ {
+ _key = key;
+ _hostAlgorithms.Add(new KeyHostAlgorithm(key.ToString(), key));
+ }
///
/// Initializes a new instance of the class.
@@ -85,17 +109,20 @@ public class PrivateKeyFile : IDisposable
/// The private key.
public PrivateKeyFile(Stream privateKey)
{
- Open(privateKey, null);
+ Open(privateKey, passPhrase: null);
+ Debug.Assert(_hostAlgorithms.Count > 0, $"{nameof(HostKeyAlgorithms)} is not set.");
}
///
/// Initializes a new instance of the class.
///
/// Name of the file.
- /// is null or empty.
- /// This method calls internally, this method does not catch exceptions from .
+ /// is or empty.
+ ///
+ /// This method calls internally, this method does not catch exceptions from .
+ ///
public PrivateKeyFile(string fileName)
- : this(fileName, null)
+ : this(fileName, passPhrase: null)
{
}
@@ -104,17 +131,23 @@ public PrivateKeyFile(string fileName)
///
/// Name of the file.
/// The pass phrase.
- /// is null or empty, or is null.
- /// This method calls internally, this method does not catch exceptions from .
+ /// is or empty, or is .
+ ///
+ /// This method calls internally, this method does not catch exceptions from .
+ ///
public PrivateKeyFile(string fileName, string passPhrase)
{
if (string.IsNullOrEmpty(fileName))
- throw new ArgumentNullException("fileName");
+ {
+ throw new ArgumentNullException(nameof(fileName));
+ }
using (var keyFile = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
Open(keyFile, passPhrase);
}
+
+ Debug.Assert(_hostAlgorithms.Count > 0, $"{nameof(HostKeyAlgorithms)} is not set.");
}
///
@@ -122,10 +155,12 @@ public PrivateKeyFile(string fileName, string passPhrase)
///
/// The private key.
/// The pass phrase.
- /// or is null.
+ /// or is .
public PrivateKeyFile(Stream privateKey, string passPhrase)
{
Open(privateKey, passPhrase);
+
+ Debug.Assert(_hostAlgorithms.Count > 0, $"{nameof(HostKeyAlgorithms)} is not set.");
}
///
@@ -133,11 +168,12 @@ public PrivateKeyFile(Stream privateKey, string passPhrase)
///
/// The private key.
/// The pass phrase.
- [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "this._key disposed in Dispose(bool) method.")]
private void Open(Stream privateKey, string passPhrase)
{
- if (privateKey == null)
- throw new ArgumentNullException("privateKey");
+ if (privateKey is null)
+ {
+ throw new ArgumentNullException(nameof(privateKey));
+ }
Match privateKeyMatch;
@@ -164,11 +200,15 @@ private void Open(Stream privateKey, string passPhrase)
if (!string.IsNullOrEmpty(cipherName) && !string.IsNullOrEmpty(salt))
{
if (string.IsNullOrEmpty(passPhrase))
+ {
throw new SshPassPhraseNullOrEmptyException("Private key is encrypted but passphrase is empty.");
+ }
var binarySalt = new byte[salt.Length / 2];
for (var i = 0; i < binarySalt.Length; i++)
+ {
binarySalt[i] = Convert.ToByte(salt.Substring(i * 2, 2), 16);
+ }
CipherInfo cipher;
switch (cipherName)
@@ -183,16 +223,16 @@ private void Open(Stream privateKey, string passPhrase)
cipher = new CipherInfo(64, (key, iv) => new DesCipher(key, new CbcCipherMode(iv), new PKCS7Padding()));
break;
case "AES-128-CBC":
- cipher = new CipherInfo(128, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), new PKCS7Padding()));
+ cipher = new CipherInfo(128, (key, iv) => new AesCipher(key, iv, AesCipherMode.CBC, pkcs7Padding: true));
break;
case "AES-192-CBC":
- cipher = new CipherInfo(192, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), new PKCS7Padding()));
+ cipher = new CipherInfo(192, (key, iv) => new AesCipher(key, iv, AesCipherMode.CBC, pkcs7Padding: true));
break;
case "AES-256-CBC":
- cipher = new CipherInfo(256, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), new PKCS7Padding()));
+ cipher = new CipherInfo(256, (key, iv) => new AesCipher(key, iv, AesCipherMode.CBC, pkcs7Padding: true));
break;
default:
- throw new SshException(string.Format(CultureInfo.CurrentCulture, "Private key cipher \"{0}\" is not supported.", cipherName));
+ throw new SshException(string.Format(CultureInfo.InvariantCulture, "Private key cipher \"{0}\" is not supported.", cipherName));
}
decryptedData = DecryptKey(cipher, binaryData, passPhrase, binarySalt);
@@ -205,22 +245,37 @@ private void Open(Stream privateKey, string passPhrase)
switch (keyName)
{
case "RSA":
- _key = new RsaKey(decryptedData);
- HostKey = new KeyHostAlgorithm("ssh-rsa", _key);
+ var rsaKey = new RsaKey(decryptedData);
+ _key = rsaKey;
+ _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-rsa", _key));
+#pragma warning disable CA2000 // Dispose objects before losing scope
+ _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-512", _key, new RsaDigitalSignature(rsaKey, HashAlgorithmName.SHA512)));
+ _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-256", _key, new RsaDigitalSignature(rsaKey, HashAlgorithmName.SHA256)));
+#pragma warning restore CA2000 // Dispose objects before losing scope
break;
case "DSA":
_key = new DsaKey(decryptedData);
- HostKey = new KeyHostAlgorithm("ssh-dss", _key);
+ _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-dss", _key));
break;
-#if FEATURE_ECDSA
case "EC":
_key = new EcdsaKey(decryptedData);
- HostKey = new KeyHostAlgorithm(_key.ToString(), _key);
+ _hostAlgorithms.Add(new KeyHostAlgorithm(_key.ToString(), _key));
break;
-#endif
case "OPENSSH":
_key = ParseOpenSshV1Key(decryptedData, passPhrase);
- HostKey = new KeyHostAlgorithm(_key.ToString(), _key);
+ if (_key is RsaKey parsedRsaKey)
+ {
+ _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-rsa", _key));
+#pragma warning disable CA2000 // Dispose objects before losing scope
+ _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-512", _key, new RsaDigitalSignature(parsedRsaKey, HashAlgorithmName.SHA512)));
+ _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-256", _key, new RsaDigitalSignature(parsedRsaKey, HashAlgorithmName.SHA256)));
+#pragma warning restore CA2000 // Dispose objects before losing scope
+ }
+ else
+ {
+ _hostAlgorithms.Add(new KeyHostAlgorithm(_key.ToString(), _key));
+ }
+
break;
case "SSH2 ENCRYPTED":
var reader = new SshDataReader(decryptedData);
@@ -230,7 +285,7 @@ private void Open(Stream privateKey, string passPhrase)
throw new SshException("Invalid SSH2 private key.");
}
- reader.ReadUInt32(); // Read total bytes length including magic number
+ _ = reader.ReadUInt32(); // Read total bytes length including magic number
var keyType = reader.ReadString(SshData.Ascii);
var ssh2CipherName = reader.ReadString(SshData.Ascii);
var blobSize = (int)reader.ReadUInt32();
@@ -243,7 +298,9 @@ private void Open(Stream privateKey, string passPhrase)
else if (ssh2CipherName == "3des-cbc")
{
if (string.IsNullOrEmpty(passPhrase))
+ {
throw new SshPassPhraseNullOrEmptyException("Private key is encrypted but passphrase is empty.");
+ }
var key = GetCipherKey(passPhrase, 192 / 8);
var ssh2Сipher = new TripleDesCipher(key, new CbcCipherMode(new byte[8]), new PKCS7Padding());
@@ -254,25 +311,34 @@ private void Open(Stream privateKey, string passPhrase)
throw new SshException(string.Format("Cipher method '{0}' is not supported.", cipherName));
}
- // TODO: Create two specific data types to avoid using SshDataReader class
+ /*
+ * TODO: Create two specific data types to avoid using SshDataReader class.
+ */
reader = new SshDataReader(keyData);
var decryptedLength = reader.ReadUInt32();
if (decryptedLength > blobSize - 4)
+ {
throw new SshException("Invalid passphrase.");
-
+ }
+
if (keyType == "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}")
{
- var exponent = reader.ReadBigIntWithBits();//e
- var d = reader.ReadBigIntWithBits();//d
- var modulus = reader.ReadBigIntWithBits();//n
- var inverseQ = reader.ReadBigIntWithBits();//u
- var q = reader.ReadBigIntWithBits();//p
- var p = reader.ReadBigIntWithBits();//q
- _key = new RsaKey(modulus, exponent, d, p, q, inverseQ);
- HostKey = new KeyHostAlgorithm("ssh-rsa", _key);
+ var exponent = reader.ReadBigIntWithBits(); // e
+ var d = reader.ReadBigIntWithBits(); // d
+ var modulus = reader.ReadBigIntWithBits(); // n
+ var inverseQ = reader.ReadBigIntWithBits(); // u
+ var q = reader.ReadBigIntWithBits(); // p
+ var p = reader.ReadBigIntWithBits(); // q
+ var decryptedRsaKey = new RsaKey(modulus, exponent, d, p, q, inverseQ);
+ _key = decryptedRsaKey;
+ _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-rsa", _key));
+#pragma warning disable CA2000 // Dispose objects before losing scope
+ _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-512", _key, new RsaDigitalSignature(decryptedRsaKey, HashAlgorithmName.SHA512)));
+ _hostAlgorithms.Add(new KeyHostAlgorithm("rsa-sha2-256", _key, new RsaDigitalSignature(decryptedRsaKey, HashAlgorithmName.SHA256)));
+#pragma warning restore CA2000 // Dispose objects before losing scope
}
else if (keyType == "dl-modp{sign{dsa-nist-sha1},dh{plain}}")
{
@@ -281,18 +347,20 @@ private void Open(Stream privateKey, string passPhrase)
{
throw new SshException("Invalid private key");
}
+
var p = reader.ReadBigIntWithBits();
var g = reader.ReadBigIntWithBits();
var q = reader.ReadBigIntWithBits();
var y = reader.ReadBigIntWithBits();
var x = reader.ReadBigIntWithBits();
_key = new DsaKey(p, q, g, y, x);
- HostKey = new KeyHostAlgorithm("ssh-dss", _key);
+ _hostAlgorithms.Add(new KeyHostAlgorithm("ssh-dss", _key));
}
else
{
throw new NotSupportedException(string.Format("Key type '{0}' is not supported.", keyType));
}
+
break;
default:
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Key '{0}' is not supported.", keyName));
@@ -329,17 +397,23 @@ private static byte[] GetCipherKey(string passphrase, int length)
/// Decryption pass phrase.
/// Decryption binary salt.
/// Decrypted byte array.
- /// , , or is null.
+ /// , , or is .
private static byte[] DecryptKey(CipherInfo cipherInfo, byte[] cipherData, string passPhrase, byte[] binarySalt)
{
- if (cipherInfo == null)
- throw new ArgumentNullException("cipherInfo");
+ if (cipherInfo is null)
+ {
+ throw new ArgumentNullException(nameof(cipherInfo));
+ }
- if (cipherData == null)
- throw new ArgumentNullException("cipherData");
+ if (cipherData is null)
+ {
+ throw new ArgumentNullException(nameof(cipherData));
+ }
- if (binarySalt == null)
- throw new ArgumentNullException("binarySalt");
+ if (binarySalt is null)
+ {
+ throw new ArgumentNullException(nameof(binarySalt));
+ }
var cipherKey = new List();
@@ -347,7 +421,7 @@ private static byte[] DecryptKey(CipherInfo cipherInfo, byte[] cipherData, strin
{
var passwordBytes = Encoding.UTF8.GetBytes(passPhrase);
- // Use 8 bytes binary salt
+ // Use 8 bytes binary salt
var initVector = passwordBytes.Concat(binarySalt.Take(8));
var hash = md5.ComputeHash(initVector);
@@ -370,14 +444,16 @@ private static byte[] DecryptKey(CipherInfo cipherInfo, byte[] cipherData, strin
/// Parses an OpenSSH V1 key file (i.e. ED25519 key) according to the the key spec:
/// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key.
///
- /// the key file data (i.e. base64 encoded data between the header/footer)
- /// passphrase or null if there isn't one
- ///
- private ED25519Key ParseOpenSshV1Key(byte [] keyFileData, string passPhrase)
+ /// The key file data (i.e. base64 encoded data between the header/footer).
+ /// Passphrase or if there isn't one.
+ ///
+ /// The OpenSSH V1 key.
+ ///
+ private static Key ParseOpenSshV1Key(byte[] keyFileData, string passPhrase)
{
var keyReader = new SshDataReader(keyFileData);
- //check magic header
+ // check magic header
var authMagic = Encoding.UTF8.GetBytes("openssh-key-v1\0");
var keyHeaderBytes = keyReader.ReadBytes(authMagic.Length);
if (!authMagic.IsEqualTo(keyHeaderBytes))
@@ -385,146 +461,187 @@ private ED25519Key ParseOpenSshV1Key(byte [] keyFileData, string passPhrase)
throw new SshException("This openssh key does not contain the 'openssh-key-v1' format magic header");
}
- //cipher will be "aes256-cbc" if using a passphrase, "none" otherwise
+ // cipher will be "aes256-cbc" if using a passphrase, "none" otherwise
var cipherName = keyReader.ReadString(Encoding.UTF8);
- //key derivation function (kdf): bcrypt or nothing
+
+ // key derivation function (kdf): bcrypt or nothing
var kdfName = keyReader.ReadString(Encoding.UTF8);
- //kdf options length: 24 if passphrase, 0 if no passphrase
+
+ // kdf options length: 24 if passphrase, 0 if no passphrase
var kdfOptionsLen = (int)keyReader.ReadUInt32();
byte[] salt = null;
- int rounds = 0;
+ var rounds = 0;
if (kdfOptionsLen > 0)
{
- var saltLength = (int)keyReader.ReadUInt32();
+ var saltLength = (int) keyReader.ReadUInt32();
salt = keyReader.ReadBytes(saltLength);
- rounds = (int)keyReader.ReadUInt32();
+ rounds = (int) keyReader.ReadUInt32();
}
- //number of public keys, only supporting 1 for now
+ // number of public keys, only supporting 1 for now
var numberOfPublicKeys = (int)keyReader.ReadUInt32();
if (numberOfPublicKeys != 1)
{
throw new SshException("At this time only one public key in the openssh key is supported.");
}
- //length of first public key section
- keyReader.ReadUInt32();
- var keyType = keyReader.ReadString(Encoding.UTF8);
- if(keyType != "ssh-ed25519")
- {
- throw new SshException("openssh key type: " + keyType + " is not supported");
- }
-
- //read public key
- var publicKeyLength = (int)keyReader.ReadUInt32(); //32
- var publicKey = keyReader.ReadBytes(publicKeyLength);
+ // read public key in ssh-format, but we dont need it
+ _ = keyReader.ReadString(Encoding.UTF8);
- //possibly encrypted private key
- var privateKeyLength = (int)keyReader.ReadUInt32();
+ // possibly encrypted private key
+ var privateKeyLength = (int) keyReader.ReadUInt32();
var privateKeyBytes = keyReader.ReadBytes(privateKeyLength);
- //decrypt private key if necessary
- if (cipherName == "aes256-cbc")
+ // decrypt private key if necessary
+ if (cipherName != "none")
{
if (string.IsNullOrEmpty(passPhrase))
{
throw new SshPassPhraseNullOrEmptyException("Private key is encrypted but passphrase is empty.");
}
+
if (string.IsNullOrEmpty(kdfName) || kdfName != "bcrypt")
{
throw new SshException("kdf " + kdfName + " is not supported for openssh key file");
}
- //inspired by the SSHj library (https://github.com/hierynomus/sshj)
- //apply the kdf to derive a key and iv from the passphrase
+ // inspired by the SSHj library (https://github.com/hierynomus/sshj)
+ // apply the kdf to derive a key and iv from the passphrase
var passPhraseBytes = Encoding.UTF8.GetBytes(passPhrase);
- byte[] keyiv = new byte[48];
+ var keyiv = new byte[48];
new BCrypt().Pbkdf(passPhraseBytes, salt, rounds, keyiv);
- byte[] key = new byte[32];
+ var key = new byte[32];
Array.Copy(keyiv, 0, key, 0, 32);
- byte[] iv = new byte[16];
+ var iv = new byte[16];
Array.Copy(keyiv, 32, iv, 0, 16);
- //now that we have the key/iv, use a cipher to decrypt the bytes
- var cipher = new AesCipher(key, new CbcCipherMode(iv), new PKCS7Padding());
- privateKeyBytes = cipher.Decrypt(privateKeyBytes);
- }
- else if (cipherName != "none")
- {
- throw new SshException("cipher name " + cipherName + " for openssh key file is not supported");
+ AesCipher cipher;
+ switch (cipherName)
+ {
+ case "aes256-cbc":
+ cipher = new AesCipher(key, iv, AesCipherMode.CBC, pkcs7Padding: false);
+ break;
+ case "aes256-ctr":
+ cipher = new AesCipher(key, iv, AesCipherMode.CTR, pkcs7Padding: false);
+ break;
+ default:
+ throw new SshException("Cipher '" + cipherName + "' is not supported for an OpenSSH key.");
+ }
+
+ try
+ {
+ privateKeyBytes = cipher.Decrypt(privateKeyBytes);
+ }
+ finally
+ {
+ cipher.Dispose();
+ }
}
- //validate private key length
+ // validate private key length
privateKeyLength = privateKeyBytes.Length;
if (privateKeyLength % 8 != 0)
{
throw new SshException("The private key section must be a multiple of the block size (8)");
}
- //now parse the data we called the private key, it actually contains the public key again
- //so we need to parse through it to get the private key bytes, plus there's some
- //validation we need to do.
+ // now parse the data we called the private key, it actually contains the public key again
+ // so we need to parse through it to get the private key bytes, plus there's some
+ // validation we need to do.
var privateKeyReader = new SshDataReader(privateKeyBytes);
- //check ints should match, they wouldn't match for example if the wrong passphrase was supplied
- int checkInt1 = (int)privateKeyReader.ReadUInt32();
- int checkInt2 = (int)privateKeyReader.ReadUInt32();
+ // check ints should match, they wouldn't match for example if the wrong passphrase was supplied
+ var checkInt1 = (int) privateKeyReader.ReadUInt32();
+ var checkInt2 = (int) privateKeyReader.ReadUInt32();
if (checkInt1 != checkInt2)
{
- throw new SshException("The checkints differed, the openssh key was not correctly decoded.");
+ throw new SshException(string.Format(CultureInfo.InvariantCulture,
+ "The random check bytes of the OpenSSH key do not match ({0} <-> {1}).",
+ checkInt1.ToString(CultureInfo.InvariantCulture),
+ checkInt2.ToString(CultureInfo.InvariantCulture)));
}
- //key type, we already know it is ssh-ed25519
- privateKeyReader.ReadString(Encoding.UTF8);
+ // key type
+ var keyType = privateKeyReader.ReadString(Encoding.UTF8);
- //public key length/bytes (again)
- var publicKeyLength2 = (int)privateKeyReader.ReadUInt32();
- privateKeyReader.ReadBytes(publicKeyLength2);
+ Key parsedKey;
+ byte[] publicKey;
+ byte[] unencryptedPrivateKey;
+ switch (keyType)
+ {
+ case "ssh-ed25519":
+ // https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent-11#section-3.2.3
+
+ // ENC(A)
+ _ = privateKeyReader.ReadBignum2();
- //length of private and public key (64)
- privateKeyReader.ReadUInt32();
- var unencryptedPrivateKey = privateKeyReader.ReadBytes(32);
- //public key (again)
- privateKeyReader.ReadBytes(32);
+ // k || ENC(A)
+ unencryptedPrivateKey = privateKeyReader.ReadBignum2();
+ parsedKey = new ED25519Key(unencryptedPrivateKey);
+ break;
+ case "ecdsa-sha2-nistp256":
+ case "ecdsa-sha2-nistp384":
+ case "ecdsa-sha2-nistp521":
+ // curve
+ var len = (int) privateKeyReader.ReadUInt32();
+ var curve = Encoding.ASCII.GetString(privateKeyReader.ReadBytes(len));
+
+ // public key
+ publicKey = privateKeyReader.ReadBignum2();
+
+ // private key
+ unencryptedPrivateKey = privateKeyReader.ReadBignum2();
+ parsedKey = new EcdsaKey(curve, publicKey, unencryptedPrivateKey.TrimLeadingZeros());
+ break;
+ case "ssh-rsa":
+ var modulus = privateKeyReader.ReadBignum(); // n
+ var exponent = privateKeyReader.ReadBignum(); // e
+ var d = privateKeyReader.ReadBignum(); // d
+ var inverseQ = privateKeyReader.ReadBignum(); // iqmp
+ var p = privateKeyReader.ReadBignum(); // p
+ var q = privateKeyReader.ReadBignum(); // q
+ parsedKey = new RsaKey(modulus, exponent, d, p, q, inverseQ);
+ break;
+ default:
+ throw new SshException("OpenSSH key type '" + keyType + "' is not supported.");
+ }
- //comment, we don't need this but we could log it, not sure if necessary
- var comment = privateKeyReader.ReadString(Encoding.UTF8);
+ parsedKey.Comment = privateKeyReader.ReadString(Encoding.UTF8);
- //The list of privatekey/comment pairs is padded with the bytes 1, 2, 3, ...
- //until the total length is a multiple of the cipher block size.
+ // The list of privatekey/comment pairs is padded with the bytes 1, 2, 3, ...
+ // until the total length is a multiple of the cipher block size.
var padding = privateKeyReader.ReadBytes();
- for (int i = 0; i < padding.Length; i++)
+ for (var i = 0; i < padding.Length; i++)
{
- if ((int)padding[i] != i + 1)
+ if ((int) padding[i] != i + 1)
{
- throw new SshException("Padding of openssh key format contained wrong byte at position: " + i);
+ throw new SshException("Padding of openssh key format contained wrong byte at position: " +
+ i.ToString(CultureInfo.InvariantCulture));
}
}
- return new ED25519Key(publicKey.Reverse(), unencryptedPrivateKey);
+ return parsedKey;
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -540,17 +657,14 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~PrivateKeyFile()
{
- Dispose(false);
+ Dispose(disposing: false);
}
- #endregion
-
- private class SshDataReader : SshData
+ private sealed class SshDataReader : SshData
{
public SshDataReader(byte[] data)
{
@@ -594,6 +708,17 @@ public BigInteger ReadBigIntWithBits()
return new BigInteger(bytesArray.Reverse());
}
+ public BigInteger ReadBignum()
+ {
+ return new BigInteger(ReadBignum2().Reverse());
+ }
+
+ public byte[] ReadBignum2()
+ {
+ var length = (int)base.ReadUInt32();
+ return base.ReadBytes(length);
+ }
+
protected override void LoadData()
{
}
diff --git a/src/Renci.SshNet/Properties/AssemblyInfo.cs b/src/Renci.SshNet/Properties/AssemblyInfo.cs
index 22e4125ce..fe5eac0d1 100644
--- a/src/Renci.SshNet/Properties/AssemblyInfo.cs
+++ b/src/Renci.SshNet/Properties/AssemblyInfo.cs
@@ -1,8 +1,10 @@
using System.Reflection;
-using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
[assembly: AssemblyTitle("SSH.NET")]
[assembly: Guid("ad816c5e-6f13-4589-9f3e-59523f8b77a4")]
[assembly: InternalsVisibleTo("Renci.SshNet.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f9194e1eb66b7e2575aaee115ee1d27bc100920e7150e43992d6f668f9737de8b9c7ae892b62b8a36dd1d57929ff1541665d101dc476d6e02390846efae7e5186eec409710fdb596e3f83740afef0d4443055937649bc5a773175b61c57615dac0f0fd10f52b52fedf76c17474cc567b3f7a79de95dde842509fb39aaf69c6c2")]
+[assembly: InternalsVisibleTo("Renci.SshNet.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f9194e1eb66b7e2575aaee115ee1d27bc100920e7150e43992d6f668f9737de8b9c7ae892b62b8a36dd1d57929ff1541665d101dc476d6e02390846efae7e5186eec409710fdb596e3f83740afef0d4443055937649bc5a773175b61c57615dac0f0fd10f52b52fedf76c17474cc567b3f7a79de95dde842509fb39aaf69c6c2")]
+[assembly: InternalsVisibleTo("Renci.SshNet.Benchmarks, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f9194e1eb66b7e2575aaee115ee1d27bc100920e7150e43992d6f668f9737de8b9c7ae892b62b8a36dd1d57929ff1541665d101dc476d6e02390846efae7e5186eec409710fdb596e3f83740afef0d4443055937649bc5a773175b61c57615dac0f0fd10f52b52fedf76c17474cc567b3f7a79de95dde842509fb39aaf69c6c2")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
diff --git a/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs b/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs
index 0883060cc..31ae72dff 100644
--- a/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs
+++ b/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs
@@ -5,23 +5,22 @@
[assembly: AssemblyDescription("SSH.NET is a Secure Shell (SSH) library for .NET, optimized for parallelism.")]
[assembly: AssemblyCompany("Renci")]
[assembly: AssemblyProduct("SSH.NET")]
-[assembly: AssemblyCopyright("Copyright Renci 2010-2021")]
+[assembly: AssemblyCopyright("Copyright Renci 2010-2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
-[assembly: AssemblyVersion("2020.0.1")]
-[assembly: AssemblyFileVersion("2020.0.1")]
-[assembly: AssemblyInformationalVersion("2020.0.1")]
+[assembly: AssemblyVersion("2023.0.1")]
+[assembly: AssemblyFileVersion("2023.0.1")]
+[assembly: AssemblyInformationalVersion("2023.0.1")]
[assembly: CLSCompliant(false)]
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
-
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
-#endif
\ No newline at end of file
+#endif
diff --git a/src/Renci.SshNet/ProxyTypes.cs b/src/Renci.SshNet/ProxyTypes.cs
index 9a7fce098..cff5eb247 100644
--- a/src/Renci.SshNet/ProxyTypes.cs
+++ b/src/Renci.SshNet/ProxyTypes.cs
@@ -5,13 +5,24 @@
///
public enum ProxyTypes
{
- /// No proxy server.
+ ///
+ /// No proxy server.
+ ///
None,
- /// A SOCKS4 proxy server.
+
+ ///
+ /// A SOCKS4 proxy server.
+ ///
Socks4,
- /// A SOCKS5 proxy server.
+
+ ///
+ /// A SOCKS5 proxy server.
+ ///
Socks5,
- /// A HTTP proxy server.
+
+ ///
+ /// An HTTP proxy server.
+ ///
Http,
}
}
diff --git a/src/Renci.SshNet/RemotePathDoubleQuoteTransformation.cs b/src/Renci.SshNet/RemotePathDoubleQuoteTransformation.cs
index 70af535a2..cafb17e9c 100644
--- a/src/Renci.SshNet/RemotePathDoubleQuoteTransformation.cs
+++ b/src/Renci.SshNet/RemotePathDoubleQuoteTransformation.cs
@@ -6,7 +6,7 @@ namespace Renci.SshNet
///
/// Encloses a path in double quotes, and escapes any embedded double quote with a backslash.
///
- internal class RemotePathDoubleQuoteTransformation : IRemotePathTransformation
+ internal sealed class RemotePathDoubleQuoteTransformation : IRemotePathTransformation
{
///
/// Encloses a path in double quotes, and escapes any embedded double quote with a backslash.
@@ -15,7 +15,7 @@ internal class RemotePathDoubleQuoteTransformation : IRemotePathTransformation
///
/// The transformed path.
///
- /// is null.
+ /// is .
///
///
///
@@ -50,21 +50,26 @@ internal class RemotePathDoubleQuoteTransformation : IRemotePathTransformation
///
public string Transform(string path)
{
- if (path == null)
+ if (path is null)
{
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
}
var transformed = new StringBuilder(path.Length);
- transformed.Append('"');
+ _ = transformed.Append('"');
+
foreach (var c in path)
{
if (c == '"')
- transformed.Append('\\');
- transformed.Append(c);
+ {
+ _ = transformed.Append('\\');
+ }
+
+ _ = transformed.Append(c);
}
- transformed.Append('"');
+
+ _ = transformed.Append('"');
return transformed.ToString();
}
diff --git a/src/Renci.SshNet/RemotePathNoneTransformation.cs b/src/Renci.SshNet/RemotePathNoneTransformation.cs
index ef51531d3..32b083206 100644
--- a/src/Renci.SshNet/RemotePathNoneTransformation.cs
+++ b/src/Renci.SshNet/RemotePathNoneTransformation.cs
@@ -5,7 +5,7 @@ namespace Renci.SshNet
///
/// Performs no transformation.
///
- internal class RemotePathNoneTransformation : IRemotePathTransformation
+ internal sealed class RemotePathNoneTransformation : IRemotePathTransformation
{
///
/// Returns the specified path without applying a transformation.
@@ -14,16 +14,16 @@ internal class RemotePathNoneTransformation : IRemotePathTransformation
///
/// The specified path as is.
///
- /// is null.
+ /// is .
///
/// This transformation is recommended for servers that do not require any quoting to preserve the
/// literal value of metacharacters, or when paths are guaranteed to never contain any such characters.
///
public string Transform(string path)
{
- if (path == null)
+ if (path is null)
{
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
}
return path;
diff --git a/src/Renci.SshNet/RemotePathShellQuoteTransformation.cs b/src/Renci.SshNet/RemotePathShellQuoteTransformation.cs
index 5093cafd8..11584fad4 100644
--- a/src/Renci.SshNet/RemotePathShellQuoteTransformation.cs
+++ b/src/Renci.SshNet/RemotePathShellQuoteTransformation.cs
@@ -6,7 +6,7 @@ namespace Renci.SshNet
///
/// Quotes a path in a way to be suitable to be used with a shell-based server.
///
- internal class RemotePathShellQuoteTransformation : IRemotePathTransformation
+ internal sealed class RemotePathShellQuoteTransformation : IRemotePathTransformation
{
///
/// Quotes a path in a way to be suitable to be used with a shell-based server.
@@ -15,7 +15,7 @@ internal class RemotePathShellQuoteTransformation : IRemotePathTransformation
///
/// A quoted path.
///
- /// is null.
+ /// is .
///
///
/// If contains a single-quote, that character is embedded
@@ -80,9 +80,9 @@ internal class RemotePathShellQuoteTransformation : IRemotePathTransformation
///
public string Transform(string path)
{
- if (path == null)
+ if (path is null)
{
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
}
// result is at least value and (likely) leading/trailing single-quotes
@@ -99,42 +99,52 @@ public string Transform(string path)
{
case ShellQuoteState.Unquoted:
// Start quoted string
- sb.Append('"');
+ _ = sb.Append('"');
break;
case ShellQuoteState.Quoted:
// Continue quoted string
break;
case ShellQuoteState.SingleQuoted:
// Close single-quoted string
- sb.Append('\'');
+ _ = sb.Append('\'');
+
// Start quoted string
- sb.Append('"');
+ _ = sb.Append('"');
+ break;
+ default:
break;
}
+
state = ShellQuoteState.Quoted;
break;
case '!':
- // In C-Shell, an exclamatation point can only be protected from shell interpretation
- // when escaped by a backslash
- // Source:
- // https://earthsci.stanford.edu/computing/unix/shell/specialchars.php
+ /*
+ * In C-Shell, an exclamatation point can only be protected from shell interpretation
+ * when escaped by a backslash.
+ *
+ * Source:
+ * https://earthsci.stanford.edu/computing/unix/shell/specialchars.php
+ */
switch (state)
{
case ShellQuoteState.Unquoted:
- sb.Append('\\');
+ _ = sb.Append('\\');
break;
case ShellQuoteState.Quoted:
// Close quoted string
- sb.Append('"');
- sb.Append('\\');
+ _ = sb.Append('"');
+ _ = sb.Append('\\');
break;
case ShellQuoteState.SingleQuoted:
// Close single quoted string
- sb.Append('\'');
- sb.Append('\\');
+ _ = sb.Append('\'');
+ _ = sb.Append('\\');
+ break;
+ default:
break;
}
+
state = ShellQuoteState.Unquoted;
break;
default:
@@ -142,23 +152,27 @@ public string Transform(string path)
{
case ShellQuoteState.Unquoted:
// Start single-quoted string
- sb.Append('\'');
+ _ = sb.Append('\'');
break;
case ShellQuoteState.Quoted:
// Close quoted string
- sb.Append('"');
+ _ = sb.Append('"');
+
// Start single-quoted string
- sb.Append('\'');
+ _ = sb.Append('\'');
break;
case ShellQuoteState.SingleQuoted:
// Continue single-quoted string
break;
+ default:
+ break;
}
+
state = ShellQuoteState.SingleQuoted;
break;
}
- sb.Append(c);
+ _ = sb.Append(c);
}
switch (state)
@@ -167,17 +181,19 @@ public string Transform(string path)
break;
case ShellQuoteState.Quoted:
// Close quoted string
- sb.Append('"');
+ _ = sb.Append('"');
break;
case ShellQuoteState.SingleQuoted:
// Close single-quoted string
- sb.Append('\'');
+ _ = sb.Append('\'');
+ break;
+ default:
break;
}
if (sb.Length == 0)
{
- sb.Append("''");
+ _ = sb.Append("''");
}
return sb.ToString();
diff --git a/src/Renci.SshNet/RemotePathTransformation.cs b/src/Renci.SshNet/RemotePathTransformation.cs
index 5e3f74fcb..7404c3e4b 100644
--- a/src/Renci.SshNet/RemotePathTransformation.cs
+++ b/src/Renci.SshNet/RemotePathTransformation.cs
@@ -27,7 +27,7 @@ public static class RemotePathTransformation
private static readonly IRemotePathTransformation DoubleQuoteTransformation = new RemotePathDoubleQuoteTransformation();
///
- /// Quotes a path in a way to be suitable to be used with a shell-based server.
+ /// Gets a that quotes a path in a way to be suitable to be used with a shell-based server.
///
///
/// A quoted path.
@@ -85,7 +85,7 @@ public static IRemotePathTransformation ShellQuote
}
///
- /// Performs no transformation.
+ /// Gets a that performs no transformation.
///
///
/// Recommended for servers that do not require any character to be escaped or enclosed in quotes,
@@ -97,7 +97,7 @@ public static IRemotePathTransformation None
}
///
- /// Encloses a path in double quotes, and escapes any embedded double quote with a backslash.
+ /// Gets a that encloses a path in double quotes, and escapes any embedded double quote with a backslash.
///
///
/// A transformation that encloses a path in double quotes, and escapes any embedded double quote with
diff --git a/src/Renci.SshNet/Renci.SshNet.csproj b/src/Renci.SshNet/Renci.SshNet.csproj
index 124ce9d4b..877b3b891 100644
--- a/src/Renci.SshNet/Renci.SshNet.csproj
+++ b/src/Renci.SshNet/Renci.SshNet.csproj
@@ -1,47 +1,23 @@
- true
- true
false
Renci.SshNet
- ../Renci.SshNet.snk
- 5
- true
- net35;net40;netstandard1.3;netstandard2.0
+ net462;netstandard2.0;netstandard2.1;net6.0;net7.0;net8.0
-
-
+
-
-
-
-
-
-
-
-
-
-
+
+
-
- FEATURE_REGEX_COMPILE;FEATURE_BINARY_SERIALIZATION;FEATURE_RNG_CREATE;FEATURE_SOCKET_SYNC;FEATURE_SOCKET_EAP;FEATURE_SOCKET_APM;FEATURE_SOCKET_POLL;FEATURE_STREAM_APM;FEATURE_DNS_SYNC;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_HASH_MD5;FEATURE_HASH_SHA1_CREATE;FEATURE_HASH_SHA256_CREATE;FEATURE_HASH_SHA384_CREATE;FEATURE_HASH_SHA512_CREATE;FEATURE_HASH_RIPEMD160_CREATE;FEATURE_HMAC_MD5;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256;FEATURE_HMAC_SHA384;FEATURE_HMAC_SHA512;FEATURE_HMAC_RIPEMD160;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_DIAGNOSTICS_TRACESOURCE;FEATURE_ENCODING_ASCII;FEATURE_ECDSA
-
-
- FEATURE_STRINGBUILDER_CLEAR;FEATURE_HASHALGORITHM_DISPOSE;FEATURE_REGEX_COMPILE;FEATURE_BINARY_SERIALIZATION;FEATURE_RNG_CREATE;FEATURE_SOCKET_SYNC;FEATURE_SOCKET_EAP;FEATURE_SOCKET_APM;FEATURE_SOCKET_SELECT;FEATURE_SOCKET_POLL;FEATURE_SOCKET_DISPOSE;FEATURE_STREAM_APM;FEATURE_DNS_SYNC;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_HASH_MD5;FEATURE_HASH_SHA1_CREATE;FEATURE_HASH_SHA256_CREATE;FEATURE_HASH_SHA384_CREATE;FEATURE_HASH_SHA512_CREATE;FEATURE_HASH_RIPEMD160_CREATE;FEATURE_HMAC_MD5;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256;FEATURE_HMAC_SHA384;FEATURE_HMAC_SHA512;FEATURE_HMAC_RIPEMD160;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_DIAGNOSTICS_TRACESOURCE;FEATURE_ENCODING_ASCII;FEATURE_ECDSA
-
-
- FEATURE_STRINGBUILDER_CLEAR;FEATURE_HASHALGORITHM_DISPOSE;FEATURE_ENCODING_ASCII;FEATURE_DIAGNOSTICS_TRACESOURCE;FEATURE_DIRECTORYINFO_ENUMERATEFILES;FEATURE_MEMORYSTREAM_TRYGETBUFFER;FEATURE_REFLECTION_TYPEINFO;FEATURE_RNG_CREATE;FEATURE_SOCKET_TAP;FEATURE_SOCKET_EAP;FEATURE_SOCKET_SYNC;FEATURE_SOCKET_SELECT;FEATURE_SOCKET_POLL;FEATURE_SOCKET_DISPOSE;FEATURE_DNS_TAP;FEATURE_STREAM_TAP;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_TAP;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_HASH_MD5;FEATURE_HASH_SHA1_CREATE;FEATURE_HASH_SHA256_CREATE;FEATURE_HASH_SHA384_CREATE;FEATURE_HASH_SHA512_CREATE;FEATURE_HMAC_MD5;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256;FEATURE_HMAC_SHA384;FEATURE_HMAC_SHA512
-
-
- FEATURE_STRINGBUILDER_CLEAR;FEATURE_HASHALGORITHM_DISPOSE;FEATURE_ENCODING_ASCII;FEATURE_DIAGNOSTICS_TRACESOURCE;FEATURE_DIRECTORYINFO_ENUMERATEFILES;FEATURE_MEMORYSTREAM_GETBUFFER;FEATURE_MEMORYSTREAM_TRYGETBUFFER;FEATURE_RNG_CREATE;FEATURE_SOCKET_TAP;FEATURE_SOCKET_APM;FEATURE_SOCKET_EAP;FEATURE_SOCKET_SYNC;FEATURE_SOCKET_SELECT;FEATURE_SOCKET_POLL;FEATURE_SOCKET_DISPOSE;FEATURE_DNS_SYNC;FEATURE_DNS_APM;FEATURE_DNS_TAP;FEATURE_STREAM_APM;FEATURE_STREAM_TAP;FEATURE_THREAD_COUNTDOWNEVENT;FEATURE_THREAD_TAP;FEATURE_THREAD_THREADPOOL;FEATURE_THREAD_SLEEP;FEATURE_WAITHANDLE_DISPOSE;FEATURE_HASH_MD5;FEATURE_HASH_SHA1_CREATE;FEATURE_HASH_SHA256_CREATE;FEATURE_HASH_SHA384_CREATE;FEATURE_HASH_SHA512_CREATE;FEATURE_HMAC_MD5;FEATURE_HMAC_SHA1;FEATURE_HMAC_SHA256;FEATURE_HMAC_SHA384;FEATURE_HMAC_SHA512;FEATURE_ECDSA
+
+ $(DefineConstants);FEATURE_SOCKET_TAP;FEATURE_SOCKET_APM;FEATURE_SOCKET_EAP;FEATURE_DNS_SYNC;FEATURE_DNS_APM;FEATURE_DNS_TAP
diff --git a/src/Renci.SshNet/ScpClient.NET.cs b/src/Renci.SshNet/ScpClient.NET.cs
deleted file mode 100644
index cb23cb695..000000000
--- a/src/Renci.SshNet/ScpClient.NET.cs
+++ /dev/null
@@ -1,358 +0,0 @@
-using System;
-using Renci.SshNet.Channels;
-using System.IO;
-using Renci.SshNet.Common;
-using System.Text.RegularExpressions;
-
-namespace Renci.SshNet
-{
- ///
- /// Provides SCP client functionality.
- ///
- public partial class ScpClient
- {
- private static readonly Regex DirectoryInfoRe = new Regex(@"D(?\d{4}) (?\d+) (?.+)");
- private static readonly Regex TimestampRe = new Regex(@"T(?\d+) 0 (?\d+) 0");
-
- ///
- /// Uploads the specified file to the remote host.
- ///
- /// The file system info.
- /// A relative or absolute path for the remote file.
- /// is null.
- /// is null.
- /// is a zero-length .
- /// A directory with the specified path exists on the remote host.
- /// The secure copy execution request was rejected by the server.
- public void Upload(FileInfo fileInfo, string path)
- {
- if (fileInfo == null)
- throw new ArgumentNullException("fileInfo");
-
- var posixPath = PosixPath.CreateAbsoluteOrRelativeFilePath(path);
-
- using (var input = ServiceFactory.CreatePipeStream())
- using (var channel = Session.CreateChannelSession())
- {
- channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length);
- channel.Open();
-
- // Pass only the directory part of the path to the server, and use the (hidden) -d option to signal
- // that we expect the target to be a directory.
- if (!channel.SendExecRequest(string.Format("scp -t -d {0}", _remotePathTransformation.Transform(posixPath.Directory))))
- {
- throw SecureExecutionRequestRejectedException();
- }
- CheckReturnCode(input);
-
- using (var source = fileInfo.OpenRead())
- {
- UploadTimes(channel, input, fileInfo);
- UploadFileModeAndName(channel, input, source.Length, posixPath.File);
- UploadFileContent(channel, input, source, fileInfo.Name);
- }
- }
- }
-
- ///
- /// Uploads the specified directory to the remote host.
- ///
- /// The directory info.
- /// A relative or absolute path for the remote directory.
- /// is null.
- /// is null.
- /// is a zero-length string.
- /// does not exist on the remote host, is not a directory or the user does not have the required permission.
- /// The secure copy execution request was rejected by the server.
- public void Upload(DirectoryInfo directoryInfo, string path)
- {
- if (directoryInfo == null)
- throw new ArgumentNullException("directoryInfo");
- if (path == null)
- throw new ArgumentNullException("path");
- if (path.Length == 0)
- throw new ArgumentException("The path cannot be a zero-length string.", "path");
-
- using (var input = ServiceFactory.CreatePipeStream())
- using (var channel = Session.CreateChannelSession())
- {
- channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length);
- channel.Open();
-
- // start copy with the following options:
- // -p preserve modification and access times
- // -r copy directories recursively
- // -d expect path to be a directory
- // -t copy to remote
- if (!channel.SendExecRequest(string.Format("scp -r -p -d -t {0}", _remotePathTransformation.Transform(path))))
- {
- throw SecureExecutionRequestRejectedException();
- }
-
- CheckReturnCode(input);
-
- UploadDirectoryContent(channel, input, directoryInfo);
- }
- }
-
- ///
- /// Downloads the specified file from the remote host to local file.
- ///
- /// Remote host file name.
- /// Local file information.
- /// is null.
- /// is null or empty.
- /// exists on the remote host, and is not a regular file.
- /// The secure copy execution request was rejected by the server.
- public void Download(string filename, FileInfo fileInfo)
- {
- if (string.IsNullOrEmpty(filename))
- throw new ArgumentException("filename");
- if (fileInfo == null)
- throw new ArgumentNullException("fileInfo");
-
- using (var input = ServiceFactory.CreatePipeStream())
- using (var channel = Session.CreateChannelSession())
- {
- channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length);
- channel.Open();
-
- // Send channel command request
- if (!channel.SendExecRequest(string.Format("scp -pf {0}", _remotePathTransformation.Transform(filename))))
- {
- throw SecureExecutionRequestRejectedException();
- }
- // Send reply
- SendSuccessConfirmation(channel);
-
- InternalDownload(channel, input, fileInfo);
- }
- }
-
- ///
- /// Downloads the specified directory from the remote host to local directory.
- ///
- /// Remote host directory name.
- /// Local directory information.
- /// is null or empty.
- /// is null.
- /// File or directory with the specified path does not exist on the remote host.
- /// The secure copy execution request was rejected by the server.
- public void Download(string directoryName, DirectoryInfo directoryInfo)
- {
- if (string.IsNullOrEmpty(directoryName))
- throw new ArgumentException("directoryName");
- if (directoryInfo == null)
- throw new ArgumentNullException("directoryInfo");
-
- using (var input = ServiceFactory.CreatePipeStream())
- using (var channel = Session.CreateChannelSession())
- {
- channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length);
- channel.Open();
-
- // Send channel command request
- if (!channel.SendExecRequest(string.Format("scp -prf {0}", _remotePathTransformation.Transform(directoryName))))
- {
- throw SecureExecutionRequestRejectedException();
- }
- // Send reply
- SendSuccessConfirmation(channel);
-
- InternalDownload(channel, input, directoryInfo);
- }
- }
-
- ///
- /// Uploads the and
- /// of the next file or directory to upload.
- ///
- /// The channel to perform the upload in.
- /// A from which any feedback from the server can be read.
- /// The file or directory to upload.
- private void UploadTimes(IChannelSession channel, Stream input, FileSystemInfo fileOrDirectory)
- {
- var zeroTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
- var modificationSeconds = (long) (fileOrDirectory.LastWriteTimeUtc - zeroTime).TotalSeconds;
- var accessSeconds = (long) (fileOrDirectory.LastAccessTimeUtc - zeroTime).TotalSeconds;
- SendData(channel, string.Format("T{0} 0 {1} 0\n", modificationSeconds, accessSeconds));
- CheckReturnCode(input);
- }
-
- ///
- /// Upload the files and subdirectories in the specified directory.
- ///
- /// The channel to perform the upload in.
- /// A from which any feedback from the server can be read.
- /// The directory to upload.
- private void UploadDirectoryContent(IChannelSession channel, Stream input, DirectoryInfo directoryInfo)
- {
- // Upload files
- var files = directoryInfo.GetFiles();
- foreach (var file in files)
- {
- using (var source = file.OpenRead())
- {
- UploadTimes(channel, input, file);
- UploadFileModeAndName(channel, input, source.Length, file.Name);
- UploadFileContent(channel, input, source, file.Name);
- }
- }
-
- // Upload directories
- var directories = directoryInfo.GetDirectories();
- foreach (var directory in directories)
- {
- UploadTimes(channel, input, directory);
- UploadDirectoryModeAndName(channel, input, directory.Name);
- UploadDirectoryContent(channel, input, directory);
- }
-
- // Mark upload of current directory complete
- SendData(channel, "E\n");
- CheckReturnCode(input);
- }
-
- ///
- /// Sets mode and name of the directory being upload.
- ///
- private void UploadDirectoryModeAndName(IChannelSession channel, Stream input, string directoryName)
- {
- SendData(channel, string.Format("D0755 0 {0}\n", directoryName));
- CheckReturnCode(input);
- }
-
- private void InternalDownload(IChannelSession channel, Stream input, FileSystemInfo fileSystemInfo)
- {
- var modifiedTime = DateTime.Now;
- var accessedTime = DateTime.Now;
-
- var startDirectoryFullName = fileSystemInfo.FullName;
- var currentDirectoryFullName = startDirectoryFullName;
- var directoryCounter = 0;
-
- while (true)
- {
- var message = ReadString(input);
-
- if (message == "E")
- {
- SendSuccessConfirmation(channel); // Send reply
-
- directoryCounter--;
-
- currentDirectoryFullName = new DirectoryInfo(currentDirectoryFullName).Parent.FullName;
-
- if (directoryCounter == 0)
- break;
- continue;
- }
-
- var match = DirectoryInfoRe.Match(message);
- if (match.Success)
- {
- SendSuccessConfirmation(channel); // Send reply
-
- // Read directory
- var filename = match.Result("${filename}");
-
- DirectoryInfo newDirectoryInfo;
- if (directoryCounter > 0)
- {
- newDirectoryInfo = Directory.CreateDirectory(Path.Combine(currentDirectoryFullName, filename));
- newDirectoryInfo.LastAccessTime = accessedTime;
- newDirectoryInfo.LastWriteTime = modifiedTime;
- }
- else
- {
- // Don't create directory for first level
- newDirectoryInfo = fileSystemInfo as DirectoryInfo;
- }
-
- directoryCounter++;
-
- currentDirectoryFullName = newDirectoryInfo.FullName;
- continue;
- }
-
- match = FileInfoRe.Match(message);
- if (match.Success)
- {
- // Read file
- SendSuccessConfirmation(channel); // Send reply
-
- var length = long.Parse(match.Result("${length}"));
- var fileName = match.Result("${filename}");
-
- var fileInfo = fileSystemInfo as FileInfo;
-
- if (fileInfo == null)
- fileInfo = new FileInfo(Path.Combine(currentDirectoryFullName, fileName));
-
- using (var output = fileInfo.OpenWrite())
- {
- InternalDownload(channel, input, output, fileName, length);
- }
-
- fileInfo.LastAccessTime = accessedTime;
- fileInfo.LastWriteTime = modifiedTime;
-
- if (directoryCounter == 0)
- break;
- continue;
- }
-
- match = TimestampRe.Match(message);
- if (match.Success)
- {
- // Read timestamp
- SendSuccessConfirmation(channel); // Send reply
-
- var mtime = long.Parse(match.Result("${mtime}"));
- var atime = long.Parse(match.Result("${atime}"));
-
- var zeroTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
- modifiedTime = zeroTime.AddSeconds(mtime);
- accessedTime = zeroTime.AddSeconds(atime);
- continue;
- }
-
- SendErrorConfirmation(channel, string.Format("\"{0}\" is not valid protocol message.", message));
- }
- }
-
- ///
- /// Return a value indicating whether the specified path is a valid SCP file path.
- ///
- /// The path to verify.
- ///
- /// if is a valid SCP file path; otherwise, .
- ///
- ///
- /// To match OpenSSH behavior (introduced as a result of CVE-2018-20685), a file path is considered
- /// invalid in any of the following conditions:
- ///
- /// -
- /// is a zero-length string.
- ///
- /// -
- /// is ".".
- ///
- /// -
- /// is "..".
- ///
- /// -
- /// contains a forward slash (/).
- ///
- ///
- ///
- private static bool IsValidScpFilePath(string path)
- {
- return path != null &&
- path.Length != 0 &&
- path != "." &&
- path != ".." &&
- path.IndexOf('/') == -1;
- }
- }
-}
diff --git a/src/Renci.SshNet/ScpClient.cs b/src/Renci.SshNet/ScpClient.cs
index 8a252cac9..8121c9702 100644
--- a/src/Renci.SshNet/ScpClient.cs
+++ b/src/Renci.SshNet/ScpClient.cs
@@ -1,11 +1,13 @@
using System;
-using Renci.SshNet.Channels;
-using System.IO;
-using Renci.SshNet.Common;
-using System.Text.RegularExpressions;
+using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.IO;
using System.Net;
-using System.Collections.Generic;
+using System.Text.RegularExpressions;
+
+using Renci.SshNet.Channels;
+using Renci.SshNet.Common;
namespace Renci.SshNet
{
@@ -14,8 +16,7 @@ namespace Renci.SshNet
///
///
///
- /// More information on the SCP protocol is available here:
- /// https://github.com/net-ssh/net-scp/blob/master/lib/net/scp.rb
+ /// More information on the SCP protocol is available here: https://github.com/net-ssh/net-scp/blob/master/lib/net/scp.rb.
///
///
/// Known issues in OpenSSH:
@@ -29,9 +30,12 @@ namespace Renci.SshNet
///
public partial class ScpClient : BaseClient
{
- private static readonly Regex FileInfoRe = new Regex(@"C(?\d{4}) (?\d+) (?.+)");
- private static readonly byte[] SuccessConfirmationCode = {0};
+ private const string Message = "filename";
+ private static readonly Regex FileInfoRe = new Regex(@"C(?\d{4}) (?\d+) (?.+)", RegexOptions.Compiled);
+ private static readonly byte[] SuccessConfirmationCode = { 0 };
private static readonly byte[] ErrorConfirmationCode = { 1 };
+ private static readonly Regex DirectoryInfoRe = new Regex(@"D(?\d{4}) (?\d+) (?.+)", RegexOptions.Compiled);
+ private static readonly Regex TimestampRe = new Regex(@"T(?\d+) 0 (?\d+) 0", RegexOptions.Compiled);
private IRemotePathTransformation _remotePathTransformation;
@@ -56,9 +60,9 @@ public partial class ScpClient : BaseClient
/// Gets or sets the transformation to apply to remote paths.
///
///
- /// The transformation to apply to remote paths. The default is .
+ /// The transformation to apply to remote paths. The default is .
///
- /// is null.
+ /// is .
///
///
/// This transformation is applied to the remote file or directory path that is passed to the
@@ -71,11 +75,17 @@ public partial class ScpClient : BaseClient
///
public IRemotePathTransformation RemotePathTransformation
{
- get { return _remotePathTransformation; }
+ get
+ {
+ return _remotePathTransformation;
+ }
set
{
- if (value == null)
- throw new ArgumentNullException("value");
+ if (value is null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
+
_remotePathTransformation = value;
}
}
@@ -90,15 +100,13 @@ public IRemotePathTransformation RemotePathTransformation
///
public event EventHandler Uploading;
- #region Constructors
-
///
/// Initializes a new instance of the class.
///
/// The connection info.
- /// is null.
+ /// is .
public ScpClient(ConnectionInfo connectionInfo)
- : this(connectionInfo, false)
+ : this(connectionInfo, ownsConnectionInfo: false)
{
}
@@ -109,12 +117,12 @@ public ScpClient(ConnectionInfo connectionInfo)
/// Connection port.
/// Authentication username.
/// Authentication password.
- /// is null.
- /// is invalid, or is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, or is or contains only whitespace characters.
/// is not within and .
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
public ScpClient(string host, int port, string username, string password)
- : this(new PasswordConnectionInfo(host, port, username, password), true)
+ : this(new PasswordConnectionInfo(host, port, username, password), ownsConnectionInfo: true)
{
}
@@ -124,8 +132,8 @@ public ScpClient(string host, int port, string username, string password)
/// Connection host.
/// Authentication username.
/// Authentication password.
- /// is null.
- /// is invalid, or is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, or is or contains only whitespace characters.
public ScpClient(string host, string username, string password)
: this(host, ConnectionInfo.DefaultPort, username, password)
{
@@ -138,12 +146,12 @@ public ScpClient(string host, string username, string password)
/// Connection port.
/// Authentication username.
/// Authentication private key file(s) .
- /// is null.
- /// is invalid, -or- is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, -or- is or contains only whitespace characters.
/// is not within and .
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
- public ScpClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)
- : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), true)
+ public ScpClient(string host, int port, string username, params IPrivateKeySource[] keyFiles)
+ : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), ownsConnectionInfo: true)
{
}
@@ -153,9 +161,9 @@ public ScpClient(string host, int port, string username, params PrivateKeyFile[]
/// Connection host.
/// Authentication username.
/// Authentication private key file(s) .
- /// is null.
- /// is invalid, -or- is null or contains only whitespace characters.
- public ScpClient(string host, string username, params PrivateKeyFile[] keyFiles)
+ /// is .
+ /// is invalid, -or- is or contains only whitespace characters.
+ public ScpClient(string host, string username, params IPrivateKeySource[] keyFiles)
: this(host, ConnectionInfo.DefaultPort, username, keyFiles)
{
}
@@ -165,9 +173,9 @@ public ScpClient(string host, string username, params PrivateKeyFile[] keyFiles)
///
/// The connection info.
/// Specified whether this instance owns the connection info.
- /// is null.
+ /// is .
///
- /// If is true, then the
+ /// If is , then the
/// connection info will be disposed when this instance is disposed.
///
private ScpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
@@ -181,10 +189,10 @@ private ScpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
/// The connection info.
/// Specified whether this instance owns the connection info.
/// The factory to use for creating new services.
- /// is null.
- /// is null.
+ /// is .
+ /// is .
///
- /// If is true, then the
+ /// If is , then the
/// connection info will be disposed when this instance is disposed.
///
internal ScpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
@@ -195,14 +203,12 @@ internal ScpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServ
_remotePathTransformation = serviceFactory.CreateRemotePathDoubleQuoteTransformation();
}
- #endregion
-
///
/// Uploads the specified stream to the remote host.
///
/// The to upload.
/// A relative or absolute path for the remote file.
- /// is null.
+ /// is .
/// is a zero-length .
/// A directory with the specified path exists on the remote host.
/// The secure copy execution request was rejected by the server.
@@ -222,6 +228,7 @@ public void Upload(Stream source, string path)
{
throw SecureExecutionRequestRejectedException();
}
+
CheckReturnCode(input);
UploadFileModeAndName(channel, input, source.Length, posixPath.File);
@@ -229,22 +236,198 @@ public void Upload(Stream source, string path)
}
}
+ ///
+ /// Uploads the specified file to the remote host.
+ ///
+ /// The file system info.
+ /// A relative or absolute path for the remote file.
+ /// is .
+ /// is .
+ /// is a zero-length .
+ /// A directory with the specified path exists on the remote host.
+ /// The secure copy execution request was rejected by the server.
+ public void Upload(FileInfo fileInfo, string path)
+ {
+ if (fileInfo is null)
+ {
+ throw new ArgumentNullException(nameof(fileInfo));
+ }
+
+ var posixPath = PosixPath.CreateAbsoluteOrRelativeFilePath(path);
+
+ using (var input = ServiceFactory.CreatePipeStream())
+ using (var channel = Session.CreateChannelSession())
+ {
+ channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length);
+ channel.Open();
+
+ // Pass only the directory part of the path to the server, and use the (hidden) -d option to signal
+ // that we expect the target to be a directory.
+ if (!channel.SendExecRequest($"scp -t -d {_remotePathTransformation.Transform(posixPath.Directory)}"))
+ {
+ throw SecureExecutionRequestRejectedException();
+ }
+
+ CheckReturnCode(input);
+
+ using (var source = fileInfo.OpenRead())
+ {
+ UploadTimes(channel, input, fileInfo);
+ UploadFileModeAndName(channel, input, source.Length, posixPath.File);
+ UploadFileContent(channel, input, source, fileInfo.Name);
+ }
+ }
+ }
+
+ ///
+ /// Uploads the specified directory to the remote host.
+ ///
+ /// The directory info.
+ /// A relative or absolute path for the remote directory.
+ /// is .
+ /// is .
+ /// is a zero-length string.
+ /// does not exist on the remote host, is not a directory or the user does not have the required permission.
+ /// The secure copy execution request was rejected by the server.
+ public void Upload(DirectoryInfo directoryInfo, string path)
+ {
+ if (directoryInfo is null)
+ {
+ throw new ArgumentNullException(nameof(directoryInfo));
+ }
+
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
+
+ if (path.Length == 0)
+ {
+ throw new ArgumentException("The path cannot be a zero-length string.", nameof(path));
+ }
+
+ using (var input = ServiceFactory.CreatePipeStream())
+ using (var channel = Session.CreateChannelSession())
+ {
+ channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length);
+ channel.Open();
+
+ // start copy with the following options:
+ // -p preserve modification and access times
+ // -r copy directories recursively
+ // -d expect path to be a directory
+ // -t copy to remote
+ if (!channel.SendExecRequest($"scp -r -p -d -t {_remotePathTransformation.Transform(path)}"))
+ {
+ throw SecureExecutionRequestRejectedException();
+ }
+
+ CheckReturnCode(input);
+
+ UploadDirectoryContent(channel, input, directoryInfo);
+ }
+ }
+
+ ///
+ /// Downloads the specified file from the remote host to local file.
+ ///
+ /// Remote host file name.
+ /// Local file information.
+ /// is .
+ /// is or empty.
+ /// exists on the remote host, and is not a regular file.
+ /// The secure copy execution request was rejected by the server.
+ public void Download(string filename, FileInfo fileInfo)
+ {
+ if (string.IsNullOrEmpty(filename))
+ {
+ throw new ArgumentException("filename");
+ }
+
+ if (fileInfo is null)
+ {
+ throw new ArgumentNullException(nameof(fileInfo));
+ }
+
+ using (var input = ServiceFactory.CreatePipeStream())
+ using (var channel = Session.CreateChannelSession())
+ {
+ channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length);
+ channel.Open();
+
+ // Send channel command request
+ if (!channel.SendExecRequest($"scp -pf {_remotePathTransformation.Transform(filename)}"))
+ {
+ throw SecureExecutionRequestRejectedException();
+ }
+
+ // Send reply
+ SendSuccessConfirmation(channel);
+
+ InternalDownload(channel, input, fileInfo);
+ }
+ }
+
+ ///
+ /// Downloads the specified directory from the remote host to local directory.
+ ///
+ /// Remote host directory name.
+ /// Local directory information.
+ /// is or empty.
+ /// is .
+ /// File or directory with the specified path does not exist on the remote host.
+ /// The secure copy execution request was rejected by the server.
+ public void Download(string directoryName, DirectoryInfo directoryInfo)
+ {
+ if (string.IsNullOrEmpty(directoryName))
+ {
+ throw new ArgumentException("directoryName");
+ }
+
+ if (directoryInfo is null)
+ {
+ throw new ArgumentNullException(nameof(directoryInfo));
+ }
+
+ using (var input = ServiceFactory.CreatePipeStream())
+ using (var channel = Session.CreateChannelSession())
+ {
+ channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length);
+ channel.Open();
+
+ // Send channel command request
+ if (!channel.SendExecRequest($"scp -prf {_remotePathTransformation.Transform(directoryName)}"))
+ {
+ throw SecureExecutionRequestRejectedException();
+ }
+
+ // Send reply
+ SendSuccessConfirmation(channel);
+
+ InternalDownload(channel, input, directoryInfo);
+ }
+ }
+
///
/// Downloads the specified file from the remote host to the stream.
///
/// A relative or absolute path for the remote file.
/// The to download the remote file to.
- /// is null or contains only whitespace characters.
- /// is null.
+ /// is or contains only whitespace characters.
+ /// is .
/// exists on the remote host, and is not a regular file.
/// The secure copy execution request was rejected by the server.
public void Download(string filename, Stream destination)
{
- if (filename.IsNullOrWhiteSpace())
- throw new ArgumentException("filename");
+ if (string.IsNullOrWhiteSpace(filename))
+ {
+ throw new ArgumentException(Message);
+ }
- if (destination == null)
- throw new ArgumentNullException("destination");
+ if (destination is null)
+ {
+ throw new ArgumentNullException(nameof(destination));
+ }
using (var input = ServiceFactory.CreatePipeStream())
using (var channel = Session.CreateChannelSession())
@@ -252,22 +435,23 @@ public void Download(string filename, Stream destination)
channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length);
channel.Open();
- // Send channel command request
- if (!channel.SendExecRequest(string.Format("scp -f {0}", _remotePathTransformation.Transform(filename))))
+ // Send channel command request
+ if (!channel.SendExecRequest(string.Concat("scp -f ", _remotePathTransformation.Transform(filename))))
{
throw SecureExecutionRequestRejectedException();
}
- SendSuccessConfirmation(channel); // Send reply
+
+ SendSuccessConfirmation(channel); // Send reply
var message = ReadString(input);
var match = FileInfoRe.Match(message);
if (match.Success)
{
- // Read file
+ // Read file
SendSuccessConfirmation(channel); // Send reply
- var length = long.Parse(match.Result("${length}"));
+ var length = long.Parse(match.Result("${length}"), CultureInfo.InvariantCulture);
var fileName = match.Result("${filename}");
InternalDownload(channel, input, destination, fileName, length);
@@ -279,6 +463,33 @@ public void Download(string filename, Stream destination)
}
}
+ private static void SendData(IChannel channel, byte[] buffer, int length)
+ {
+ channel.SendData(buffer, 0, length);
+ }
+
+ private static void SendData(IChannel channel, byte[] buffer)
+ {
+ channel.SendData(buffer);
+ }
+
+ private static int ReadByte(Stream stream)
+ {
+ var b = stream.ReadByte();
+
+ if (b == -1)
+ {
+ throw new SshException("Stream has been closed.");
+ }
+
+ return b;
+ }
+
+ private static SshException SecureExecutionRequestRejectedException()
+ {
+ throw new SshException("Secure copy execution request was rejected by the server. Please consult the server logs.");
+ }
+
///
/// Sets mode, size and name of file being upload.
///
@@ -334,48 +545,14 @@ private void UploadFileContent(IChannelSession channel, Stream input, Stream sou
CheckReturnCode(input);
}
- private void InternalDownload(IChannel channel, Stream input, Stream output, string filename, long length)
- {
- var buffer = new byte[Math.Min(length, BufferSize)];
- var needToRead = length;
-
- do
- {
- var read = input.Read(buffer, 0, (int) Math.Min(needToRead, BufferSize));
-
- output.Write(buffer, 0, read);
-
- RaiseDownloadingEvent(filename, length, length - needToRead);
-
- needToRead -= read;
- }
- while (needToRead > 0);
-
- output.Flush();
-
- // Raise one more time when file downloaded
- RaiseDownloadingEvent(filename, length, length - needToRead);
-
- // Send confirmation byte after last data byte was read
- SendSuccessConfirmation(channel);
-
- CheckReturnCode(input);
- }
-
private void RaiseDownloadingEvent(string filename, long size, long downloaded)
{
- if (Downloading != null)
- {
- Downloading(this, new ScpDownloadEventArgs(filename, size, downloaded));
- }
+ Downloading?.Invoke(this, new ScpDownloadEventArgs(filename, size, downloaded));
}
private void RaiseUploadingEvent(string filename, long size, long uploaded)
{
- if (Uploading != null)
- {
- Uploading(this, new ScpUploadEventArgs(filename, size, uploaded));
- }
+ Uploading?.Invoke(this, new ScpUploadEventArgs(filename, size, uploaded));
}
private static void SendSuccessConfirmation(IChannel channel)
@@ -410,24 +587,6 @@ private void SendData(IChannel channel, string command)
channel.SendData(ConnectionInfo.Encoding.GetBytes(command));
}
- private static void SendData(IChannel channel, byte[] buffer, int length)
- {
- channel.SendData(buffer, 0, length);
- }
-
- private static void SendData(IChannel channel, byte[] buffer)
- {
- channel.SendData(buffer);
- }
-
- private static int ReadByte(Stream stream)
- {
- var b = stream.ReadByte();
- if (b == -1)
- throw new SshException("Stream has been closed.");
- return b;
- }
-
///
/// Read a LF-terminated string from the .
///
@@ -442,7 +601,7 @@ private string ReadString(Stream stream)
var buffer = new List();
var b = ReadByte(stream);
- if (b == 1 || b == 2)
+ if (b is 1 or 2)
{
hasError = true;
b = ReadByte(stream);
@@ -457,13 +616,211 @@ private string ReadString(Stream stream)
var readBytes = buffer.ToArray();
if (hasError)
+ {
throw new ScpException(ConnectionInfo.Encoding.GetString(readBytes, 0, readBytes.Length));
+ }
+
return ConnectionInfo.Encoding.GetString(readBytes, 0, readBytes.Length);
}
- private static SshException SecureExecutionRequestRejectedException()
+ ///
+ /// Uploads the and
+ /// of the next file or directory to upload.
+ ///
+ /// The channel to perform the upload in.
+ /// A from which any feedback from the server can be read.
+ /// The file or directory to upload.
+ private void UploadTimes(IChannelSession channel, Stream input, FileSystemInfo fileOrDirectory)
{
- throw new SshException("Secure copy execution request was rejected by the server. Please consult the server logs.");
+#if NET ||NETSTANDARD2_1_OR_GREATER
+ var zeroTime = DateTime.UnixEpoch;
+#else
+ var zeroTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
+#endif
+ var modificationSeconds = (long) (fileOrDirectory.LastWriteTimeUtc - zeroTime).TotalSeconds;
+ var accessSeconds = (long) (fileOrDirectory.LastAccessTimeUtc - zeroTime).TotalSeconds;
+ SendData(channel, string.Format(CultureInfo.InvariantCulture, "T{0} 0 {1} 0\n", modificationSeconds, accessSeconds));
+ CheckReturnCode(input);
+ }
+
+ ///
+ /// Upload the files and subdirectories in the specified directory.
+ ///
+ /// The channel to perform the upload in.
+ /// A from which any feedback from the server can be read.
+ /// The directory to upload.
+ private void UploadDirectoryContent(IChannelSession channel, Stream input, DirectoryInfo directoryInfo)
+ {
+ // Upload files
+ var files = directoryInfo.GetFiles();
+ foreach (var file in files)
+ {
+ using (var source = file.OpenRead())
+ {
+ UploadTimes(channel, input, file);
+ UploadFileModeAndName(channel, input, source.Length, file.Name);
+ UploadFileContent(channel, input, source, file.Name);
+ }
+ }
+
+ // Upload directories
+ var directories = directoryInfo.GetDirectories();
+ foreach (var directory in directories)
+ {
+ UploadTimes(channel, input, directory);
+ UploadDirectoryModeAndName(channel, input, directory.Name);
+ UploadDirectoryContent(channel, input, directory);
+ }
+
+ // Mark upload of current directory complete
+ SendData(channel, "E\n");
+ CheckReturnCode(input);
+ }
+
+ ///
+ /// Sets mode and name of the directory being upload.
+ ///
+ private void UploadDirectoryModeAndName(IChannelSession channel, Stream input, string directoryName)
+ {
+ SendData(channel, string.Format("D0755 0 {0}\n", directoryName));
+ CheckReturnCode(input);
+ }
+
+ private void InternalDownload(IChannel channel, Stream input, Stream output, string filename, long length)
+ {
+ var buffer = new byte[Math.Min(length, BufferSize)];
+ var needToRead = length;
+
+ do
+ {
+ var read = input.Read(buffer, 0, (int) Math.Min(needToRead, BufferSize));
+
+ output.Write(buffer, 0, read);
+
+ RaiseDownloadingEvent(filename, length, length - needToRead);
+
+ needToRead -= read;
+ }
+ while (needToRead > 0);
+
+ output.Flush();
+
+ // Raise one more time when file downloaded
+ RaiseDownloadingEvent(filename, length, length - needToRead);
+
+ // Send confirmation byte after last data byte was read
+ SendSuccessConfirmation(channel);
+
+ CheckReturnCode(input);
+ }
+
+ private void InternalDownload(IChannelSession channel, Stream input, FileSystemInfo fileSystemInfo)
+ {
+ var modifiedTime = DateTime.Now;
+ var accessedTime = DateTime.Now;
+
+ var startDirectoryFullName = fileSystemInfo.FullName;
+ var currentDirectoryFullName = startDirectoryFullName;
+ var directoryCounter = 0;
+
+ while (true)
+ {
+ var message = ReadString(input);
+
+ if (message == "E")
+ {
+ SendSuccessConfirmation(channel); // Send reply
+
+ directoryCounter--;
+
+ currentDirectoryFullName = new DirectoryInfo(currentDirectoryFullName).Parent.FullName;
+
+ if (directoryCounter == 0)
+ {
+ break;
+ }
+
+ continue;
+ }
+
+ var match = DirectoryInfoRe.Match(message);
+ if (match.Success)
+ {
+ SendSuccessConfirmation(channel); // Send reply
+
+ // Read directory
+ var filename = match.Result("${filename}");
+
+ DirectoryInfo newDirectoryInfo;
+ if (directoryCounter > 0)
+ {
+ newDirectoryInfo = Directory.CreateDirectory(Path.Combine(currentDirectoryFullName, filename));
+ newDirectoryInfo.LastAccessTime = accessedTime;
+ newDirectoryInfo.LastWriteTime = modifiedTime;
+ }
+ else
+ {
+ // Don't create directory for first level
+ newDirectoryInfo = fileSystemInfo as DirectoryInfo;
+ }
+
+ directoryCounter++;
+
+ currentDirectoryFullName = newDirectoryInfo.FullName;
+ continue;
+ }
+
+ match = FileInfoRe.Match(message);
+ if (match.Success)
+ {
+ // Read file
+ SendSuccessConfirmation(channel); // Send reply
+
+ var length = long.Parse(match.Result("${length}"), CultureInfo.InvariantCulture);
+ var fileName = match.Result("${filename}");
+
+ if (fileSystemInfo is not FileInfo fileInfo)
+ {
+ fileInfo = new FileInfo(Path.Combine(currentDirectoryFullName, fileName));
+ }
+
+ using (var output = fileInfo.OpenWrite())
+ {
+ InternalDownload(channel, input, output, fileName, length);
+ }
+
+ fileInfo.LastAccessTime = accessedTime;
+ fileInfo.LastWriteTime = modifiedTime;
+
+ if (directoryCounter == 0)
+ {
+ break;
+ }
+
+ continue;
+ }
+
+ match = TimestampRe.Match(message);
+ if (match.Success)
+ {
+ // Read timestamp
+ SendSuccessConfirmation(channel); // Send reply
+
+ var mtime = long.Parse(match.Result("${mtime}"), CultureInfo.InvariantCulture);
+ var atime = long.Parse(match.Result("${atime}"), CultureInfo.InvariantCulture);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ var zeroTime = DateTime.UnixEpoch;
+#else
+ var zeroTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
+#endif
+ modifiedTime = zeroTime.AddSeconds(mtime);
+ accessedTime = zeroTime.AddSeconds(atime);
+ continue;
+ }
+
+ SendErrorConfirmation(channel, string.Format("\"{0}\" is not valid protocol message.", message));
+ }
}
}
}
diff --git a/src/Renci.SshNet/Security/BouncyCastle/.editorconfig b/src/Renci.SshNet/Security/BouncyCastle/.editorconfig
new file mode 100644
index 000000000..9440813d4
--- /dev/null
+++ b/src/Renci.SshNet/Security/BouncyCastle/.editorconfig
@@ -0,0 +1,6 @@
+[*.cs]
+
+generated_code = true
+
+# Do not reported any diagnostics for "imported" code
+dotnet_analyzer_diagnostic.severity = none
diff --git a/src/Renci.SshNet/Security/BouncyCastle/crypto/prng/CryptoApiRandomGenerator.cs b/src/Renci.SshNet/Security/BouncyCastle/crypto/prng/CryptoApiRandomGenerator.cs
index 5dd468b04..50ae6f38d 100644
--- a/src/Renci.SshNet/Security/BouncyCastle/crypto/prng/CryptoApiRandomGenerator.cs
+++ b/src/Renci.SshNet/Security/BouncyCastle/crypto/prng/CryptoApiRandomGenerator.cs
@@ -9,9 +9,7 @@ internal class CryptoApiRandomGenerator
private readonly RandomNumberGenerator rndProv;
public CryptoApiRandomGenerator()
-#if FEATURE_RNG_CREATE || FEATURE_RNG_CSP
: this(Abstractions.CryptoAbstraction.CreateRandomNumberGenerator())
-#endif
{
}
@@ -34,15 +32,7 @@ public virtual void AddSeedMaterial(long seed)
public virtual void NextBytes(byte[] bytes)
{
-#if FEATURE_RNG_CREATE || FEATURE_RNG_CSP
rndProv.GetBytes(bytes);
-#else
- if (bytes == null)
- throw new ArgumentNullException("bytes");
-
- var buffer = Windows.Security.Cryptography.CryptographicBuffer.GenerateRandom((uint)bytes.Length);
- System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.CopyTo(buffer, bytes);
-#endif
}
public virtual void NextBytes(byte[] bytes, int start, int len)
diff --git a/src/Renci.SshNet/Security/BouncyCastle/crypto/prng/IRandomGenerator.cs b/src/Renci.SshNet/Security/BouncyCastle/crypto/prng/IRandomGenerator.cs
index 5bb0c3540..57e49ea71 100644
--- a/src/Renci.SshNet/Security/BouncyCastle/crypto/prng/IRandomGenerator.cs
+++ b/src/Renci.SshNet/Security/BouncyCastle/crypto/prng/IRandomGenerator.cs
@@ -23,4 +23,4 @@ internal interface IRandomGenerator
/// Length of segment to fill.
void NextBytes(byte[] bytes, int start, int len);
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Security/BouncyCastle/math/BigInteger.cs b/src/Renci.SshNet/Security/BouncyCastle/math/BigInteger.cs
index 635a25409..a98959efe 100644
--- a/src/Renci.SshNet/Security/BouncyCastle/math/BigInteger.cs
+++ b/src/Renci.SshNet/Security/BouncyCastle/math/BigInteger.cs
@@ -648,7 +648,9 @@ public BigInteger(
int nBytes = GetByteLength(sizeInBits);
byte[] b = new byte[nBytes];
+#pragma warning disable CA5394 // Do not use insecure randomness
random.NextBytes(b);
+#pragma warning restore CA5394 // Do not use insecure randomness
// strip off any excess bits in the MSB
int xBits = BitsPerByte * nBytes - sizeInBits;
@@ -658,6 +660,7 @@ public BigInteger(
this.sign = this.magnitude.Length < 1 ? 0 : 1;
}
+#pragma warning disable CA5394 // Do not use insecure randomness
public BigInteger(
int bitLength,
int certainty,
@@ -716,6 +719,7 @@ public BigInteger(
}
}
}
+#pragma warning restore CA5394 // Do not use insecure randomness
public BigInteger Abs()
{
diff --git a/src/Renci.SshNet/Security/BouncyCastle/math/ec/endo/GlvEndomorphism.cs b/src/Renci.SshNet/Security/BouncyCastle/math/ec/endo/GlvEndomorphism.cs
index 143a369b3..acfae5264 100644
--- a/src/Renci.SshNet/Security/BouncyCastle/math/ec/endo/GlvEndomorphism.cs
+++ b/src/Renci.SshNet/Security/BouncyCastle/math/ec/endo/GlvEndomorphism.cs
@@ -3,7 +3,7 @@
namespace Renci.SshNet.Security.Org.BouncyCastle.Math.EC.Endo
{
internal interface GlvEndomorphism
- : ECEndomorphism
+ : ECEndomorphism
{
BigInteger[] DecomposeScalar(BigInteger k);
}
diff --git a/src/Renci.SshNet/Security/BouncyCastle/security/SecureRandom.cs b/src/Renci.SshNet/Security/BouncyCastle/security/SecureRandom.cs
index 377817e01..6e86c47ca 100644
--- a/src/Renci.SshNet/Security/BouncyCastle/security/SecureRandom.cs
+++ b/src/Renci.SshNet/Security/BouncyCastle/security/SecureRandom.cs
@@ -58,7 +58,9 @@ public SecureRandom()
///
/// The source to generate all random bytes from.
public SecureRandom(IRandomGenerator generator)
+#pragma warning disable CA5394 // Do not use insecure randomness
: base(0)
+#pragma warning restore CA5394 // Do not use insecure randomness
{
this.generator = generator;
}
diff --git a/src/Renci.SshNet/Security/CertificateHostAlgorithm.cs b/src/Renci.SshNet/Security/CertificateHostAlgorithm.cs
index 0f0e4ada3..41d5f4103 100644
--- a/src/Renci.SshNet/Security/CertificateHostAlgorithm.cs
+++ b/src/Renci.SshNet/Security/CertificateHostAlgorithm.cs
@@ -29,7 +29,7 @@ public CertificateHostAlgorithm(string name)
///
/// The data.
/// Signed data.
- ///
+ /// Always.
public override byte[] Sign(byte[] data)
{
throw new NotImplementedException();
@@ -40,8 +40,8 @@ public override byte[] Sign(byte[] data)
///
/// The data.
/// The signature.
- /// true if signature was successfully verified; otherwise false.
- ///
+ /// if signature was successfully verified; otherwise .
+ /// Always.
public override bool VerifySignature(byte[] data, byte[] signature)
{
throw new NotImplementedException();
diff --git a/src/Renci.SshNet/Security/Chaos.NaCl/.editorconfig b/src/Renci.SshNet/Security/Chaos.NaCl/.editorconfig
new file mode 100644
index 000000000..9440813d4
--- /dev/null
+++ b/src/Renci.SshNet/Security/Chaos.NaCl/.editorconfig
@@ -0,0 +1,6 @@
+[*.cs]
+
+generated_code = true
+
+# Do not reported any diagnostics for "imported" code
+dotnet_analyzer_diagnostic.severity = none
diff --git a/src/Renci.SshNet/Security/Cryptography/.editorconfig b/src/Renci.SshNet/Security/Cryptography/.editorconfig
new file mode 100644
index 000000000..7e36b6e59
--- /dev/null
+++ b/src/Renci.SshNet/Security/Cryptography/.editorconfig
@@ -0,0 +1,12 @@
+[Bcrypt.cs]
+
+generated_code = true
+
+# IDE0005: Remove unnecessary using directives
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0005
+dotnet_diagnostic.IDE0005.severity = none
+
+# IDE0007: Use var instead of explicit type
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0007-ide0008
+#
+dotnet_diagnostic.IDE0007.severity = none
\ No newline at end of file
diff --git a/src/Renci.SshNet/Security/Cryptography/AsymmetricCipher.cs b/src/Renci.SshNet/Security/Cryptography/AsymmetricCipher.cs
index 91d0c77ff..74e4a733b 100644
--- a/src/Renci.SshNet/Security/Cryptography/AsymmetricCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/AsymmetricCipher.cs
@@ -3,7 +3,7 @@
///
/// Base class for asymmetric cipher implementations.
///
- public abstract class AsymmetricCipher : Cipher
+ public abstract class AsymmetricCipher : Cipher
{
///
/// Gets the minimum data size.
diff --git a/src/Renci.SshNet/Security/Cryptography/Bcrypt.cs b/src/Renci.SshNet/Security/Cryptography/Bcrypt.cs
index 837d00318..14f6169a5 100644
--- a/src/Renci.SshNet/Security/Cryptography/Bcrypt.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Bcrypt.cs
@@ -499,14 +499,10 @@ public static string GenerateSalt(int workFactor)
throw new ArgumentOutOfRangeException("workFactor", "The work factor must be between 4 and 31 (inclusive)");
byte[] rnd = new byte[BCRYPT_SALT_LEN];
-#if FEATURE_RNG_CREATE
+
RandomNumberGenerator rng = RandomNumberGenerator.Create();
-#elif FEATURE_RNG_CSP
- RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
-#endif
-#if FEATURE_RNG_CREATE || FEATURE_RNG_CSP
+
rng.GetBytes(rnd);
-#endif
StringBuilder rs = new StringBuilder();
rs.AppendFormat("$2a${0:00}$", workFactor);
diff --git a/src/Renci.SshNet/Security/Cryptography/BlockCipher.cs b/src/Renci.SshNet/Security/Cryptography/BlockCipher.cs
index 18cf81cb6..b9f7dde58 100644
--- a/src/Renci.SshNet/Security/Cryptography/BlockCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/BlockCipher.cs
@@ -52,7 +52,7 @@ public byte BlockSize
/// Size of the block.
/// Cipher mode.
/// Cipher padding.
- /// is null.
+ /// is .
protected BlockCipher(byte[] key, byte blockSize, CipherMode mode, CipherPadding padding)
: base(key)
{
@@ -60,27 +60,29 @@ protected BlockCipher(byte[] key, byte blockSize, CipherMode mode, CipherPadding
_mode = mode;
_padding = padding;
- if (_mode != null)
- _mode.Init(this);
+ _mode?.Init(this);
}
///
/// Encrypts the specified data.
///
- /// The data.
- /// The zero-based offset in at which to begin encrypting.
- /// The number of bytes to encrypt from .
- /// Encrypted data
- public override byte[] Encrypt(byte[] data, int offset, int length)
+ /// The data.
+ /// The zero-based offset in at which to begin encrypting.
+ /// The number of bytes to encrypt from .
+ ///
+ /// The encrypted data.
+ ///
+ public override byte[] Encrypt(byte[] input, int offset, int length)
{
if (length % _blockSize > 0)
{
- if (_padding == null)
+ if (_padding is null)
{
throw new ArgumentException("data");
}
+
var paddingLength = _blockSize - (length % _blockSize);
- data = _padding.Pad(data, offset, length, paddingLength);
+ input = _padding.Pad(input, offset, length, paddingLength);
length += paddingLength;
offset = 0;
}
@@ -90,13 +92,13 @@ public override byte[] Encrypt(byte[] data, int offset, int length)
for (var i = 0; i < length / _blockSize; i++)
{
- if (_mode == null)
+ if (_mode is null)
{
- writtenBytes += EncryptBlock(data, offset + (i * _blockSize), _blockSize, output, i * _blockSize);
+ writtenBytes += EncryptBlock(input, offset + (i * _blockSize), _blockSize, output, i * _blockSize);
}
else
{
- writtenBytes += _mode.EncryptBlock(data, offset + (i * _blockSize), _blockSize, output, i * _blockSize);
+ writtenBytes += _mode.EncryptBlock(input, offset + (i * _blockSize), _blockSize, output, i * _blockSize);
}
}
@@ -111,33 +113,36 @@ public override byte[] Encrypt(byte[] data, int offset, int length)
///
/// Decrypts the specified data.
///
- /// The data.
- /// Decrypted data
- public override byte[] Decrypt(byte[] data)
+ /// The data.
+ ///
+ /// The decrypted data.
+ ///
+ public override byte[] Decrypt(byte[] input)
{
- return Decrypt(data, 0, data.Length);
+ return Decrypt(input, 0, input.Length);
}
///
/// Decrypts the specified input.
///
- /// The input.
- /// The zero-based offset in at which to begin decrypting.
- /// The number of bytes to decrypt from .
+ /// The input.
+ /// The zero-based offset in at which to begin decrypting.
+ /// The number of bytes to decrypt from .
///
/// The decrypted data.
///
- public override byte[] Decrypt(byte[] data, int offset, int length)
+ public override byte[] Decrypt(byte[] input, int offset, int length)
{
if (length % _blockSize > 0)
{
- if (_padding == null)
+ if (_padding is null)
{
throw new ArgumentException("data");
}
- data = _padding.Pad(_blockSize, data, offset, length);
+
+ input = _padding.Pad(_blockSize, input, offset, length);
offset = 0;
- length = data.Length;
+ length = input.Length;
}
var output = new byte[length];
@@ -145,13 +150,13 @@ public override byte[] Decrypt(byte[] data, int offset, int length)
var writtenBytes = 0;
for (var i = 0; i < length / _blockSize; i++)
{
- if (_mode == null)
+ if (_mode is null)
{
- writtenBytes += DecryptBlock(data, offset + (i * _blockSize), _blockSize, output, i * _blockSize);
+ writtenBytes += DecryptBlock(input, offset + (i * _blockSize), _blockSize, output, i * _blockSize);
}
else
{
- writtenBytes += _mode.DecryptBlock(data, offset + (i * _blockSize), _blockSize, output, i * _blockSize);
+ writtenBytes += _mode.DecryptBlock(input, offset + (i * _blockSize), _blockSize, output, i * _blockSize);
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/CipherDigitalSignature.cs b/src/Renci.SshNet/Security/Cryptography/CipherDigitalSignature.cs
index 752f97014..e61b5d655 100644
--- a/src/Renci.SshNet/Security/Cryptography/CipherDigitalSignature.cs
+++ b/src/Renci.SshNet/Security/Cryptography/CipherDigitalSignature.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Security.Cryptography
{
///
- /// Implements digital signature where where asymmetric cipher is used,
+ /// Implements digital signature where where asymmetric cipher is used.
///
public abstract class CipherDigitalSignature : DigitalSignature
{
@@ -18,8 +18,10 @@ public abstract class CipherDigitalSignature : DigitalSignature
/// The cipher.
protected CipherDigitalSignature(ObjectIdentifier oid, AsymmetricCipher cipher)
{
- if (cipher == null)
- throw new ArgumentNullException("cipher");
+ if (cipher is null)
+ {
+ throw new ArgumentNullException(nameof(cipher));
+ }
_cipher = cipher;
_oid = oid;
@@ -31,7 +33,7 @@ protected CipherDigitalSignature(ObjectIdentifier oid, AsymmetricCipher cipher)
/// The input.
/// The signature.
///
- /// True if signature was successfully verified; otherwise false.
+ /// if signature was successfully verified; otherwise .
///
public override bool Verify(byte[] input, byte[] signature)
{
@@ -50,10 +52,10 @@ public override bool Verify(byte[] input, byte[] signature)
///
public override byte[] Sign(byte[] input)
{
- // Calculate hash value
+ // Calculate hash value
var hashData = Hash(input);
- // Calculate DER string
+ // Calculate DER string
var derEncodedHash = DerEncode(hashData);
return _cipher.Encrypt(derEncodedHash).TrimLeadingZeros();
@@ -70,7 +72,9 @@ public override byte[] Sign(byte[] input)
/// Encodes hash using DER.
///
/// The hash data.
- /// DER Encoded byte array
+ ///
+ /// DER Encoded byte array.
+ ///
protected byte[] DerEncode(byte[] hashData)
{
var alg = new DerData();
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.BclImpl.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.BclImpl.cs
new file mode 100644
index 000000000..0941489f5
--- /dev/null
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.BclImpl.cs
@@ -0,0 +1,108 @@
+using System;
+using System.Security.Cryptography;
+
+using Renci.SshNet.Common;
+
+namespace Renci.SshNet.Security.Cryptography.Ciphers
+{
+ public partial class AesCipher
+ {
+ private sealed class BclImpl : BlockCipher, IDisposable
+ {
+ private readonly Aes _aes;
+ private readonly ICryptoTransform _encryptor;
+ private readonly ICryptoTransform _decryptor;
+
+ public BclImpl(
+ byte[] key,
+ byte[] iv,
+ System.Security.Cryptography.CipherMode cipherMode,
+ PaddingMode paddingMode)
+ : base(key, 16, mode: null, padding: null)
+ {
+ var aes = Aes.Create();
+ aes.Key = key;
+
+ if (cipherMode != System.Security.Cryptography.CipherMode.ECB)
+ {
+ if (iv is null)
+ {
+ throw new ArgumentNullException(nameof(iv));
+ }
+
+ aes.IV = iv.Take(16);
+ }
+
+ aes.Mode = cipherMode;
+ aes.Padding = paddingMode;
+ aes.FeedbackSize = 128; // We use CFB128
+ _aes = aes;
+ _encryptor = aes.CreateEncryptor();
+ _decryptor = aes.CreateDecryptor();
+ }
+
+ public override byte[] Encrypt(byte[] input, int offset, int length)
+ {
+ if (_aes.Padding != PaddingMode.None)
+ {
+ // If padding has been specified, call TransformFinalBlock to apply
+ // the padding and reset the state.
+ return _encryptor.TransformFinalBlock(input, offset, length);
+ }
+
+ // Otherwise, (the most important case) assume this instance is
+ // used for one direction of an SSH connection, whereby the
+ // encrypted data in all packets are considered a single data
+ // stream i.e. we do not want to reset the state between calls to Encrypt.
+ var output = new byte[length];
+ _ = _encryptor.TransformBlock(input, offset, length, output, 0);
+ return output;
+ }
+
+ public override byte[] Decrypt(byte[] input, int offset, int length)
+ {
+ if (_aes.Padding != PaddingMode.None)
+ {
+ // If padding has been specified, call TransformFinalBlock to apply
+ // the padding and reset the state.
+ return _decryptor.TransformFinalBlock(input, offset, length);
+ }
+
+ // Otherwise, (the most important case) assume this instance is
+ // used for one direction of an SSH connection, whereby the
+ // encrypted data in all packets are considered a single data
+ // stream i.e. we do not want to reset the state between calls to Decrypt.
+ var output = new byte[length];
+ _ = _decryptor.TransformBlock(input, offset, length, output, 0);
+ return output;
+ }
+
+ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
+ {
+ throw new NotImplementedException($"Invalid usage of {nameof(EncryptBlock)}.");
+ }
+
+ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
+ {
+ throw new NotImplementedException($"Invalid usage of {nameof(DecryptBlock)}.");
+ }
+
+ private void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _aes.Dispose();
+ _encryptor.Dispose();
+ _decryptor.Dispose();
+ }
+ }
+
+ public void Dispose()
+ {
+ // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
+ }
+ }
+ }
+}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.BlockImpl.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.BlockImpl.cs
new file mode 100644
index 000000000..ff261d767
--- /dev/null
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.BlockImpl.cs
@@ -0,0 +1,54 @@
+using System;
+using System.Security.Cryptography;
+
+namespace Renci.SshNet.Security.Cryptography.Ciphers
+{
+ public partial class AesCipher
+ {
+ private sealed class BlockImpl : BlockCipher, IDisposable
+ {
+ private readonly Aes _aes;
+ private readonly ICryptoTransform _encryptor;
+ private readonly ICryptoTransform _decryptor;
+
+ public BlockImpl(byte[] key, CipherMode mode, CipherPadding padding)
+ : base(key, 16, mode, padding)
+ {
+ var aes = Aes.Create();
+ aes.Key = key;
+ aes.Mode = System.Security.Cryptography.CipherMode.ECB;
+ aes.Padding = PaddingMode.None;
+ _aes = aes;
+ _encryptor = aes.CreateEncryptor();
+ _decryptor = aes.CreateDecryptor();
+ }
+
+ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
+ {
+ return _encryptor.TransformBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
+ }
+
+ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
+ {
+ return _decryptor.TransformBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
+ }
+
+ private void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _aes.Dispose();
+ _encryptor.Dispose();
+ _decryptor.Dispose();
+ }
+ }
+
+ public void Dispose()
+ {
+ // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
+ }
+ }
+ }
+}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.CtrImpl.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.CtrImpl.cs
new file mode 100644
index 000000000..dacaf4a79
--- /dev/null
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.CtrImpl.cs
@@ -0,0 +1,219 @@
+using System;
+#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
+using System.Buffers.Binary;
+using System.Numerics;
+#endif
+using System.Security.Cryptography;
+
+namespace Renci.SshNet.Security.Cryptography.Ciphers
+{
+ public partial class AesCipher
+ {
+ private sealed class CtrImpl : BlockCipher, IDisposable
+ {
+ private readonly Aes _aes;
+
+ private readonly ICryptoTransform _encryptor;
+
+#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
+ private ulong _ivUpper; // The upper 64 bits of the IV
+ private ulong _ivLower; // The lower 64 bits of the IV
+#else
+ // The same on netfx
+ private readonly uint[] _packedIV;
+#endif
+
+ public CtrImpl(
+ byte[] key,
+ byte[] iv)
+ : base(key, 16, mode: null, padding: null)
+ {
+ var aes = Aes.Create();
+ aes.Key = key;
+ aes.Mode = System.Security.Cryptography.CipherMode.ECB;
+ aes.Padding = PaddingMode.None;
+ _aes = aes;
+ _encryptor = aes.CreateEncryptor();
+
+#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
+ _ivLower = BinaryPrimitives.ReadUInt64BigEndian(iv.AsSpan(8));
+ _ivUpper = BinaryPrimitives.ReadUInt64BigEndian(iv);
+#else
+ _packedIV = GetPackedIV(iv);
+#endif
+ }
+
+ public override byte[] Encrypt(byte[] input, int offset, int length)
+ {
+ return CTREncryptDecrypt(input, offset, length);
+ }
+
+ public override byte[] Decrypt(byte[] input, int offset, int length)
+ {
+ return CTREncryptDecrypt(input, offset, length);
+ }
+
+ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
+ {
+ throw new NotImplementedException($"Invalid usage of {nameof(DecryptBlock)}.");
+ }
+
+ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
+ {
+ throw new NotImplementedException($"Invalid usage of {nameof(EncryptBlock)}.");
+ }
+
+ private byte[] CTREncryptDecrypt(byte[] data, int offset, int length)
+ {
+ var count = length / BlockSize;
+ if (length % BlockSize != 0)
+ {
+ count++;
+ }
+
+ var buffer = new byte[count * BlockSize];
+ CTRCreateCounterArray(buffer);
+ _ = _encryptor.TransformBlock(buffer, 0, buffer.Length, buffer, 0);
+ ArrayXOR(buffer, data, offset, length);
+
+ // adjust output for non-blocksized lengths
+ if (buffer.Length > length)
+ {
+ Array.Resize(ref buffer, length);
+ }
+
+ return buffer;
+ }
+
+#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
+
+ // creates the Counter array filled with incrementing copies of IV
+ private void CTRCreateCounterArray(byte[] buffer)
+ {
+ for (var i = 0; i < buffer.Length; i += 16)
+ {
+ BinaryPrimitives.WriteUInt64BigEndian(buffer.AsSpan(i + 8), _ivLower);
+ BinaryPrimitives.WriteUInt64BigEndian(buffer.AsSpan(i), _ivUpper);
+
+ _ivLower += 1;
+ _ivUpper += (_ivLower == 0) ? 1UL : 0UL;
+ }
+ }
+
+ // XOR 2 arrays using Vector
+ private static void ArrayXOR(byte[] buffer, byte[] data, int offset, int length)
+ {
+ var i = 0;
+
+ var oneVectorFromEnd = length - Vector.Count;
+ for (; i <= oneVectorFromEnd; i += Vector.Count)
+ {
+ var v = new Vector(buffer, i) ^ new Vector(data, offset + i);
+ v.CopyTo(buffer, i);
+ }
+
+ for (; i < length; i++)
+ {
+ buffer[i] ^= data[offset + i];
+ }
+ }
+
+#else
+ // creates the Counter array filled with incrementing copies of IV
+ private void CTRCreateCounterArray(byte[] buffer)
+ {
+ // fill array with IV, increment by 1 for each copy
+ var words = buffer.Length / 4;
+ var counter = new uint[words];
+ for (var i = 0; i < words; i += 4)
+ {
+ // write IV to buffer (big endian)
+ counter[i] = _packedIV[0];
+ counter[i + 1] = _packedIV[1];
+ counter[i + 2] = _packedIV[2];
+ counter[i + 3] = _packedIV[3];
+
+ // increment IV (little endian)
+ if (_packedIV[3] < 0xFF000000u)
+ {
+ _packedIV[3] += 0x01000000u;
+ }
+ else
+ {
+ var j = 3;
+ do
+ {
+ _packedIV[j] = SwapEndianness(SwapEndianness(_packedIV[j]) + 1);
+ }
+ while (_packedIV[j] == 0 && --j >= 0);
+ }
+ }
+
+ // copy uint[] to byte[]
+ Buffer.BlockCopy(counter, 0, buffer, 0, buffer.Length);
+ }
+
+ // XOR 2 arrays using Uint[] and blockcopy
+ private static void ArrayXOR(byte[] buffer, byte[] data, int offset, int length)
+ {
+ var words = length / 4;
+ if (length % 4 != 0)
+ {
+ words++;
+ }
+
+ // convert original data to words
+ var datawords = new uint[words];
+ Buffer.BlockCopy(data, offset, datawords, 0, length);
+
+ // convert encrypted IV counter to words
+ var bufferwords = new uint[words];
+ Buffer.BlockCopy(buffer, 0, bufferwords, 0, length);
+
+ // XOR encrypted Counter with input data
+ for (var i = 0; i < words; i++)
+ {
+ bufferwords[i] = bufferwords[i] ^ datawords[i];
+ }
+
+ // copy uint[] to byte[]
+ Buffer.BlockCopy(bufferwords, 0, buffer, 0, length);
+ }
+
+ // pack the IV into an array of uint[4]
+ private static uint[] GetPackedIV(byte[] iv)
+ {
+ var packedIV = new uint[4];
+ packedIV[0] = BitConverter.ToUInt32(iv, 0);
+ packedIV[1] = BitConverter.ToUInt32(iv, 4);
+ packedIV[2] = BitConverter.ToUInt32(iv, 8);
+ packedIV[3] = BitConverter.ToUInt32(iv, 12);
+
+ return packedIV;
+ }
+
+ private static uint SwapEndianness(uint x)
+ {
+ x = (x >> 16) | (x << 16);
+ return ((x & 0xFF00FF00) >> 8) | ((x & 0x00FF00FF) << 8);
+ }
+#endif
+
+ private void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _aes.Dispose();
+ _encryptor.Dispose();
+ }
+ }
+
+ public void Dispose()
+ {
+ // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
+ }
+ }
+ }
+}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.cs
index b42258624..447e1aee3 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.cs
@@ -1,836 +1,99 @@
-using System;
-using System.Globalization;
-using Renci.SshNet.Common;
+using System;
+using System.Security.Cryptography;
+
+using Renci.SshNet.Security.Cryptography.Ciphers.Modes;
+using Renci.SshNet.Security.Cryptography.Ciphers.Paddings;
namespace Renci.SshNet.Security.Cryptography.Ciphers
{
///
/// AES cipher implementation.
///
- public sealed class AesCipher : BlockCipher
+ public sealed partial class AesCipher : BlockCipher, IDisposable
{
- private const uint m1 = 0x80808080;
-
- private const uint m2 = 0x7f7f7f7f;
-
- private const uint m3 = 0x0000001b;
-
- private int _rounds;
-
- private uint[] _encryptionKey;
-
- private uint[] _decryptionKey;
-
- private uint C0, C1, C2, C3;
-
- #region Static Definition Tables
-
- private static readonly byte[] S =
- {
- 99, 124, 119, 123, 242, 107, 111, 197,
- 48, 1, 103, 43, 254, 215, 171, 118,
- 202, 130, 201, 125, 250, 89, 71, 240,
- 173, 212, 162, 175, 156, 164, 114, 192,
- 183, 253, 147, 38, 54, 63, 247, 204,
- 52, 165, 229, 241, 113, 216, 49, 21,
- 4, 199, 35, 195, 24, 150, 5, 154,
- 7, 18, 128, 226, 235, 39, 178, 117,
- 9, 131, 44, 26, 27, 110, 90, 160,
- 82, 59, 214, 179, 41, 227, 47, 132,
- 83, 209, 0, 237, 32, 252, 177, 91,
- 106, 203, 190, 57, 74, 76, 88, 207,
- 208, 239, 170, 251, 67, 77, 51, 133,
- 69, 249, 2, 127, 80, 60, 159, 168,
- 81, 163, 64, 143, 146, 157, 56, 245,
- 188, 182, 218, 33, 16, 255, 243, 210,
- 205, 12, 19, 236, 95, 151, 68, 23,
- 196, 167, 126, 61, 100, 93, 25, 115,
- 96, 129, 79, 220, 34, 42, 144, 136,
- 70, 238, 184, 20, 222, 94, 11, 219,
- 224, 50, 58, 10, 73, 6, 36, 92,
- 194, 211, 172, 98, 145, 149, 228, 121,
- 231, 200, 55, 109, 141, 213, 78, 169,
- 108, 86, 244, 234, 101, 122, 174, 8,
- 186, 120, 37, 46, 28, 166, 180, 198,
- 232, 221, 116, 31, 75, 189, 139, 138,
- 112, 62, 181, 102, 72, 3, 246, 14,
- 97, 53, 87, 185, 134, 193, 29, 158,
- 225, 248, 152, 17, 105, 217, 142, 148,
- 155, 30, 135, 233, 206, 85, 40, 223,
- 140, 161, 137, 13, 191, 230, 66, 104,
- 65, 153, 45, 15, 176, 84, 187, 22
- };
-
- // The inverse S-box
- private static readonly byte[] Si =
- {
- 82, 9, 106, 213, 48, 54, 165, 56,
- 191, 64, 163, 158, 129, 243, 215, 251,
- 124, 227, 57, 130, 155, 47, 255, 135,
- 52, 142, 67, 68, 196, 222, 233, 203,
- 84, 123, 148, 50, 166, 194, 35, 61,
- 238, 76, 149, 11, 66, 250, 195, 78,
- 8, 46, 161, 102, 40, 217, 36, 178,
- 118, 91, 162, 73, 109, 139, 209, 37,
- 114, 248, 246, 100, 134, 104, 152, 22,
- 212, 164, 92, 204, 93, 101, 182, 146,
- 108, 112, 72, 80, 253, 237, 185, 218,
- 94, 21, 70, 87, 167, 141, 157, 132,
- 144, 216, 171, 0, 140, 188, 211, 10,
- 247, 228, 88, 5, 184, 179, 69, 6,
- 208, 44, 30, 143, 202, 63, 15, 2,
- 193, 175, 189, 3, 1, 19, 138, 107,
- 58, 145, 17, 65, 79, 103, 220, 234,
- 151, 242, 207, 206, 240, 180, 230, 115,
- 150, 172, 116, 34, 231, 173, 53, 133,
- 226, 249, 55, 232, 28, 117, 223, 110,
- 71, 241, 26, 113, 29, 41, 197, 137,
- 111, 183, 98, 14, 170, 24, 190, 27,
- 252, 86, 62, 75, 198, 210, 121, 32,
- 154, 219, 192, 254, 120, 205, 90, 244,
- 31, 221, 168, 51, 136, 7, 199, 49,
- 177, 18, 16, 89, 39, 128, 236, 95,
- 96, 81, 127, 169, 25, 181, 74, 13,
- 45, 229, 122, 159, 147, 201, 156, 239,
- 160, 224, 59, 77, 174, 42, 245, 176,
- 200, 235, 187, 60, 131, 83, 153, 97,
- 23, 43, 4, 126, 186, 119, 214, 38,
- 225, 105, 20, 99, 85, 33, 12, 125
- };
-
- // vector used in calculating key schedule (powers of x in GF(256))
- private static readonly byte[] rcon =
- {
- 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
- 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91
- };
-
- // precomputation tables of calculations for rounds
- private static readonly uint[] T0 =
- {
- 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff,
- 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102,
- 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d,
- 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa,
- 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41,
- 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453,
- 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d,
- 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83,
- 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2,
- 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795,
- 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a,
- 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df,
- 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912,
- 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc,
- 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7,
- 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413,
- 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040,
- 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d,
- 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0,
- 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed,
- 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a,
- 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78,
- 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080,
- 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1,
- 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020,
- 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18,
- 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488,
- 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a,
- 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0,
- 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54,
- 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b,
- 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad,
- 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992,
- 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd,
- 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3,
- 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda,
- 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8,
- 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4,
- 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a,
- 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697,
- 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96,
- 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c,
- 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7,
- 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969,
- 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9,
- 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9,
- 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715,
- 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5,
- 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65,
- 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929,
- 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d,
- 0x3a16162c
- };
-
- private static readonly uint[] T1 =
- {
- 0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d,
- 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203,
- 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6,
- 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87,
- 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec,
- 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7,
- 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae,
- 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f,
- 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293,
- 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552,
- 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f,
- 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d,
- 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b,
- 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2,
- 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761,
- 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397,
- 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060,
- 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46,
- 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8,
- 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16,
- 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf,
- 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844,
- 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0,
- 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104,
- 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030,
- 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814,
- 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc,
- 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47,
- 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0,
- 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e,
- 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3,
- 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76,
- 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db,
- 0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e,
- 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337,
- 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7,
- 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4,
- 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e,
- 0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f,
- 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751,
- 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd,
- 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42,
- 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701,
- 0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0,
- 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938,
- 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970,
- 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592,
- 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a,
- 0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da,
- 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0,
- 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6,
- 0x16162c3a
- };
-
- private static readonly uint[] T2 =
- {
- 0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2,
- 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301,
- 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab,
- 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d,
- 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad,
- 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4,
- 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93,
- 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc,
- 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371,
- 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7,
- 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05,
- 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2,
- 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09,
- 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e,
- 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6,
- 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784,
- 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020,
- 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb,
- 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858,
- 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb,
- 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45,
- 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c,
- 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040,
- 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5,
- 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010,
- 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c,
- 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44,
- 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d,
- 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060,
- 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a,
- 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8,
- 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db,
- 0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49,
- 0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3,
- 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4,
- 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d,
- 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c,
- 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a,
- 0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25,
- 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6,
- 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b,
- 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e,
- 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6,
- 0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9,
- 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1,
- 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9,
- 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287,
- 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf,
- 0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf,
- 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099,
- 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb,
- 0x162c3a16
- };
-
- private static readonly uint[] T3 =
- {
- 0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2,
- 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101,
- 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab,
- 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d,
- 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad,
- 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4,
- 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393,
- 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc,
- 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171,
- 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7,
- 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505,
- 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2,
- 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909,
- 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e,
- 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6,
- 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484,
- 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020,
- 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb,
- 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858,
- 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb,
- 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545,
- 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c,
- 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040,
- 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5,
- 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010,
- 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c,
- 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444,
- 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d,
- 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060,
- 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a,
- 0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8,
- 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb,
- 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949,
- 0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3,
- 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4,
- 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d,
- 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c,
- 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a,
- 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525,
- 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6,
- 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b,
- 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e,
- 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6,
- 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9,
- 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1,
- 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9,
- 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787,
- 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf,
- 0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf,
- 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999,
- 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb,
- 0x2c3a1616
- };
-
- private static readonly uint[] Tinv0 =
- {
- 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b,
- 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad,
- 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526,
- 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d,
- 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03,
- 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458,
- 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899,
- 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d,
- 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1,
- 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f,
- 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3,
- 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3,
- 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a,
- 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506,
- 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05,
- 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd,
- 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491,
- 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6,
- 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7,
- 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000,
- 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd,
- 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68,
- 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4,
- 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c,
- 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e,
- 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af,
- 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644,
- 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8,
- 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85,
- 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc,
- 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411,
- 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322,
- 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6,
- 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850,
- 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e,
- 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf,
- 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd,
- 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa,
- 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea,
- 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235,
- 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1,
- 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43,
- 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1,
- 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb,
- 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a,
- 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7,
- 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418,
- 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478,
- 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16,
- 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08,
- 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48,
- 0x4257b8d0
- };
-
- private static readonly uint[] Tinv1 =
- {
- 0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb,
- 0x459d1ff1, 0x58faacab, 0x03e34b93, 0xfa302055, 0x6d76adf6,
- 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680,
- 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0x0eea4598, 0xc0fe5de1,
- 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7,
- 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3,
- 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b,
- 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4,
- 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0,
- 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19,
- 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x024b72e2, 0x8f1fe357,
- 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x0837d3a5,
- 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b,
- 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5,
- 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532,
- 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51,
- 0x8a213ef9, 0x06dd963d, 0x053eddae, 0xbde64d46, 0x8d5491b5,
- 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697,
- 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738,
- 0xeec879db, 0x0a7ca147, 0x0f427ce9, 0x1e84f8c9, 0x00000000,
- 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb,
- 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821,
- 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2,
- 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16,
- 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0x0d090e0b,
- 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x0775af4c,
- 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5,
- 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863,
- 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d,
- 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3,
- 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa,
- 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef,
- 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0x0bd49836, 0x81f5a6cf,
- 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d,
- 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e,
- 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3,
- 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09,
- 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e,
- 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x099fead4,
- 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0,
- 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a,
- 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d,
- 0x4daacc54, 0x0496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8,
- 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e,
- 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c,
- 0x0ca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735,
- 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879,
- 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886,
- 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672,
- 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x01a83971, 0xb30c08de,
- 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874,
- 0x57b8d042
- };
-
- private static readonly uint[] Tinv2 =
- {
- 0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b,
- 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d,
- 0xcc889176, 0x02f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044,
- 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0,
- 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f,
- 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321,
- 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e,
- 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a,
- 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077,
- 0x6bbb84ae, 0x81fe1ca0, 0x08f9942b, 0x48705868, 0x458f19fd,
- 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f,
- 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508,
- 0x2830f287, 0xbf23b2a5, 0x0302ba6a, 0x16ed5c82, 0xcf8a2b1c,
- 0x79a792b4, 0x07f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x0506d5be,
- 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1,
- 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110,
- 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d,
- 0xc471055d, 0x06046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9,
- 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b,
- 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x00000000,
- 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0x0efdfbff,
- 0x850f5638, 0xae3d1ed5, 0x2d362739, 0x0f0a64d9, 0x5c6821a6,
- 0x5b9bd154, 0x36243a2e, 0x0a0cb167, 0x57930fe7, 0xeeb4d296,
- 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a,
- 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x090e0b0d,
- 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07,
- 0x99eebbdd, 0x7fa3fd60, 0x01f79f26, 0x725cbcf5, 0x6644c53b,
- 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1,
- 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24,
- 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330,
- 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48,
- 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90,
- 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81,
- 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92,
- 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7,
- 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312,
- 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978,
- 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6,
- 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409,
- 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066,
- 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x04f14a98,
- 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0,
- 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f,
- 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0x0bfb2e41,
- 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61,
- 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9,
- 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce,
- 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db,
- 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3,
- 0xe2bc0c25, 0x3c288b49, 0x0dff4195, 0xa8397101, 0x0c08deb3,
- 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c,
- 0xb8d04257
- };
-
- private static readonly uint[] Tinv3 =
- {
- 0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab,
- 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76,
- 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435,
- 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe,
- 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x03e75f8f,
- 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174,
- 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58,
- 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace,
- 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764,
- 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45,
- 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f,
- 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837,
- 0x30f28728, 0x23b2a5bf, 0x02ba6a03, 0xed5c8216, 0x8a2b1ccf,
- 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x06d5be05,
- 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x0532e18a,
- 0xa475ebf6, 0x0b39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e,
- 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54,
- 0x71055dc4, 0x046fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd,
- 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x07888b89, 0xe7385b19,
- 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x00000000,
- 0x09838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e,
- 0x0f563885, 0x3d1ed5ae, 0x3627392d, 0x0a64d90f, 0x6821a65c,
- 0x9bd1545b, 0x243a2e36, 0x0cb1670a, 0x930fe757, 0xb4d296ee,
- 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12,
- 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0x0e0b0d09,
- 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775,
- 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66,
- 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4,
- 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a,
- 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2,
- 0x0dec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894,
- 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033,
- 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5,
- 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278,
- 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739,
- 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225,
- 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826,
- 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff,
- 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f,
- 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2,
- 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804,
- 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef,
- 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c,
- 0x467f5165, 0x9d04ea5e, 0x015d358c, 0xfa737487, 0xfb2e410b,
- 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7,
- 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961,
- 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14,
- 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44,
- 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d,
- 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x08deb30c,
- 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c,
- 0xd04257b8
- };
-
- #endregion
+ private readonly BlockCipher _impl;
///
/// Initializes a new instance of the class.
///
/// The key.
/// The mode.
- /// The padding.
- /// is null.
+ /// The IV.
+ /// Enable PKCS7 padding.
+ /// is .
/// Keysize is not valid for this algorithm.
- public AesCipher(byte[] key, CipherMode mode, CipherPadding padding)
- : base(key, 16, mode, padding)
+ public AesCipher(byte[] key, byte[] iv, AesCipherMode mode, bool pkcs7Padding = false)
+ : base(key, 16, mode: null, padding: null)
{
- var keySize = key.Length * 8;
-
- if (!(keySize == 256 || keySize == 192 || keySize == 128))
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "KeySize '{0}' is not valid for this algorithm.", keySize));
- }
-
- ///
- /// Encrypts the specified region of the input byte array and copies the encrypted data to the specified region of the output byte array.
- ///
- /// The input data to encrypt.
- /// The offset into the input byte array from which to begin using data.
- /// The number of bytes in the input byte array to use as data.
- /// The output to which to write encrypted data.
- /// The offset into the output byte array from which to begin writing data.
- ///
- /// The number of bytes encrypted.
- ///
- /// or is null.
- /// or is too short.
- public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
- {
- if (inputBuffer == null)
- throw new ArgumentNullException("inputBuffer");
-
- if (outputBuffer == null)
- throw new ArgumentNullException("outputBuffer");
-
- if ((inputOffset + (32 / 2)) > inputBuffer.Length)
+ if (mode == AesCipherMode.OFB)
{
- throw new IndexOutOfRangeException("input buffer too short");
+ // OFB is not supported on modern .NET
+ _impl = new BlockImpl(key, new OfbCipherMode(iv), pkcs7Padding ? new PKCS7Padding() : null);
}
-
- if ((outputOffset + (32 / 2)) > outputBuffer.Length)
+#if !NET6_0_OR_GREATER
+ else if (mode == AesCipherMode.CFB)
{
- throw new IndexOutOfRangeException("output buffer too short");
+ // CFB not supported on NetStandard 2.1
+ _impl = new BlockImpl(key, new CfbCipherMode(iv), pkcs7Padding ? new PKCS7Padding() : null);
}
-
- if (_encryptionKey == null)
+#endif
+ else if (mode == AesCipherMode.CTR)
{
- _encryptionKey = GenerateWorkingKey(true, Key);
+ // CTR not supported by the BCL, use an optimized implementation
+ _impl = new CtrImpl(key, iv);
}
-
- UnPackBlock(inputBuffer, inputOffset);
-
- EncryptBlock(_encryptionKey);
-
- PackBlock(outputBuffer, outputOffset);
-
- return BlockSize;
- }
-
- ///
- /// Decrypts the specified region of the input byte array and copies the decrypted data to the specified region of the output byte array.
- ///
- /// The input data to decrypt.
- /// The offset into the input byte array from which to begin using data.
- /// The number of bytes in the input byte array to use as data.
- /// The output to which to write decrypted data.
- /// The offset into the output byte array from which to begin writing data.
- ///
- /// The number of bytes decrypted.
- ///
- /// or is null.
- /// or is too short.
- public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
- {
- if (inputBuffer == null)
- throw new ArgumentNullException("inputBuffer");
-
- if (outputBuffer == null)
- throw new ArgumentNullException("outputBuffer");
-
- if ((inputOffset + (32 / 2)) > inputBuffer.Length)
- {
- throw new IndexOutOfRangeException("input buffer too short");
- }
-
- if ((outputOffset + (32 / 2)) > outputBuffer.Length)
- {
- throw new IndexOutOfRangeException("output buffer too short");
- }
-
- if (_decryptionKey == null)
- {
- _decryptionKey = GenerateWorkingKey(false, Key);
- }
-
- UnPackBlock(inputBuffer, inputOffset);
-
- DecryptBlock(_decryptionKey);
-
- PackBlock(outputBuffer, outputOffset);
-
- return BlockSize;
- }
-
- private uint[] GenerateWorkingKey(bool isEncryption, byte[] key)
- {
- int KC = key.Length / 4; // key length in words
-
- if (((KC != 4) && (KC != 6) && (KC != 8)) || ((KC * 4) != key.Length))
- throw new ArgumentException("Key length not 128/192/256 bits.");
-
- _rounds = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes
- uint[] W = new uint[(_rounds + 1) * 4]; // 4 words in a block
-
- //
- // copy the key into the round key array
- //
-
- int t = 0;
-
- for (int i = 0; i < key.Length; t++)
- {
- W[(t >> 2) * 4 + (t & 3)] = Pack.LittleEndianToUInt32(key, i);
- i += 4;
- }
-
- //
- // while not enough round key material calculated
- // calculate new values
- //
- int k = (_rounds + 1) << 2;
- for (int i = KC; (i < k); i++)
- {
- uint temp = W[((i - 1) >> 2) * 4 + ((i - 1) & 3)];
- if ((i % KC) == 0)
- {
- temp = SubWord(Shift(temp, 8)) ^ rcon[(i / KC) - 1];
- }
- else if ((KC > 6) && ((i % KC) == 4))
- {
- temp = SubWord(temp);
- }
-
- W[(i >> 2) * 4 + (i & 3)] = W[((i - KC) >> 2) * 4 + ((i - KC) & 3)] ^ temp;
- }
-
- if (!isEncryption)
+ else
{
- for (int j = 1; j < _rounds; j++)
- {
- for (int i = 0; i < 4; i++)
- {
- W[j * 4 + i] = InvMcol(W[j * 4 + i]);
- }
- }
+ _impl = new BclImpl(
+ key,
+ iv,
+ (System.Security.Cryptography.CipherMode) mode,
+ pkcs7Padding ? PaddingMode.PKCS7 : PaddingMode.None);
}
-
- return W;
}
- private static uint Shift(uint r, int shift)
- {
- return (r >> shift) | (r << (32 - shift));
- }
-
- private static uint FFmulX(uint x)
- {
- return ((x & m2) << 1) ^ (((x & m1) >> 7) * m3);
- }
-
- private static uint InvMcol(uint x)
+ ///
+ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
- uint f2 = FFmulX(x);
- uint f4 = FFmulX(f2);
- uint f8 = FFmulX(f4);
- uint f9 = x ^ f8;
-
- return f2 ^ f4 ^ f8 ^ Shift(f2 ^ f9, 8) ^ Shift(f4 ^ f9, 16) ^ Shift(f9, 24);
+ return _impl.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
}
- private static uint SubWord(uint x)
+ ///
+ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
- return (uint)S[x & 255]
- | (((uint)S[(x >> 8) & 255]) << 8)
- | (((uint)S[(x >> 16) & 255]) << 16)
- | (((uint)S[(x >> 24) & 255]) << 24);
+ return _impl.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
}
- private void UnPackBlock(byte[] bytes, int off)
+ ///
+ public override byte[] Encrypt(byte[] input, int offset, int length)
{
- C0 = Pack.LittleEndianToUInt32(bytes, off);
- C1 = Pack.LittleEndianToUInt32(bytes, off + 4);
- C2 = Pack.LittleEndianToUInt32(bytes, off + 8);
- C3 = Pack.LittleEndianToUInt32(bytes, off + 12);
+ return _impl.Encrypt(input, offset, length);
}
- private void PackBlock(byte[] bytes, int off)
+ ///
+ public override byte[] Decrypt(byte[] input, int offset, int length)
{
- Pack.UInt32ToLittleEndian(C0, bytes, off);
- Pack.UInt32ToLittleEndian(C1, bytes, off + 4);
- Pack.UInt32ToLittleEndian(C2, bytes, off + 8);
- Pack.UInt32ToLittleEndian(C3, bytes, off + 12);
+ return _impl.Decrypt(input, offset, length);
}
- private void EncryptBlock(uint[] KW)
+ ///
+ /// Dispose the instance.
+ ///
+ /// Set to True to dispose of resouces.
+ public void Dispose(bool disposing)
{
- int r;
- uint r0, r1, r2, r3;
-
- C0 ^= KW[0 * 4 + 0];
- C1 ^= KW[0 * 4 + 1];
- C2 ^= KW[0 * 4 + 2];
- C3 ^= KW[0 * 4 + 3];
-
- for (r = 1; r < _rounds - 1;)
+ if (disposing && _impl is IDisposable disposableImpl)
{
- r0 = T0[C0 & 255] ^ T1[(C1 >> 8) & 255] ^ T2[(C2 >> 16) & 255] ^ T3[C3 >> 24] ^ KW[r * 4 + 0];
- r1 = T0[C1 & 255] ^ T1[(C2 >> 8) & 255] ^ T2[(C3 >> 16) & 255] ^ T3[C0 >> 24] ^ KW[r * 4 + 1];
- r2 = T0[C2 & 255] ^ T1[(C3 >> 8) & 255] ^ T2[(C0 >> 16) & 255] ^ T3[C1 >> 24] ^ KW[r * 4 + 2];
- r3 = T0[C3 & 255] ^ T1[(C0 >> 8) & 255] ^ T2[(C1 >> 16) & 255] ^ T3[C2 >> 24] ^ KW[r++ * 4 + 3];
- C0 = T0[r0 & 255] ^ T1[(r1 >> 8) & 255] ^ T2[(r2 >> 16) & 255] ^ T3[r3 >> 24] ^ KW[r * 4 + 0];
- C1 = T0[r1 & 255] ^ T1[(r2 >> 8) & 255] ^ T2[(r3 >> 16) & 255] ^ T3[r0 >> 24] ^ KW[r * 4 + 1];
- C2 = T0[r2 & 255] ^ T1[(r3 >> 8) & 255] ^ T2[(r0 >> 16) & 255] ^ T3[r1 >> 24] ^ KW[r * 4 + 2];
- C3 = T0[r3 & 255] ^ T1[(r0 >> 8) & 255] ^ T2[(r1 >> 16) & 255] ^ T3[r2 >> 24] ^ KW[r++ * 4 + 3];
+ disposableImpl.Dispose();
}
-
- r0 = T0[C0 & 255] ^ T1[(C1 >> 8) & 255] ^ T2[(C2 >> 16) & 255] ^ T3[C3 >> 24] ^ KW[r * 4 + 0];
- r1 = T0[C1 & 255] ^ T1[(C2 >> 8) & 255] ^ T2[(C3 >> 16) & 255] ^ T3[C0 >> 24] ^ KW[r * 4 + 1];
- r2 = T0[C2 & 255] ^ T1[(C3 >> 8) & 255] ^ T2[(C0 >> 16) & 255] ^ T3[C1 >> 24] ^ KW[r * 4 + 2];
- r3 = T0[C3 & 255] ^ T1[(C0 >> 8) & 255] ^ T2[(C1 >> 16) & 255] ^ T3[C2 >> 24] ^ KW[r++ * 4 + 3];
-
- // the final round's table is a simple function of S so we don't use a whole other four tables for it
-
- C0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)S[(r2 >> 16) & 255]) << 16) ^ (((uint)S[r3 >> 24]) << 24) ^ KW[r * 4 + 0];
- C1 = (uint)S[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)S[r0 >> 24]) << 24) ^ KW[r * 4 + 1];
- C2 = (uint)S[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[r1 >> 24]) << 24) ^ KW[r * 4 + 2];
- C3 = (uint)S[r3 & 255] ^ (((uint)S[(r0 >> 8) & 255]) << 8) ^ (((uint)S[(r1 >> 16) & 255]) << 16) ^ (((uint)S[r2 >> 24]) << 24) ^ KW[r * 4 + 3];
}
- private void DecryptBlock(uint[] KW)
+ ///
+ public void Dispose()
{
- int r;
- uint r0, r1, r2, r3;
-
- C0 ^= KW[_rounds * 4 + 0];
- C1 ^= KW[_rounds * 4 + 1];
- C2 ^= KW[_rounds * 4 + 2];
- C3 ^= KW[_rounds * 4 + 3];
-
- for (r = _rounds - 1; r > 1;)
- {
- r0 = Tinv0[C0 & 255] ^ Tinv1[(C3 >> 8) & 255] ^ Tinv2[(C2 >> 16) & 255] ^ Tinv3[C1 >> 24] ^ KW[r * 4 + 0];
- r1 = Tinv0[C1 & 255] ^ Tinv1[(C0 >> 8) & 255] ^ Tinv2[(C3 >> 16) & 255] ^ Tinv3[C2 >> 24] ^ KW[r * 4 + 1];
- r2 = Tinv0[C2 & 255] ^ Tinv1[(C1 >> 8) & 255] ^ Tinv2[(C0 >> 16) & 255] ^ Tinv3[C3 >> 24] ^ KW[r * 4 + 2];
- r3 = Tinv0[C3 & 255] ^ Tinv1[(C2 >> 8) & 255] ^ Tinv2[(C1 >> 16) & 255] ^ Tinv3[C0 >> 24] ^ KW[r-- * 4 + 3];
- C0 = Tinv0[r0 & 255] ^ Tinv1[(r3 >> 8) & 255] ^ Tinv2[(r2 >> 16) & 255] ^ Tinv3[r1 >> 24] ^ KW[r * 4 + 0];
- C1 = Tinv0[r1 & 255] ^ Tinv1[(r0 >> 8) & 255] ^ Tinv2[(r3 >> 16) & 255] ^ Tinv3[r2 >> 24] ^ KW[r * 4 + 1];
- C2 = Tinv0[r2 & 255] ^ Tinv1[(r1 >> 8) & 255] ^ Tinv2[(r0 >> 16) & 255] ^ Tinv3[r3 >> 24] ^ KW[r * 4 + 2];
- C3 = Tinv0[r3 & 255] ^ Tinv1[(r2 >> 8) & 255] ^ Tinv2[(r1 >> 16) & 255] ^ Tinv3[r0 >> 24] ^ KW[r-- * 4 + 3];
- }
-
- r0 = Tinv0[C0 & 255] ^ Tinv1[(C3 >> 8) & 255] ^ Tinv2[(C2 >> 16) & 255] ^ Tinv3[C1 >> 24] ^ KW[r * 4 + 0];
- r1 = Tinv0[C1 & 255] ^ Tinv1[(C0 >> 8) & 255] ^ Tinv2[(C3 >> 16) & 255] ^ Tinv3[C2 >> 24] ^ KW[r * 4 + 1];
- r2 = Tinv0[C2 & 255] ^ Tinv1[(C1 >> 8) & 255] ^ Tinv2[(C0 >> 16) & 255] ^ Tinv3[C3 >> 24] ^ KW[r * 4 + 2];
- r3 = Tinv0[C3 & 255] ^ Tinv1[(C2 >> 8) & 255] ^ Tinv2[(C1 >> 16) & 255] ^ Tinv3[C0 >> 24] ^ KW[r * 4 + 3];
-
- // the final round's table is a simple function of Si so we don't use a whole other four tables for it
-
- C0 = (uint)Si[r0 & 255] ^ (((uint)Si[(r3 >> 8) & 255]) << 8) ^ (((uint)Si[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[r1 >> 24]) << 24) ^ KW[0 * 4 + 0];
- C1 = (uint)Si[r1 & 255] ^ (((uint)Si[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)Si[r2 >> 24]) << 24) ^ KW[0 * 4 + 1];
- C2 = (uint)Si[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)Si[r3 >> 24]) << 24) ^ KW[0 * 4 + 2];
- C3 = (uint)Si[r3 & 255] ^ (((uint)Si[(r2 >> 8) & 255]) << 8) ^ (((uint)Si[(r1 >> 16) & 255]) << 16) ^ (((uint)Si[r0 >> 24]) << 24) ^ KW[0 * 4 + 3];
+ // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
}
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipherMode.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipherMode.cs
new file mode 100644
index 000000000..51ebfdd14
--- /dev/null
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipherMode.cs
@@ -0,0 +1,26 @@
+namespace Renci.SshNet.Security.Cryptography.Ciphers
+{
+ ///
+ /// Custom AES Cipher Mode, follows System.Security.Cryptography.CipherMode.
+ ///
+ public enum AesCipherMode
+ {
+ /// CBC Mode.
+ CBC = 1,
+
+ /// ECB Mode.
+ ECB = 2,
+
+ /// OFB Mode.
+ OFB = 3,
+
+ /// CFB Mode.
+ CFB = 4,
+
+ /// CTS Mode.
+ CTS = 5,
+
+ /// CTR Mode.
+ CTR = 6
+ }
+}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/Arc4Cipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/Arc4Cipher.cs
index 0707ce2e2..41387ee02 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/Arc4Cipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/Arc4Cipher.cs
@@ -3,14 +3,16 @@
namespace Renci.SshNet.Security.Cryptography.Ciphers
{
///
- /// Implements ARCH4 cipher algorithm
+ /// Implements ARCH4 cipher algorithm.
///
public sealed class Arc4Cipher : StreamCipher
{
- private static readonly int STATE_LENGTH = 256;
+#pragma warning disable SA1310 // Field names should not contain underscore
+ private const int STATE_LENGTH = 256;
+#pragma warning restore SA1310 // Field names should not contain underscore
///
- /// Holds the state of the RC4 engine
+ /// Holds the state of the RC4 engine.
///
private byte[] _engineState;
@@ -18,8 +20,6 @@ public sealed class Arc4Cipher : StreamCipher
private int _y;
- private byte[] _workingKey;
-
///
/// Gets the minimum data size.
///
@@ -35,19 +35,19 @@ public override byte MinimumSize
/// Initializes a new instance of the class.
///
/// The key.
- /// if set to true will disharged first 1536 bytes.
- /// is null.
+ /// if set to will disharged first 1536 bytes.
+ /// is .
public Arc4Cipher(byte[] key, bool dischargeFirstBytes)
: base(key)
{
- _workingKey = key;
- SetKey(_workingKey);
- // The first 1536 bytes of keystream
- // generated by the cipher MUST be discarded, and the first byte of the
- // first encrypted packet MUST be encrypted using the 1537th byte of
- // keystream.
+ SetKey(key);
+
+ // The first 1536 bytes of keystream generated by the cipher MUST be discarded, and the first byte of the
+ // first encrypted packet MUST be encrypted using the 1537th byte of keystream.
if (dischargeFirstBytes)
- Encrypt(new byte[1536]);
+ {
+ _ = Encrypt(new byte[1536]);
+ }
}
///
@@ -94,7 +94,7 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC
public override byte[] Encrypt(byte[] input, int offset, int length)
{
var output = new byte[length];
- ProcessBytes(input, offset, length, output, 0);
+ _ = ProcessBytes(input, offset, length, output, 0);
return output;
}
@@ -121,21 +121,19 @@ public override byte[] Decrypt(byte[] input)
///
public override byte[] Decrypt(byte[] input, int offset, int length)
{
- var output = new byte[length];
- ProcessBytes(input, offset, length, output, 0);
- return output;
+ return Encrypt(input, offset, length);
}
private int ProcessBytes(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if ((inputOffset + inputCount) > inputBuffer.Length)
{
- throw new IndexOutOfRangeException("input buffer too short");
+ throw new ArgumentException("input buffer too short");
}
if ((outputOffset + inputCount) > outputBuffer.Length)
{
- throw new IndexOutOfRangeException("output buffer too short");
+ throw new ArgumentException("output buffer too short");
}
for (var i = 0; i < inputCount; i++)
@@ -151,20 +149,16 @@ private int ProcessBytes(byte[] inputBuffer, int inputOffset, int inputCount, by
// xor
outputBuffer[i + outputOffset] = (byte)(inputBuffer[i + inputOffset] ^ _engineState[(_engineState[_x] + _engineState[_y]) & 0xff]);
}
+
return inputCount;
}
private void SetKey(byte[] keyBytes)
{
- _workingKey = keyBytes;
-
_x = 0;
_y = 0;
- if (_engineState == null)
- {
- _engineState = new byte[STATE_LENGTH];
- }
+ _engineState ??= new byte[STATE_LENGTH];
// reset the state of the engine
for (var i = 0; i < STATE_LENGTH; i++)
@@ -178,6 +172,7 @@ private void SetKey(byte[] keyBytes)
for (var i = 0; i < STATE_LENGTH; i++)
{
i2 = ((keyBytes[i1] & 0xff) + _engineState[i] + i2) & 0xff;
+
// do the byte-swap inline
var tmp = _engineState[i];
_engineState[i] = _engineState[i2];
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/BlowfishCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/BlowfishCipher.cs
index d68d39886..6e04c999c 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/BlowfishCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/BlowfishCipher.cs
@@ -8,6 +8,12 @@ namespace Renci.SshNet.Security.Cryptography.Ciphers
///
public sealed class BlowfishCipher : BlockCipher
{
+ private const int Rounds = 16;
+
+ private const int SboxSk = 256;
+
+ private const int PSize = Rounds + 2;
+
#region Static reference tables
private static readonly uint[] KP =
@@ -293,19 +299,16 @@ public sealed class BlowfishCipher : BlockCipher
#endregion
- private const int Rounds = 16;
-
- private const int SboxSk = 256;
-
- private const int PSize = Rounds + 2;
-
///
- /// The s-boxes
+ /// The s-boxes.
///
- private readonly uint[] _s0, _s1, _s2, _s3;
+ private readonly uint[] _s0;
+ private readonly uint[] _s1;
+ private readonly uint[] _s2;
+ private readonly uint[] _s3;
///
- /// The p-array
+ /// The p-array.
///
private readonly uint[] _p;
@@ -315,15 +318,17 @@ public sealed class BlowfishCipher : BlockCipher
/// The key.
/// The mode.
/// The padding.
- /// is null.
+ /// is .
/// Keysize is not valid for this algorithm.
public BlowfishCipher(byte[] key, CipherMode mode, CipherPadding padding)
: base(key, 8, mode, padding)
{
var keySize = key.Length * 8;
- if (keySize < 1 || keySize > 448)
+ if (keySize is < 1 or > 448)
+ {
throw new ArgumentException(string.Format("KeySize '{0}' is not valid for this algorithm.", keySize));
+ }
_s0 = new uint[SboxSk];
_s1 = new uint[SboxSk];
@@ -348,14 +353,16 @@ public BlowfishCipher(byte[] key, CipherMode mode, CipherPadding padding)
public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (inputCount != BlockSize)
+ {
throw new ArgumentException("inputCount");
+ }
- uint xl = Pack.BigEndianToUInt32(inputBuffer, inputOffset);
- uint xr = Pack.BigEndianToUInt32(inputBuffer, inputOffset + 4);
+ var xl = Pack.BigEndianToUInt32(inputBuffer, inputOffset);
+ var xr = Pack.BigEndianToUInt32(inputBuffer, inputOffset + 4);
xl ^= _p[0];
- for (int i = 1; i < Rounds; i += 2)
+ for (var i = 1; i < Rounds; i += 2)
{
xr ^= F(xl) ^ _p[i];
xl ^= F(xr) ^ _p[i + 1];
@@ -383,7 +390,9 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC
public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (inputCount != BlockSize)
+ {
throw new ArgumentException("inputCount");
+ }
var xl = Pack.BigEndianToUInt32(inputBuffer, inputOffset);
var xr = Pack.BigEndianToUInt32(inputBuffer, inputOffset + 4);
@@ -406,7 +415,7 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC
private uint F(uint x)
{
- return (((_s0[x >> 24] + _s1[(x >> 16) & 0xff]) ^ _s2[(x >> 8) & 0xff]) + _s3[x & 0xff]);
+ return ((_s0[x >> 24] + _s1[(x >> 16) & 0xff]) ^ _s2[(x >> 8) & 0xff]) + _s3[x & 0xff];
}
private void SetKey(byte[] key)
@@ -451,6 +460,7 @@ private void SetKey(byte[] key)
keyIndex = 0;
}
}
+
// XOR the newly created 32 bit chunk onto the P-array
_p[i] ^= data;
}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/CastCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/CastCipher.cs
index e7577f39f..d23887856 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/CastCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/CastCipher.cs
@@ -4,21 +4,21 @@
namespace Renci.SshNet.Security.Cryptography.Ciphers
{
///
- /// Implements CAST cipher algorithm
+ /// Implements CAST cipher algorithm.
///
public sealed class CastCipher : BlockCipher
{
- private static readonly int MaxRounds = 16;
+ private const int MaxRounds = 16;
- private static readonly int RedRounds = 12;
+ private const int RedRounds = 12;
///
- /// The rotating round key
+ /// The rotating round key.
///
private readonly int[] _kr = new int[17];
///
- /// The masking round key
+ /// The masking round key.
///
private readonly uint[] _km = new uint[17];
@@ -30,7 +30,7 @@ public sealed class CastCipher : BlockCipher
/// The key.
/// The mode.
/// The padding.
- /// is null.
+ /// is .
/// Keysize is not valid for this algorithm.
public CastCipher(byte[] key, CipherMode mode, CipherPadding padding)
: base(key, 8, mode, padding)
@@ -38,7 +38,9 @@ public CastCipher(byte[] key, CipherMode mode, CipherPadding padding)
var keySize = key.Length * 8;
if (!(keySize >= 40 && keySize <= 128 && keySize % 8 == 0))
+ {
throw new ArgumentException(string.Format("KeySize '{0}' is not valid for this algorithm.", keySize));
+ }
SetKey(key);
}
@@ -56,9 +58,11 @@ public CastCipher(byte[] key, CipherMode mode, CipherPadding padding)
///
public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
- // process the input block
- // batch the units up into a 32 bit chunk and go for it
- // the array is in bytes, the increment is 8x8 bits = 64
+ /*
+ * process the input block
+ * batch the units up into a 32 bit chunk and go for it
+ * the array is in bytes, the increment is 8x8 bits = 64
+ */
var l0 = Pack.BigEndianToUInt32(inputBuffer, inputOffset);
var r0 = Pack.BigEndianToUInt32(inputBuffer, inputOffset + 4);
@@ -573,7 +577,6 @@ private void SetKey(byte[] key)
/// The input to be processed.
/// The mask to be used from Km[n].
/// The rotation value to be used.
- ///
private static uint F1(uint d, uint kmi, int kri)
{
var I = kmi + d;
@@ -587,7 +590,6 @@ private static uint F1(uint d, uint kmi, int kri)
/// The input to be processed.
/// The mask to be used from Km[n].
/// The rotation value to be used.
- ///
private static uint F2(uint d, uint kmi, int kri)
{
var I = kmi ^ d;
@@ -601,7 +603,6 @@ private static uint F2(uint d, uint kmi, int kri)
/// The input to be processed.
/// The mask to be used from Km[n].
/// The rotation value to be used.
- ///
private static uint F3(uint d, uint kmi, int kri)
{
var I = kmi - d;
@@ -625,6 +626,7 @@ private void CastEncipher(uint l0, uint r0, uint[] result)
var rp = ri; // equivalent to R[i-1]
li = rp;
+
switch (i)
{
case 1:
@@ -649,6 +651,9 @@ private void CastEncipher(uint l0, uint r0, uint[] result)
case 15:
ri = lp ^ F3(rp, _km[i], _kr[i]);
break;
+ default:
+ // We should never get here as max. rounds is 16
+ break;
}
}
@@ -666,6 +671,7 @@ private void CastDecipher(uint l16, uint r16, uint[] result)
var rp = ri; // equivalent to R[i-1]
li = rp;
+
switch (i)
{
case 1:
@@ -690,6 +696,9 @@ private void CastDecipher(uint l16, uint r16, uint[] result)
case 15:
ri = lp ^ F3(rp, _km[i], _kr[i]);
break;
+ default:
+ // We should never get here as max. rounds is 16
+ break;
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/CipherMode.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/CipherMode.cs
index 7352a12f0..490756aff 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/CipherMode.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/CipherMode.cs
@@ -3,10 +3,12 @@
namespace Renci.SshNet.Security.Cryptography.Ciphers
{
///
- /// Base class for cipher mode implementations
+ /// Base class for cipher mode implementations.
///
public abstract class CipherMode
{
+#pragma warning disable SA1401 // Fields should be private
+#pragma warning disable SA1306 // Field names should begin with lower-case letter
///
/// Gets the cipher.
///
@@ -21,6 +23,8 @@ public abstract class CipherMode
/// Holds block size of the cipher.
///
protected int _blockSize;
+#pragma warning restore SA1306 // Field names should begin with lower-case letter
+#pragma warning restore SA1401 // Fields should be private
///
/// Initializes a new instance of the class.
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/CipherPadding.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/CipherPadding.cs
index 5013865cb..914babc11 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/CipherPadding.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/CipherPadding.cs
@@ -1,7 +1,7 @@
namespace Renci.SshNet.Security.Cryptography.Ciphers
{
///
- /// Base class for cipher padding implementations
+ /// Base class for cipher padding implementations.
///
public abstract class CipherPadding
{
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/DesCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/DesCipher.cs
index 1f6a2aa95..f2d2e4035 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/DesCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/DesCipher.cs
@@ -12,9 +12,7 @@ public class DesCipher : BlockCipher
private int[] _decryptionKey;
- #region Static tables
-
- private static readonly short[] Bytebit = {128, 64, 32, 16, 8, 4, 2, 1};
+ private static readonly short[] Bytebit = { 128, 64, 32, 16, 8, 4, 2, 1 };
private static readonly int[] Bigbyte =
{
@@ -212,15 +210,13 @@ public class DesCipher : BlockCipher
0x00001040, 0x00040040, 0x10000000, 0x10041000
};
- #endregion
-
///
/// Initializes a new instance of the class.
///
/// The key.
/// The mode.
/// The padding.
- /// is null.
+ /// is .
public DesCipher(byte[] key, CipherMode mode, CipherPadding padding)
: base(key, 8, mode, padding)
{
@@ -240,16 +236,17 @@ public DesCipher(byte[] key, CipherMode mode, CipherPadding padding)
public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if ((inputOffset + BlockSize) > inputBuffer.Length)
- throw new IndexOutOfRangeException("input buffer too short");
+ {
+ throw new ArgumentException("input buffer too short");
+ }
if ((outputOffset + BlockSize) > outputBuffer.Length)
- throw new IndexOutOfRangeException("output buffer too short");
-
- if (_encryptionKey == null)
{
- _encryptionKey = GenerateWorkingKey(true, Key);
+ throw new ArgumentException("output buffer too short");
}
+ _encryptionKey ??= GenerateWorkingKey(encrypting: true, Key);
+
DesFunc(_encryptionKey, inputBuffer, inputOffset, outputBuffer, outputOffset);
return BlockSize;
@@ -269,16 +266,17 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC
public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if ((inputOffset + BlockSize) > inputBuffer.Length)
- throw new IndexOutOfRangeException("input buffer too short");
+ {
+ throw new ArgumentException("input buffer too short");
+ }
if ((outputOffset + BlockSize) > outputBuffer.Length)
- throw new IndexOutOfRangeException("output buffer too short");
-
- if (_decryptionKey == null)
{
- _decryptionKey = GenerateWorkingKey(false, Key);
+ throw new ArgumentException("output buffer too short");
}
+ _decryptionKey ??= GenerateWorkingKey(encrypting: false, Key);
+
DesFunc(_decryptionKey, inputBuffer, inputOffset, outputBuffer, outputOffset);
return BlockSize;
@@ -287,25 +285,25 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC
///
/// Generates the working key.
///
- /// if set to true [encrypting].
+ /// if set to [encrypting].
/// The key.
/// Generated working key.
protected int[] GenerateWorkingKey(bool encrypting, byte[] key)
{
ValidateKey();
- int[] newKey = new int[32];
- bool[] pc1m = new bool[56];
- bool[] pcr = new bool[56];
+ var newKey = new int[32];
+ var pc1m = new bool[56];
+ var pcr = new bool[56];
- for (int j = 0; j < 56; j++)
+ for (var j = 0; j < 56; j++)
{
int l = Pc1[j];
- pc1m[j] = ((key[(uint)l >> 3] & Bytebit[l & 07]) != 0);
+ pc1m[j] = (key[(uint) l >> 3] & Bytebit[l & 07]) != 0;
}
- for (int i = 0; i < 16; i++)
+ for (var i = 0; i < 16; i++)
{
int l, m;
@@ -321,7 +319,7 @@ protected int[] GenerateWorkingKey(bool encrypting, byte[] key)
var n = m + 1;
newKey[m] = newKey[n] = 0;
- for (int j = 0; j < 28; j++)
+ for (var j = 0; j < 28; j++)
{
l = j + Totrot[i];
if (l < 28)
@@ -334,7 +332,7 @@ protected int[] GenerateWorkingKey(bool encrypting, byte[] key)
}
}
- for (int j = 28; j < 56; j++)
+ for (var j = 28; j < 56; j++)
{
l = j + Totrot[i];
if (l < 56)
@@ -347,7 +345,7 @@ protected int[] GenerateWorkingKey(bool encrypting, byte[] key)
}
}
- for (int j = 0; j < 24; j++)
+ for (var j = 0; j < 24; j++)
{
if (pcr[Pc2[j]])
{
@@ -361,10 +359,11 @@ protected int[] GenerateWorkingKey(bool encrypting, byte[] key)
}
}
- //
- // store the processed key
- //
- for (int i = 0; i != 32; i += 2)
+ /*
+ * store the processed key
+ */
+
+ for (var i = 0; i != 32; i += 2)
{
var i1 = newKey[i];
var i2 = newKey[i + 1];
@@ -391,7 +390,9 @@ protected virtual void ValidateKey()
var keySize = Key.Length * 8;
if (keySize != 64)
+ {
throw new ArgumentException(string.Format("KeySize '{0}' is not valid for this algorithm.", keySize));
+ }
}
///
@@ -409,16 +410,16 @@ protected static void DesFunc(int[] wKey, byte[] input, int inOff, byte[] outByt
var work = ((left >> 4) ^ right) & 0x0f0f0f0f;
right ^= work;
- left ^= (work << 4);
+ left ^= work << 4;
work = ((left >> 16) ^ right) & 0x0000ffff;
right ^= work;
- left ^= (work << 16);
+ left ^= work << 16;
work = ((right >> 2) ^ left) & 0x33333333;
left ^= work;
- right ^= (work << 2);
+ right ^= work << 2;
work = ((right >> 8) ^ left) & 0x00ff00ff;
left ^= work;
- right ^= (work << 8);
+ right ^= work << 8;
right = (right << 1) | (right >> 31);
work = (left ^ right) & 0xaaaaaaaa;
left ^= work;
@@ -428,24 +429,24 @@ protected static void DesFunc(int[] wKey, byte[] input, int inOff, byte[] outByt
for (var round = 0; round < 8; round++)
{
work = (right << 28) | (right >> 4);
- work ^= (uint)wKey[round * 4 + 0];
+ work ^= (uint)wKey[(round * 4) + 0];
var fval = Sp7[work & 0x3f];
fval |= Sp5[(work >> 8) & 0x3f];
fval |= Sp3[(work >> 16) & 0x3f];
fval |= Sp1[(work >> 24) & 0x3f];
- work = right ^ (uint) wKey[round * 4 + 1];
+ work = right ^ (uint) wKey[(round * 4) + 1];
fval |= Sp8[work & 0x3f];
fval |= Sp6[(work >> 8) & 0x3f];
fval |= Sp4[(work >> 16) & 0x3f];
fval |= Sp2[(work >> 24) & 0x3f];
left ^= fval;
work = (left << 28) | (left >> 4);
- work ^= (uint)wKey[round * 4 + 2];
+ work ^= (uint)wKey[(round * 4) + 2];
fval = Sp7[work & 0x3f];
fval |= Sp5[(work >> 8) & 0x3f];
fval |= Sp3[(work >> 16) & 0x3f];
fval |= Sp1[(work >> 24) & 0x3f];
- work = left ^ (uint)wKey[round * 4 + 3];
+ work = left ^ (uint)wKey[(round * 4) + 3];
fval |= Sp8[work & 0x3f];
fval |= Sp6[(work >> 8) & 0x3f];
fval |= Sp4[(work >> 16) & 0x3f];
@@ -460,16 +461,16 @@ protected static void DesFunc(int[] wKey, byte[] input, int inOff, byte[] outByt
left = (left << 31) | (left >> 1);
work = ((left >> 8) ^ right) & 0x00ff00ff;
right ^= work;
- left ^= (work << 8);
+ left ^= work << 8;
work = ((left >> 2) ^ right) & 0x33333333;
right ^= work;
- left ^= (work << 2);
+ left ^= work << 2;
work = ((right >> 16) ^ left) & 0x0000ffff;
left ^= work;
- right ^= (work << 16);
+ right ^= work << 16;
work = ((right >> 4) ^ left) & 0x0f0f0f0f;
left ^= work;
- right ^= (work << 4);
+ right ^= work << 4;
Pack.UInt32ToBigEndian(right, outBytes, outOff);
Pack.UInt32ToBigEndian(left, outBytes, outOff + 4);
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CbcCipherMode.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CbcCipherMode.cs
index c6ac2f0ab..a2b9243d4 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CbcCipherMode.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CbcCipherMode.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Security.Cryptography.Ciphers.Modes
{
///
- /// Implements CBC cipher mode
+ /// Implements CBC cipher mode.
///
public class CbcCipherMode : CipherMode
{
@@ -31,20 +31,26 @@ public CbcCipherMode(byte[] iv)
public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (inputBuffer.Length - inputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid input buffer");
+ }
if (outputBuffer.Length - outputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid output buffer");
+ }
if (inputCount != _blockSize)
+ {
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "inputCount must be {0}.", _blockSize));
+ }
- for (int i = 0; i < _blockSize; i++)
+ for (var i = 0; i < _blockSize; i++)
{
IV[i] ^= inputBuffer[inputOffset + i];
}
- Cipher.EncryptBlock(IV, 0, inputCount, outputBuffer, outputOffset);
+ _ = Cipher.EncryptBlock(IV, 0, inputCount, outputBuffer, outputOffset);
Buffer.BlockCopy(outputBuffer, outputOffset, IV, 0, IV.Length);
@@ -65,17 +71,23 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC
public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (inputBuffer.Length - inputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid input buffer");
+ }
if (outputBuffer.Length - outputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid output buffer");
+ }
if (inputCount != _blockSize)
+ {
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "inputCount must be {0}.", _blockSize));
+ }
- Cipher.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
+ _ = Cipher.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
- for (int i = 0; i < _blockSize; i++)
+ for (var i = 0; i < _blockSize; i++)
{
outputBuffer[outputOffset + i] ^= IV[i];
}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CfbCipherMode.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CfbCipherMode.cs
index 3171e2bbc..23a4bb2f7 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CfbCipherMode.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CfbCipherMode.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Security.Cryptography.Ciphers.Modes
{
///
- /// Implements CFB cipher mode
+ /// Implements CFB cipher mode.
///
public class CfbCipherMode : CipherMode
{
@@ -34,17 +34,23 @@ public CfbCipherMode(byte[] iv)
public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (inputBuffer.Length - inputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid input buffer");
+ }
if (outputBuffer.Length - outputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid output buffer");
+ }
if (inputCount != _blockSize)
+ {
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "inputCount must be {0}.", _blockSize));
+ }
- Cipher.EncryptBlock(IV, 0, IV.Length, _ivOutput, 0);
+ _ = Cipher.EncryptBlock(IV, 0, IV.Length, _ivOutput, 0);
- for (int i = 0; i < _blockSize; i++)
+ for (var i = 0; i < _blockSize; i++)
{
outputBuffer[outputOffset + i] = (byte)(_ivOutput[i] ^ inputBuffer[inputOffset + i]);
}
@@ -69,20 +75,26 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC
public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (inputBuffer.Length - inputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid input buffer");
+ }
if (outputBuffer.Length - outputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid output buffer");
+ }
if (inputCount != _blockSize)
+ {
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "inputCount must be {0}.", _blockSize));
+ }
- Cipher.EncryptBlock(IV, 0, IV.Length, _ivOutput, 0);
+ _ = Cipher.EncryptBlock(IV, 0, IV.Length, _ivOutput, 0);
Buffer.BlockCopy(IV, _blockSize, IV, 0, IV.Length - _blockSize);
Buffer.BlockCopy(inputBuffer, inputOffset, IV, IV.Length - _blockSize, _blockSize);
- for (int i = 0; i < _blockSize; i++)
+ for (var i = 0; i < _blockSize; i++)
{
outputBuffer[outputOffset + i] = (byte)(_ivOutput[i] ^ inputBuffer[inputOffset + i]);
}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CtrCipherMode.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CtrCipherMode.cs
index cbe5d7e60..a0ae5010b 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CtrCipherMode.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CtrCipherMode.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Security.Cryptography.Ciphers.Modes
{
///
- /// Implements CTR cipher mode
+ /// Implements CTR cipher mode.
///
public class CtrCipherMode : CipherMode
{
@@ -34,23 +34,32 @@ public CtrCipherMode(byte[] iv)
public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (inputBuffer.Length - inputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid input buffer");
+ }
if (outputBuffer.Length - outputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid output buffer");
+ }
if (inputCount != _blockSize)
+ {
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "inputCount must be {0}.", _blockSize));
+ }
- Cipher.EncryptBlock(IV, 0, IV.Length, _ivOutput, 0);
+ _ = Cipher.EncryptBlock(IV, 0, IV.Length, _ivOutput, 0);
- for (int i = 0; i < _blockSize; i++)
+ for (var i = 0; i < _blockSize; i++)
{
outputBuffer[outputOffset + i] = (byte)(_ivOutput[i] ^ inputBuffer[inputOffset + i]);
}
- int j = IV.Length;
- while (--j >= 0 && ++IV[j] == 0) ;
+ var j = IV.Length;
+ while (--j >= 0 && ++IV[j] == 0)
+ {
+ // Intentionally empty block
+ }
return _blockSize;
}
@@ -68,26 +77,7 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC
///
public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
- if (inputBuffer.Length - inputOffset < _blockSize)
- throw new ArgumentException("Invalid input buffer");
-
- if (outputBuffer.Length - outputOffset < _blockSize)
- throw new ArgumentException("Invalid output buffer");
-
- if (inputCount != _blockSize)
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "inputCount must be {0}.", _blockSize));
-
- Cipher.EncryptBlock(IV, 0, IV.Length, _ivOutput, 0);
-
- for (int i = 0; i < _blockSize; i++)
- {
- outputBuffer[outputOffset + i] = (byte)(_ivOutput[i] ^ inputBuffer[inputOffset + i]);
- }
-
- int j = IV.Length;
- while (--j >= 0 && ++IV[j] == 0) ;
-
- return _blockSize;
+ return EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
}
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/OfbCipherMode.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/OfbCipherMode.cs
index a13cfb0a1..70b6473d3 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/OfbCipherMode.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/OfbCipherMode.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Security.Cryptography.Ciphers.Modes
{
///
- /// Implements OFB cipher mode
+ /// Implements OFB cipher mode.
///
public class OfbCipherMode : CipherMode
{
@@ -34,24 +34,29 @@ public OfbCipherMode(byte[] iv)
public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (inputBuffer.Length - inputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid input buffer");
+ }
if (outputBuffer.Length - outputOffset < _blockSize)
+ {
throw new ArgumentException("Invalid output buffer");
+ }
if (inputCount != _blockSize)
+ {
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "inputCount must be {0}.", _blockSize));
+ }
- Cipher.EncryptBlock(IV, 0, IV.Length, _ivOutput, 0);
+ _ = Cipher.EncryptBlock(IV, 0, IV.Length, _ivOutput, 0);
- for (int i = 0; i < _blockSize; i++)
+ Buffer.BlockCopy(_ivOutput, 0, IV, 0, IV.Length);
+
+ for (var i = 0; i < _blockSize; i++)
{
- outputBuffer[outputOffset + i] = (byte)(_ivOutput[i] ^ inputBuffer[inputOffset + i]);
+ outputBuffer[outputOffset + i] = (byte) (_ivOutput[i] ^ inputBuffer[inputOffset + i]);
}
- Buffer.BlockCopy(IV, _blockSize, IV, 0, IV.Length - _blockSize);
- Buffer.BlockCopy(outputBuffer, outputOffset, IV, IV.Length - _blockSize, _blockSize);
-
return _blockSize;
}
@@ -68,26 +73,7 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC
///
public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
- if (inputBuffer.Length - inputOffset < _blockSize)
- throw new ArgumentException("Invalid input buffer");
-
- if (outputBuffer.Length - outputOffset < _blockSize)
- throw new ArgumentException("Invalid output buffer");
-
- if (inputCount != _blockSize)
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "inputCount must be {0}.", _blockSize));
-
- Cipher.EncryptBlock(IV, 0, IV.Length, _ivOutput, 0);
-
- for (int i = 0; i < _blockSize; i++)
- {
- outputBuffer[outputOffset + i] = (byte)(_ivOutput[i] ^ inputBuffer[inputOffset + i]);
- }
-
- Buffer.BlockCopy(IV, _blockSize, IV, 0, IV.Length - _blockSize);
- Buffer.BlockCopy(outputBuffer, outputOffset, IV, IV.Length - _blockSize, _blockSize);
-
- return _blockSize;
+ return EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
}
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/Paddings/PKCS5Padding.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/Paddings/PKCS5Padding.cs
index 70d94c20f..18e85c597 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/Paddings/PKCS5Padding.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/Paddings/PKCS5Padding.cs
@@ -3,7 +3,7 @@
namespace Renci.SshNet.Security.Cryptography.Ciphers.Paddings
{
///
- /// Implements PKCS5 cipher padding
+ /// Implements PKCS5 cipher padding.
///
public class PKCS5Padding : CipherPadding
{
@@ -37,10 +37,12 @@ public override byte[] Pad(byte[] input, int offset, int length, int paddingleng
{
var output = new byte[length + paddinglength];
Buffer.BlockCopy(input, offset, output, 0, length);
+
for (var i = 0; i < paddinglength; i++)
{
output[length + i] = (byte) paddinglength;
}
+
return output;
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/Paddings/PKCS7Padding.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/Paddings/PKCS7Padding.cs
index 2623d8fd0..eb950abf4 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/Paddings/PKCS7Padding.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/Paddings/PKCS7Padding.cs
@@ -3,7 +3,7 @@
namespace Renci.SshNet.Security.Cryptography.Ciphers.Paddings
{
///
- /// Implements PKCS7 cipher padding
+ /// Implements PKCS7 cipher padding.
///
public class PKCS7Padding : CipherPadding
{
@@ -37,10 +37,12 @@ public override byte[] Pad(byte[] input, int offset, int length, int paddingleng
{
var output = new byte[length + paddinglength];
Buffer.BlockCopy(input, offset, output, 0, length);
+
for (var i = 0; i < paddinglength; i++)
{
output[length + i] = (byte) paddinglength;
}
+
return output;
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/RsaCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/RsaCipher.cs
index 116471bde..8cb58a93e 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/RsaCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/RsaCipher.cs
@@ -8,8 +8,6 @@ namespace Renci.SshNet.Security.Cryptography.Ciphers
///
public class RsaCipher : AsymmetricCipher
{
- private readonly bool _isPrivate;
-
private readonly RsaKey _key;
///
@@ -18,26 +16,27 @@ public class RsaCipher : AsymmetricCipher
/// The RSA key.
public RsaCipher(RsaKey key)
{
- if (key == null)
- throw new ArgumentNullException("key");
+ if (key is null)
+ {
+ throw new ArgumentNullException(nameof(key));
+ }
_key = key;
- _isPrivate = !_key.D.IsZero;
}
///
/// Encrypts the specified data.
///
- /// The data.
- /// The zero-based offset in at which to begin encrypting.
- /// The number of bytes to encrypt from .
+ /// The data.
+ /// The zero-based offset in at which to begin encrypting.
+ /// The number of bytes to encrypt from .
/// Encrypted data.
- public override byte[] Encrypt(byte[] data, int offset, int length)
+ public override byte[] Encrypt(byte[] input, int offset, int length)
{
- // Calculate signature
+ // Calculate signature
var bitLength = _key.Modulus.BitLength;
- var paddedBlock = new byte[bitLength / 8 + (bitLength % 8 > 0 ? 1 : 0) - 1];
+ var paddedBlock = new byte[(bitLength / 8) + (bitLength % 8 > 0 ? 1 : 0) - 1];
paddedBlock[0] = 0x01;
for (var i = 1; i < paddedBlock.Length - length - 1; i++)
@@ -45,7 +44,7 @@ public override byte[] Encrypt(byte[] data, int offset, int length)
paddedBlock[i] = 0xFF;
}
- Buffer.BlockCopy(data, offset, paddedBlock, paddedBlock.Length - length, length);
+ Buffer.BlockCopy(input, offset, paddedBlock, paddedBlock.Length - length, length);
return Transform(paddedBlock);
}
@@ -53,38 +52,44 @@ public override byte[] Encrypt(byte[] data, int offset, int length)
///
/// Decrypts the specified data.
///
- /// The data.
+ /// The data.
///
/// The decrypted data.
///
/// Only block type 01 or 02 are supported.
/// Thrown when decrypted block type is not supported.
- public override byte[] Decrypt(byte[] data)
+ public override byte[] Decrypt(byte[] input)
{
- return Decrypt(data, 0, data.Length);
+ return Decrypt(input, 0, input.Length);
}
///
/// Decrypts the specified input.
///
- /// The input.
- /// The zero-based offset in at which to begin decrypting.
- /// The number of bytes to decrypt from .
+ /// The input.
+ /// The zero-based offset in at which to begin decrypting.
+ /// The number of bytes to decrypt from .
///
/// The decrypted data.
///
/// Only block type 01 or 02 are supported.
/// Thrown when decrypted block type is not supported.
- public override byte[] Decrypt(byte[] data, int offset, int length)
+ public override byte[] Decrypt(byte[] input, int offset, int length)
{
- var paddedBlock = Transform(data, offset, length);
+ var paddedBlock = Transform(input, offset, length);
- if (paddedBlock[0] != 1 && paddedBlock[0] != 2)
+ if (paddedBlock[0] is not 1 and not 2)
+ {
throw new NotSupportedException("Only block type 01 or 02 are supported.");
+ }
var position = 1;
+
while (position < paddedBlock.Length && paddedBlock[position] != 0)
+ {
position++;
+ }
+
position++;
var result = new byte[paddedBlock.Length - position];
@@ -108,35 +113,39 @@ private byte[] Transform(byte[] data, int offset, int length)
BigInteger result;
- if (_isPrivate)
+ var isPrivate = !_key.D.IsZero;
+
+ if (isPrivate)
{
var random = BigInteger.One;
var max = _key.Modulus - 1;
var bitLength = _key.Modulus.BitLength;
if (max < BigInteger.One)
+ {
throw new SshException("Invalid RSA key.");
+ }
while (random <= BigInteger.One || random >= max)
{
random = BigInteger.Random(bitLength);
}
- var blindedInput = BigInteger.PositiveMod((BigInteger.ModPow(random, _key.Exponent, _key.Modulus) * input), _key.Modulus);
+ var blindedInput = BigInteger.PositiveMod(BigInteger.ModPow(random, _key.Exponent, _key.Modulus) * input, _key.Modulus);
// mP = ((input Mod p) ^ dP)) Mod p
- var mP = BigInteger.ModPow((blindedInput % _key.P), _key.DP, _key.P);
+ var mP = BigInteger.ModPow(blindedInput % _key.P, _key.DP, _key.P);
// mQ = ((input Mod q) ^ dQ)) Mod q
- var mQ = BigInteger.ModPow((blindedInput % _key.Q), _key.DQ, _key.Q);
+ var mQ = BigInteger.ModPow(blindedInput % _key.Q, _key.DQ, _key.Q);
- var h = BigInteger.PositiveMod(((mP - mQ) * _key.InverseQ), _key.P);
+ var h = BigInteger.PositiveMod((mP - mQ) * _key.InverseQ, _key.P);
- var m = h * _key.Q + mQ;
+ var m = (h * _key.Q) + mQ;
var rInv = BigInteger.ModInverse(random, _key.Modulus);
- result = BigInteger.PositiveMod((m * rInv), _key.Modulus);
+ result = BigInteger.PositiveMod(m * rInv, _key.Modulus);
}
else
{
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/SerpentCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/SerpentCipher.cs
index 613059467..6f19e176d 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/SerpentCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/SerpentCipher.cs
@@ -11,7 +11,12 @@ public sealed class SerpentCipher : BlockCipher
private const int Phi = unchecked((int)0x9E3779B9); // (Sqrt(5) - 1) * 2**31
private readonly int[] _workingKey;
- private int _x0, _x1, _x2, _x3; // registers
+
+ // registers
+ private int _x0;
+ private int _x1;
+ private int _x2;
+ private int _x3;
///
/// Initializes a new instance of the class.
@@ -19,15 +24,17 @@ public sealed class SerpentCipher : BlockCipher
/// The key.
/// The mode.
/// The padding.
- /// is null.
+ /// is .
/// Keysize is not valid for this algorithm.
public SerpentCipher(byte[] key, CipherMode mode, CipherPadding padding)
: base(key, 16, mode, padding)
{
var keySize = key.Length * 8;
- if (!(keySize == 128 || keySize == 192 || keySize == 256))
+ if (keySize is not (128 or 192 or 256))
+ {
throw new ArgumentException(string.Format("KeySize '{0}' is not valid for this algorithm.", keySize));
+ }
_workingKey = MakeWorkingKey(key);
}
@@ -46,44 +53,77 @@ public SerpentCipher(byte[] key, CipherMode mode, CipherPadding padding)
public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (inputCount != BlockSize)
+ {
throw new ArgumentException("inputCount");
+ }
_x3 = BytesToWord(inputBuffer, inputOffset);
_x2 = BytesToWord(inputBuffer, inputOffset + 4);
_x1 = BytesToWord(inputBuffer, inputOffset + 8);
_x0 = BytesToWord(inputBuffer, inputOffset + 12);
- Sb0(_workingKey[0] ^ _x0, _workingKey[1] ^ _x1, _workingKey[2] ^ _x2, _workingKey[3] ^ _x3); LT();
- Sb1(_workingKey[4] ^ _x0, _workingKey[5] ^ _x1, _workingKey[6] ^ _x2, _workingKey[7] ^ _x3); LT();
- Sb2(_workingKey[8] ^ _x0, _workingKey[9] ^ _x1, _workingKey[10] ^ _x2, _workingKey[11] ^ _x3); LT();
- Sb3(_workingKey[12] ^ _x0, _workingKey[13] ^ _x1, _workingKey[14] ^ _x2, _workingKey[15] ^ _x3); LT();
- Sb4(_workingKey[16] ^ _x0, _workingKey[17] ^ _x1, _workingKey[18] ^ _x2, _workingKey[19] ^ _x3); LT();
- Sb5(_workingKey[20] ^ _x0, _workingKey[21] ^ _x1, _workingKey[22] ^ _x2, _workingKey[23] ^ _x3); LT();
- Sb6(_workingKey[24] ^ _x0, _workingKey[25] ^ _x1, _workingKey[26] ^ _x2, _workingKey[27] ^ _x3); LT();
- Sb7(_workingKey[28] ^ _x0, _workingKey[29] ^ _x1, _workingKey[30] ^ _x2, _workingKey[31] ^ _x3); LT();
- Sb0(_workingKey[32] ^ _x0, _workingKey[33] ^ _x1, _workingKey[34] ^ _x2, _workingKey[35] ^ _x3); LT();
- Sb1(_workingKey[36] ^ _x0, _workingKey[37] ^ _x1, _workingKey[38] ^ _x2, _workingKey[39] ^ _x3); LT();
- Sb2(_workingKey[40] ^ _x0, _workingKey[41] ^ _x1, _workingKey[42] ^ _x2, _workingKey[43] ^ _x3); LT();
- Sb3(_workingKey[44] ^ _x0, _workingKey[45] ^ _x1, _workingKey[46] ^ _x2, _workingKey[47] ^ _x3); LT();
- Sb4(_workingKey[48] ^ _x0, _workingKey[49] ^ _x1, _workingKey[50] ^ _x2, _workingKey[51] ^ _x3); LT();
- Sb5(_workingKey[52] ^ _x0, _workingKey[53] ^ _x1, _workingKey[54] ^ _x2, _workingKey[55] ^ _x3); LT();
- Sb6(_workingKey[56] ^ _x0, _workingKey[57] ^ _x1, _workingKey[58] ^ _x2, _workingKey[59] ^ _x3); LT();
- Sb7(_workingKey[60] ^ _x0, _workingKey[61] ^ _x1, _workingKey[62] ^ _x2, _workingKey[63] ^ _x3); LT();
- Sb0(_workingKey[64] ^ _x0, _workingKey[65] ^ _x1, _workingKey[66] ^ _x2, _workingKey[67] ^ _x3); LT();
- Sb1(_workingKey[68] ^ _x0, _workingKey[69] ^ _x1, _workingKey[70] ^ _x2, _workingKey[71] ^ _x3); LT();
- Sb2(_workingKey[72] ^ _x0, _workingKey[73] ^ _x1, _workingKey[74] ^ _x2, _workingKey[75] ^ _x3); LT();
- Sb3(_workingKey[76] ^ _x0, _workingKey[77] ^ _x1, _workingKey[78] ^ _x2, _workingKey[79] ^ _x3); LT();
- Sb4(_workingKey[80] ^ _x0, _workingKey[81] ^ _x1, _workingKey[82] ^ _x2, _workingKey[83] ^ _x3); LT();
- Sb5(_workingKey[84] ^ _x0, _workingKey[85] ^ _x1, _workingKey[86] ^ _x2, _workingKey[87] ^ _x3); LT();
- Sb6(_workingKey[88] ^ _x0, _workingKey[89] ^ _x1, _workingKey[90] ^ _x2, _workingKey[91] ^ _x3); LT();
- Sb7(_workingKey[92] ^ _x0, _workingKey[93] ^ _x1, _workingKey[94] ^ _x2, _workingKey[95] ^ _x3); LT();
- Sb0(_workingKey[96] ^ _x0, _workingKey[97] ^ _x1, _workingKey[98] ^ _x2, _workingKey[99] ^ _x3); LT();
- Sb1(_workingKey[100] ^ _x0, _workingKey[101] ^ _x1, _workingKey[102] ^ _x2, _workingKey[103] ^ _x3); LT();
- Sb2(_workingKey[104] ^ _x0, _workingKey[105] ^ _x1, _workingKey[106] ^ _x2, _workingKey[107] ^ _x3); LT();
- Sb3(_workingKey[108] ^ _x0, _workingKey[109] ^ _x1, _workingKey[110] ^ _x2, _workingKey[111] ^ _x3); LT();
- Sb4(_workingKey[112] ^ _x0, _workingKey[113] ^ _x1, _workingKey[114] ^ _x2, _workingKey[115] ^ _x3); LT();
- Sb5(_workingKey[116] ^ _x0, _workingKey[117] ^ _x1, _workingKey[118] ^ _x2, _workingKey[119] ^ _x3); LT();
- Sb6(_workingKey[120] ^ _x0, _workingKey[121] ^ _x1, _workingKey[122] ^ _x2, _workingKey[123] ^ _x3); LT();
+ Sb0(_workingKey[0] ^ _x0, _workingKey[1] ^ _x1, _workingKey[2] ^ _x2, _workingKey[3] ^ _x3);
+ LT();
+ Sb1(_workingKey[4] ^ _x0, _workingKey[5] ^ _x1, _workingKey[6] ^ _x2, _workingKey[7] ^ _x3);
+ LT();
+ Sb2(_workingKey[8] ^ _x0, _workingKey[9] ^ _x1, _workingKey[10] ^ _x2, _workingKey[11] ^ _x3);
+ LT();
+ Sb3(_workingKey[12] ^ _x0, _workingKey[13] ^ _x1, _workingKey[14] ^ _x2, _workingKey[15] ^ _x3);
+ LT();
+ Sb4(_workingKey[16] ^ _x0, _workingKey[17] ^ _x1, _workingKey[18] ^ _x2, _workingKey[19] ^ _x3);
+ LT();
+ Sb5(_workingKey[20] ^ _x0, _workingKey[21] ^ _x1, _workingKey[22] ^ _x2, _workingKey[23] ^ _x3);
+ LT();
+ Sb6(_workingKey[24] ^ _x0, _workingKey[25] ^ _x1, _workingKey[26] ^ _x2, _workingKey[27] ^ _x3);
+ LT();
+ Sb7(_workingKey[28] ^ _x0, _workingKey[29] ^ _x1, _workingKey[30] ^ _x2, _workingKey[31] ^ _x3);
+ LT();
+ Sb0(_workingKey[32] ^ _x0, _workingKey[33] ^ _x1, _workingKey[34] ^ _x2, _workingKey[35] ^ _x3);
+ LT();
+ Sb1(_workingKey[36] ^ _x0, _workingKey[37] ^ _x1, _workingKey[38] ^ _x2, _workingKey[39] ^ _x3);
+ LT();
+ Sb2(_workingKey[40] ^ _x0, _workingKey[41] ^ _x1, _workingKey[42] ^ _x2, _workingKey[43] ^ _x3);
+ LT();
+ Sb3(_workingKey[44] ^ _x0, _workingKey[45] ^ _x1, _workingKey[46] ^ _x2, _workingKey[47] ^ _x3);
+ LT();
+ Sb4(_workingKey[48] ^ _x0, _workingKey[49] ^ _x1, _workingKey[50] ^ _x2, _workingKey[51] ^ _x3);
+ LT();
+ Sb5(_workingKey[52] ^ _x0, _workingKey[53] ^ _x1, _workingKey[54] ^ _x2, _workingKey[55] ^ _x3);
+ LT();
+ Sb6(_workingKey[56] ^ _x0, _workingKey[57] ^ _x1, _workingKey[58] ^ _x2, _workingKey[59] ^ _x3);
+ LT();
+ Sb7(_workingKey[60] ^ _x0, _workingKey[61] ^ _x1, _workingKey[62] ^ _x2, _workingKey[63] ^ _x3);
+ LT();
+ Sb0(_workingKey[64] ^ _x0, _workingKey[65] ^ _x1, _workingKey[66] ^ _x2, _workingKey[67] ^ _x3);
+ LT();
+ Sb1(_workingKey[68] ^ _x0, _workingKey[69] ^ _x1, _workingKey[70] ^ _x2, _workingKey[71] ^ _x3);
+ LT();
+ Sb2(_workingKey[72] ^ _x0, _workingKey[73] ^ _x1, _workingKey[74] ^ _x2, _workingKey[75] ^ _x3);
+ LT();
+ Sb3(_workingKey[76] ^ _x0, _workingKey[77] ^ _x1, _workingKey[78] ^ _x2, _workingKey[79] ^ _x3);
+ LT();
+ Sb4(_workingKey[80] ^ _x0, _workingKey[81] ^ _x1, _workingKey[82] ^ _x2, _workingKey[83] ^ _x3);
+ LT();
+ Sb5(_workingKey[84] ^ _x0, _workingKey[85] ^ _x1, _workingKey[86] ^ _x2, _workingKey[87] ^ _x3);
+ LT();
+ Sb6(_workingKey[88] ^ _x0, _workingKey[89] ^ _x1, _workingKey[90] ^ _x2, _workingKey[91] ^ _x3);
+ LT();
+ Sb7(_workingKey[92] ^ _x0, _workingKey[93] ^ _x1, _workingKey[94] ^ _x2, _workingKey[95] ^ _x3);
+ LT();
+ Sb0(_workingKey[96] ^ _x0, _workingKey[97] ^ _x1, _workingKey[98] ^ _x2, _workingKey[99] ^ _x3);
+ LT();
+ Sb1(_workingKey[100] ^ _x0, _workingKey[101] ^ _x1, _workingKey[102] ^ _x2, _workingKey[103] ^ _x3);
+ LT();
+ Sb2(_workingKey[104] ^ _x0, _workingKey[105] ^ _x1, _workingKey[106] ^ _x2, _workingKey[107] ^ _x3);
+ LT();
+ Sb3(_workingKey[108] ^ _x0, _workingKey[109] ^ _x1, _workingKey[110] ^ _x2, _workingKey[111] ^ _x3);
+ LT();
+ Sb4(_workingKey[112] ^ _x0, _workingKey[113] ^ _x1, _workingKey[114] ^ _x2, _workingKey[115] ^ _x3);
+ LT();
+ Sb5(_workingKey[116] ^ _x0, _workingKey[117] ^ _x1, _workingKey[118] ^ _x2, _workingKey[119] ^ _x3);
+ LT();
+ Sb6(_workingKey[120] ^ _x0, _workingKey[121] ^ _x1, _workingKey[122] ^ _x2, _workingKey[123] ^ _x3);
+ LT();
Sb7(_workingKey[124] ^ _x0, _workingKey[125] ^ _x1, _workingKey[126] ^ _x2, _workingKey[127] ^ _x3);
WordToBytes(_workingKey[131] ^ _x3, outputBuffer, outputOffset);
@@ -108,7 +148,9 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC
public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (inputCount != BlockSize)
+ {
throw new ArgumentException("inputCount");
+ }
_x3 = _workingKey[131] ^ BytesToWord(inputBuffer, inputOffset);
_x2 = _workingKey[130] ^ BytesToWord(inputBuffer, inputOffset + 4);
@@ -116,68 +158,253 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC
_x0 = _workingKey[128] ^ BytesToWord(inputBuffer, inputOffset + 12);
Ib7(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[124]; _x1 ^= _workingKey[125]; _x2 ^= _workingKey[126]; _x3 ^= _workingKey[127];
- InverseLT(); Ib6(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[120]; _x1 ^= _workingKey[121]; _x2 ^= _workingKey[122]; _x3 ^= _workingKey[123];
- InverseLT(); Ib5(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[116]; _x1 ^= _workingKey[117]; _x2 ^= _workingKey[118]; _x3 ^= _workingKey[119];
- InverseLT(); Ib4(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[112]; _x1 ^= _workingKey[113]; _x2 ^= _workingKey[114]; _x3 ^= _workingKey[115];
- InverseLT(); Ib3(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[108]; _x1 ^= _workingKey[109]; _x2 ^= _workingKey[110]; _x3 ^= _workingKey[111];
- InverseLT(); Ib2(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[104]; _x1 ^= _workingKey[105]; _x2 ^= _workingKey[106]; _x3 ^= _workingKey[107];
- InverseLT(); Ib1(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[100]; _x1 ^= _workingKey[101]; _x2 ^= _workingKey[102]; _x3 ^= _workingKey[103];
- InverseLT(); Ib0(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[96]; _x1 ^= _workingKey[97]; _x2 ^= _workingKey[98]; _x3 ^= _workingKey[99];
- InverseLT(); Ib7(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[92]; _x1 ^= _workingKey[93]; _x2 ^= _workingKey[94]; _x3 ^= _workingKey[95];
- InverseLT(); Ib6(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[88]; _x1 ^= _workingKey[89]; _x2 ^= _workingKey[90]; _x3 ^= _workingKey[91];
- InverseLT(); Ib5(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[84]; _x1 ^= _workingKey[85]; _x2 ^= _workingKey[86]; _x3 ^= _workingKey[87];
- InverseLT(); Ib4(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[80]; _x1 ^= _workingKey[81]; _x2 ^= _workingKey[82]; _x3 ^= _workingKey[83];
- InverseLT(); Ib3(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[76]; _x1 ^= _workingKey[77]; _x2 ^= _workingKey[78]; _x3 ^= _workingKey[79];
- InverseLT(); Ib2(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[72]; _x1 ^= _workingKey[73]; _x2 ^= _workingKey[74]; _x3 ^= _workingKey[75];
- InverseLT(); Ib1(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[68]; _x1 ^= _workingKey[69]; _x2 ^= _workingKey[70]; _x3 ^= _workingKey[71];
- InverseLT(); Ib0(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[64]; _x1 ^= _workingKey[65]; _x2 ^= _workingKey[66]; _x3 ^= _workingKey[67];
- InverseLT(); Ib7(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[60]; _x1 ^= _workingKey[61]; _x2 ^= _workingKey[62]; _x3 ^= _workingKey[63];
- InverseLT(); Ib6(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[56]; _x1 ^= _workingKey[57]; _x2 ^= _workingKey[58]; _x3 ^= _workingKey[59];
- InverseLT(); Ib5(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[52]; _x1 ^= _workingKey[53]; _x2 ^= _workingKey[54]; _x3 ^= _workingKey[55];
- InverseLT(); Ib4(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[48]; _x1 ^= _workingKey[49]; _x2 ^= _workingKey[50]; _x3 ^= _workingKey[51];
- InverseLT(); Ib3(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[44]; _x1 ^= _workingKey[45]; _x2 ^= _workingKey[46]; _x3 ^= _workingKey[47];
- InverseLT(); Ib2(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[40]; _x1 ^= _workingKey[41]; _x2 ^= _workingKey[42]; _x3 ^= _workingKey[43];
- InverseLT(); Ib1(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[36]; _x1 ^= _workingKey[37]; _x2 ^= _workingKey[38]; _x3 ^= _workingKey[39];
- InverseLT(); Ib0(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[32]; _x1 ^= _workingKey[33]; _x2 ^= _workingKey[34]; _x3 ^= _workingKey[35];
- InverseLT(); Ib7(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[28]; _x1 ^= _workingKey[29]; _x2 ^= _workingKey[30]; _x3 ^= _workingKey[31];
- InverseLT(); Ib6(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[24]; _x1 ^= _workingKey[25]; _x2 ^= _workingKey[26]; _x3 ^= _workingKey[27];
- InverseLT(); Ib5(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[20]; _x1 ^= _workingKey[21]; _x2 ^= _workingKey[22]; _x3 ^= _workingKey[23];
- InverseLT(); Ib4(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[16]; _x1 ^= _workingKey[17]; _x2 ^= _workingKey[18]; _x3 ^= _workingKey[19];
- InverseLT(); Ib3(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[12]; _x1 ^= _workingKey[13]; _x2 ^= _workingKey[14]; _x3 ^= _workingKey[15];
- InverseLT(); Ib2(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[8]; _x1 ^= _workingKey[9]; _x2 ^= _workingKey[10]; _x3 ^= _workingKey[11];
- InverseLT(); Ib1(_x0, _x1, _x2, _x3);
- _x0 ^= _workingKey[4]; _x1 ^= _workingKey[5]; _x2 ^= _workingKey[6]; _x3 ^= _workingKey[7];
- InverseLT(); Ib0(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[124];
+ _x1 ^= _workingKey[125];
+ _x2 ^= _workingKey[126];
+ _x3 ^= _workingKey[127];
+
+ InverseLT();
+ Ib6(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[120];
+ _x1 ^= _workingKey[121];
+ _x2 ^= _workingKey[122];
+ _x3 ^= _workingKey[123];
+
+ InverseLT();
+ Ib5(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[116];
+ _x1 ^= _workingKey[117];
+ _x2 ^= _workingKey[118];
+ _x3 ^= _workingKey[119];
+
+ InverseLT();
+ Ib4(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[112];
+ _x1 ^= _workingKey[113];
+ _x2 ^= _workingKey[114];
+ _x3 ^= _workingKey[115];
+ InverseLT();
+ Ib3(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[108];
+ _x1 ^= _workingKey[109];
+ _x2 ^= _workingKey[110];
+ _x3 ^= _workingKey[111];
+
+ InverseLT();
+ Ib2(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[104];
+ _x1 ^= _workingKey[105];
+ _x2 ^= _workingKey[106];
+ _x3 ^= _workingKey[107];
+
+ InverseLT();
+ Ib1(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[100];
+ _x1 ^= _workingKey[101];
+ _x2 ^= _workingKey[102];
+ _x3 ^= _workingKey[103];
+
+ InverseLT();
+ Ib0(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[96];
+ _x1 ^= _workingKey[97];
+ _x2 ^= _workingKey[98];
+ _x3 ^= _workingKey[99];
+
+ InverseLT();
+ Ib7(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[92];
+ _x1 ^= _workingKey[93];
+ _x2 ^= _workingKey[94];
+ _x3 ^= _workingKey[95];
+
+ InverseLT();
+ Ib6(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[88];
+ _x1 ^= _workingKey[89];
+ _x2 ^= _workingKey[90];
+ _x3 ^= _workingKey[91];
+
+ InverseLT();
+ Ib5(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[84];
+ _x1 ^= _workingKey[85];
+ _x2 ^= _workingKey[86];
+ _x3 ^= _workingKey[87];
+
+ InverseLT();
+ Ib4(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[80];
+ _x1 ^= _workingKey[81];
+ _x2 ^= _workingKey[82];
+ _x3 ^= _workingKey[83];
+
+ InverseLT();
+ Ib3(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[76];
+ _x1 ^= _workingKey[77];
+ _x2 ^= _workingKey[78];
+ _x3 ^= _workingKey[79];
+
+ InverseLT();
+ Ib2(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[72];
+ _x1 ^= _workingKey[73];
+ _x2 ^= _workingKey[74];
+ _x3 ^= _workingKey[75];
+
+ InverseLT();
+ Ib1(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[68];
+ _x1 ^= _workingKey[69];
+ _x2 ^= _workingKey[70];
+ _x3 ^= _workingKey[71];
+
+ InverseLT();
+ Ib0(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[64];
+ _x1 ^= _workingKey[65];
+ _x2 ^= _workingKey[66];
+ _x3 ^= _workingKey[67];
+
+ InverseLT();
+ Ib7(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[60];
+ _x1 ^= _workingKey[61];
+ _x2 ^= _workingKey[62];
+ _x3 ^= _workingKey[63];
+
+ InverseLT();
+ Ib6(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[56];
+ _x1 ^= _workingKey[57];
+ _x2 ^= _workingKey[58];
+ _x3 ^= _workingKey[59];
+
+ InverseLT();
+ Ib5(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[52];
+ _x1 ^= _workingKey[53];
+ _x2 ^= _workingKey[54];
+ _x3 ^= _workingKey[55];
+
+ InverseLT();
+ Ib4(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[48];
+ _x1 ^= _workingKey[49];
+ _x2 ^= _workingKey[50];
+ _x3 ^= _workingKey[51];
+
+ InverseLT();
+ Ib3(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[44];
+ _x1 ^= _workingKey[45];
+ _x2 ^= _workingKey[46];
+ _x3 ^= _workingKey[47];
+
+ InverseLT();
+ Ib2(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[40];
+ _x1 ^= _workingKey[41];
+ _x2 ^= _workingKey[42];
+ _x3 ^= _workingKey[43];
+
+ InverseLT();
+ Ib1(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[36];
+ _x1 ^= _workingKey[37];
+ _x2 ^= _workingKey[38];
+ _x3 ^= _workingKey[39];
+
+ InverseLT();
+ Ib0(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[32];
+ _x1 ^= _workingKey[33];
+ _x2 ^= _workingKey[34];
+ _x3 ^= _workingKey[35];
+
+ InverseLT();
+ Ib7(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[28];
+ _x1 ^= _workingKey[29];
+ _x2 ^= _workingKey[30];
+ _x3 ^= _workingKey[31];
+
+ InverseLT();
+ Ib6(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[24];
+ _x1 ^= _workingKey[25];
+ _x2 ^= _workingKey[26];
+ _x3 ^= _workingKey[27];
+
+ InverseLT();
+ Ib5(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[20];
+ _x1 ^= _workingKey[21];
+ _x2 ^= _workingKey[22];
+ _x3 ^= _workingKey[23];
+
+ InverseLT();
+ Ib4(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[16];
+ _x1 ^= _workingKey[17];
+ _x2 ^= _workingKey[18];
+ _x3 ^= _workingKey[19];
+
+ InverseLT();
+ Ib3(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[12];
+ _x1 ^= _workingKey[13];
+ _x2 ^= _workingKey[14];
+ _x3 ^= _workingKey[15];
+
+ InverseLT();
+ Ib2(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[8];
+ _x1 ^= _workingKey[9];
+ _x2 ^= _workingKey[10];
+ _x3 ^= _workingKey[11];
+
+ InverseLT();
+ Ib1(_x0, _x1, _x2, _x3);
+
+ _x0 ^= _workingKey[4];
+ _x1 ^= _workingKey[5];
+ _x2 ^= _workingKey[6];
+ _x3 ^= _workingKey[7];
+
+ InverseLT();
+ Ib0(_x0, _x1, _x2, _x3);
WordToBytes(_x3 ^ _workingKey[3], outputBuffer, outputOffset);
WordToBytes(_x2 ^ _workingKey[2], outputBuffer, outputOffset + 4);
@@ -187,7 +414,6 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC
return BlockSize;
}
-
///
/// Expand a user-supplied key material into a session key.
///
@@ -198,9 +424,7 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC
/// is not multiple of 4 bytes.
private int[] MakeWorkingKey(byte[] key)
{
- //
// pad key to 256 bits
- //
var kPad = new int[16];
int off;
var length = 0;
@@ -223,15 +447,11 @@ private int[] MakeWorkingKey(byte[] key)
throw new ArgumentException("key must be a multiple of 4 bytes");
}
- //
// expand the padded key up to 33 x 128 bits of key material
- //
const int amount = (Rounds + 1) * 4;
var w = new int[amount];
- //
// compute w0 to w7 from w-8 to w-1
- //
for (var i = 8; i < 16; i++)
{
kPad[i] = RotateLeft(kPad[i - 8] ^ kPad[i - 5] ^ kPad[i - 3] ^ kPad[i - 1] ^ Phi ^ (i - 8), 11);
@@ -239,134 +459,263 @@ private int[] MakeWorkingKey(byte[] key)
Buffer.BlockCopy(kPad, 8, w, 0, 8);
- //
// compute w8 to w136
- //
for (var i = 8; i < amount; i++)
{
w[i] = RotateLeft(w[i - 8] ^ w[i - 5] ^ w[i - 3] ^ w[i - 1] ^ Phi ^ i, 11);
}
- //
// create the working keys by processing w with the Sbox and IP
- //
Sb3(w[0], w[1], w[2], w[3]);
- w[0] = _x0; w[1] = _x1; w[2] = _x2; w[3] = _x3;
+ w[0] = _x0;
+ w[1] = _x1;
+ w[2] = _x2;
+ w[3] = _x3;
+
Sb2(w[4], w[5], w[6], w[7]);
- w[4] = _x0; w[5] = _x1; w[6] = _x2; w[7] = _x3;
+ w[4] = _x0;
+ w[5] = _x1;
+ w[6] = _x2;
+ w[7] = _x3;
+
Sb1(w[8], w[9], w[10], w[11]);
- w[8] = _x0; w[9] = _x1; w[10] = _x2; w[11] = _x3;
+ w[8] = _x0;
+ w[9] = _x1;
+ w[10] = _x2;
+ w[11] = _x3;
+
Sb0(w[12], w[13], w[14], w[15]);
- w[12] = _x0; w[13] = _x1; w[14] = _x2; w[15] = _x3;
+ w[12] = _x0;
+ w[13] = _x1;
+ w[14] = _x2;
+ w[15] = _x3;
+
Sb7(w[16], w[17], w[18], w[19]);
- w[16] = _x0; w[17] = _x1; w[18] = _x2; w[19] = _x3;
+ w[16] = _x0;
+ w[17] = _x1;
+ w[18] = _x2;
+ w[19] = _x3;
+
Sb6(w[20], w[21], w[22], w[23]);
- w[20] = _x0; w[21] = _x1; w[22] = _x2; w[23] = _x3;
+ w[20] = _x0;
+ w[21] = _x1;
+ w[22] = _x2;
+ w[23] = _x3;
+
Sb5(w[24], w[25], w[26], w[27]);
- w[24] = _x0; w[25] = _x1; w[26] = _x2; w[27] = _x3;
+ w[24] = _x0;
+ w[25] = _x1;
+ w[26] = _x2;
+ w[27] = _x3;
+
Sb4(w[28], w[29], w[30], w[31]);
- w[28] = _x0; w[29] = _x1; w[30] = _x2; w[31] = _x3;
+ w[28] = _x0;
+ w[29] = _x1;
+ w[30] = _x2;
+ w[31] = _x3;
+
Sb3(w[32], w[33], w[34], w[35]);
- w[32] = _x0; w[33] = _x1; w[34] = _x2; w[35] = _x3;
+ w[32] = _x0;
+ w[33] = _x1;
+ w[34] = _x2;
+ w[35] = _x3;
+
Sb2(w[36], w[37], w[38], w[39]);
- w[36] = _x0; w[37] = _x1; w[38] = _x2; w[39] = _x3;
+ w[36] = _x0;
+ w[37] = _x1;
+ w[38] = _x2;
+ w[39] = _x3;
+
Sb1(w[40], w[41], w[42], w[43]);
- w[40] = _x0; w[41] = _x1; w[42] = _x2; w[43] = _x3;
+ w[40] = _x0;
+ w[41] = _x1;
+ w[42] = _x2;
+ w[43] = _x3;
+
Sb0(w[44], w[45], w[46], w[47]);
- w[44] = _x0; w[45] = _x1; w[46] = _x2; w[47] = _x3;
+ w[44] = _x0;
+ w[45] = _x1;
+ w[46] = _x2;
+ w[47] = _x3;
+
Sb7(w[48], w[49], w[50], w[51]);
- w[48] = _x0; w[49] = _x1; w[50] = _x2; w[51] = _x3;
+ w[48] = _x0;
+ w[49] = _x1;
+ w[50] = _x2;
+ w[51] = _x3;
+
Sb6(w[52], w[53], w[54], w[55]);
- w[52] = _x0; w[53] = _x1; w[54] = _x2; w[55] = _x3;
+ w[52] = _x0;
+ w[53] = _x1;
+ w[54] = _x2;
+ w[55] = _x3;
+
Sb5(w[56], w[57], w[58], w[59]);
- w[56] = _x0; w[57] = _x1; w[58] = _x2; w[59] = _x3;
+ w[56] = _x0;
+ w[57] = _x1;
+ w[58] = _x2;
+ w[59] = _x3;
+
Sb4(w[60], w[61], w[62], w[63]);
- w[60] = _x0; w[61] = _x1; w[62] = _x2; w[63] = _x3;
+ w[60] = _x0;
+ w[61] = _x1;
+ w[62] = _x2;
+ w[63] = _x3;
+
Sb3(w[64], w[65], w[66], w[67]);
- w[64] = _x0; w[65] = _x1; w[66] = _x2; w[67] = _x3;
+ w[64] = _x0;
+ w[65] = _x1;
+ w[66] = _x2;
+ w[67] = _x3;
+
Sb2(w[68], w[69], w[70], w[71]);
- w[68] = _x0; w[69] = _x1; w[70] = _x2; w[71] = _x3;
+ w[68] = _x0;
+ w[69] = _x1;
+ w[70] = _x2;
+ w[71] = _x3;
+
Sb1(w[72], w[73], w[74], w[75]);
- w[72] = _x0; w[73] = _x1; w[74] = _x2; w[75] = _x3;
+ w[72] = _x0;
+ w[73] = _x1;
+ w[74] = _x2;
+ w[75] = _x3;
+
Sb0(w[76], w[77], w[78], w[79]);
- w[76] = _x0; w[77] = _x1; w[78] = _x2; w[79] = _x3;
+ w[76] = _x0;
+ w[77] = _x1;
+ w[78] = _x2;
+ w[79] = _x3;
+
Sb7(w[80], w[81], w[82], w[83]);
- w[80] = _x0; w[81] = _x1; w[82] = _x2; w[83] = _x3;
+ w[80] = _x0;
+ w[81] = _x1;
+ w[82] = _x2;
+ w[83] = _x3;
+
Sb6(w[84], w[85], w[86], w[87]);
- w[84] = _x0; w[85] = _x1; w[86] = _x2; w[87] = _x3;
+ w[84] = _x0;
+ w[85] = _x1;
+ w[86] = _x2;
+ w[87] = _x3;
+
Sb5(w[88], w[89], w[90], w[91]);
- w[88] = _x0; w[89] = _x1; w[90] = _x2; w[91] = _x3;
+ w[88] = _x0;
+ w[89] = _x1;
+ w[90] = _x2;
+ w[91] = _x3;
+
Sb4(w[92], w[93], w[94], w[95]);
- w[92] = _x0; w[93] = _x1; w[94] = _x2; w[95] = _x3;
+ w[92] = _x0;
+ w[93] = _x1;
+ w[94] = _x2;
+ w[95] = _x3;
+
Sb3(w[96], w[97], w[98], w[99]);
- w[96] = _x0; w[97] = _x1; w[98] = _x2; w[99] = _x3;
+ w[96] = _x0;
+ w[97] = _x1;
+ w[98] = _x2;
+ w[99] = _x3;
+
Sb2(w[100], w[101], w[102], w[103]);
- w[100] = _x0; w[101] = _x1; w[102] = _x2; w[103] = _x3;
+ w[100] = _x0;
+ w[101] = _x1;
+ w[102] = _x2;
+ w[103] = _x3;
+
Sb1(w[104], w[105], w[106], w[107]);
- w[104] = _x0; w[105] = _x1; w[106] = _x2; w[107] = _x3;
+ w[104] = _x0;
+ w[105] = _x1;
+ w[106] = _x2;
+ w[107] = _x3;
+
Sb0(w[108], w[109], w[110], w[111]);
- w[108] = _x0; w[109] = _x1; w[110] = _x2; w[111] = _x3;
+ w[108] = _x0;
+ w[109] = _x1;
+ w[110] = _x2;
+ w[111] = _x3;
+
Sb7(w[112], w[113], w[114], w[115]);
- w[112] = _x0; w[113] = _x1; w[114] = _x2; w[115] = _x3;
+ w[112] = _x0;
+ w[113] = _x1;
+ w[114] = _x2;
+ w[115] = _x3;
+
Sb6(w[116], w[117], w[118], w[119]);
- w[116] = _x0; w[117] = _x1; w[118] = _x2; w[119] = _x3;
+ w[116] = _x0;
+ w[117] = _x1;
+ w[118] = _x2;
+ w[119] = _x3;
+
Sb5(w[120], w[121], w[122], w[123]);
- w[120] = _x0; w[121] = _x1; w[122] = _x2; w[123] = _x3;
+ w[120] = _x0;
+ w[121] = _x1;
+ w[122] = _x2;
+ w[123] = _x3;
+
Sb4(w[124], w[125], w[126], w[127]);
- w[124] = _x0; w[125] = _x1; w[126] = _x2; w[127] = _x3;
+ w[124] = _x0;
+ w[125] = _x1;
+ w[126] = _x2;
+ w[127] = _x3;
+
Sb3(w[128], w[129], w[130], w[131]);
- w[128] = _x0; w[129] = _x1; w[130] = _x2; w[131] = _x3;
+ w[128] = _x0;
+ w[129] = _x1;
+ w[130] = _x2;
+ w[131] = _x3;
return w;
}
private static int RotateLeft(int x, int bits)
{
- return ((x << bits) | (int)((uint)x >> (32 - bits)));
+ return (x << bits) | (int) ((uint) x >> (32 - bits));
}
private static int RotateRight(int x, int bits)
{
- return ((int)((uint)x >> bits) | (x << (32 - bits)));
+ return (int) ((uint) x >> bits) | (x << (32 - bits));
}
private static int BytesToWord(byte[] src, int srcOff)
{
- return (((src[srcOff] & 0xff) << 24) | ((src[srcOff + 1] & 0xff) << 16) |
- ((src[srcOff + 2] & 0xff) << 8) | ((src[srcOff + 3] & 0xff)));
+ return ((src[srcOff] & 0xff) << 24) | ((src[srcOff + 1] & 0xff) << 16) |
+ ((src[srcOff + 2] & 0xff) << 8) | (src[srcOff + 3] & 0xff);
}
private static void WordToBytes(int word, byte[] dst, int dstOff)
{
- dst[dstOff + 3] = (byte)(word);
- dst[dstOff + 2] = (byte)((uint)word >> 8);
- dst[dstOff + 1] = (byte)((uint)word >> 16);
- dst[dstOff] = (byte)((uint)word >> 24);
+ dst[dstOff + 3] = (byte) word;
+ dst[dstOff + 2] = (byte) ((uint)word >> 8);
+ dst[dstOff + 1] = (byte) ((uint)word >> 16);
+ dst[dstOff] = (byte) ((uint)word >> 24);
}
/*
- * The sboxes below are based on the work of Brian Gladman and
- * Sam Simpson, whose original notice appears below.
- *
- * For further details see:
- * http://fp.gladman.plus.com/cryptography_technology/serpent/
- *
- */
-
- /* Partially optimised Serpent S Box bool functions derived */
- /* using a recursive descent analyser but without a full search */
- /* of all subtrees. This set of S boxes is the result of work */
- /* by Sam Simpson and Brian Gladman using the spare time on a */
- /* cluster of high capacity servers to search for S boxes with */
- /* this customised search engine. There are now an average of */
- /* 15.375 terms per S box. */
- /* */
- /* Copyright: Dr B. R Gladman (gladman@seven77.demon.co.uk) */
- /* and Sam Simpson (s.simpson@mia.co.uk) */
- /* 17th December 1998 */
- /* */
- /* We hereby give permission for information in this file to be */
- /* used freely subject only to acknowledgement of its origin. */
+ * The sboxes below are based on the work of Brian Gladman and
+ * Sam Simpson, whose original notice appears below.
+ *
+ * For further details see:
+ * http://fp.gladman.plus.com/cryptography_technology/serpent/
+ *
+ */
+
+ /*
+ * Partially optimised Serpent S Box bool functions derived
+ * using a recursive descent analyser but without a full search
+ * of all subtrees. This set of S boxes is the result of work
+ * by Sam Simpson and Brian Gladman using the spare time on a
+ * cluster of high capacity servers to search for S boxes with
+ * this customised search engine. There are now an average of
+ * 15.375 terms per S box.
+ *
+ * Copyright: Dr B. R Gladman (gladman@seven77.demon.co.uk)
+ * and Sam Simpson (s.simpson@mia.co.uk)
+ * 17th December 1998
+ *
+ * We hereby give permission for information in this file to be
+ * used freely subject only to acknowledgement of its origin.
+ */
///
/// S0 - { 3, 8,15, 1,10, 6, 5,11,14,13, 4, 2, 7, 0, 9,12 } - 15 terms.
@@ -377,13 +726,13 @@ private static void WordToBytes(int word, byte[] dst, int dstOff)
/// The d.
private void Sb0(int a, int b, int c, int d)
{
- int t1 = a ^ d;
- int t3 = c ^ t1;
- int t4 = b ^ t3;
+ var t1 = a ^ d;
+ var t3 = c ^ t1;
+ var t4 = b ^ t3;
_x3 = (a & d) ^ t4;
- int t7 = a ^ (b & t1);
+ var t7 = a ^ (b & t1);
_x2 = t4 ^ (c | t7);
- int t12 = _x3 & (t3 ^ t7);
+ var t12 = _x3 & (t3 ^ t7);
_x1 = (~t3) ^ t12;
_x0 = t12 ^ (~t7);
}
@@ -397,12 +746,12 @@ private void Sb0(int a, int b, int c, int d)
/// The d.
private void Ib0(int a, int b, int c, int d)
{
- int t1 = ~a;
- int t2 = a ^ b;
- int t4 = d ^ (t1 | t2);
- int t5 = c ^ t4;
+ var t1 = ~a;
+ var t2 = a ^ b;
+ var t4 = d ^ (t1 | t2);
+ var t5 = c ^ t4;
_x2 = t2 ^ t5;
- int t8 = t1 ^ (d & t2);
+ var t8 = t1 ^ (d & t2);
_x1 = t4 ^ (_x2 & t8);
_x3 = (a & t4) ^ (t5 | _x1);
_x0 = _x3 ^ (t5 ^ t8);
@@ -417,13 +766,13 @@ private void Ib0(int a, int b, int c, int d)
/// The d.
private void Sb1(int a, int b, int c, int d)
{
- int t2 = b ^ (~a);
- int t5 = c ^ (a | t2);
+ var t2 = b ^ (~a);
+ var t5 = c ^ (a | t2);
_x2 = d ^ t5;
- int t7 = b ^ (d | t2);
- int t8 = t2 ^ _x2;
+ var t7 = b ^ (d | t2);
+ var t8 = t2 ^ _x2;
_x3 = t8 ^ (t5 & t7);
- int t11 = t5 ^ t7;
+ var t11 = t5 ^ t7;
_x1 = _x3 ^ t11;
_x0 = t5 ^ (t8 & t11);
}
@@ -437,15 +786,15 @@ private void Sb1(int a, int b, int c, int d)
/// The d.
private void Ib1(int a, int b, int c, int d)
{
- int t1 = b ^ d;
- int t3 = a ^ (b & t1);
- int t4 = t1 ^ t3;
+ var t1 = b ^ d;
+ var t3 = a ^ (b & t1);
+ var t4 = t1 ^ t3;
_x3 = c ^ t4;
- int t7 = b ^ (t1 & t3);
- int t8 = _x3 | t7;
+ var t7 = b ^ (t1 & t3);
+ var t8 = _x3 | t7;
_x1 = t3 ^ t8;
- int t10 = ~_x1;
- int t11 = _x3 ^ t7;
+ var t10 = ~_x1;
+ var t11 = _x3 ^ t7;
_x0 = t10 ^ t11;
_x2 = t4 ^ (t10 | t11);
}
@@ -459,13 +808,13 @@ private void Ib1(int a, int b, int c, int d)
/// The d.
private void Sb2(int a, int b, int c, int d)
{
- int t1 = ~a;
- int t2 = b ^ d;
- int t3 = c & t1;
+ var t1 = ~a;
+ var t2 = b ^ d;
+ var t3 = c & t1;
_x0 = t2 ^ t3;
- int t5 = c ^ t1;
- int t6 = c ^ _x0;
- int t7 = b & t6;
+ var t5 = c ^ t1;
+ var t6 = c ^ _x0;
+ var t7 = b & t6;
_x3 = t5 ^ t7;
_x2 = a ^ ((d | t7) & (_x0 | t5));
_x1 = (t2 ^ _x3) ^ (_x2 ^ (d | t1));
@@ -480,18 +829,18 @@ private void Sb2(int a, int b, int c, int d)
/// The d.
private void Ib2(int a, int b, int c, int d)
{
- int t1 = b ^ d;
- int t2 = ~t1;
- int t3 = a ^ c;
- int t4 = c ^ t1;
- int t5 = b & t4;
+ var t1 = b ^ d;
+ var t2 = ~t1;
+ var t3 = a ^ c;
+ var t4 = c ^ t1;
+ var t5 = b & t4;
_x0 = t3 ^ t5;
- int t7 = a | t2;
- int t8 = d ^ t7;
- int t9 = t3 | t8;
+ var t7 = a | t2;
+ var t8 = d ^ t7;
+ var t9 = t3 | t8;
_x3 = t1 ^ t9;
- int t11 = ~t4;
- int t12 = _x0 | _x3;
+ var t11 = ~t4;
+ var t12 = _x0 | _x3;
_x1 = t11 ^ t12;
_x2 = (d & t11) ^ (t3 ^ t12);
}
@@ -505,24 +854,24 @@ private void Ib2(int a, int b, int c, int d)
/// The d.
private void Sb3(int a, int b, int c, int d)
{
- int t1 = a ^ b;
- int t2 = a & c;
- int t3 = a | d;
- int t4 = c ^ d;
- int t5 = t1 & t3;
- int t6 = t2 | t5;
+ var t1 = a ^ b;
+ var t2 = a & c;
+ var t3 = a | d;
+ var t4 = c ^ d;
+ var t5 = t1 & t3;
+ var t6 = t2 | t5;
_x2 = t4 ^ t6;
- int t8 = b ^ t3;
- int t9 = t6 ^ t8;
- int t10 = t4 & t9;
+ var t8 = b ^ t3;
+ var t9 = t6 ^ t8;
+ var t10 = t4 & t9;
_x0 = t1 ^ t10;
- int t12 = _x2 & _x0;
+ var t12 = _x2 & _x0;
_x1 = t9 ^ t12;
_x3 = (b | d) ^ (t4 ^ t12);
}
///
- /// InvS3 - { 0, 9,10, 7,11,14, 6,13, 3, 5,12, 2, 4, 8,15, 1 } - 15 terms
+ /// InvS3 - { 0, 9,10, 7,11,14, 6,13, 3, 5,12, 2, 4, 8,15, 1 } - 15 terms.
///
/// A.
/// The b.
@@ -530,18 +879,18 @@ private void Sb3(int a, int b, int c, int d)
/// The d.
private void Ib3(int a, int b, int c, int d)
{
- int t1 = a | b;
- int t2 = b ^ c;
- int t3 = b & t2;
- int t4 = a ^ t3;
- int t5 = c ^ t4;
- int t6 = d | t4;
+ var t1 = a | b;
+ var t2 = b ^ c;
+ var t3 = b & t2;
+ var t4 = a ^ t3;
+ var t5 = c ^ t4;
+ var t6 = d | t4;
_x0 = t2 ^ t6;
- int t8 = t2 | t6;
- int t9 = d ^ t8;
+ var t8 = t2 | t6;
+ var t9 = d ^ t8;
_x2 = t5 ^ t9;
- int t11 = t1 ^ t9;
- int t12 = _x0 & t11;
+ var t11 = t1 ^ t9;
+ var t12 = _x0 & t11;
_x3 = t4 ^ t12;
_x1 = _x3 ^ (_x0 ^ t11);
}
@@ -555,17 +904,17 @@ private void Ib3(int a, int b, int c, int d)
/// The d.
private void Sb4(int a, int b, int c, int d)
{
- int t1 = a ^ d;
- int t2 = d & t1;
- int t3 = c ^ t2;
- int t4 = b | t3;
+ var t1 = a ^ d;
+ var t2 = d & t1;
+ var t3 = c ^ t2;
+ var t4 = b | t3;
_x3 = t1 ^ t4;
- int t6 = ~b;
- int t7 = t1 | t6;
+ var t6 = ~b;
+ var t7 = t1 | t6;
_x0 = t3 ^ t7;
- int t9 = a & _x0;
- int t10 = t1 ^ t6;
- int t11 = t4 & t10;
+ var t9 = a & _x0;
+ var t10 = t1 ^ t6;
+ var t11 = t4 & t10;
_x2 = t9 ^ t11;
_x1 = (a ^ t3) ^ (t10 & _x2);
}
@@ -579,17 +928,17 @@ private void Sb4(int a, int b, int c, int d)
/// The d.
private void Ib4(int a, int b, int c, int d)
{
- int t1 = c | d;
- int t2 = a & t1;
- int t3 = b ^ t2;
- int t4 = a & t3;
- int t5 = c ^ t4;
+ var t1 = c | d;
+ var t2 = a & t1;
+ var t3 = b ^ t2;
+ var t4 = a & t3;
+ var t5 = c ^ t4;
_x1 = d ^ t5;
- int t7 = ~a;
- int t8 = t5 & _x1;
+ var t7 = ~a;
+ var t8 = t5 & _x1;
_x3 = t3 ^ t8;
- int t10 = _x1 | t7;
- int t11 = d ^ t10;
+ var t10 = _x1 | t7;
+ var t11 = d ^ t10;
_x0 = _x3 ^ t11;
_x2 = (t3 & t11) ^ (_x1 ^ t7);
}
@@ -603,18 +952,18 @@ private void Ib4(int a, int b, int c, int d)
/// The d.
private void Sb5(int a, int b, int c, int d)
{
- int t1 = ~a;
- int t2 = a ^ b;
- int t3 = a ^ d;
- int t4 = c ^ t1;
- int t5 = t2 | t3;
+ var t1 = ~a;
+ var t2 = a ^ b;
+ var t3 = a ^ d;
+ var t4 = c ^ t1;
+ var t5 = t2 | t3;
_x0 = t4 ^ t5;
- int t7 = d & _x0;
- int t8 = t2 ^ _x0;
+ var t7 = d & _x0;
+ var t8 = t2 ^ _x0;
_x1 = t7 ^ t8;
- int t10 = t1 | _x0;
- int t11 = t2 | t7;
- int t12 = t3 ^ t10;
+ var t10 = t1 | _x0;
+ var t11 = t2 | t7;
+ var t12 = t3 ^ t10;
_x2 = t11 ^ t12;
_x3 = (b ^ t7) ^ (_x1 & t12);
}
@@ -628,17 +977,17 @@ private void Sb5(int a, int b, int c, int d)
/// The d.
private void Ib5(int a, int b, int c, int d)
{
- int t1 = ~c;
- int t2 = b & t1;
- int t3 = d ^ t2;
- int t4 = a & t3;
- int t5 = b ^ t1;
+ var t1 = ~c;
+ var t2 = b & t1;
+ var t3 = d ^ t2;
+ var t4 = a & t3;
+ var t5 = b ^ t1;
_x3 = t4 ^ t5;
- int t7 = b | _x3;
- int t8 = a & t7;
+ var t7 = b | _x3;
+ var t8 = a & t7;
_x1 = t3 ^ t8;
- int t10 = a | d;
- int t11 = t1 ^ t7;
+ var t10 = a | d;
+ var t11 = t1 ^ t7;
_x0 = t10 ^ t11;
_x2 = (b & t10) ^ (t4 | (a ^ c));
}
@@ -652,17 +1001,17 @@ private void Ib5(int a, int b, int c, int d)
/// The d.
private void Sb6(int a, int b, int c, int d)
{
- int t1 = ~a;
- int t2 = a ^ d;
- int t3 = b ^ t2;
- int t4 = t1 | t2;
- int t5 = c ^ t4;
+ var t1 = ~a;
+ var t2 = a ^ d;
+ var t3 = b ^ t2;
+ var t4 = t1 | t2;
+ var t5 = c ^ t4;
_x1 = b ^ t5;
- int t7 = t2 | _x1;
- int t8 = d ^ t7;
- int t9 = t5 & t8;
+ var t7 = t2 | _x1;
+ var t8 = d ^ t7;
+ var t9 = t5 & t8;
_x2 = t3 ^ t9;
- int t11 = t5 ^ t8;
+ var t11 = t5 ^ t8;
_x0 = _x2 ^ t11;
_x3 = (~t5) ^ (t3 & t11);
}
@@ -676,17 +1025,17 @@ private void Sb6(int a, int b, int c, int d)
/// The d.
private void Ib6(int a, int b, int c, int d)
{
- int t1 = ~a;
- int t2 = a ^ b;
- int t3 = c ^ t2;
- int t4 = c | t1;
- int t5 = d ^ t4;
+ var t1 = ~a;
+ var t2 = a ^ b;
+ var t3 = c ^ t2;
+ var t4 = c | t1;
+ var t5 = d ^ t4;
_x1 = t3 ^ t5;
- int t7 = t3 & t5;
- int t8 = t2 ^ t7;
- int t9 = b | t8;
+ var t7 = t3 & t5;
+ var t8 = t2 ^ t7;
+ var t9 = b | t8;
_x3 = t5 ^ t9;
- int t11 = b | _x3;
+ var t11 = b | _x3;
_x0 = t8 ^ t11;
_x2 = (d & t1) ^ (t3 ^ t11);
}
@@ -700,18 +1049,18 @@ private void Ib6(int a, int b, int c, int d)
/// The d.
private void Sb7(int a, int b, int c, int d)
{
- int t1 = b ^ c;
- int t2 = c & t1;
- int t3 = d ^ t2;
- int t4 = a ^ t3;
- int t5 = d | t1;
- int t6 = t4 & t5;
+ var t1 = b ^ c;
+ var t2 = c & t1;
+ var t3 = d ^ t2;
+ var t4 = a ^ t3;
+ var t5 = d | t1;
+ var t6 = t4 & t5;
_x1 = b ^ t6;
- int t8 = t3 | _x1;
- int t9 = a & t4;
+ var t8 = t3 | _x1;
+ var t9 = a & t4;
_x3 = t1 ^ t9;
- int t11 = t4 ^ t8;
- int t12 = _x3 & t11;
+ var t11 = t4 ^ t8;
+ var t12 = _x3 & t11;
_x2 = t3 ^ t12;
_x0 = (~t11) ^ (_x3 & _x2);
}
@@ -725,12 +1074,12 @@ private void Sb7(int a, int b, int c, int d)
/// The d.
private void Ib7(int a, int b, int c, int d)
{
- int t3 = c | (a & b);
- int t4 = d & (a | b);
+ var t3 = c | (a & b);
+ var t4 = d & (a | b);
_x3 = t3 ^ t4;
- int t6 = ~d;
- int t7 = b ^ t4;
- int t9 = t7 | (_x3 ^ t6);
+ var t6 = ~d;
+ var t7 = b ^ t4;
+ var t9 = t7 | (_x3 ^ t6);
_x1 = a ^ t9;
_x0 = (c ^ t7) ^ (d | _x1);
_x2 = (t3 ^ _x1) ^ (_x0 ^ (a & _x3));
@@ -741,10 +1090,10 @@ private void Ib7(int a, int b, int c, int d)
///
private void LT()
{
- int x0 = RotateLeft(_x0, 13);
- int x2 = RotateLeft(_x2, 3);
- int x1 = _x1 ^ x0 ^ x2;
- int x3 = _x3 ^ x2 ^ x0 << 3;
+ var x0 = RotateLeft(_x0, 13);
+ var x2 = RotateLeft(_x2, 3);
+ var x1 = _x1 ^ x0 ^ x2;
+ var x3 = _x3 ^ x2 ^ x0 << 3;
_x1 = RotateLeft(x1, 1);
_x3 = RotateLeft(x3, 7);
@@ -757,10 +1106,10 @@ private void LT()
///
private void InverseLT()
{
- int x2 = RotateRight(_x2, 22) ^ _x3 ^ (_x1 << 7);
- int x0 = RotateRight(_x0, 5) ^ _x1 ^ _x3;
- int x3 = RotateRight(_x3, 7);
- int x1 = RotateRight(_x1, 1);
+ var x2 = RotateRight(_x2, 22) ^ _x3 ^ (_x1 << 7);
+ var x0 = RotateRight(_x0, 5) ^ _x1 ^ _x3;
+ var x3 = RotateRight(_x3, 7);
+ var x1 = RotateRight(_x1, 1);
_x3 = x3 ^ x2 ^ x0 << 3;
_x1 = x1 ^ x0 ^ x2;
_x2 = RotateRight(x2, 3);
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/TripleDesCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/TripleDesCipher.cs
index a9db5db53..eb1c0839d 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/TripleDesCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/TripleDesCipher.cs
@@ -20,7 +20,7 @@ public sealed class TripleDesCipher : DesCipher
/// The key.
/// The mode.
/// The padding.
- /// is null.
+ /// is .
public TripleDesCipher(byte[] key, CipherMode mode, CipherPadding padding)
: base(key, mode, padding)
{
@@ -40,12 +40,16 @@ public TripleDesCipher(byte[] key, CipherMode mode, CipherPadding padding)
public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if ((inputOffset + BlockSize) > inputBuffer.Length)
- throw new IndexOutOfRangeException("input buffer too short");
+ {
+ throw new ArgumentException("input buffer too short");
+ }
if ((outputOffset + BlockSize) > outputBuffer.Length)
- throw new IndexOutOfRangeException("output buffer too short");
+ {
+ throw new ArgumentException("output buffer too short");
+ }
- if (_encryptionKey1 == null || _encryptionKey2 == null || _encryptionKey3 == null)
+ if (_encryptionKey1 is null || _encryptionKey2 is null || _encryptionKey3 is null)
{
var part1 = new byte[8];
var part2 = new byte[8];
@@ -53,16 +57,15 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC
Buffer.BlockCopy(Key, 0, part1, 0, 8);
Buffer.BlockCopy(Key, 8, part2, 0, 8);
- _encryptionKey1 = GenerateWorkingKey(true, part1);
-
- _encryptionKey2 = GenerateWorkingKey(false, part2);
+ _encryptionKey1 = GenerateWorkingKey(encrypting: true, part1);
+ _encryptionKey2 = GenerateWorkingKey(encrypting: false, part2);
if (Key.Length == 24)
{
var part3 = new byte[8];
Buffer.BlockCopy(Key, 16, part3, 0, 8);
- _encryptionKey3 = GenerateWorkingKey(true, part3);
+ _encryptionKey3 = GenerateWorkingKey(encrypting: true, part3);
}
else
{
@@ -70,7 +73,7 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC
}
}
- byte[] temp = new byte[BlockSize];
+ var temp = new byte[BlockSize];
DesFunc(_encryptionKey1, inputBuffer, inputOffset, temp, 0);
DesFunc(_encryptionKey2, temp, 0, temp, 0);
@@ -93,12 +96,16 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC
public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if ((inputOffset + BlockSize) > inputBuffer.Length)
- throw new IndexOutOfRangeException("input buffer too short");
+ {
+ throw new ArgumentException("input buffer too short");
+ }
if ((outputOffset + BlockSize) > outputBuffer.Length)
- throw new IndexOutOfRangeException("output buffer too short");
+ {
+ throw new ArgumentException("output buffer too short");
+ }
- if (_decryptionKey1 == null || _decryptionKey2 == null || _decryptionKey3 == null)
+ if (_decryptionKey1 is null || _decryptionKey2 is null || _decryptionKey3 is null)
{
var part1 = new byte[8];
var part2 = new byte[8];
@@ -106,15 +113,15 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC
Buffer.BlockCopy(Key, 0, part1, 0, 8);
Buffer.BlockCopy(Key, 8, part2, 0, 8);
- _decryptionKey1 = GenerateWorkingKey(false, part1);
- _decryptionKey2 = GenerateWorkingKey(true, part2);
+ _decryptionKey1 = GenerateWorkingKey(encrypting: false, part1);
+ _decryptionKey2 = GenerateWorkingKey(encrypting: true, part2);
if (Key.Length == 24)
{
var part3 = new byte[8];
Buffer.BlockCopy(Key, 16, part3, 0, 8);
- _decryptionKey3 = GenerateWorkingKey(false, part3);
+ _decryptionKey3 = GenerateWorkingKey(encrypting: false, part3);
}
else
{
@@ -122,7 +129,7 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC
}
}
- byte[] temp = new byte[BlockSize];
+ var temp = new byte[BlockSize];
DesFunc(_decryptionKey3, inputBuffer, inputOffset, temp, 0);
DesFunc(_decryptionKey2, temp, 0, temp, 0);
@@ -138,8 +145,10 @@ protected override void ValidateKey()
{
var keySize = Key.Length * 8;
- if (!(keySize == 128 || keySize == 128 + 64))
+ if (keySize is not (128 or 128 + 64))
+ {
throw new ArgumentException(string.Format("KeySize '{0}' is not valid for this algorithm.", keySize));
+ }
}
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/TwofishCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/TwofishCipher.cs
index 8f7c8bba0..7ef039cc3 100644
--- a/src/Renci.SshNet/Security/Cryptography/Ciphers/TwofishCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/TwofishCipher.cs
@@ -3,27 +3,93 @@
namespace Renci.SshNet.Security.Cryptography.Ciphers
{
///
- /// Implements Twofish cipher algorithm
+ /// Implements Twofish cipher algorithm.
///
public sealed class TwofishCipher : BlockCipher
{
+ /**
+ * Define the fixed p0/p1 permutations used in keyed S-box lookup.
+ * By changing the following constant definitions, the S-boxes will
+ * automatically Get changed in the Twofish engine.
+ */
+#pragma warning disable SA1310 // Field names should not contain underscore
+ private const int P_00 = 1;
+ private const int P_01 = 0;
+ private const int P_02 = 0;
+ private const int P_03 = P_01 ^ 1;
+ private const int P_04 = 1;
+
+ private const int P_10 = 0;
+ private const int P_11 = 0;
+ private const int P_12 = 1;
+ private const int P_13 = P_11 ^ 1;
+ private const int P_14 = 0;
+
+ private const int P_20 = 1;
+ private const int P_21 = 1;
+ private const int P_22 = 0;
+ private const int P_23 = P_21 ^ 1;
+ private const int P_24 = 0;
+
+ private const int P_30 = 0;
+ private const int P_31 = 1;
+ private const int P_32 = 1;
+ private const int P_33 = P_31 ^ 1;
+ private const int P_34 = 1;
+
+ /* Primitive polynomial for GF(256) */
+ private const int GF256_FDBK = 0x169;
+ private const int GF256_FDBK_2 = GF256_FDBK / 2;
+ private const int GF256_FDBK_4 = GF256_FDBK / 4;
+
+ private const int RS_GF_FDBK = 0x14D; // field generator
+
+ private const int ROUNDS = 16;
+ private const int MAX_ROUNDS = 16; // bytes = 128 bits
+ private const int MAX_KEY_BITS = 256;
+
+ private const int INPUT_WHITEN = 0;
+ private const int OUTPUT_WHITEN = INPUT_WHITEN + (16 / 4); // 4
+ private const int ROUND_SUBKEYS = OUTPUT_WHITEN + (16 / 4); // 8
+
+ private const int TOTAL_SUBKEYS = ROUND_SUBKEYS + (2 * MAX_ROUNDS); // 40
+
+ private const int SK_STEP = 0x02020202;
+ private const int SK_BUMP = 0x01010101;
+ private const int SK_ROTL = 9;
+#pragma warning restore SA1310 // Field names should not contain underscore
+
+ private readonly int[] _gMDS0 = new int[MAX_KEY_BITS];
+ private readonly int[] _gMDS1 = new int[MAX_KEY_BITS];
+ private readonly int[] _gMDS2 = new int[MAX_KEY_BITS];
+ private readonly int[] _gMDS3 = new int[MAX_KEY_BITS];
+
+ private readonly int _k64Cnt;
+
+ /*
+ * _gSubKeys[] and _gSBox[] are eventually used in the
+ * encryption and decryption methods.
+ */
+ private int[] _gSubKeys;
+ private int[] _gSBox;
+
///
/// Initializes a new instance of the class.
///
/// The key.
/// The mode.
/// The padding.
- /// is null.
+ /// is .
/// Keysize is not valid for this algorithm.
public TwofishCipher(byte[] key, CipherMode mode, CipherPadding padding)
: base(key, 16, mode, padding)
{
var keySize = key.Length * 8;
- if (!(keySize == 128 || keySize == 192 || keySize == 256))
+ if (keySize is not (128 or 192 or 256))
+ {
throw new ArgumentException(string.Format("KeySize '{0}' is not valid for this algorithm.", keySize));
-
- // TODO: Refactor this algorithm
+ }
// calculate the MDS matrix
var m1 = new int[2];
@@ -42,13 +108,13 @@ public TwofishCipher(byte[] key, CipherMode mode, CipherPadding padding)
mX[1] = Mx_X(j) & 0xff;
mY[1] = Mx_Y(j) & 0xff;
- gMDS0[i] = m1[P_00] | mX[P_00] << 8 | mY[P_00] << 16 | mY[P_00] << 24;
+ _gMDS0[i] = m1[P_00] | mX[P_00] << 8 | mY[P_00] << 16 | mY[P_00] << 24;
- gMDS1[i] = mY[P_10] | mY[P_10] << 8 | mX[P_10] << 16 | m1[P_10] << 24;
+ _gMDS1[i] = mY[P_10] | mY[P_10] << 8 | mX[P_10] << 16 | m1[P_10] << 24;
- gMDS2[i] = mX[P_20] | mY[P_20] << 8 | m1[P_20] << 16 | mY[P_20] << 24;
+ _gMDS2[i] = mX[P_20] | mY[P_20] << 8 | m1[P_20] << 16 | mY[P_20] << 24;
- gMDS3[i] = mX[P_30] | m1[P_30] << 8 | mY[P_30] << 16 | mX[P_30] << 24;
+ _gMDS3[i] = mX[P_30] | m1[P_30] << 8 | mY[P_30] << 16 | mX[P_30] << 24;
}
_k64Cnt = key.Length / 8; // pre-padded ?
@@ -68,31 +134,31 @@ public TwofishCipher(byte[] key, CipherMode mode, CipherPadding padding)
///
public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
- var x0 = BytesTo32Bits(inputBuffer, inputOffset) ^ gSubKeys[INPUT_WHITEN];
- var x1 = BytesTo32Bits(inputBuffer, inputOffset + 4) ^ gSubKeys[INPUT_WHITEN + 1];
- var x2 = BytesTo32Bits(inputBuffer, inputOffset + 8) ^ gSubKeys[INPUT_WHITEN + 2];
- var x3 = BytesTo32Bits(inputBuffer, inputOffset + 12) ^ gSubKeys[INPUT_WHITEN + 3];
+ var x0 = BytesTo32Bits(inputBuffer, inputOffset) ^ _gSubKeys[INPUT_WHITEN];
+ var x1 = BytesTo32Bits(inputBuffer, inputOffset + 4) ^ _gSubKeys[INPUT_WHITEN + 1];
+ var x2 = BytesTo32Bits(inputBuffer, inputOffset + 8) ^ _gSubKeys[INPUT_WHITEN + 2];
+ var x3 = BytesTo32Bits(inputBuffer, inputOffset + 12) ^ _gSubKeys[INPUT_WHITEN + 3];
var k = ROUND_SUBKEYS;
for (var r = 0; r < ROUNDS; r += 2)
{
- var t0 = Fe32_0(gSBox, x0);
- var t1 = Fe32_3(gSBox, x1);
- x2 ^= t0 + t1 + gSubKeys[k++];
+ var t0 = Fe32_0(_gSBox, x0);
+ var t1 = Fe32_3(_gSBox, x1);
+ x2 ^= t0 + t1 + _gSubKeys[k++];
x2 = (int)((uint)x2 >> 1) | x2 << 31;
- x3 = (x3 << 1 | (int)((uint)x3 >> 31)) ^ (t0 + 2 * t1 + gSubKeys[k++]);
+ x3 = (x3 << 1 | (int)((uint)x3 >> 31)) ^ (t0 + (2 * t1) + _gSubKeys[k++]);
- t0 = Fe32_0(gSBox, x2);
- t1 = Fe32_3(gSBox, x3);
- x0 ^= t0 + t1 + gSubKeys[k++];
+ t0 = Fe32_0(_gSBox, x2);
+ t1 = Fe32_3(_gSBox, x3);
+ x0 ^= t0 + t1 + _gSubKeys[k++];
x0 = (int)((uint)x0 >> 1) | x0 << 31;
- x1 = (x1 << 1 | (int)((uint)x1 >> 31)) ^ (t0 + 2 * t1 + gSubKeys[k++]);
+ x1 = (x1 << 1 | (int)((uint)x1 >> 31)) ^ (t0 + (2 * t1) + _gSubKeys[k++]);
}
- Bits32ToBytes(x2 ^ gSubKeys[OUTPUT_WHITEN], outputBuffer, outputOffset);
- Bits32ToBytes(x3 ^ gSubKeys[OUTPUT_WHITEN + 1], outputBuffer, outputOffset + 4);
- Bits32ToBytes(x0 ^ gSubKeys[OUTPUT_WHITEN + 2], outputBuffer, outputOffset + 8);
- Bits32ToBytes(x1 ^ gSubKeys[OUTPUT_WHITEN + 3], outputBuffer, outputOffset + 12);
+ Bits32ToBytes(x2 ^ _gSubKeys[OUTPUT_WHITEN], outputBuffer, outputOffset);
+ Bits32ToBytes(x3 ^ _gSubKeys[OUTPUT_WHITEN + 1], outputBuffer, outputOffset + 4);
+ Bits32ToBytes(x0 ^ _gSubKeys[OUTPUT_WHITEN + 2], outputBuffer, outputOffset + 8);
+ Bits32ToBytes(x1 ^ _gSubKeys[OUTPUT_WHITEN + 3], outputBuffer, outputOffset + 12);
return BlockSize;
}
@@ -110,37 +176,35 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC
///
public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
- var x2 = BytesTo32Bits(inputBuffer, inputOffset) ^ gSubKeys[OUTPUT_WHITEN];
- var x3 = BytesTo32Bits(inputBuffer, inputOffset + 4) ^ gSubKeys[OUTPUT_WHITEN + 1];
- var x0 = BytesTo32Bits(inputBuffer, inputOffset + 8) ^ gSubKeys[OUTPUT_WHITEN + 2];
- var x1 = BytesTo32Bits(inputBuffer, inputOffset + 12) ^ gSubKeys[OUTPUT_WHITEN + 3];
+ var x2 = BytesTo32Bits(inputBuffer, inputOffset) ^ _gSubKeys[OUTPUT_WHITEN];
+ var x3 = BytesTo32Bits(inputBuffer, inputOffset + 4) ^ _gSubKeys[OUTPUT_WHITEN + 1];
+ var x0 = BytesTo32Bits(inputBuffer, inputOffset + 8) ^ _gSubKeys[OUTPUT_WHITEN + 2];
+ var x1 = BytesTo32Bits(inputBuffer, inputOffset + 12) ^ _gSubKeys[OUTPUT_WHITEN + 3];
- var k = ROUND_SUBKEYS + 2 * ROUNDS - 1;
+ var k = ROUND_SUBKEYS + (2 * ROUNDS) - 1;
for (var r = 0; r < ROUNDS; r += 2)
{
- var t0 = Fe32_0(gSBox, x2);
- var t1 = Fe32_3(gSBox, x3);
- x1 ^= t0 + 2 * t1 + gSubKeys[k--];
- x0 = (x0 << 1 | (int)((uint)x0 >> 31)) ^ (t0 + t1 + gSubKeys[k--]);
- x1 = (int)((uint)x1 >> 1) | x1 << 31;
-
- t0 = Fe32_0(gSBox, x0);
- t1 = Fe32_3(gSBox, x1);
- x3 ^= t0 + 2 * t1 + gSubKeys[k--];
- x2 = (x2 << 1 | (int)((uint)x2 >> 31)) ^ (t0 + t1 + gSubKeys[k--]);
- x3 = (int)((uint)x3 >> 1) | x3 << 31;
+ var t0 = Fe32_0(_gSBox, x2);
+ var t1 = Fe32_3(_gSBox, x3);
+ x1 ^= t0 + (2 * t1) + _gSubKeys[k--];
+ x0 = (x0 << 1 | (int) ((uint) x0 >> 31)) ^ (t0 + t1 + _gSubKeys[k--]);
+ x1 = (int) ((uint) x1 >> 1) | x1 << 31;
+
+ t0 = Fe32_0(_gSBox, x0);
+ t1 = Fe32_3(_gSBox, x1);
+ x3 ^= t0 + (2 * t1) + _gSubKeys[k--];
+ x2 = (x2 << 1 | (int) ((uint) x2 >> 31)) ^ (t0 + t1 + _gSubKeys[k--]);
+ x3 = (int) ((uint) x3 >> 1) | x3 << 31;
}
- Bits32ToBytes(x0 ^ gSubKeys[INPUT_WHITEN], outputBuffer, outputOffset);
- Bits32ToBytes(x1 ^ gSubKeys[INPUT_WHITEN + 1], outputBuffer, outputOffset + 4);
- Bits32ToBytes(x2 ^ gSubKeys[INPUT_WHITEN + 2], outputBuffer, outputOffset + 8);
- Bits32ToBytes(x3 ^ gSubKeys[INPUT_WHITEN + 3], outputBuffer, outputOffset + 12);
+ Bits32ToBytes(x0 ^ _gSubKeys[INPUT_WHITEN], outputBuffer, outputOffset);
+ Bits32ToBytes(x1 ^ _gSubKeys[INPUT_WHITEN + 1], outputBuffer, outputOffset + 4);
+ Bits32ToBytes(x2 ^ _gSubKeys[INPUT_WHITEN + 2], outputBuffer, outputOffset + 8);
+ Bits32ToBytes(x3 ^ _gSubKeys[INPUT_WHITEN + 3], outputBuffer, outputOffset + 12);
return BlockSize;
}
- #region Static Definition Tables
-
private static readonly byte[] P =
{
// p0
@@ -160,6 +224,7 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC
0x57, 0xC7, 0x8D, 0x74, 0xB7, 0xC4, 0x9F, 0x72, 0x7E, 0x15, 0x22, 0x12, 0x58, 0x07, 0x99, 0x34,
0x6E, 0x50, 0xDE, 0x68, 0x65, 0xBC, 0xDB, 0xF8, 0xC8, 0xA8, 0x2B, 0x40, 0xDC, 0xFE, 0x32, 0xA4,
0xCA, 0x10, 0x21, 0xF0, 0xD3, 0x5D, 0x0F, 0x00, 0x6F, 0x9D, 0x36, 0x42, 0x4A, 0x5E, 0xC1, 0xE0,
+
// p1
0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8, 0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B,
0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1, 0x30, 0x0F, 0xF8, 0x1B, 0x87, 0xFA, 0x06, 0x3F,
@@ -179,83 +244,13 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC
0xD7, 0x61, 0x1E, 0xB4, 0x50, 0x04, 0xF6, 0xC2, 0x16, 0x25, 0x86, 0x56, 0x55, 0x09, 0xBE, 0x91
};
- #endregion
-
- /**
- * Define the fixed p0/p1 permutations used in keyed S-box lookup.
- * By changing the following constant definitions, the S-boxes will
- * automatically Get changed in the Twofish engine.
- */
- private const int P_00 = 1;
- private const int P_01 = 0;
- private const int P_02 = 0;
- private const int P_03 = P_01 ^ 1;
- private const int P_04 = 1;
-
- private const int P_10 = 0;
- private const int P_11 = 0;
- private const int P_12 = 1;
- private const int P_13 = P_11 ^ 1;
- private const int P_14 = 0;
-
- private const int P_20 = 1;
- private const int P_21 = 1;
- private const int P_22 = 0;
- private const int P_23 = P_21 ^ 1;
- private const int P_24 = 0;
-
- private const int P_30 = 0;
- private const int P_31 = 1;
- private const int P_32 = 1;
- private const int P_33 = P_31 ^ 1;
- private const int P_34 = 1;
-
- /* Primitive polynomial for GF(256) */
- private const int GF256_FDBK = 0x169;
- private const int GF256_FDBK_2 = GF256_FDBK / 2;
- private const int GF256_FDBK_4 = GF256_FDBK / 4;
-
- private const int RS_GF_FDBK = 0x14D; // field generator
-
- //====================================
- // Useful constants
- //====================================
-
- private const int ROUNDS = 16;
- private const int MAX_ROUNDS = 16; // bytes = 128 bits
- private const int MAX_KEY_BITS = 256;
-
- private const int INPUT_WHITEN = 0;
- private const int OUTPUT_WHITEN = INPUT_WHITEN + 16 / 4; // 4
- private const int ROUND_SUBKEYS = OUTPUT_WHITEN + 16 / 4;// 8
-
- private const int TOTAL_SUBKEYS = ROUND_SUBKEYS + 2 * MAX_ROUNDS;// 40
-
- private const int SK_STEP = 0x02020202;
- private const int SK_BUMP = 0x01010101;
- private const int SK_ROTL = 9;
-
- private readonly int[] gMDS0 = new int[MAX_KEY_BITS];
- private readonly int[] gMDS1 = new int[MAX_KEY_BITS];
- private readonly int[] gMDS2 = new int[MAX_KEY_BITS];
- private readonly int[] gMDS3 = new int[MAX_KEY_BITS];
-
- /**
- * gSubKeys[] and gSBox[] are eventually used in the
- * encryption and decryption methods.
- */
- private int[] gSubKeys;
- private int[] gSBox;
-
- private readonly int _k64Cnt;
-
private void SetKey(byte[] key)
{
var k32e = new int[MAX_KEY_BITS / 64]; // 4
var k32o = new int[MAX_KEY_BITS / 64]; // 4
var sBoxKeys = new int[MAX_KEY_BITS / 64]; // 4
- gSubKeys = new int[TOTAL_SUBKEYS];
+ _gSubKeys = new int[TOTAL_SUBKEYS];
if (_k64Cnt < 1)
{
@@ -290,9 +285,9 @@ private void SetKey(byte[] key)
var b = F32(q + SK_BUMP, k32o);
b = b << 8 | (int)((uint)b >> 24);
a += b;
- gSubKeys[i * 2] = a;
+ _gSubKeys[i * 2] = a;
a += b;
- gSubKeys[i * 2 + 1] = a << SK_ROTL | (int)((uint)a >> (32 - SK_ROTL));
+ _gSubKeys[(i * 2) + 1] = a << SK_ROTL | (int)((uint)a >> (32 - SK_ROTL));
}
/*
@@ -302,38 +297,41 @@ private void SetKey(byte[] key)
var k1 = sBoxKeys[1];
var k2 = sBoxKeys[2];
var k3 = sBoxKeys[3];
- gSBox = new int[4 * MAX_KEY_BITS];
+ _gSBox = new int[4 * MAX_KEY_BITS];
for (var i = 0; i < MAX_KEY_BITS; i++)
{
int b1, b2, b3;
var b0 = b1 = b2 = b3 = i;
+
+#pragma warning disable IDE0010 // Add missing cases
switch (_k64Cnt & 3)
{
case 1:
- gSBox[i * 2] = gMDS0[(P[P_01 * 256 + b0] & 0xff) ^ M_b0(k0)];
- gSBox[i * 2 + 1] = gMDS1[(P[P_11 * 256 + b1] & 0xff) ^ M_b1(k0)];
- gSBox[i * 2 + 0x200] = gMDS2[(P[P_21 * 256 + b2] & 0xff) ^ M_b2(k0)];
- gSBox[i * 2 + 0x201] = gMDS3[(P[P_31 * 256 + b3] & 0xff) ^ M_b3(k0)];
+ _gSBox[i * 2] = _gMDS0[(P[(P_01 * 256) + b0] & 0xff) ^ M_b0(k0)];
+ _gSBox[(i * 2) + 1] = _gMDS1[(P[(P_11 * 256) + b1] & 0xff) ^ M_b1(k0)];
+ _gSBox[(i * 2) + 0x200] = _gMDS2[(P[(P_21 * 256) + b2] & 0xff) ^ M_b2(k0)];
+ _gSBox[(i * 2) + 0x201] = _gMDS3[(P[(P_31 * 256) + b3] & 0xff) ^ M_b3(k0)];
break;
case 0: /* 256 bits of key */
- b0 = (P[P_04 * 256 + b0] & 0xff) ^ M_b0(k3);
- b1 = (P[P_14 * 256 + b1] & 0xff) ^ M_b1(k3);
- b2 = (P[P_24 * 256 + b2] & 0xff) ^ M_b2(k3);
- b3 = (P[P_34 * 256 + b3] & 0xff) ^ M_b3(k3);
+ b0 = (P[(P_04 * 256) + b0] & 0xff) ^ M_b0(k3);
+ b1 = (P[(P_14 * 256) + b1] & 0xff) ^ M_b1(k3);
+ b2 = (P[(P_24 * 256) + b2] & 0xff) ^ M_b2(k3);
+ b3 = (P[(P_34 * 256) + b3] & 0xff) ^ M_b3(k3);
goto case 3;
case 3:
- b0 = (P[P_03 * 256 + b0] & 0xff) ^ M_b0(k2);
- b1 = (P[P_13 * 256 + b1] & 0xff) ^ M_b1(k2);
- b2 = (P[P_23 * 256 + b2] & 0xff) ^ M_b2(k2);
- b3 = (P[P_33 * 256 + b3] & 0xff) ^ M_b3(k2);
+ b0 = (P[(P_03 * 256) + b0] & 0xff) ^ M_b0(k2);
+ b1 = (P[(P_13 * 256) + b1] & 0xff) ^ M_b1(k2);
+ b2 = (P[(P_23 * 256) + b2] & 0xff) ^ M_b2(k2);
+ b3 = (P[(P_33 * 256) + b3] & 0xff) ^ M_b3(k2);
goto case 2;
case 2:
- gSBox[i * 2] = gMDS0[(P[P_01 * 256 + (P[P_02 * 256 + b0] & 0xff) ^ M_b0(k1)] & 0xff) ^ M_b0(k0)];
- gSBox[i * 2 + 1] = gMDS1[(P[P_11 * 256 + (P[P_12 * 256 + b1] & 0xff) ^ M_b1(k1)] & 0xff) ^ M_b1(k0)];
- gSBox[i * 2 + 0x200] = gMDS2[(P[P_21 * 256 + (P[P_22 * 256 + b2] & 0xff) ^ M_b2(k1)] & 0xff) ^ M_b2(k0)];
- gSBox[i * 2 + 0x201] = gMDS3[(P[P_31 * 256 + (P[P_32 * 256 + b3] & 0xff) ^ M_b3(k1)] & 0xff) ^ M_b3(k0)];
+ _gSBox[i * 2] = _gMDS0[(P[(P_01 * 256) + (P[(P_02 * 256) + b0] & 0xff) ^ M_b0(k1)] & 0xff) ^ M_b0(k0)];
+ _gSBox[(i * 2) + 1] = _gMDS1[(P[(P_11 * 256) + (P[(P_12 * 256) + b1] & 0xff) ^ M_b1(k1)] & 0xff) ^ M_b1(k0)];
+ _gSBox[(i * 2) + 0x200] = _gMDS2[(P[(P_21 * 256) + (P[(P_22 * 256) + b2] & 0xff) ^ M_b2(k1)] & 0xff) ^ M_b2(k0)];
+ _gSBox[(i * 2) + 0x201] = _gMDS3[(P[(P_31 * 256) + (P[(P_32 * 256) + b3] & 0xff) ^ M_b3(k1)] & 0xff) ^ M_b3(k0)];
break;
}
+#pragma warning restore IDE0010 // Add missing cases
}
/*
@@ -359,34 +357,38 @@ private int F32(int x, int[] k32)
var k3 = k32[3];
var result = 0;
+
+#pragma warning disable IDE0010 // Add missing cases
switch (_k64Cnt & 3)
{
case 1:
- result = gMDS0[(P[P_01 * 256 + b0] & 0xff) ^ M_b0(k0)] ^
- gMDS1[(P[P_11 * 256 + b1] & 0xff) ^ M_b1(k0)] ^
- gMDS2[(P[P_21 * 256 + b2] & 0xff) ^ M_b2(k0)] ^
- gMDS3[(P[P_31 * 256 + b3] & 0xff) ^ M_b3(k0)];
+ result = _gMDS0[(P[(P_01 * 256) + b0] & 0xff) ^ M_b0(k0)] ^
+ _gMDS1[(P[(P_11 * 256) + b1] & 0xff) ^ M_b1(k0)] ^
+ _gMDS2[(P[(P_21 * 256) + b2] & 0xff) ^ M_b2(k0)] ^
+ _gMDS3[(P[(P_31 * 256) + b3] & 0xff) ^ M_b3(k0)];
break;
case 0: /* 256 bits of key */
- b0 = (P[P_04 * 256 + b0] & 0xff) ^ M_b0(k3);
- b1 = (P[P_14 * 256 + b1] & 0xff) ^ M_b1(k3);
- b2 = (P[P_24 * 256 + b2] & 0xff) ^ M_b2(k3);
- b3 = (P[P_34 * 256 + b3] & 0xff) ^ M_b3(k3);
+ b0 = (P[(P_04 * 256) + b0] & 0xff) ^ M_b0(k3);
+ b1 = (P[(P_14 * 256) + b1] & 0xff) ^ M_b1(k3);
+ b2 = (P[(P_24 * 256) + b2] & 0xff) ^ M_b2(k3);
+ b3 = (P[(P_34 * 256) + b3] & 0xff) ^ M_b3(k3);
goto case 3;
case 3:
- b0 = (P[P_03 * 256 + b0] & 0xff) ^ M_b0(k2);
- b1 = (P[P_13 * 256 + b1] & 0xff) ^ M_b1(k2);
- b2 = (P[P_23 * 256 + b2] & 0xff) ^ M_b2(k2);
- b3 = (P[P_33 * 256 + b3] & 0xff) ^ M_b3(k2);
+ b0 = (P[(P_03 * 256) + b0] & 0xff) ^ M_b0(k2);
+ b1 = (P[(P_13 * 256) + b1] & 0xff) ^ M_b1(k2);
+ b2 = (P[(P_23 * 256) + b2] & 0xff) ^ M_b2(k2);
+ b3 = (P[(P_33 * 256) + b3] & 0xff) ^ M_b3(k2);
goto case 2;
case 2:
result =
- gMDS0[(P[P_01 * 256 + (P[P_02 * 256 + b0] & 0xff) ^ M_b0(k1)] & 0xff) ^ M_b0(k0)] ^
- gMDS1[(P[P_11 * 256 + (P[P_12 * 256 + b1] & 0xff) ^ M_b1(k1)] & 0xff) ^ M_b1(k0)] ^
- gMDS2[(P[P_21 * 256 + (P[P_22 * 256 + b2] & 0xff) ^ M_b2(k1)] & 0xff) ^ M_b2(k0)] ^
- gMDS3[(P[P_31 * 256 + (P[P_32 * 256 + b3] & 0xff) ^ M_b3(k1)] & 0xff) ^ M_b3(k0)];
+ _gMDS0[(P[(P_01 * 256) + (P[(P_02 * 256) + b0] & 0xff) ^ M_b0(k1)] & 0xff) ^ M_b0(k0)] ^
+ _gMDS1[(P[(P_11 * 256) + (P[(P_12 * 256) + b1] & 0xff) ^ M_b1(k1)] & 0xff) ^ M_b1(k0)] ^
+ _gMDS2[(P[(P_21 * 256) + (P[(P_22 * 256) + b2] & 0xff) ^ M_b2(k1)] & 0xff) ^ M_b2(k0)] ^
+ _gMDS3[(P[(P_31 * 256) + (P[(P_32 * 256) + b3] & 0xff) ^ M_b3(k1)] & 0xff) ^ M_b3(k0)];
break;
}
+#pragma warning restore IDE0010 // Add missing cases
+
return result;
}
@@ -402,6 +404,7 @@ private int F32(int x, int[] k32)
private static int RS_MDS_Encode(int k0, int k1)
{
var r = k1;
+
// shift 1 byte at a time
r = RS_rem(r);
r = RS_rem(r);
@@ -422,30 +425,25 @@ private static int RS_MDS_Encode(int k0, int k1)
*
* G(x) = x^4 + (a+1/a)x^3 + ax^2 + (a+1/a)x + 1
*
- * where a = primitive root of field generator 0x14D
+ * where a = primitive root of field generator 0x14D.
*
*/
private static int RS_rem(int x)
{
- var b = (int)(((uint)x >> 24) & 0xff);
- var g2 = ((b << 1) ^
- ((b & 0x80) != 0 ? RS_GF_FDBK : 0)) & 0xff;
- var g3 = ((int)((uint)b >> 1) ^
- ((b & 0x01) != 0 ? (int)((uint)RS_GF_FDBK >> 1) : 0)) ^ g2;
- return ((x << 8) ^ (g3 << 24) ^ (g2 << 16) ^ (g3 << 8) ^ b);
+ var b = (int) (((uint) x >> 24) & 0xff);
+ var g2 = ((b << 1) ^ ((b & 0x80) != 0 ? RS_GF_FDBK : 0)) & 0xff;
+ var g3 = ((int) ((uint) b >> 1) ^ ((b & 0x01) != 0 ? (int) ((uint) RS_GF_FDBK >> 1) : 0)) ^ g2;
+ return (x << 8) ^ (g3 << 24) ^ (g2 << 16) ^ (g3 << 8) ^ b;
}
private static int LFSR1(int x)
{
- return (x >> 1) ^
- (((x & 0x01) != 0) ? GF256_FDBK_2 : 0);
+ return (x >> 1) ^ (((x & 0x01) != 0) ? GF256_FDBK_2 : 0);
}
private static int LFSR2(int x)
{
- return (x >> 2) ^
- (((x & 0x02) != 0) ? GF256_FDBK_2 : 0) ^
- (((x & 0x01) != 0) ? GF256_FDBK_4 : 0);
+ return (x >> 2) ^ (((x & 0x02) != 0) ? GF256_FDBK_2 : 0) ^ (((x & 0x01) != 0) ? GF256_FDBK_4 : 0);
}
private static int Mx_X(int x)
@@ -458,45 +456,53 @@ private static int Mx_Y(int x)
return x ^ LFSR1(x) ^ LFSR2(x);
} // EF
+#pragma warning disable IDE1006 // Naming Styles
private static int M_b0(int x)
+#pragma warning restore IDE1006 // Naming Styles
{
return x & 0xff;
}
+#pragma warning disable IDE1006 // Naming Styles
private static int M_b1(int x)
+#pragma warning restore IDE1006 // Naming Styles
{
return (int)((uint)x >> 8) & 0xff;
}
+#pragma warning disable IDE1006 // Naming Styles
private static int M_b2(int x)
+#pragma warning restore IDE1006 // Naming Styles
{
return (int)((uint)x >> 16) & 0xff;
}
+#pragma warning disable IDE1006 // Naming Styles
private static int M_b3(int x)
+#pragma warning restore IDE1006 // Naming Styles
{
return (int)((uint)x >> 24) & 0xff;
}
private static int Fe32_0(int[] gSBox1, int x)
{
- return gSBox1[0x000 + 2 * (x & 0xff)] ^
- gSBox1[0x001 + 2 * ((int)((uint)x >> 8) & 0xff)] ^
- gSBox1[0x200 + 2 * ((int)((uint)x >> 16) & 0xff)] ^
- gSBox1[0x201 + 2 * ((int)((uint)x >> 24) & 0xff)];
+ return gSBox1[0x000 + (2 * (x & 0xff))] ^
+ gSBox1[0x001 + (2 * ((int)((uint)x >> 8) & 0xff))] ^
+ gSBox1[0x200 + (2 * ((int)((uint)x >> 16) & 0xff))] ^
+ gSBox1[0x201 + (2 * ((int)((uint)x >> 24) & 0xff))];
}
private static int Fe32_3(int[] gSBox1, int x)
{
- return gSBox1[0x000 + 2 * ((int)((uint)x >> 24) & 0xff)] ^
- gSBox1[0x001 + 2 * (x & 0xff)] ^
- gSBox1[0x200 + 2 * ((int)((uint)x >> 8) & 0xff)] ^
- gSBox1[0x201 + 2 * ((int)((uint)x >> 16) & 0xff)];
+ return gSBox1[0x000 + (2 * ((int) ((uint) x >> 24) & 0xff))] ^
+ gSBox1[0x001 + (2 * (x & 0xff))] ^
+ gSBox1[0x200 + (2 * ((int)((uint)x >> 8) & 0xff))] ^
+ gSBox1[0x201 + (2 * ((int)((uint)x >> 16) & 0xff))];
}
private static int BytesTo32Bits(byte[] b, int p)
{
- return ((b[p] & 0xff)) |
+ return (b[p] & 0xff) |
((b[p + 1] & 0xff) << 8) |
((b[p + 2] & 0xff) << 16) |
((b[p + 3] & 0xff) << 24);
diff --git a/src/Renci.SshNet/Security/Cryptography/DigitalSignature.cs b/src/Renci.SshNet/Security/Cryptography/DigitalSignature.cs
index 29e2fa379..3e7cee7db 100644
--- a/src/Renci.SshNet/Security/Cryptography/DigitalSignature.cs
+++ b/src/Renci.SshNet/Security/Cryptography/DigitalSignature.cs
@@ -1,7 +1,7 @@
namespace Renci.SshNet.Security.Cryptography
{
///
- /// Base class for signature implementations
+ /// Base class for signature implementations.
///
public abstract class DigitalSignature
{
@@ -10,7 +10,9 @@ public abstract class DigitalSignature
///
/// The input.
/// The signature.
- /// True if signature was successfully verified; otherwise false.
+ ///
+ /// if signature was successfully verified; otherwise .
+ ///
public abstract bool Verify(byte[] input, byte[] signature);
///
diff --git a/src/Renci.SshNet/Security/Cryptography/DsaDigitalSignature.cs b/src/Renci.SshNet/Security/Cryptography/DsaDigitalSignature.cs
index 06275bdad..a5aae17c0 100644
--- a/src/Renci.SshNet/Security/Cryptography/DsaDigitalSignature.cs
+++ b/src/Renci.SshNet/Security/Cryptography/DsaDigitalSignature.cs
@@ -1,5 +1,6 @@
using System;
using System.Security.Cryptography;
+
using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
@@ -10,19 +11,21 @@ namespace Renci.SshNet.Security.Cryptography
///
public class DsaDigitalSignature : DigitalSignature, IDisposable
{
- private HashAlgorithm _hash;
-
private readonly DsaKey _key;
+ private HashAlgorithm _hash;
+ private bool _isDisposed;
///
/// Initializes a new instance of the class.
///
/// The DSA key.
- /// is null.
+ /// is .
public DsaDigitalSignature(DsaKey key)
{
- if (key == null)
- throw new ArgumentNullException("key");
+ if (key is null)
+ {
+ throw new ArgumentNullException(nameof(key));
+ }
_key = key;
@@ -35,7 +38,7 @@ public DsaDigitalSignature(DsaKey key)
/// The input.
/// The signature.
///
- /// true if signature was successfully verified; otherwise false.
+ /// if signature was successfully verified; otherwise .
///
/// Invalid signature.
public override bool Verify(byte[] input, byte[] signature)
@@ -45,9 +48,11 @@ public override bool Verify(byte[] input, byte[] signature)
var hm = new BigInteger(hashInput.Reverse().Concat(new byte[] { 0 }));
if (signature.Length != 40)
+ {
throw new InvalidOperationException("Invalid signature.");
+ }
- // Extract r and s numbers from the signature
+ // Extract r and s numbers from the signature
var rBytes = new byte[21];
var sBytes = new byte[21];
@@ -60,29 +65,33 @@ public override bool Verify(byte[] input, byte[] signature)
var r = new BigInteger(rBytes);
var s = new BigInteger(sBytes);
- // Reject the signature if 0 < r < q or 0 < s < q is not satisfied.
+ // Reject the signature if 0 < r < q or 0 < s < q is not satisfied.
if (r <= 0 || r >= _key.Q)
+ {
return false;
+ }
if (s <= 0 || s >= _key.Q)
+ {
return false;
+ }
- // Calculate w = s−1 mod q
+ // Calculate w = s−1 mod q
var w = BigInteger.ModInverse(s, _key.Q);
- // Calculate u1 = H(m)·w mod q
- var u1 = hm * w % _key.Q;
+ // Calculate u1 = H(m)·w mod q
+ var u1 = (hm * w) % _key.Q;
- // Calculate u2 = r * w mod q
- var u2 = r * w % _key.Q;
+ // Calculate u2 = r * w mod q
+ var u2 = (r * w) % _key.Q;
u1 = BigInteger.ModPow(_key.G, u1, _key.P);
u2 = BigInteger.ModPow(_key.Y, u2, _key.P);
- // Calculate v = ((g pow u1 * y pow u2) mod p) mod q
+ // Calculate v = ((g pow u1 * y pow u2) mod p) mod q
var v = ((u1 * u2) % _key.P) % _key.Q;
- // The signature is valid if v = r
+ // The signature is valid if v = r
return v == r;
}
@@ -105,37 +114,40 @@ public override byte[] Sign(byte[] input)
do
{
- BigInteger k = BigInteger.Zero;
+ var k = BigInteger.Zero;
do
{
- // Generate a random per-message value k where 0 < k < q
+ // Generate a random per-message value k where 0 < k < q
var bitLength = _key.Q.BitLength;
if (_key.Q < BigInteger.Zero)
+ {
throw new SshException("Invalid DSA key.");
+ }
while (k <= 0 || k >= _key.Q)
{
k = BigInteger.Random(bitLength);
}
- // Calculate r = ((g pow k) mod p) mod q
+ // Calculate r = ((g pow k) mod p) mod q
r = BigInteger.ModPow(_key.G, k, _key.P) % _key.Q;
- // In the unlikely case that r = 0, start again with a different random k
- } while (r.IsZero);
-
+ // In the unlikely case that r = 0, start again with a different random k
+ }
+ while (r.IsZero);
- // Calculate s = ((k pow −1)(H(m) + x*r)) mod q
- k = (BigInteger.ModInverse(k, _key.Q) * (m + _key.X * r));
+ // Calculate s = ((k pow −1)(H(m) + x*r)) mod q
+ k = BigInteger.ModInverse(k, _key.Q) * (m + (_key.X * r));
s = k % _key.Q;
- // In the unlikely case that s = 0, start again with a different random k
- } while (s.IsZero);
+ // In the unlikely case that s = 0, start again with a different random k
+ }
+ while (s.IsZero);
- // The signature is (r, s)
+ // The signature is (r, s)
var signature = new byte[40];
// issue #1918: pad part with zero's on the left if length is less than 20
@@ -149,27 +161,25 @@ public override byte[] Sign(byte[] input)
return signature;
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -185,14 +195,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~DsaDigitalSignature()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/DsaKey.cs b/src/Renci.SshNet/Security/Cryptography/DsaKey.cs
index 5e9907f7b..b0f915cc0 100644
--- a/src/Renci.SshNet/Security/Cryptography/DsaKey.cs
+++ b/src/Renci.SshNet/Security/Cryptography/DsaKey.cs
@@ -1,68 +1,42 @@
using System;
+
using Renci.SshNet.Common;
using Renci.SshNet.Security.Cryptography;
namespace Renci.SshNet.Security
{
///
- /// Contains DSA private and public key
+ /// Contains DSA private and public key.
///
public class DsaKey : Key, IDisposable
{
+ private DsaDigitalSignature _digitalSignature;
+ private bool _isDisposed;
+
///
/// Gets the P.
///
- public BigInteger P
- {
- get
- {
- return _privateKey[0];
- }
- }
+ public BigInteger P { get; }
///
/// Gets the Q.
///
- public BigInteger Q
- {
- get
- {
- return _privateKey[1];
- }
- }
+ public BigInteger Q { get; }
///
/// Gets the G.
///
- public BigInteger G
- {
- get
- {
- return _privateKey[2];
- }
- }
+ public BigInteger G { get; }
///
/// Gets public key Y.
///
- public BigInteger Y
- {
- get
- {
- return _privateKey[3];
- }
- }
+ public BigInteger Y { get; }
///
/// Gets private key X.
///
- public BigInteger X
- {
- get
- {
- return _privateKey[4];
- }
- }
+ public BigInteger X { get; }
///
/// Gets the length of the key.
@@ -78,27 +52,29 @@ public override int KeyLength
}
}
- private DsaDigitalSignature _digitalSignature;
///
/// Gets the digital signature.
///
- protected override DigitalSignature DigitalSignature
+ protected internal override DigitalSignature DigitalSignature
{
get
{
- if (_digitalSignature == null)
- {
- _digitalSignature = new DsaDigitalSignature(this);
- }
+ _digitalSignature ??= new DsaDigitalSignature(this);
return _digitalSignature;
}
}
///
- /// Gets or sets the public.
+ /// Gets the DSA public key.
///
///
- /// The public.
+ /// An array whose values are:
+ ///
+ /// - 0
+ /// - 1
+ /// - 2
+ /// - 3
+ ///
///
public override BigInteger[] Public
{
@@ -106,32 +82,54 @@ public override BigInteger[] Public
{
return new[] { P, Q, G, Y };
}
- set
- {
- if (value.Length != 4)
- throw new InvalidOperationException("Invalid public key.");
-
- _privateKey = value;
- }
}
///
/// Initializes a new instance of the class.
///
- public DsaKey()
+ /// The encoded public key data.
+ public DsaKey(SshKeyData publicKeyData)
{
- _privateKey = new BigInteger[5];
+ if (publicKeyData is null)
+ {
+ throw new ArgumentNullException(nameof(publicKeyData));
+ }
+
+ if (publicKeyData.Name != "ssh-dss" || publicKeyData.Keys.Length != 4)
+ {
+ throw new ArgumentException($"Invalid DSA public key data. ({publicKeyData.Name}, {publicKeyData.Keys.Length}).", nameof(publicKeyData));
+ }
+
+ P = publicKeyData.Keys[0];
+ Q = publicKeyData.Keys[1];
+ G = publicKeyData.Keys[2];
+ Y = publicKeyData.Keys[3];
}
///
/// Initializes a new instance of the class.
///
- /// DER encoded private key data.
- public DsaKey(byte[] data)
- : base(data)
+ /// DER encoded private key data.
+ public DsaKey(byte[] privateKeyData)
{
- if (_privateKey.Length != 5)
- throw new InvalidOperationException("Invalid private key.");
+ if (privateKeyData is null)
+ {
+ throw new ArgumentNullException(nameof(privateKeyData));
+ }
+
+ var der = new DerData(privateKeyData);
+ _ = der.ReadBigInteger(); // skip version
+
+ P = der.ReadBigInteger();
+ Q = der.ReadBigInteger();
+ G = der.ReadBigInteger();
+ Y = der.ReadBigInteger();
+ X = der.ReadBigInteger();
+
+ if (!der.IsEndOfData)
+ {
+ throw new InvalidOperationException("Invalid private key (expected EOF).");
+ }
}
///
@@ -144,35 +142,32 @@ public DsaKey(byte[] data)
/// The x.
public DsaKey(BigInteger p, BigInteger q, BigInteger g, BigInteger y, BigInteger x)
{
- _privateKey = new BigInteger[5];
- _privateKey[0] = p;
- _privateKey[1] = q;
- _privateKey[2] = g;
- _privateKey[3] = y;
- _privateKey[4] = x;
+ P = p;
+ Q = q;
+ G = g;
+ Y = y;
+ X = x;
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -188,14 +183,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~DsaKey()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/ED25519DigitalSignature.cs b/src/Renci.SshNet/Security/Cryptography/ED25519DigitalSignature.cs
index be68fd481..2d3cdb956 100644
--- a/src/Renci.SshNet/Security/Cryptography/ED25519DigitalSignature.cs
+++ b/src/Renci.SshNet/Security/Cryptography/ED25519DigitalSignature.cs
@@ -10,16 +10,19 @@ namespace Renci.SshNet.Security.Cryptography
public class ED25519DigitalSignature : DigitalSignature, IDisposable
{
private readonly ED25519Key _key;
+ private bool _isDisposed;
///
/// Initializes a new instance of the class.
///
/// The ED25519Key key.
- /// is null.
+ /// is .
public ED25519DigitalSignature(ED25519Key key)
{
- if (key == null)
- throw new ArgumentNullException("key");
+ if (key is null)
+ {
+ throw new ArgumentNullException(nameof(key));
+ }
_key = key;
}
@@ -30,7 +33,7 @@ public ED25519DigitalSignature(ED25519Key key)
/// The input.
/// The signature.
///
- /// true if signature was successfully verified; otherwise false.
+ /// if signature was successfully verified; otherwise .
///
/// Invalid signature.
public override bool Verify(byte[] input, byte[] signature)
@@ -51,27 +54,25 @@ public override byte[] Sign(byte[] input)
return Ed25519.Sign(input, _key.PrivateKey);
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -80,14 +81,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~ED25519DigitalSignature()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Security/Cryptography/ED25519Key.cs b/src/Renci.SshNet/Security/Cryptography/ED25519Key.cs
index 83ac1c8cd..5ee2332c0 100644
--- a/src/Renci.SshNet/Security/Cryptography/ED25519Key.cs
+++ b/src/Renci.SshNet/Security/Cryptography/ED25519Key.cs
@@ -1,43 +1,41 @@
using System;
+
using Renci.SshNet.Common;
-using Renci.SshNet.Security.Cryptography;
using Renci.SshNet.Security.Chaos.NaCl;
+using Renci.SshNet.Security.Cryptography;
namespace Renci.SshNet.Security
{
///
- /// Contains ED25519 private and public key
+ /// Contains ED25519 private and public key.
///
public class ED25519Key : Key, IDisposable
{
private ED25519DigitalSignature _digitalSignature;
-
- private byte[] publicKey = new byte[Ed25519.PublicKeySizeInBytes];
- private byte[] privateKey = new byte[Ed25519.ExpandedPrivateKeySizeInBytes];
+ private bool _isDisposed;
///
- /// Gets the Key String.
+ /// Gets the name of the key.
///
+ ///
+ /// The name of the key.
+ ///
public override string ToString()
{
return "ssh-ed25519";
}
///
- /// Gets or sets the public.
+ /// Gets the Ed25519 public key.
///
///
- /// The public.
+ /// An array with encoded at index 0.
///
public override BigInteger[] Public
{
get
{
- return new BigInteger[] { publicKey.ToBigInteger() };
- }
- set
- {
- publicKey = value[0].ToByteArray().Reverse().TrimLeadingZeros().Pad(Ed25519.PublicKeySizeInBytes);
+ return new BigInteger[] { PublicKey.ToBigInteger2() };
}
}
@@ -51,88 +49,86 @@ public override int KeyLength
{
get
{
- return PublicKey.Length;
+ return PublicKey.Length * 8;
}
}
///
/// Gets the digital signature.
///
- protected override DigitalSignature DigitalSignature
+ protected internal override DigitalSignature DigitalSignature
{
get
{
- if (_digitalSignature == null)
- {
- _digitalSignature = new ED25519DigitalSignature(this);
- }
+ _digitalSignature ??= new ED25519DigitalSignature(this);
return _digitalSignature;
}
}
///
- /// Gets the PublicKey Bytes
+ /// Gets the PublicKey Bytes.
///
- public byte[] PublicKey
- {
- get
- {
- return publicKey;
- }
- }
+ public byte[] PublicKey { get; }
///
- /// Gets the PrivateKey Bytes
+ /// Gets the PrivateKey Bytes.
///
- public byte[] PrivateKey
- {
- get
- {
- return privateKey;
- }
- }
+ public byte[] PrivateKey { get; }
///
/// Initializes a new instance of the class.
///
- public ED25519Key()
+ /// The encoded public key data.
+ public ED25519Key(SshKeyData publicKeyData)
{
+ if (publicKeyData is null)
+ {
+ throw new ArgumentNullException(nameof(publicKeyData));
+ }
+
+ if (publicKeyData.Name != "ssh-ed25519" || publicKeyData.Keys.Length != 1)
+ {
+ throw new ArgumentException($"Invalid Ed25519 public key data ({publicKeyData.Name}, {publicKeyData.Keys.Length}).", nameof(publicKeyData));
+ }
+
+ PublicKey = publicKeyData.Keys[0].ToByteArray().Reverse().TrimLeadingZeros().Pad(Ed25519.PublicKeySizeInBytes);
+ PrivateKey = new byte[Ed25519.ExpandedPrivateKeySizeInBytes];
}
///
/// Initializes a new instance of the class.
///
- /// pk data.
- /// sk data.
- public ED25519Key(byte[] pk, byte[] sk)
+ ///
+ /// The private key data k || ENC(A) as described in RFC 8032.
+ ///
+ public ED25519Key(byte[] privateKeyData)
{
- publicKey = pk.TrimLeadingZeros().Pad(Ed25519.PublicKeySizeInBytes);
var seed = new byte[Ed25519.PrivateKeySeedSizeInBytes];
- Buffer.BlockCopy(sk, 0, seed, 0, seed.Length);
- Ed25519.KeyPairFromSeed(out publicKey, out privateKey, seed);
+ Buffer.BlockCopy(privateKeyData, 0, seed, 0, seed.Length);
+ Ed25519.KeyPairFromSeed(out var publicKey, out var privateKey, seed);
+ PublicKey = publicKey;
+ PrivateKey = privateKey;
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -141,14 +137,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~ED25519Key()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/EcdsaDigitalSignature.cs b/src/Renci.SshNet/Security/Cryptography/EcdsaDigitalSignature.cs
index 38d60966e..74f114341 100644
--- a/src/Renci.SshNet/Security/Cryptography/EcdsaDigitalSignature.cs
+++ b/src/Renci.SshNet/Security/Cryptography/EcdsaDigitalSignature.cs
@@ -1,8 +1,10 @@
-#if FEATURE_ECDSA
-using System;
-using Renci.SshNet.Common;
+using System;
using System.Globalization;
+#if NETFRAMEWORK
using System.Security.Cryptography;
+#endif // NETFRAMEWORK
+
+using Renci.SshNet.Common;
namespace Renci.SshNet.Security.Cryptography
{
@@ -12,16 +14,19 @@ namespace Renci.SshNet.Security.Cryptography
public class EcdsaDigitalSignature : DigitalSignature, IDisposable
{
private readonly EcdsaKey _key;
+ private bool _isDisposed;
///
/// Initializes a new instance of the class.
///
/// The ECDSA key.
- /// is null.
+ /// is .
public EcdsaDigitalSignature(EcdsaKey key)
{
- if (key == null)
- throw new ArgumentNullException("key");
+ if (key is null)
+ {
+ throw new ArgumentNullException(nameof(key));
+ }
_key = key;
}
@@ -32,19 +37,19 @@ public EcdsaDigitalSignature(EcdsaKey key)
/// The input.
/// The signature.
///
- /// true if signature was successfully verified; otherwise false.
+ /// if signature was successfully verified; otherwise .
///
public override bool Verify(byte[] input, byte[] signature)
{
// for 521 sig_size is 132
var sig_size = _key.KeyLength == 521 ? 132 : _key.KeyLength / 4;
var ssh_data = new SshDataSignature(signature, sig_size);
-#if NETSTANDARD2_0
- return _key.Ecdsa.VerifyData(input, ssh_data.Signature, _key.HashAlgorithm);
-#else
+#if NETFRAMEWORK
var ecdsa = (ECDsaCng)_key.Ecdsa;
ecdsa.HashAlgorithm = _key.HashAlgorithm;
return ecdsa.VerifyData(input, ssh_data.Signature);
+#else
+ return _key.Ecdsa.VerifyData(input, ssh_data.Signature, _key.HashAlgorithm);
#endif
}
@@ -57,39 +62,36 @@ public override bool Verify(byte[] input, byte[] signature)
///
public override byte[] Sign(byte[] input)
{
-#if NETSTANDARD2_0
- var signed = _key.Ecdsa.SignData(input, _key.HashAlgorithm);
-#else
+#if NETFRAMEWORK
var ecdsa = (ECDsaCng)_key.Ecdsa;
ecdsa.HashAlgorithm = _key.HashAlgorithm;
var signed = ecdsa.SignData(input);
+#else
+ var signed = _key.Ecdsa.SignData(input, _key.HashAlgorithm);
#endif
- var ssh_data = new SshDataSignature(signed.Length);
- ssh_data.Signature = signed;
+ var ssh_data = new SshDataSignature(signed.Length) { Signature = signed };
return ssh_data.GetBytes();
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -98,92 +100,88 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~EcdsaDigitalSignature()
{
- Dispose(false);
+ Dispose(disposing: false);
}
- #endregion
- }
-
- class SshDataSignature : SshData
- {
- private int _signature_size;
+ private sealed class SshDataSignature : SshData
+ {
+ private readonly int _signature_size;
- private byte[] _signature_r;
- private byte[] _signature_s;
+ private byte[] _signature_r;
+ private byte[] _signature_s;
- public byte[] Signature
- {
- get
+ public byte[] Signature
{
- var signature = new byte[_signature_size];
- Buffer.BlockCopy(_signature_r, 0, signature, 0, _signature_r.Length);
- Buffer.BlockCopy(_signature_s, 0, signature, _signature_r.Length, _signature_s.Length);
- return signature;
+ get
+ {
+ var signature = new byte[_signature_size];
+ Buffer.BlockCopy(_signature_r, 0, signature, 0, _signature_r.Length);
+ Buffer.BlockCopy(_signature_s, 0, signature, _signature_r.Length, _signature_s.Length);
+ return signature;
+ }
+ set
+ {
+ var signed_r = new byte[_signature_size / 2];
+ Buffer.BlockCopy(value, 0, signed_r, 0, signed_r.Length);
+ _signature_r = signed_r.ToBigInteger2().ToByteArray().Reverse();
+
+ var signed_s = new byte[_signature_size / 2];
+ Buffer.BlockCopy(value, signed_r.Length, signed_s, 0, signed_s.Length);
+ _signature_s = signed_s.ToBigInteger2().ToByteArray().Reverse();
+ }
}
- set
- {
- var signed_r = new byte[_signature_size / 2];
- Buffer.BlockCopy(value, 0, signed_r, 0, signed_r.Length);
- _signature_r = signed_r.ToBigInteger2().ToByteArray().Reverse();
- var signed_s = new byte[_signature_size / 2];
- Buffer.BlockCopy(value, signed_r.Length, signed_s, 0, signed_s.Length);
- _signature_s = signed_s.ToBigInteger2().ToByteArray().Reverse();
+ public SshDataSignature(int sig_size)
+ {
+ _signature_size = sig_size;
}
- }
- public SshDataSignature(int sig_size)
- {
- _signature_size = sig_size;
- }
+ public SshDataSignature(byte[] data, int sig_size)
+ {
+ _signature_size = sig_size;
+ Load(data);
+ }
- public SshDataSignature(byte[] data, int sig_size)
- {
- _signature_size = sig_size;
- Load(data);
- }
+ protected override void LoadData()
+ {
+ _signature_r = ReadBinary().TrimLeadingZeros().Pad(_signature_size / 2);
+ _signature_s = ReadBinary().TrimLeadingZeros().Pad(_signature_size / 2);
+ }
- protected override void LoadData()
- {
- _signature_r = ReadBinary().TrimLeadingZeros().Pad(_signature_size / 2);
- _signature_s = ReadBinary().TrimLeadingZeros().Pad(_signature_size / 2);
- }
+ protected override void SaveData()
+ {
+ WriteBinaryString(_signature_r.ToBigInteger2().ToByteArray().Reverse());
+ WriteBinaryString(_signature_s.ToBigInteger2().ToByteArray().Reverse());
+ }
- protected override void SaveData()
- {
- WriteBinaryString(_signature_r.ToBigInteger2().ToByteArray().Reverse());
- WriteBinaryString(_signature_s.ToBigInteger2().ToByteArray().Reverse());
- }
+ public new byte[] ReadBinary()
+ {
+ var length = ReadUInt32();
- public new byte[] ReadBinary()
- {
- var length = ReadUInt32();
+ if (length > int.MaxValue)
+ {
+ throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Strings longer than {0} is not supported.", int.MaxValue));
+ }
- if (length > int.MaxValue)
- {
- throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Strings longer than {0} is not supported.", int.MaxValue));
+ return ReadBytes((int) length);
}
- return ReadBytes((int)length);
- }
-
- protected override int BufferCapacity
- {
- get
+ protected override int BufferCapacity
{
- var capacity = base.BufferCapacity;
- capacity += 4; // r length
- capacity += _signature_r.Length; // signature r
- capacity += 4; // s length
- capacity += _signature_s.Length; // signature s
- return capacity;
+ get
+ {
+ var capacity = base.BufferCapacity;
+ capacity += 4; // r length
+ capacity += _signature_r.Length; // signature r
+ capacity += 4; // s length
+ capacity += _signature_s.Length; // signature s
+ return capacity;
+ }
}
}
}
}
-#endif
\ No newline at end of file
diff --git a/src/Renci.SshNet/Security/Cryptography/EcdsaKey.cs b/src/Renci.SshNet/Security/Cryptography/EcdsaKey.cs
index 58861f020..7898a92c9 100644
--- a/src/Renci.SshNet/Security/Cryptography/EcdsaKey.cs
+++ b/src/Renci.SshNet/Security/Cryptography/EcdsaKey.cs
@@ -1,25 +1,35 @@
-#if FEATURE_ECDSA
-using System;
+using System;
+#if NETFRAMEWORK
+using System.Globalization;
using System.IO;
-using System.Text;
using System.Runtime.InteropServices;
+#endif // NETFRAMEWORK
using System.Security.Cryptography;
+using System.Text;
+
using Renci.SshNet.Common;
using Renci.SshNet.Security.Cryptography;
namespace Renci.SshNet.Security
{
///
- /// Contains ECDSA (ecdsa-sha2-nistp{256,384,521}) private and public key
+ /// Contains ECDSA (ecdsa-sha2-nistp{256,384,521}) private and public key.
///
public class EcdsaKey : Key, IDisposable
{
- internal const string ECDSA_P256_OID_VALUE = "1.2.840.10045.3.1.7"; // Also called nistP256 or secP256r1
- internal const string ECDSA_P384_OID_VALUE = "1.3.132.0.34"; // Also called nistP384 or secP384r1
- internal const string ECDSA_P521_OID_VALUE = "1.3.132.0.35"; // Also called nistP521or secP521r1
+#pragma warning disable SA1310 // Field names should not contain underscore
+ private const string ECDSA_P256_OID_VALUE = "1.2.840.10045.3.1.7"; // Also called nistP256 or secP256r1
+ private const string ECDSA_P384_OID_VALUE = "1.3.132.0.34"; // Also called nistP384 or secP384r1
+ private const string ECDSA_P521_OID_VALUE = "1.3.132.0.35"; // Also called nistP521or secP521r1
+#pragma warning restore SA1310 // Field names should not contain underscore
+
+ private EcdsaDigitalSignature _digitalSignature;
+ private bool _isDisposed;
-#if !NETSTANDARD2_0
- internal enum KeyBlobMagicNumber : int
+#if NETFRAMEWORK
+ private CngKey _key;
+
+ internal enum KeyBlobMagicNumber
{
BCRYPT_ECDSA_PUBLIC_P256_MAGIC = 0x31534345,
BCRYPT_ECDSA_PRIVATE_P256_MAGIC = 0x32534345,
@@ -43,58 +53,60 @@ internal enum KeyBlobMagicNumber : int
internal struct BCRYPT_ECCKEY_BLOB
{
internal KeyBlobMagicNumber Magic;
- internal int cbKey;
+ internal int CbKey;
}
-
- private CngKey key;
#endif
///
- /// Gets the SSH name of the ECDSA Key
+ /// Gets the SSH name of the ECDSA Key.
///
+ ///
+ /// The SSH name of the ECDSA Key.
+ ///
public override string ToString()
{
return string.Format("ecdsa-sha2-nistp{0}", KeyLength);
}
-#if NETSTANDARD2_0
+#if NETFRAMEWORK
///
- /// Gets the HashAlgorithm to use
+ /// Gets the HashAlgorithm to use.
///
- public HashAlgorithmName HashAlgorithm
+ public CngAlgorithm HashAlgorithm
{
get
{
- switch (KeyLength)
+ switch (Ecdsa.KeySize)
{
case 256:
- return HashAlgorithmName.SHA256;
+ return CngAlgorithm.Sha256;
case 384:
- return HashAlgorithmName.SHA384;
+ return CngAlgorithm.Sha384;
case 521:
- return HashAlgorithmName.SHA512;
+ return CngAlgorithm.Sha512;
+ default:
+ throw new SshException("Unknown KeySize: " + Ecdsa.KeySize.ToString(CultureInfo.InvariantCulture));
}
- return HashAlgorithmName.SHA256;
}
}
#else
///
- /// Gets the HashAlgorithm to use
+ /// Gets the HashAlgorithm to use.
///
- public CngAlgorithm HashAlgorithm
+ public HashAlgorithmName HashAlgorithm
{
get
{
- switch (Ecdsa.KeySize)
+ switch (KeyLength)
{
case 256:
- return CngAlgorithm.Sha256;
+ return HashAlgorithmName.SHA256;
case 384:
- return CngAlgorithm.Sha384;
+ return HashAlgorithmName.SHA384;
case 521:
- return CngAlgorithm.Sha512;
+ return HashAlgorithmName.SHA512;
default:
- throw new SshException("Unknown KeySize: " + Ecdsa.KeySize);
+ return HashAlgorithmName.SHA256;
}
}
}
@@ -114,28 +126,25 @@ public override int KeyLength
}
}
- private EcdsaDigitalSignature _digitalSignature;
-
///
/// Gets the digital signature.
///
- protected override DigitalSignature DigitalSignature
+ protected internal override DigitalSignature DigitalSignature
{
get
{
- if (_digitalSignature == null)
- {
- _digitalSignature = new EcdsaDigitalSignature(this);
- }
+ _digitalSignature ??= new EcdsaDigitalSignature(this);
+
return _digitalSignature;
}
}
///
- /// Gets or sets the public.
+ /// Gets the ECDSA public key.
///
///
- /// The public.
+ /// An array with the ASCII-encoded curve identifier (e.g. "nistp256")
+ /// at index 0, and the public curve point Q at index 1.
///
public override BigInteger[] Public
{
@@ -144,39 +153,19 @@ public override BigInteger[] Public
byte[] curve;
byte[] qx;
byte[] qy;
-#if NETSTANDARD2_0
- var parameter = Ecdsa.ExportParameters(false);
- qx = parameter.Q.X;
- qy = parameter.Q.Y;
- switch (parameter.Curve.Oid.FriendlyName)
- {
- case "ECDSA_P256":
- case "nistP256":
- curve = Encoding.ASCII.GetBytes("nistp256");
- break;
- case "ECDSA_P384":
- case "nistP384":
- curve = Encoding.ASCII.GetBytes("nistp384");
- break;
- case "ECDSA_P521":
- case "nistP521":
- curve = Encoding.ASCII.GetBytes("nistp521");
- break;
- default:
- throw new SshException("Unexpected Curve Name: " + parameter.Curve.Oid.FriendlyName);
- }
-#else
- var blob = key.Export(CngKeyBlobFormat.EccPublicBlob);
+#if NETFRAMEWORK
+ var blob = _key.Export(CngKeyBlobFormat.EccPublicBlob);
KeyBlobMagicNumber magic;
using (var br = new BinaryReader(new MemoryStream(blob)))
{
magic = (KeyBlobMagicNumber)br.ReadInt32();
- int cbKey = br.ReadInt32();
+ var cbKey = br.ReadInt32();
qx = br.ReadBytes(cbKey);
qy = br.ReadBytes(cbKey);
}
+#pragma warning disable IDE0010 // Add missing cases
switch (magic)
{
case KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P256_MAGIC:
@@ -191,7 +180,30 @@ public override BigInteger[] Public
default:
throw new SshException("Unexpected Curve Magic: " + magic);
}
+#pragma warning restore IDE0010 // Add missing cases
+#else
+ var parameter = Ecdsa.ExportParameters(includePrivateParameters: false);
+ qx = parameter.Q.X;
+ qy = parameter.Q.Y;
+ switch (parameter.Curve.Oid.FriendlyName)
+ {
+ case "ECDSA_P256":
+ case "nistP256":
+ curve = Encoding.ASCII.GetBytes("nistp256");
+ break;
+ case "ECDSA_P384":
+ case "nistP384":
+ curve = Encoding.ASCII.GetBytes("nistp384");
+ break;
+ case "ECDSA_P521":
+ case "nistP521":
+ curve = Encoding.ASCII.GetBytes("nistp521");
+ break;
+ default:
+ throw new SshException("Unexpected Curve Name: " + parameter.Curve.Oid.FriendlyName);
+ }
#endif
+
// Make ECPoint from x and y
// Prepend 04 (uncompressed format) + qx-bytes + qy-bytes
var q = new byte[1 + qx.Length + qy.Length];
@@ -202,34 +214,47 @@ public override BigInteger[] Public
// returns Curve-Name and x/y as ECPoint
return new[] { new BigInteger(curve.Reverse()), new BigInteger(q.Reverse()) };
}
- set
- {
- var curve_s = Encoding.ASCII.GetString(value[0].ToByteArray().Reverse());
- string curve_oid = GetCurveOid(curve_s);
-
- var publickey = value[1].ToByteArray().Reverse();
- Import(curve_oid, publickey, null);
- }
}
///
- /// Gets ECDsa Object
+ /// Gets the PrivateKey Bytes.
+ ///
+ public byte[] PrivateKey { get; private set; }
+
+ ///
+ /// Gets the object.
///
public ECDsa Ecdsa { get; private set; }
///
/// Initializes a new instance of the class.
///
- public EcdsaKey()
+ /// The encoded public key data.
+ public EcdsaKey(SshKeyData publicKeyData)
{
+ if (publicKeyData is null)
+ {
+ throw new ArgumentNullException(nameof(publicKeyData));
+ }
+
+ if (!publicKeyData.Name.StartsWith("ecdsa-sha2-", StringComparison.Ordinal) || publicKeyData.Keys.Length != 2)
+ {
+ throw new ArgumentException($"Invalid ECDSA public key data. ({publicKeyData.Name}, {publicKeyData.Keys.Length}).", nameof(publicKeyData));
+ }
+
+ var curve_s = Encoding.ASCII.GetString(publicKeyData.Keys[0].ToByteArray().Reverse());
+ var curve_oid = GetCurveOid(curve_s);
+
+ var publickey = publicKeyData.Keys[1].ToByteArray().Reverse();
+ Import(curve_oid, publickey, privatekey: null);
}
///
/// Initializes a new instance of the class.
///
- /// The curve name
- /// Value of publickey
- /// Value of privatekey
+ /// The curve name.
+ /// Value of publickey.
+ /// Value of privatekey.
public EcdsaKey(string curve, byte[] publickey, byte[] privatekey)
{
Import(GetCurveOid(curve), publickey, privatekey);
@@ -242,7 +267,7 @@ public EcdsaKey(string curve, byte[] publickey, byte[] privatekey)
public EcdsaKey(byte[] data)
{
var der = new DerData(data);
- var version = der.ReadBigInteger(); // skip version
+ _ = der.ReadBigInteger(); // skip version
// PrivateKey
var privatekey = der.ReadOctetString().TrimLeadingZeros();
@@ -250,27 +275,39 @@ public EcdsaKey(byte[] data)
// Construct
var s0 = der.ReadByte();
if ((s0 & 0xe0) != 0xa0)
+ {
throw new SshException(string.Format("UnexpectedDER: wanted constructed tag (0xa0-0xbf), got: {0:X}", s0));
+ }
+
var tag = s0 & 0x1f;
if (tag != 0)
+ {
throw new SshException(string.Format("expected tag 0 in DER privkey, got: {0}", tag));
+ }
+
var construct = der.ReadBytes(der.ReadLength()); // object length
// curve OID
- var curve_der = new DerData(construct, true);
+ var curve_der = new DerData(construct, construct: true);
var curve = curve_der.ReadObject();
// Construct
s0 = der.ReadByte();
if ((s0 & 0xe0) != 0xa0)
+ {
throw new SshException(string.Format("UnexpectedDER: wanted constructed tag (0xa0-0xbf), got: {0:X}", s0));
+ }
+
tag = s0 & 0x1f;
if (tag != 1)
+ {
throw new SshException(string.Format("expected tag 1 in DER privkey, got: {0}", tag));
+ }
+
construct = der.ReadBytes(der.ReadLength()); // object length
// PublicKey
- var pubkey_der = new DerData(construct, true);
+ var pubkey_der = new DerData(construct, construct: true);
var pubkey = pubkey_der.ReadBitString().TrimLeadingZeros();
Import(OidByteArrayToString(curve), pubkey, privatekey);
@@ -278,49 +315,43 @@ public EcdsaKey(byte[] data)
private void Import(string curve_oid, byte[] publickey, byte[] privatekey)
{
-#if NETSTANDARD2_0
- var curve = ECCurve.CreateFromValue(curve_oid);
- var parameter = new ECParameters
- {
- Curve = curve
- };
+#if NETFRAMEWORK
+ KeyBlobMagicNumber curve_magic;
- // ECPoint as BigInteger(2)
- var cord_size = (publickey.Length - 1) / 2;
- var qx = new byte[cord_size];
- Buffer.BlockCopy(publickey, 1, qx, 0, qx.Length);
-
- var qy = new byte[cord_size];
- Buffer.BlockCopy(publickey, cord_size + 1, qy, 0, qy.Length);
-
- parameter.Q.X = qx;
- parameter.Q.Y = qy;
-
- if (privatekey != null)
- parameter.D = privatekey.TrimLeadingZeros().Pad(cord_size);
-
- Ecdsa = ECDsa.Create(parameter);
-#else
- var curve_magic = KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_GENERIC_MAGIC;
switch (GetCurveName(curve_oid))
{
case "nistp256":
if (privatekey != null)
+ {
curve_magic = KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P256_MAGIC;
+ }
else
+ {
curve_magic = KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P256_MAGIC;
+ }
+
break;
case "nistp384":
if (privatekey != null)
+ {
curve_magic = KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P384_MAGIC;
+ }
else
+ {
curve_magic = KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P384_MAGIC;
+ }
+
break;
case "nistp521":
if (privatekey != null)
+ {
curve_magic = KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P521_MAGIC;
+ }
else
+ {
curve_magic = KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P521_MAGIC;
+ }
+
break;
default:
throw new SshException("Unknown: " + curve_oid);
@@ -335,14 +366,19 @@ private void Import(string curve_oid, byte[] publickey, byte[] privatekey)
Buffer.BlockCopy(publickey, cord_size + 1, qy, 0, qy.Length);
if (privatekey != null)
+ {
privatekey = privatekey.Pad(cord_size);
+ PrivateKey = privatekey;
+ }
- int headerSize = Marshal.SizeOf(typeof(BCRYPT_ECCKEY_BLOB));
- int blobSize = headerSize + qx.Length + qy.Length;
+ var headerSize = Marshal.SizeOf(typeof(BCRYPT_ECCKEY_BLOB));
+ var blobSize = headerSize + qx.Length + qy.Length;
if (privatekey != null)
+ {
blobSize += privatekey.Length;
+ }
- byte[] blob = new byte[blobSize];
+ var blob = new byte[blobSize];
using (var bw = new BinaryWriter(new MemoryStream(blob)))
{
bw.Write((int)curve_magic);
@@ -350,30 +386,59 @@ private void Import(string curve_oid, byte[] publickey, byte[] privatekey)
bw.Write(qx); // q.x
bw.Write(qy); // q.y
if (privatekey != null)
+ {
bw.Write(privatekey); // d
+ }
+ }
+
+ _key = CngKey.Import(blob, privatekey is null ? CngKeyBlobFormat.EccPublicBlob : CngKeyBlobFormat.EccPrivateBlob);
+
+ Ecdsa = new ECDsaCng(_key);
+#else
+ var curve = ECCurve.CreateFromValue(curve_oid);
+ var parameter = new ECParameters
+ {
+ Curve = curve
+ };
+
+ // ECPoint as BigInteger(2)
+ var cord_size = (publickey.Length - 1) / 2;
+ var qx = new byte[cord_size];
+ Buffer.BlockCopy(publickey, 1, qx, 0, qx.Length);
+
+ var qy = new byte[cord_size];
+ Buffer.BlockCopy(publickey, cord_size + 1, qy, 0, qy.Length);
+
+ parameter.Q.X = qx;
+ parameter.Q.Y = qy;
+
+ if (privatekey != null)
+ {
+ parameter.D = privatekey.TrimLeadingZeros().Pad(cord_size);
+ PrivateKey = parameter.D;
}
- key = CngKey.Import(blob, privatekey == null ? CngKeyBlobFormat.EccPublicBlob : CngKeyBlobFormat.EccPrivateBlob);
- Ecdsa = new ECDsaCng(key);
+ Ecdsa = ECDsa.Create(parameter);
#endif
}
- private string GetCurveOid(string curve_s)
+ private static string GetCurveOid(string curve_s)
{
- switch (curve_s.ToLower())
+ switch (curve_s.ToUpperInvariant())
{
- case "nistp256":
+ case "NISTP256":
return ECDSA_P256_OID_VALUE;
- case "nistp384":
+ case "NISTP384":
return ECDSA_P384_OID_VALUE;
- case "nistp521":
+ case "NISTP521":
return ECDSA_P521_OID_VALUE;
default:
throw new SshException("Unexpected Curve Name: " + curve_s);
}
}
- private string GetCurveName(string oid)
+#if NETFRAMEWORK
+ private static string GetCurveName(string oid)
{
switch (oid)
{
@@ -387,27 +452,29 @@ private string GetCurveName(string oid)
throw new SshException("Unexpected OID: " + oid);
}
}
+#endif // NETFRAMEWORK
- private string OidByteArrayToString(byte[] oid)
+ private static string OidByteArrayToString(byte[] oid)
{
- StringBuilder retVal = new StringBuilder();
+ var retVal = new StringBuilder();
- for (int i = 0; i < oid.Length; i++)
+ for (var i = 0; i < oid.Length; i++)
{
if (i == 0)
{
- int b = oid[0] % 40;
- int a = (oid[0] - b) / 40;
- retVal.AppendFormat("{0}.{1}", a, b);
+ var b = oid[0] % 40;
+ var a = (oid[0] - b) / 40;
+ _ = retVal.AppendFormat("{0}.{1}", a, b);
}
else
{
if (oid[i] < 128)
- retVal.AppendFormat(".{0}", oid[i]);
+ {
+ _ = retVal.AppendFormat(".{0}", oid[i]);
+ }
else
{
- retVal.AppendFormat(".{0}",
- ((oid[i] - 128) * 128) + oid[i + 1]);
+ _ = retVal.AppendFormat(".{0}", ((oid[i] - 128) * 128) + oid[i + 1]);
i++;
}
}
@@ -416,27 +483,25 @@ private string OidByteArrayToString(byte[] oid)
return retVal.ToString();
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -445,15 +510,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~EcdsaKey()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
-#endif
\ No newline at end of file
diff --git a/src/Renci.SshNet/Security/Cryptography/HMACMD5.cs b/src/Renci.SshNet/Security/Cryptography/HMACMD5.cs
index 86b246432..bd9585448 100644
--- a/src/Renci.SshNet/Security/Cryptography/HMACMD5.cs
+++ b/src/Renci.SshNet/Security/Cryptography/HMACMD5.cs
@@ -1,6 +1,4 @@
-#if FEATURE_HMAC_MD5
-
-using System.Security.Cryptography;
+using System.Security.Cryptography;
using Renci.SshNet.Common;
namespace Renci.SshNet.Security.Cryptography
@@ -13,22 +11,29 @@ public class HMACMD5 : System.Security.Cryptography.HMACMD5
private readonly int _hashSize;
///
- /// Initializes a with the specified key.
+ /// Initializes a new instance of the class with the specified key.
///
/// The key.
public HMACMD5(byte[] key)
+#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
: base(key)
+#pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms
{
+#pragma warning disable MA0056 // Do not call overridable members in constructor
_hashSize = base.HashSize;
+#pragma warning restore MA0056 // Do not call overridable members in constructor
}
///
- /// Initializes a with the specified key and size of the computed hash code.
+ /// Initializes a new instance of the class with the specified key
+ /// and size of the computed hash code.
///
/// The key.
/// The size, in bits, of the computed hash code.
public HMACMD5(byte[] key, int hashSize)
+#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
: base(key)
+#pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms
{
_hashSize = hashSize;
}
@@ -52,10 +57,10 @@ public override int HashSize
///
protected override byte[] HashFinal()
{
+#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
var hash = base.HashFinal();
+#pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms
return hash.Take(HashSize / 8);
}
}
}
-
-#endif // FEATURE_HMAC_MD5
diff --git a/src/Renci.SshNet/Security/Cryptography/HMACSHA1.cs b/src/Renci.SshNet/Security/Cryptography/HMACSHA1.cs
index d8f47af12..ca4adfdaf 100644
--- a/src/Renci.SshNet/Security/Cryptography/HMACSHA1.cs
+++ b/src/Renci.SshNet/Security/Cryptography/HMACSHA1.cs
@@ -1,6 +1,5 @@
-#if FEATURE_HMAC_SHA1
+using System.Security.Cryptography;
-using System.Security.Cryptography;
using Renci.SshNet.Common;
namespace Renci.SshNet.Security.Cryptography
@@ -13,22 +12,28 @@ public class HMACSHA1 : System.Security.Cryptography.HMACSHA1
private readonly int _hashSize;
///
- /// Initializes a with the specified key.
+ /// Initializes a new instance of the class with the specified key.
///
/// The key.
public HMACSHA1(byte[] key)
+#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
: base(key)
+#pragma warning restore CA5350 // Do Not Use Weak Cryptographic Algorithms
{
+#pragma warning disable MA0056 // Do not call overridable members in constructor
_hashSize = base.HashSize;
+#pragma warning restore MA0056 // Do not call overridable members in constructor
}
///
- /// Initializes a with the specified key and size of the computed hash code.
+ /// Initializes a new instance of the class with the specified key and size of the computed hash code.
///
/// The key.
/// The size, in bits, of the computed hash code.
public HMACSHA1(byte[] key, int hashSize)
+#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
: base(key)
+#pragma warning restore CA5350 // Do Not Use Weak Cryptographic Algorithms
{
_hashSize = hashSize;
}
@@ -52,10 +57,10 @@ public override int HashSize
///
protected override byte[] HashFinal()
{
+#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
var hash = base.HashFinal();
+#pragma warning restore CA5350 // Do Not Use Weak Cryptographic Algorithms
return hash.Take(HashSize / 8);
}
}
}
-
-#endif // FEATURE_HMAC_SHA1
diff --git a/src/Renci.SshNet/Security/Cryptography/HMACSHA256.cs b/src/Renci.SshNet/Security/Cryptography/HMACSHA256.cs
index cb1c31859..20f752a86 100644
--- a/src/Renci.SshNet/Security/Cryptography/HMACSHA256.cs
+++ b/src/Renci.SshNet/Security/Cryptography/HMACSHA256.cs
@@ -1,6 +1,4 @@
-#if FEATURE_HMAC_SHA256
-
-using System.Security.Cryptography;
+using System.Security.Cryptography;
using Renci.SshNet.Common;
namespace Renci.SshNet.Security.Cryptography
@@ -13,17 +11,20 @@ public class HMACSHA256 : System.Security.Cryptography.HMACSHA256
private readonly int _hashSize;
///
- /// Initializes a with the specified key.
+ /// Initializes a new instance of the class with the specified key.
///
/// The key.
public HMACSHA256(byte[] key)
: base(key)
{
+#pragma warning disable MA0056 // Do not call overridable members in constructor
_hashSize = base.HashSize;
+#pragma warning restore MA0056 // Do not call overridable members in constructor
}
///
- /// Initializes a with the specified key and size of the computed hash code.
+ /// Initializes a new instance of the class with the specified key
+ /// and size of the computed hash code.
///
/// The key.
/// The size, in bits, of the computed hash code.
@@ -50,7 +51,6 @@ public override int HashSize
///
/// The computed hash code.
///
-
protected override byte[] HashFinal()
{
var hash = base.HashFinal();
@@ -58,5 +58,3 @@ protected override byte[] HashFinal()
}
}
}
-
-#endif // FEATURE_HMAC_SHA256
diff --git a/src/Renci.SshNet/Security/Cryptography/HMACSHA384.cs b/src/Renci.SshNet/Security/Cryptography/HMACSHA384.cs
index 142e51ed7..e13d720c8 100644
--- a/src/Renci.SshNet/Security/Cryptography/HMACSHA384.cs
+++ b/src/Renci.SshNet/Security/Cryptography/HMACSHA384.cs
@@ -1,6 +1,4 @@
-#if FEATURE_HMAC_SHA384
-
-using System.Security.Cryptography;
+using System.Security.Cryptography;
using Renci.SshNet.Common;
namespace Renci.SshNet.Security.Cryptography
@@ -13,17 +11,20 @@ public class HMACSHA384 : System.Security.Cryptography.HMACSHA384
private readonly int _hashSize;
///
- /// Initializes a with the specified key.
+ /// Initializes a new instance of the class with the specified key.
///
/// The key.
public HMACSHA384(byte[] key)
: base(key)
{
+#pragma warning disable MA0056 // Do not call overridable members in constructor
_hashSize = base.HashSize;
+#pragma warning restore MA0056 // Do not call overridable members in constructor
}
///
- /// Initializes a with the specified key and size of the computed hash code.
+ /// Initializes a new instance of the class with the specified key
+ /// and size of the computed hash code.
///
/// The key.
/// The size, in bits, of the computed hash code.
@@ -57,5 +58,3 @@ protected override byte[] HashFinal()
}
}
}
-
-#endif // FEATURE_HMAC_SHA384
diff --git a/src/Renci.SshNet/Security/Cryptography/HMACSHA512.cs b/src/Renci.SshNet/Security/Cryptography/HMACSHA512.cs
index a297ed088..8d756efef 100644
--- a/src/Renci.SshNet/Security/Cryptography/HMACSHA512.cs
+++ b/src/Renci.SshNet/Security/Cryptography/HMACSHA512.cs
@@ -1,6 +1,4 @@
-#if FEATURE_HMAC_SHA512
-
-using System.Security.Cryptography;
+using System.Security.Cryptography;
using Renci.SshNet.Common;
namespace Renci.SshNet.Security.Cryptography
@@ -13,17 +11,20 @@ public class HMACSHA512 : System.Security.Cryptography.HMACSHA512
private readonly int _hashSize;
///
- /// Initializes a with the specified key.
+ /// Initializes a new instance of the class with the specified key.
///
/// The key.
public HMACSHA512(byte[] key)
: base(key)
{
+#pragma warning disable MA0056 // Do not call overridable members in constructor
_hashSize = base.HashSize;
+#pragma warning restore MA0056 // Do not call overridable members in constructor
}
///
- /// Initializes a with the specified key and size of the computed hash code.
+ /// Initializes a new instance of the class with the specified key
+ /// and size of the computed hash code.
///
/// The key.
/// The size, in bits, of the computed hash code.
@@ -57,5 +58,3 @@ protected override byte[] HashFinal()
}
}
}
-
-#endif // FEATURE_HMAC_SHA512
diff --git a/src/Renci.SshNet/Security/Cryptography/Key.cs b/src/Renci.SshNet/Security/Cryptography/Key.cs
index c668a66c3..54ecac7e4 100644
--- a/src/Renci.SshNet/Security/Cryptography/Key.cs
+++ b/src/Renci.SshNet/Security/Cryptography/Key.cs
@@ -1,32 +1,25 @@
-using System;
-using System.Collections.Generic;
-using Renci.SshNet.Common;
+using Renci.SshNet.Common;
using Renci.SshNet.Security.Cryptography;
namespace Renci.SshNet.Security
{
///
- /// Base class for asymmetric cipher algorithms
+ /// Base class for asymmetric cipher algorithms.
///
public abstract class Key
{
///
- /// Specifies array of big integers that represent private key
+ /// Gets the default digital signature implementation for this key.
///
- protected BigInteger[] _privateKey;
+ protected internal abstract DigitalSignature DigitalSignature { get; }
///
- /// Gets the key specific digital signature.
- ///
- protected abstract DigitalSignature DigitalSignature { get; }
-
- ///
- /// Gets or sets the public key.
+ /// Gets the public key.
///
///
/// The public.
///
- public abstract BigInteger[] Public { get; set; }
+ public abstract BigInteger[] Public { get; }
///
/// Gets the length of the key.
@@ -37,32 +30,9 @@ public abstract class Key
public abstract int KeyLength { get; }
///
- /// Initializes a new instance of the class.
+ /// Gets or sets the key comment.
///
- /// DER encoded private key data.
- protected Key(byte[] data)
- {
- if (data == null)
- throw new ArgumentNullException("data");
-
- var der = new DerData(data);
- der.ReadBigInteger(); // skip version
-
- var keys = new List();
- while (!der.IsEndOfData)
- {
- keys.Add(der.ReadBigInteger());
- }
-
- _privateKey = keys.ToArray();
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- protected Key()
- {
- }
+ public string Comment { get; set; }
///
/// Signs the specified data with the key.
@@ -81,7 +51,7 @@ public byte[] Sign(byte[] data)
///
/// The data to verify.
/// The signature to verify against.
- /// True is signature was successfully verifies; otherwise false.
+ /// is signature was successfully verifies; otherwise .
public bool VerifySignature(byte[] data, byte[] signature)
{
return DigitalSignature.Verify(data, signature);
diff --git a/src/Renci.SshNet/Security/Cryptography/RsaDigitalSignature.cs b/src/Renci.SshNet/Security/Cryptography/RsaDigitalSignature.cs
index 15ac6c056..00a4898f9 100644
--- a/src/Renci.SshNet/Security/Cryptography/RsaDigitalSignature.cs
+++ b/src/Renci.SshNet/Security/Cryptography/RsaDigitalSignature.cs
@@ -1,6 +1,5 @@
using System;
using System.Security.Cryptography;
-using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
using Renci.SshNet.Security.Cryptography.Ciphers;
@@ -14,13 +13,24 @@ public class RsaDigitalSignature : CipherDigitalSignature, IDisposable
private HashAlgorithm _hash;
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class with the SHA-1 hash algorithm.
///
/// The RSA key.
public RsaDigitalSignature(RsaKey rsaKey)
- : base(new ObjectIdentifier(1, 3, 14, 3, 2, 26), new RsaCipher(rsaKey))
+ : this(rsaKey, HashAlgorithmName.SHA1)
+ {
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The RSA key.
+ /// The hash algorithm to use in the digital signature.
+ public RsaDigitalSignature(RsaKey rsaKey, HashAlgorithmName hashAlgorithmName)
+ : base(ObjectIdentifier.FromHashAlgorithmName(hashAlgorithmName), new RsaCipher(rsaKey))
{
- _hash = CryptoAbstraction.CreateSHA1();
+ _hash = CryptoConfig.CreateFromName(hashAlgorithmName.Name) as HashAlgorithm
+ ?? throw new ArgumentException($"Could not create {nameof(HashAlgorithm)} from `{hashAlgorithmName}`.", nameof(hashAlgorithmName));
}
///
@@ -44,18 +54,20 @@ protected override byte[] Hash(byte[] input)
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -76,7 +88,7 @@ protected virtual void Dispose(bool disposing)
///
~RsaDigitalSignature()
{
- Dispose(false);
+ Dispose(disposing: false);
}
#endregion
diff --git a/src/Renci.SshNet/Security/Cryptography/RsaKey.cs b/src/Renci.SshNet/Security/Cryptography/RsaKey.cs
index 6d8a55534..f342db6c1 100644
--- a/src/Renci.SshNet/Security/Cryptography/RsaKey.cs
+++ b/src/Renci.SshNet/Security/Cryptography/RsaKey.cs
@@ -1,113 +1,92 @@
using System;
+
using Renci.SshNet.Common;
using Renci.SshNet.Security.Cryptography;
namespace Renci.SshNet.Security
{
///
- /// Contains RSA private and public key
+ /// Contains the RSA private and public key.
///
public class RsaKey : Key, IDisposable
{
+ private bool _isDisposed;
+ private RsaDigitalSignature _digitalSignature;
+
///
- /// Gets the modulus.
+ /// Gets the name of the key.
///
- public BigInteger Modulus
+ ///
+ /// The name of the key.
+ ///
+ public override string ToString()
{
- get
- {
- return _privateKey[0];
- }
+ return "ssh-rsa";
}
+ ///
+ /// Gets the modulus.
+ ///
+ ///
+ /// The modulus.
+ ///
+ public BigInteger Modulus { get; }
+
///
/// Gets the exponent.
///
- public BigInteger Exponent
- {
- get
- {
- return _privateKey[1];
- }
- }
+ ///
+ /// The exponent.
+ ///
+ public BigInteger Exponent { get; }
///
/// Gets the D.
///
- public BigInteger D
- {
- get
- {
- if (_privateKey.Length > 2)
- return _privateKey[2];
- return BigInteger.Zero;
- }
- }
+ ///
+ /// The D.
+ ///
+ public BigInteger D { get; }
///
/// Gets the P.
///
- public BigInteger P
- {
- get
- {
- if (_privateKey.Length > 3)
- return _privateKey[3];
- return BigInteger.Zero;
- }
- }
+ ///
+ /// The P.
+ ///
+ public BigInteger P { get; }
///
/// Gets the Q.
///
- public BigInteger Q
- {
- get
- {
- if (_privateKey.Length > 4)
- return _privateKey[4];
- return BigInteger.Zero;
- }
- }
+ ///
+ /// The Q.
+ ///
+ public BigInteger Q { get; }
///
/// Gets the DP.
///
- public BigInteger DP
- {
- get
- {
- if (_privateKey.Length > 5)
- return _privateKey[5];
- return BigInteger.Zero;
- }
- }
+ ///
+ /// The DP.
+ ///
+ public BigInteger DP { get; }
///
/// Gets the DQ.
///
- public BigInteger DQ
- {
- get
- {
- if (_privateKey.Length > 6)
- return _privateKey[6];
- return BigInteger.Zero;
- }
- }
+ ///
+ /// The DQ.
+ ///
+ public BigInteger DQ { get; }
///
/// Gets the inverse Q.
///
- public BigInteger InverseQ
- {
- get
- {
- if (_privateKey.Length > 7)
- return _privateKey[7];
- return BigInteger.Zero;
- }
- }
+ ///
+ /// The inverse Q.
+ ///
+ public BigInteger InverseQ { get; }
///
/// Gets the length of the key.
@@ -123,27 +102,28 @@ public override int KeyLength
}
}
- private RsaDigitalSignature _digitalSignature;
///
- /// Gets the digital signature.
+ /// Gets the digital signature implementation for this key.
///
- protected override DigitalSignature DigitalSignature
+ ///
+ /// An implementation of an RSA digital signature using the SHA-1 hash algorithm.
+ ///
+ protected internal override DigitalSignature DigitalSignature
{
get
{
- if (_digitalSignature == null)
- {
- _digitalSignature = new RsaDigitalSignature(this);
- }
+ _digitalSignature ??= new RsaDigitalSignature(this);
+
return _digitalSignature;
}
}
///
- /// Gets or sets the public.
+ /// Gets the RSA public key.
///
///
- /// The public.
+ /// An array with at index 0, and
+ /// at index 1.
///
public override BigInteger[] Public
{
@@ -151,32 +131,55 @@ public override BigInteger[] Public
{
return new[] { Exponent, Modulus };
}
- set
- {
- if (value.Length != 2)
- throw new InvalidOperationException("Invalid private key.");
-
- _privateKey = new[] { value[1], value[0] };
- }
}
///
/// Initializes a new instance of the class.
///
- public RsaKey()
+ /// The encoded public key data.
+ public RsaKey(SshKeyData publicKeyData)
{
+ if (publicKeyData is null)
+ {
+ throw new ArgumentNullException(nameof(publicKeyData));
+ }
+ if (publicKeyData.Name != "ssh-rsa" || publicKeyData.Keys.Length != 2)
+ {
+ throw new ArgumentException($"Invalid RSA public key data. ({publicKeyData.Name}, {publicKeyData.Keys.Length}).", nameof(publicKeyData));
+ }
+
+ Exponent = publicKeyData.Keys[0];
+ Modulus = publicKeyData.Keys[1];
}
///
/// Initializes a new instance of the class.
///
- /// DER encoded private key data.
- public RsaKey(byte[] data)
- : base(data)
+ /// DER encoded private key data.
+ public RsaKey(byte[] privateKeyData)
{
- if (_privateKey.Length != 8)
- throw new InvalidOperationException("Invalid private key.");
+ if (privateKeyData is null)
+ {
+ throw new ArgumentNullException(nameof(privateKeyData));
+ }
+
+ var der = new DerData(privateKeyData);
+ _ = der.ReadBigInteger(); // skip version
+
+ Modulus = der.ReadBigInteger();
+ Exponent = der.ReadBigInteger();
+ D = der.ReadBigInteger();
+ P = der.ReadBigInteger();
+ Q = der.ReadBigInteger();
+ DP = der.ReadBigInteger();
+ DQ = der.ReadBigInteger();
+ InverseQ = der.ReadBigInteger();
+
+ if (!der.IsEndOfData)
+ {
+ throw new InvalidOperationException("Invalid private key (expected EOF).");
+ }
}
///
@@ -190,44 +193,41 @@ public RsaKey(byte[] data)
/// The inverse Q.
public RsaKey(BigInteger modulus, BigInteger exponent, BigInteger d, BigInteger p, BigInteger q, BigInteger inverseQ)
{
- _privateKey = new BigInteger[8];
- _privateKey[0] = modulus;
- _privateKey[1] = exponent;
- _privateKey[2] = d;
- _privateKey[3] = p;
- _privateKey[4] = q;
- _privateKey[5] = PrimeExponent(d, p);
- _privateKey[6] = PrimeExponent(d, q);
- _privateKey[7] = inverseQ;
+ Modulus = modulus;
+ Exponent = exponent;
+ D = d;
+ P = p;
+ Q = q;
+ DP = PrimeExponent(d, p);
+ DQ = PrimeExponent(d, q);
+ InverseQ = inverseQ;
}
private static BigInteger PrimeExponent(BigInteger privateExponent, BigInteger prime)
{
- BigInteger pe = prime - new BigInteger(1);
+ var pe = prime - BigInteger.One;
return privateExponent % pe;
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -248,9 +248,7 @@ protected virtual void Dispose(bool disposing)
///
~RsaKey()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/Security/Cryptography/StreamCipher.cs b/src/Renci.SshNet/Security/Cryptography/StreamCipher.cs
index 1f1c2cad9..c8ebfdd8a 100644
--- a/src/Renci.SshNet/Security/Cryptography/StreamCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/StreamCipher.cs
@@ -11,7 +11,7 @@ public abstract class StreamCipher : SymmetricCipher
/// Initializes a new instance of the class.
///
/// The key.
- /// is null.
+ /// is .
protected StreamCipher(byte[] key)
: base(key)
{
diff --git a/src/Renci.SshNet/Security/Cryptography/SymmetricCipher.cs b/src/Renci.SshNet/Security/Cryptography/SymmetricCipher.cs
index a1c8a2a90..33140bd9c 100644
--- a/src/Renci.SshNet/Security/Cryptography/SymmetricCipher.cs
+++ b/src/Renci.SshNet/Security/Cryptography/SymmetricCipher.cs
@@ -16,11 +16,13 @@ public abstract class SymmetricCipher : Cipher
/// Initializes a new instance of the class.
///
/// The key.
- /// is null.
+ /// is .
protected SymmetricCipher(byte[] key)
{
- if (key == null)
- throw new ArgumentNullException("key");
+ if (key is null)
+ {
+ throw new ArgumentNullException(nameof(key));
+ }
Key = key;
}
diff --git a/src/Renci.SshNet/Security/GroupExchangeHashData.cs b/src/Renci.SshNet/Security/GroupExchangeHashData.cs
index 12b5fbf11..921841094 100644
--- a/src/Renci.SshNet/Security/GroupExchangeHashData.cs
+++ b/src/Renci.SshNet/Security/GroupExchangeHashData.cs
@@ -3,7 +3,7 @@
namespace Renci.SshNet.Security
{
- internal class GroupExchangeHashData : SshData
+ internal sealed class GroupExchangeHashData : SshData
{
private byte[] _serverVersion;
private byte[] _clientVersion;
@@ -16,7 +16,6 @@ public string ServerVersion
set { _serverVersion = Utf8.GetBytes(value); }
}
-
public string ClientVersion
{
private get { return Utf8.GetString(_clientVersion, 0, _clientVersion.Length); }
diff --git a/src/Renci.SshNet/Security/HostAlgorithm.cs b/src/Renci.SshNet/Security/HostAlgorithm.cs
index a087a89ec..4d2c035b4 100644
--- a/src/Renci.SshNet/Security/HostAlgorithm.cs
+++ b/src/Renci.SshNet/Security/HostAlgorithm.cs
@@ -36,7 +36,7 @@ protected HostAlgorithm(string name)
///
/// The data.
/// The signature.
- /// True is signature was successfully verifies; otherwise false.
+ /// is signature was successfully verifies; otherwise .
public abstract bool VerifySignature(byte[] data, byte[] signature);
}
}
diff --git a/src/Renci.SshNet/Security/IKeyExchange.cs b/src/Renci.SshNet/Security/IKeyExchange.cs
index b6f9bb080..7ffd2f465 100644
--- a/src/Renci.SshNet/Security/IKeyExchange.cs
+++ b/src/Renci.SshNet/Security/IKeyExchange.cs
@@ -1,5 +1,6 @@
using System;
using System.Security.Cryptography;
+
using Renci.SshNet.Common;
using Renci.SshNet.Compression;
using Renci.SshNet.Messages.Transport;
@@ -37,8 +38,9 @@ public interface IKeyExchange : IDisposable
/// Starts the key exchange algorithm.
///
/// The session.
- /// Key exchange init message.
- void Start(Session session, KeyExchangeInitMessage message);
+ /// The key exchange init message received from the server.
+ /// Whether to send a key exchange init message in response.
+ void Start(Session session, KeyExchangeInitMessage message, bool sendClientInitMessage);
///
/// Finishes the key exchange algorithm.
diff --git a/src/Renci.SshNet/Security/KeyExchange.cs b/src/Renci.SshNet/Security/KeyExchange.cs
index a13c272a6..f01a4b117 100644
--- a/src/Renci.SshNet/Security/KeyExchange.cs
+++ b/src/Renci.SshNet/Security/KeyExchange.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
+
using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
using Renci.SshNet.Compression;
@@ -12,7 +13,7 @@
namespace Renci.SshNet.Security
{
///
- /// Represents base class for different key exchange algorithm implementations
+ /// Represents base class for different key exchange algorithm implementations.
///
public abstract class KeyExchange : Algorithm, IKeyExchange
{
@@ -24,7 +25,7 @@ public abstract class KeyExchange : Algorithm, IKeyExchange
private Type _decompressionType;
///
- /// Gets or sets the session.
+ /// Gets the session.
///
///
/// The session.
@@ -49,10 +50,8 @@ public byte[] ExchangeHash
{
get
{
- if (_exchangeHash == null)
- {
- _exchangeHash = CalculateHash();
- }
+ _exchangeHash ??= CalculateHash();
+
return _exchangeHash;
}
}
@@ -62,18 +61,17 @@ public byte[] ExchangeHash
///
public event EventHandler HostKeyReceived;
- ///
- /// Starts key exchange algorithm
- ///
- /// The session.
- /// Key exchange init message.
- public virtual void Start(Session session, KeyExchangeInitMessage message)
+ ///
+ public virtual void Start(Session session, KeyExchangeInitMessage message, bool sendClientInitMessage)
{
Session = session;
- SendMessage(session.ClientInitMessage);
+ if (sendClientInitMessage)
+ {
+ SendMessage(session.ClientInitMessage);
+ }
- // Determine encryption algorithm
+ // Determine encryption algorithm
var clientEncryptionAlgorithmName = (from b in session.ConnectionInfo.Encryptions.Keys
from a in message.EncryptionAlgorithmsClientToServer
where a == b
@@ -86,7 +84,7 @@ from a in message.EncryptionAlgorithmsClientToServer
session.ConnectionInfo.CurrentClientEncryption = clientEncryptionAlgorithmName;
- // Determine encryption algorithm
+ // Determine encryption algorithm
var serverDecryptionAlgorithmName = (from b in session.ConnectionInfo.Encryptions.Keys
from a in message.EncryptionAlgorithmsServerToClient
where a == b
@@ -98,7 +96,7 @@ from a in message.EncryptionAlgorithmsServerToClient
session.ConnectionInfo.CurrentServerEncryption = serverDecryptionAlgorithmName;
- // Determine client hmac algorithm
+ // Determine client hmac algorithm
var clientHmacAlgorithmName = (from b in session.ConnectionInfo.HmacAlgorithms.Keys
from a in message.MacAlgorithmsClientToServer
where a == b
@@ -110,7 +108,7 @@ from a in message.MacAlgorithmsClientToServer
session.ConnectionInfo.CurrentClientHmacAlgorithm = clientHmacAlgorithmName;
- // Determine server hmac algorithm
+ // Determine server hmac algorithm
var serverHmacAlgorithmName = (from b in session.ConnectionInfo.HmacAlgorithms.Keys
from a in message.MacAlgorithmsServerToClient
where a == b
@@ -122,7 +120,7 @@ from a in message.MacAlgorithmsServerToClient
session.ConnectionInfo.CurrentServerHmacAlgorithm = serverHmacAlgorithmName;
- // Determine compression algorithm
+ // Determine compression algorithm
var compressionAlgorithmName = (from b in session.ConnectionInfo.CompressionAlgorithms.Keys
from a in message.CompressionAlgorithmsClientToServer
where a == b
@@ -134,7 +132,7 @@ from a in message.CompressionAlgorithmsClientToServer
session.ConnectionInfo.CurrentClientCompressionAlgorithm = compressionAlgorithmName;
- // Determine decompression algorithm
+ // Determine decompression algorithm
var decompressionAlgorithmName = (from b in session.ConnectionInfo.CompressionAlgorithms.Keys
from a in message.CompressionAlgorithmsServerToClient
where a == b
@@ -159,15 +157,12 @@ from a in message.CompressionAlgorithmsServerToClient
///
public virtual void Finish()
{
- // Validate hash
- if (ValidateExchangeHash())
- {
- SendMessage(new NewKeysMessage());
- }
- else
+ if (!ValidateExchangeHash())
{
throw new SshConnectionException("Key exchange negotiation failed.", DisconnectReason.KeyExchangeFailed);
}
+
+ SendMessage(new NewKeysMessage());
}
///
@@ -176,24 +171,22 @@ public virtual void Finish()
/// Server cipher.
public Cipher CreateServerCipher()
{
- // Resolve Session ID
+ // Resolve Session ID
var sessionId = Session.SessionId ?? ExchangeHash;
- // Calculate server to client initial IV
+ // Calculate server to client initial IV
var serverVector = Hash(GenerateSessionKey(SharedKey, ExchangeHash, 'B', sessionId));
- // Calculate server to client encryption
+ // Calculate server to client encryption
var serverKey = Hash(GenerateSessionKey(SharedKey, ExchangeHash, 'D', sessionId));
serverKey = GenerateSessionKey(SharedKey, ExchangeHash, serverKey, _serverCipherInfo.KeySize / 8);
- DiagnosticAbstraction.Log(string.Format("[{0}] Creating server cipher (Name:{1},Key:{2},IV:{3})",
+ DiagnosticAbstraction.Log(string.Format("[{0}] Creating {1} server cipher.",
Session.ToHex(Session.SessionId),
- Session.ConnectionInfo.CurrentServerEncryption,
- Session.ToHex(serverKey),
- Session.ToHex(serverVector)));
+ Session.ConnectionInfo.CurrentServerEncryption));
- // Create server cipher
+ // Create server cipher
return _serverCipherInfo.Cipher(serverKey, serverVector);
}
@@ -203,63 +196,87 @@ public Cipher CreateServerCipher()
/// Client cipher.
public Cipher CreateClientCipher()
{
- // Resolve Session ID
+ // Resolve Session ID
var sessionId = Session.SessionId ?? ExchangeHash;
- // Calculate client to server initial IV
+ // Calculate client to server initial IV
var clientVector = Hash(GenerateSessionKey(SharedKey, ExchangeHash, 'A', sessionId));
- // Calculate client to server encryption
+ // Calculate client to server encryption
var clientKey = Hash(GenerateSessionKey(SharedKey, ExchangeHash, 'C', sessionId));
clientKey = GenerateSessionKey(SharedKey, ExchangeHash, clientKey, _clientCipherInfo.KeySize / 8);
- // Create client cipher
+ DiagnosticAbstraction.Log(string.Format("[{0}] Creating {1} client cipher.",
+ Session.ToHex(Session.SessionId),
+ Session.ConnectionInfo.CurrentClientEncryption));
+
+ // Create client cipher
return _clientCipherInfo.Cipher(clientKey, clientVector);
}
///
/// Creates the server side hash algorithm to use.
///
- /// Hash algorithm
+ ///
+ /// The server-side hash algorithm.
+ ///
public HashAlgorithm CreateServerHash()
{
- // Resolve Session ID
+ // Resolve Session ID
var sessionId = Session.SessionId ?? ExchangeHash;
- var serverKey = Hash(GenerateSessionKey(SharedKey, ExchangeHash, 'F', sessionId));
+ var serverKey = GenerateSessionKey(SharedKey,
+ ExchangeHash,
+ Hash(GenerateSessionKey(SharedKey, ExchangeHash, 'F', sessionId)),
+ _serverHashInfo.KeySize / 8);
- serverKey = GenerateSessionKey(SharedKey, ExchangeHash, serverKey, _serverHashInfo.KeySize / 8);
+ DiagnosticAbstraction.Log(string.Format("[{0}] Creating {1} server hmac algorithm.",
+ Session.ToHex(Session.SessionId),
+ Session.ConnectionInfo.CurrentServerHmacAlgorithm));
- //return serverHMac;
return _serverHashInfo.HashAlgorithm(serverKey);
}
///
/// Creates the client side hash algorithm to use.
///
- /// Hash algorithm
+ ///
+ /// The client-side hash algorithm.
+ ///
public HashAlgorithm CreateClientHash()
{
- // Resolve Session ID
+ // Resolve Session ID
var sessionId = Session.SessionId ?? ExchangeHash;
- var clientKey = Hash(GenerateSessionKey(SharedKey, ExchangeHash, 'E', sessionId));
-
- clientKey = GenerateSessionKey(SharedKey, ExchangeHash, clientKey, _clientHashInfo.KeySize / 8);
+ var clientKey = GenerateSessionKey(SharedKey,
+ ExchangeHash,
+ Hash(GenerateSessionKey(SharedKey, ExchangeHash, 'E', sessionId)),
+ _clientHashInfo.KeySize / 8);
+
+ DiagnosticAbstraction.Log(string.Format("[{0}] Creating {1} client hmac algorithm.",
+ Session.ToHex(Session.SessionId),
+ Session.ConnectionInfo.CurrentClientHmacAlgorithm));
- //return clientHMac;
return _clientHashInfo.HashAlgorithm(clientKey);
}
///
/// Creates the compression algorithm to use to deflate data.
///
- /// Compression method.
+ ///
+ /// The compression method.
+ ///
public Compressor CreateCompressor()
{
- if (_compressionType == null)
+ if (_compressionType is null)
+ {
return null;
+ }
+
+ DiagnosticAbstraction.Log(string.Format("[{0}] Creating {1} client compressor.",
+ Session.ToHex(Session.SessionId),
+ Session.ConnectionInfo.CurrentClientCompressionAlgorithm));
var compressor = _compressionType.CreateInstance();
@@ -271,11 +288,19 @@ public Compressor CreateCompressor()
///
/// Creates the compression algorithm to use to inflate data.
///
- /// Compression method.
+ ///
+ /// The decompression method.
+ ///
public Compressor CreateDecompressor()
{
- if (_compressionType == null)
+ if (_decompressionType is null)
+ {
return null;
+ }
+
+ DiagnosticAbstraction.Log(string.Format("[{0}] Creating {1} server decompressor.",
+ Session.ToHex(Session.SessionId),
+ Session.ConnectionInfo.CurrentServerCompressionAlgorithm));
var decompressor = _decompressionType.CreateInstance();
@@ -289,7 +314,7 @@ public Compressor CreateDecompressor()
///
/// The host algorithm.
///
- /// true if the specified host can be trusted; otherwise, false.
+ /// if the specified host can be trusted; otherwise, .
///
protected bool CanTrustHostKey(KeyHostAlgorithm host)
{
@@ -310,6 +335,28 @@ protected bool CanTrustHostKey(KeyHostAlgorithm host)
/// true if exchange hash is valid; otherwise false.
protected abstract bool ValidateExchangeHash();
+ private protected bool ValidateExchangeHash(byte[] encodedKey, byte[] encodedSignature)
+ {
+ var exchangeHash = CalculateHash();
+
+ var signatureData = new KeyHostAlgorithm.SignatureKeyData();
+ signatureData.Load(encodedSignature);
+
+ var keyAlgorithm = Session.ConnectionInfo.HostKeyAlgorithms[signatureData.AlgorithmName](encodedKey);
+
+ Session.ConnectionInfo.CurrentHostKeyAlgorithm = signatureData.AlgorithmName;
+
+ if (CanTrustHostKey(keyAlgorithm))
+ {
+ // keyAlgorithm.VerifySignature decodes the signature data before verifying.
+ // But as we have already decoded the data to find the signature algorithm,
+ // we just verify the decoded data directly through the DigitalSignature.
+ return keyAlgorithm.DigitalSignature.Verify(exchangeHash, signatureData.Signature);
+ }
+
+ return false;
+ }
+
///
/// Calculates key exchange hash value.
///
@@ -321,12 +368,12 @@ protected bool CanTrustHostKey(KeyHostAlgorithm host)
///
/// The hash data.
///
- /// Hashed bytes
+ /// The hash of the data.
///
protected abstract byte[] Hash(byte[] hashData);
///
- /// Sends SSH message to the server
+ /// Sends SSH message to the server.
///
/// The message.
protected void SendMessage(Message message)
@@ -341,7 +388,9 @@ protected void SendMessage(Message message)
/// The exchange hash.
/// The key.
/// The size.
- ///
+ ///
+ /// The session key.
+ ///
private byte[] GenerateSessionKey(byte[] sharedKey, byte[] exchangeHash, byte[] key, int size)
{
var result = new List(key);
@@ -368,7 +417,9 @@ private byte[] GenerateSessionKey(byte[] sharedKey, byte[] exchangeHash, byte[]
/// The exchange hash.
/// The p.
/// The session id.
- ///
+ ///
+ /// The session key.
+ ///
private static byte[] GenerateSessionKey(byte[] sharedKey, byte[] exchangeHash, char p, byte[] sessionId)
{
var sessionKeyGeneration = new SessionKeyGeneration
@@ -381,7 +432,7 @@ private static byte[] GenerateSessionKey(byte[] sharedKey, byte[] exchangeHash,
return sessionKeyGeneration.GetBytes();
}
- private class SessionKeyGeneration : SshData
+ private sealed class SessionKeyGeneration : SshData
{
public byte[] SharedKey { get; set; }
@@ -425,7 +476,7 @@ protected override void SaveData()
}
}
- private class SessionKeyAdjustment : SshData
+ private sealed class SessionKeyAdjustment : SshData
{
public byte[] SharedKey { get; set; }
@@ -472,14 +523,14 @@ protected override void SaveData()
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
}
@@ -490,7 +541,7 @@ protected virtual void Dispose(bool disposing)
///
~KeyExchange()
{
- Dispose(false);
+ Dispose(disposing: false);
}
#endregion
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellman.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellman.cs
index 375c3a59d..7dfc51e34 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellman.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellman.cs
@@ -1,15 +1,16 @@
using System;
-using System.Text;
-using Renci.SshNet.Messages.Transport;
+
using Renci.SshNet.Common;
+using Renci.SshNet.Messages.Transport;
namespace Renci.SshNet.Security
{
///
- /// Represents base class for Diffie Hellman key exchange algorithm
+ /// Represents base class for Diffie Hellman key exchange algorithm.
///
internal abstract class KeyExchangeDiffieHellman : KeyExchange
{
+#pragma warning disable SA1401 // Fields should be private
///
/// Specifies key exchange group number.
///
@@ -21,12 +22,12 @@ internal abstract class KeyExchangeDiffieHellman : KeyExchange
protected BigInteger _prime;
///
- /// Specifies client payload
+ /// Specifies client payload.
///
protected byte[] _clientPayload;
///
- /// Specifies server payload
+ /// Specifies server payload.
///
protected byte[] _serverPayload;
@@ -54,6 +55,7 @@ internal abstract class KeyExchangeDiffieHellman : KeyExchange
/// Specifies signature data.
///
protected byte[] _signature;
+#pragma warning restore SA1401 // Fields should be private
///
/// Gets the size, in bits, of the computed hash code.
@@ -71,29 +73,13 @@ internal abstract class KeyExchangeDiffieHellman : KeyExchange
///
protected override bool ValidateExchangeHash()
{
- var exchangeHash = CalculateHash();
-
- var length = Pack.BigEndianToUInt32(_hostKey);
- var algorithmName = Encoding.UTF8.GetString(_hostKey, 4, (int)length);
- var key = Session.ConnectionInfo.HostKeyAlgorithms[algorithmName](_hostKey);
-
- Session.ConnectionInfo.CurrentHostKeyAlgorithm = algorithmName;
-
- if (CanTrustHostKey(key))
- {
- return key.VerifySignature(exchangeHash, _signature);
- }
- return false;
+ return ValidateExchangeHash(_hostKey, _signature);
}
- ///
- /// Starts key exchange algorithm
- ///
- /// The session.
- /// Key exchange init message.
- public override void Start(Session session, KeyExchangeInitMessage message)
+ ///
+ public override void Start(Session session, KeyExchangeInitMessage message, bool sendClientInitMessage)
{
- base.Start(session, message);
+ base.Start(session, message, sendClientInitMessage);
_serverPayload = message.GetBytes();
_clientPayload = Session.ClientInitMessage.GetBytes();
@@ -105,10 +91,14 @@ public override void Start(Session session, KeyExchangeInitMessage message)
protected void PopulateClientExchangeValue()
{
if (_group.IsZero)
+ {
throw new ArgumentNullException("_group");
+ }
if (_prime.IsZero)
+ {
throw new ArgumentNullException("_prime");
+ }
// generate private exponent that is twice the hash size (RFC 4419) with a minimum
// of 1024 bits (whatever is less)
@@ -118,11 +108,13 @@ protected void PopulateClientExchangeValue()
do
{
- // create private component
+ // Create private component
_privateExponent = BigInteger.Random(privateExponentSize);
- // generate public component
+
+ // Generate public component
clientExchangeValue = BigInteger.ModPow(_group, _privateExponent, _prime);
- } while (clientExchangeValue < 1 || clientExchangeValue > (_prime - 1));
+ }
+ while (clientExchangeValue < 1 || clientExchangeValue > (_prime - 1));
_clientExchangeValue = clientExchangeValue.ToByteArray().Reverse();
}
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup14Sha1.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup14Sha1.cs
index ec7a237dd..be0bfe745 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup14Sha1.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup14Sha1.cs
@@ -5,10 +5,10 @@ namespace Renci.SshNet.Security
///
/// Represents "diffie-hellman-group14-sha1" algorithm implementation.
///
- internal class KeyExchangeDiffieHellmanGroup14Sha1 : KeyExchangeDiffieHellmanGroupSha1
+ internal sealed class KeyExchangeDiffieHellmanGroup14Sha1 : KeyExchangeDiffieHellmanGroupSha1
{
///
- /// https://tools.ietf.org/html/rfc2409#section-6.2
+ /// Defined in https://tools.ietf.org/html/rfc2409#section-6.2.
///
private static readonly byte[] SecondOkleyGroupReversed =
{
@@ -59,4 +59,4 @@ public override BigInteger GroupPrime
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup14Sha256.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup14Sha256.cs
index 276077a09..9687875e7 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup14Sha256.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup14Sha256.cs
@@ -5,10 +5,10 @@ namespace Renci.SshNet.Security
///
/// Represents "diffie-hellman-group14-sha256" algorithm implementation.
///
- internal class KeyExchangeDiffieHellmanGroup14Sha256 : KeyExchangeDiffieHellmanGroupSha256
+ internal sealed class KeyExchangeDiffieHellmanGroup14Sha256 : KeyExchangeDiffieHellmanGroupSha256
{
///
- /// https://tools.ietf.org/html/rfc2409#section-6.2
+ /// Defined in https://tools.ietf.org/html/rfc2409#section-6.2.
///
private static readonly byte[] SecondOkleyGroupReversed =
{
@@ -59,4 +59,4 @@ public override BigInteger GroupPrime
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup16Sha512.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup16Sha512.cs
index 48f7e178a..ba8403fec 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup16Sha512.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup16Sha512.cs
@@ -5,45 +5,45 @@ namespace Renci.SshNet.Security
///
/// Represents "diffie-hellman-group16-sha512" algorithm implementation.
///
- internal class KeyExchangeDiffieHellmanGroup16Sha512 : KeyExchangeDiffieHellmanGroupSha512
+ internal sealed class KeyExchangeDiffieHellmanGroup16Sha512 : KeyExchangeDiffieHellmanGroupSha512
{
///
- /// https://tools.ietf.org/html/rfc3526#section-5
+ /// Defined in https://tools.ietf.org/html/rfc3526#section-5.
///
private static readonly byte[] MoreModularExponentialGroup16Reversed =
{
- 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x99,0x31,0x06,0x34,0xc9,0x35,0xf4,0x4d,
- 0x8f,0xc0,0xa6,0x90,0xdc,0xb7,0xff,0x86,0xc1,0xdd,0x8f,0x8d,0x98,0xea,0xb4,0x93,
- 0xa9,0x5a,0xb0,0xd5,0x27,0x91,0x06,0xd0,0x1c,0x48,0x70,0x21,0x76,0xdd,0x1b,0xb8,
- 0xaf,0xd7,0xe2,0xce,0x70,0x29,0x61,0x1f,0xed,0xe7,0x5b,0x51,0x86,0xa1,0x3b,0x23,
- 0xa2,0xc3,0x90,0xa0,0x4f,0x96,0xb2,0x99,0x5d,0xc0,0x6b,0x4e,0x47,0x59,0x7c,0x28,
- 0xa6,0xca,0xbe,0x1f,0x14,0xfc,0x8e,0x2e,0xf9,0x8e,0xde,0x04,0xdb,0xc2,0xbb,0xdb,
- 0xe8,0x4c,0xd4,0x2a,0xca,0xe9,0x83,0x25,0xda,0x0b,0x15,0xb6,0x34,0x68,0x94,0x1a,
- 0x3c,0xe2,0xf4,0x6a,0x18,0x27,0xc3,0x99,0x26,0x5b,0xba,0xbd,0x10,0x9a,0x71,0x88,
- 0xd7,0xe6,0x87,0xa7,0x12,0x3c,0x72,0x1a,0x01,0x08,0x21,0xa9,0x20,0xd1,0x82,0x4b,
- 0x8e,0x10,0xfd,0xe0,0xfc,0x5b,0xdb,0x43,0x31,0xab,0xe5,0x74,0xa0,0x4f,0xe2,0x08,
- 0xe2,0x46,0xd9,0xba,0xc0,0x88,0x09,0x77,0x6c,0x5d,0x61,0x7a,0x57,0x17,0xe1,0xbb,
- 0x0c,0x20,0x7b,0x17,0x18,0x2b,0x1f,0x52,0x64,0x6a,0xc8,0x3e,0x73,0x02,0x76,0xd8,
- 0x64,0x08,0x8a,0xd9,0x06,0xfa,0x2f,0xf1,0x6b,0xee,0xd2,0x1a,0x26,0xd2,0xe3,0xce,
- 0x9d,0x61,0x25,0x4a,0xe0,0x94,0x8c,0x1e,0xd7,0x33,0x09,0xdb,0x8c,0xae,0xf5,0xab,
- 0xc7,0xe4,0xe1,0xa6,0x85,0x0f,0x97,0xb3,0x7d,0x0c,0x06,0x5d,0x57,0x71,0xea,0x8a,
- 0x0a,0xef,0xdb,0x58,0x04,0x85,0xfb,0xec,0x64,0xba,0x1c,0xdf,0xab,0x21,0x55,0xa8,
- 0x33,0x7a,0x50,0x04,0x0d,0x17,0x33,0xad,0x2d,0xc4,0xaa,0x8a,0x5a,0x8e,0x72,0x15,
- 0x10,0x05,0xfa,0x98,0x18,0x26,0xd2,0x15,0xe5,0x6a,0x95,0xea,0x7c,0x49,0x95,0x39,
- 0x18,0x17,0x58,0x95,0xf6,0xcb,0x2b,0xde,0xc9,0x52,0x4c,0x6f,0xf0,0x5d,0xc5,0xb5,
- 0x8f,0xa2,0x07,0xec,0xa2,0x83,0x27,0x9b,0x03,0x86,0x0e,0x18,0x2c,0x77,0x9e,0xe3,
- 0x3b,0xce,0x36,0x2e,0x46,0x5e,0x90,0x32,0x7c,0x21,0x18,0xca,0x08,0x6c,0x74,0xf1,
- 0x04,0x98,0xbc,0x4a,0x4e,0x35,0x0c,0x67,0x6d,0x96,0x96,0x70,0x07,0x29,0xd5,0x9e,
- 0xbb,0x52,0x85,0x20,0x56,0xf3,0x62,0x1c,0x96,0xad,0xa3,0xdc,0x23,0x5d,0x65,0x83,
- 0x5f,0xcf,0x24,0xfd,0xa8,0x3f,0x16,0x69,0x9a,0xd3,0x55,0x1c,0x36,0x48,0xda,0x98,
- 0x05,0xbf,0x63,0xa1,0xb8,0x7c,0x00,0xc2,0x3d,0x5b,0xe4,0xec,0x51,0x66,0x28,0x49,
- 0xe6,0x1f,0x4b,0x7c,0x11,0x24,0x9f,0xae,0xa5,0x9f,0x89,0x5a,0xfb,0x6b,0x38,0xee,
- 0xed,0xb7,0x06,0xf4,0xb6,0x5c,0xff,0x0b,0x6b,0xed,0x37,0xa6,0xe9,0x42,0x4c,0xf4,
- 0xc6,0x7e,0x5e,0x62,0x76,0xb5,0x85,0xe4,0x45,0xc2,0x51,0x6d,0x6d,0x35,0xe1,0x4f,
- 0x37,0x14,0x5f,0xf2,0x6d,0x0a,0x2b,0x30,0x1b,0x43,0x3a,0xcd,0xb3,0x19,0x95,0xef,
- 0xdd,0x04,0x34,0x8e,0x79,0x08,0x4a,0x51,0x22,0x9b,0x13,0x3b,0xa6,0xbe,0x0b,0x02,
- 0x74,0xcc,0x67,0x8a,0x08,0x4e,0x02,0x29,0xd1,0x1c,0xdc,0x80,0x8b,0x62,0xc6,0xc4,
- 0x34,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x99, 0x31, 0x06, 0x34, 0xc9, 0x35, 0xf4, 0x4d,
+ 0x8f, 0xc0, 0xa6, 0x90, 0xdc, 0xb7, 0xff, 0x86, 0xc1, 0xdd, 0x8f, 0x8d, 0x98, 0xea, 0xb4, 0x93,
+ 0xa9, 0x5a, 0xb0, 0xd5, 0x27, 0x91, 0x06, 0xd0, 0x1c, 0x48, 0x70, 0x21, 0x76, 0xdd, 0x1b, 0xb8,
+ 0xaf, 0xd7, 0xe2, 0xce, 0x70, 0x29, 0x61, 0x1f, 0xed, 0xe7, 0x5b, 0x51, 0x86, 0xa1, 0x3b, 0x23,
+ 0xa2, 0xc3, 0x90, 0xa0, 0x4f, 0x96, 0xb2, 0x99, 0x5d, 0xc0, 0x6b, 0x4e, 0x47, 0x59, 0x7c, 0x28,
+ 0xa6, 0xca, 0xbe, 0x1f, 0x14, 0xfc, 0x8e, 0x2e, 0xf9, 0x8e, 0xde, 0x04, 0xdb, 0xc2, 0xbb, 0xdb,
+ 0xe8, 0x4c, 0xd4, 0x2a, 0xca, 0xe9, 0x83, 0x25, 0xda, 0x0b, 0x15, 0xb6, 0x34, 0x68, 0x94, 0x1a,
+ 0x3c, 0xe2, 0xf4, 0x6a, 0x18, 0x27, 0xc3, 0x99, 0x26, 0x5b, 0xba, 0xbd, 0x10, 0x9a, 0x71, 0x88,
+ 0xd7, 0xe6, 0x87, 0xa7, 0x12, 0x3c, 0x72, 0x1a, 0x01, 0x08, 0x21, 0xa9, 0x20, 0xd1, 0x82, 0x4b,
+ 0x8e, 0x10, 0xfd, 0xe0, 0xfc, 0x5b, 0xdb, 0x43, 0x31, 0xab, 0xe5, 0x74, 0xa0, 0x4f, 0xe2, 0x08,
+ 0xe2, 0x46, 0xd9, 0xba, 0xc0, 0x88, 0x09, 0x77, 0x6c, 0x5d, 0x61, 0x7a, 0x57, 0x17, 0xe1, 0xbb,
+ 0x0c, 0x20, 0x7b, 0x17, 0x18, 0x2b, 0x1f, 0x52, 0x64, 0x6a, 0xc8, 0x3e, 0x73, 0x02, 0x76, 0xd8,
+ 0x64, 0x08, 0x8a, 0xd9, 0x06, 0xfa, 0x2f, 0xf1, 0x6b, 0xee, 0xd2, 0x1a, 0x26, 0xd2, 0xe3, 0xce,
+ 0x9d, 0x61, 0x25, 0x4a, 0xe0, 0x94, 0x8c, 0x1e, 0xd7, 0x33, 0x09, 0xdb, 0x8c, 0xae, 0xf5, 0xab,
+ 0xc7, 0xe4, 0xe1, 0xa6, 0x85, 0x0f, 0x97, 0xb3, 0x7d, 0x0c, 0x06, 0x5d, 0x57, 0x71, 0xea, 0x8a,
+ 0x0a, 0xef, 0xdb, 0x58, 0x04, 0x85, 0xfb, 0xec, 0x64, 0xba, 0x1c, 0xdf, 0xab, 0x21, 0x55, 0xa8,
+ 0x33, 0x7a, 0x50, 0x04, 0x0d, 0x17, 0x33, 0xad, 0x2d, 0xc4, 0xaa, 0x8a, 0x5a, 0x8e, 0x72, 0x15,
+ 0x10, 0x05, 0xfa, 0x98, 0x18, 0x26, 0xd2, 0x15, 0xe5, 0x6a, 0x95, 0xea, 0x7c, 0x49, 0x95, 0x39,
+ 0x18, 0x17, 0x58, 0x95, 0xf6, 0xcb, 0x2b, 0xde, 0xc9, 0x52, 0x4c, 0x6f, 0xf0, 0x5d, 0xc5, 0xb5,
+ 0x8f, 0xa2, 0x07, 0xec, 0xa2, 0x83, 0x27, 0x9b, 0x03, 0x86, 0x0e, 0x18, 0x2c, 0x77, 0x9e, 0xe3,
+ 0x3b, 0xce, 0x36, 0x2e, 0x46, 0x5e, 0x90, 0x32, 0x7c, 0x21, 0x18, 0xca, 0x08, 0x6c, 0x74, 0xf1,
+ 0x04, 0x98, 0xbc, 0x4a, 0x4e, 0x35, 0x0c, 0x67, 0x6d, 0x96, 0x96, 0x70, 0x07, 0x29, 0xd5, 0x9e,
+ 0xbb, 0x52, 0x85, 0x20, 0x56, 0xf3, 0x62, 0x1c, 0x96, 0xad, 0xa3, 0xdc, 0x23, 0x5d, 0x65, 0x83,
+ 0x5f, 0xcf, 0x24, 0xfd, 0xa8, 0x3f, 0x16, 0x69, 0x9a, 0xd3, 0x55, 0x1c, 0x36, 0x48, 0xda, 0x98,
+ 0x05, 0xbf, 0x63, 0xa1, 0xb8, 0x7c, 0x00, 0xc2, 0x3d, 0x5b, 0xe4, 0xec, 0x51, 0x66, 0x28, 0x49,
+ 0xe6, 0x1f, 0x4b, 0x7c, 0x11, 0x24, 0x9f, 0xae, 0xa5, 0x9f, 0x89, 0x5a, 0xfb, 0x6b, 0x38, 0xee,
+ 0xed, 0xb7, 0x06, 0xf4, 0xb6, 0x5c, 0xff, 0x0b, 0x6b, 0xed, 0x37, 0xa6, 0xe9, 0x42, 0x4c, 0xf4,
+ 0xc6, 0x7e, 0x5e, 0x62, 0x76, 0xb5, 0x85, 0xe4, 0x45, 0xc2, 0x51, 0x6d, 0x6d, 0x35, 0xe1, 0x4f,
+ 0x37, 0x14, 0x5f, 0xf2, 0x6d, 0x0a, 0x2b, 0x30, 0x1b, 0x43, 0x3a, 0xcd, 0xb3, 0x19, 0x95, 0xef,
+ 0xdd, 0x04, 0x34, 0x8e, 0x79, 0x08, 0x4a, 0x51, 0x22, 0x9b, 0x13, 0x3b, 0xa6, 0xbe, 0x0b, 0x02,
+ 0x74, 0xcc, 0x67, 0x8a, 0x08, 0x4e, 0x02, 0x29, 0xd1, 0x1c, 0xdc, 0x80, 0x8b, 0x62, 0xc6, 0xc4,
+ 0x34, 0xc2, 0x68, 0x21, 0xa2, 0xda, 0x0f, 0xc9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x00
};
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup1Sha1.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup1Sha1.cs
index 3a8de7f42..d0ff2c01d 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup1Sha1.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroup1Sha1.cs
@@ -5,7 +5,7 @@ namespace Renci.SshNet.Security
///
/// Represents "diffie-hellman-group1-sha1" algorithm implementation.
///
- internal class KeyExchangeDiffieHellmanGroup1Sha1 : KeyExchangeDiffieHellmanGroupSha1
+ internal sealed class KeyExchangeDiffieHellmanGroup1Sha1 : KeyExchangeDiffieHellmanGroupSha1
{
private static readonly byte[] SecondOkleyGroupReversed =
{
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeSha1.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeSha1.cs
index a7f1b7420..791e2c44b 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeSha1.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeSha1.cs
@@ -5,7 +5,7 @@ namespace Renci.SshNet.Security
///
/// Represents "diffie-hellman-group-exchange-sha1" algorithm implementation.
///
- internal class KeyExchangeDiffieHellmanGroupExchangeSha1 : KeyExchangeDiffieHellmanGroupExchangeShaBase
+ internal sealed class KeyExchangeDiffieHellmanGroupExchangeSha1 : KeyExchangeDiffieHellmanGroupExchangeShaBase
{
///
/// Gets algorithm name.
@@ -31,7 +31,7 @@ protected override int HashSize
///
/// The hash data.
///
- /// Hashed bytes
+ /// The hash of the data.
///
protected override byte[] Hash(byte[] hashData)
{
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeSha256.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeSha256.cs
index dca2de712..2e286345c 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeSha256.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeSha256.cs
@@ -5,7 +5,7 @@ namespace Renci.SshNet.Security
///
/// Represents "diffie-hellman-group-exchange-sha256" algorithm implementation.
///
- internal class KeyExchangeDiffieHellmanGroupExchangeSha256 : KeyExchangeDiffieHellmanGroupExchangeShaBase
+ internal sealed class KeyExchangeDiffieHellmanGroupExchangeSha256 : KeyExchangeDiffieHellmanGroupExchangeShaBase
{
///
/// Gets algorithm name.
@@ -29,15 +29,15 @@ protected override int HashSize
///
/// Hashes the specified data bytes.
///
- /// Data to hash.
+ /// Data to hash.
///
- /// Hashed bytes
+ /// The hash of the data.
///
- protected override byte[] Hash(byte[] hashBytes)
+ protected override byte[] Hash(byte[] hashData)
{
using (var sha256 = CryptoAbstraction.CreateSHA256())
{
- return sha256.ComputeHash(hashBytes);
+ return sha256.ComputeHash(hashData);
}
}
}
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeShaBase.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeShaBase.cs
index 755f77f2e..5774f2c34 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeShaBase.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupExchangeShaBase.cs
@@ -39,17 +39,14 @@ protected override byte[] CalculateHash()
return Hash(groupExchangeHashData.GetBytes());
}
- ///
- /// Starts key exchange algorithm
- ///
- /// The session.
- /// Key exchange init message.
- public override void Start(Session session, KeyExchangeInitMessage message)
+ ///
+ public override void Start(Session session, KeyExchangeInitMessage message, bool sendClientInitMessage)
{
- base.Start(session, message);
+ base.Start(session, message, sendClientInitMessage);
// Register SSH_MSG_KEX_DH_GEX_GROUP message
Session.RegisterMessage("SSH_MSG_KEX_DH_GEX_GROUP");
+
// Subscribe to KeyExchangeDhGroupExchangeGroupReceived events
Session.KeyExchangeDhGroupExchangeGroupReceived += Session_KeyExchangeDhGroupExchangeGroupReceived;
@@ -75,11 +72,13 @@ private void Session_KeyExchangeDhGroupExchangeGroupReceived(object sender, Mess
// Unregister SSH_MSG_KEX_DH_GEX_GROUP message once received
Session.UnRegisterMessage("SSH_MSG_KEX_DH_GEX_GROUP");
+
// Unsubscribe from KeyExchangeDhGroupExchangeGroupReceived events
Session.KeyExchangeDhGroupExchangeGroupReceived -= Session_KeyExchangeDhGroupExchangeGroupReceived;
// Register in order to be able to receive SSH_MSG_KEX_DH_GEX_REPLY message
Session.RegisterMessage("SSH_MSG_KEX_DH_GEX_REPLY");
+
// Subscribe to KeyExchangeDhGroupExchangeReplyReceived events
Session.KeyExchangeDhGroupExchangeReplyReceived += Session_KeyExchangeDhGroupExchangeReplyReceived;
@@ -99,6 +98,7 @@ private void Session_KeyExchangeDhGroupExchangeReplyReceived(object sender, Mess
// Unregister SSH_MSG_KEX_DH_GEX_REPLY message once received
Session.UnRegisterMessage("SSH_MSG_KEX_DH_GEX_REPLY");
+
// Unsubscribe from KeyExchangeDhGroupExchangeReplyReceived events
Session.KeyExchangeDhGroupExchangeReplyReceived -= Session_KeyExchangeDhGroupExchangeReplyReceived;
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha1.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha1.cs
index 675ee2cfe..4669eb8ae 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha1.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha1.cs
@@ -23,7 +23,7 @@ protected override int HashSize
///
/// The hash data.
///
- /// Hashed bytes
+ /// The hash of the data.
///
protected override byte[] Hash(byte[] hashData)
{
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha256.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha256.cs
index 6cb674601..ea29e6e2f 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha256.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha256.cs
@@ -23,7 +23,7 @@ protected override int HashSize
///
/// The hash data.
///
- /// Hashed bytes
+ /// The hash of the data.
///
protected override byte[] Hash(byte[] hashData)
{
@@ -33,4 +33,4 @@ protected override byte[] Hash(byte[] hashData)
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha512.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha512.cs
index 54369b849..60a8e5f7c 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha512.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupSha512.cs
@@ -23,7 +23,7 @@ protected override int HashSize
///
/// The hash data.
///
- /// Hashed bytes
+ /// The hash of the data.
///
protected override byte[] Hash(byte[] hashData)
{
@@ -33,4 +33,4 @@ protected override byte[] Hash(byte[] hashData)
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupShaBase.cs b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupShaBase.cs
index 2618b63ac..b0db30eaa 100644
--- a/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupShaBase.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeDiffieHellmanGroupShaBase.cs
@@ -13,37 +13,10 @@ internal abstract class KeyExchangeDiffieHellmanGroupShaBase : KeyExchangeDiffie
///
public abstract BigInteger GroupPrime { get; }
- ///
- /// Calculates key exchange hash value.
- ///
- ///
- /// Key exchange hash.
- ///
- protected override byte[] CalculateHash()
- {
- var keyExchangeHashData = new KeyExchangeHashData
- {
- ClientVersion = Session.ClientVersion,
- ServerVersion = Session.ServerVersion,
- ClientPayload = _clientPayload,
- ServerPayload = _serverPayload,
- HostKey = _hostKey,
- ClientExchangeValue = _clientExchangeValue,
- ServerExchangeValue = _serverExchangeValue,
- SharedKey = SharedKey,
- };
-
- return Hash(keyExchangeHashData.GetBytes());
- }
-
- ///
- /// Starts key exchange algorithm
- ///
- /// The session.
- /// Key exchange init message.
- public override void Start(Session session, KeyExchangeInitMessage message)
+ ///
+ public override void Start(Session session, KeyExchangeInitMessage message, bool sendClientInitMessage)
{
- base.Start(session, message);
+ base.Start(session, message, sendClientInitMessage);
Session.RegisterMessage("SSH_MSG_KEXDH_REPLY");
@@ -67,16 +40,39 @@ public override void Finish()
Session.KeyExchangeDhReplyMessageReceived -= Session_KeyExchangeDhReplyMessageReceived;
}
+ ///
+ /// Calculates key exchange hash value.
+ ///
+ ///
+ /// Key exchange hash.
+ ///
+ protected override byte[] CalculateHash()
+ {
+ var keyExchangeHashData = new KeyExchangeHashData
+ {
+ ClientVersion = Session.ClientVersion,
+ ServerVersion = Session.ServerVersion,
+ ClientPayload = _clientPayload,
+ ServerPayload = _serverPayload,
+ HostKey = _hostKey,
+ ClientExchangeValue = _clientExchangeValue,
+ ServerExchangeValue = _serverExchangeValue,
+ SharedKey = SharedKey,
+ };
+
+ return Hash(keyExchangeHashData.GetBytes());
+ }
+
private void Session_KeyExchangeDhReplyMessageReceived(object sender, MessageEventArgs e)
{
var message = e.Message;
- // Unregister message once received
+ // Unregister message once received
Session.UnRegisterMessage("SSH_MSG_KEXDH_REPLY");
HandleServerDhReply(message.HostKey, message.F, message.Signature);
- // When SSH_MSG_KEXDH_REPLY received key exchange is completed
+ // When SSH_MSG_KEXDH_REPLY received key exchange is completed
Finish();
}
}
diff --git a/src/Renci.SshNet/Security/KeyExchangeEC.cs b/src/Renci.SshNet/Security/KeyExchangeEC.cs
index 79cdf5be7..8bc61e7fc 100644
--- a/src/Renci.SshNet/Security/KeyExchangeEC.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeEC.cs
@@ -1,18 +1,17 @@
-using System.Text;
-using Renci.SshNet.Messages.Transport;
-using Renci.SshNet.Common;
+using Renci.SshNet.Messages.Transport;
namespace Renci.SshNet.Security
{
internal abstract class KeyExchangeEC : KeyExchange
{
+#pragma warning disable SA1401 // Fields should be private
///
- /// Specifies client payload
+ /// Specifies client payload.
///
protected byte[] _clientPayload;
///
- /// Specifies server payload
+ /// Specifies server payload.
///
protected byte[] _serverPayload;
@@ -35,6 +34,7 @@ internal abstract class KeyExchangeEC : KeyExchange
/// Specifies signature data.
///
protected byte[] _signature;
+#pragma warning restore SA1401 // Fields should be private
///
/// Gets the size, in bits, of the computed hash code.
@@ -75,32 +75,16 @@ protected override byte[] CalculateHash()
///
protected override bool ValidateExchangeHash()
{
- var exchangeHash = CalculateHash();
-
- var length = Pack.BigEndianToUInt32(_hostKey);
- var algorithmName = Encoding.UTF8.GetString(_hostKey, 4, (int)length);
- var key = Session.ConnectionInfo.HostKeyAlgorithms[algorithmName](_hostKey);
-
- Session.ConnectionInfo.CurrentHostKeyAlgorithm = algorithmName;
-
- if (CanTrustHostKey(key))
- {
- return key.VerifySignature(exchangeHash, _signature);
- }
- return false;
+ return ValidateExchangeHash(_hostKey, _signature);
}
- ///
- /// Starts key exchange algorithm
- ///
- /// The session.
- /// Key exchange init message.
- public override void Start(Session session, KeyExchangeInitMessage message)
+ ///
+ public override void Start(Session session, KeyExchangeInitMessage message, bool sendClientInitMessage)
{
- base.Start(session, message);
+ base.Start(session, message, sendClientInitMessage);
_serverPayload = message.GetBytes();
_clientPayload = Session.ClientInitMessage.GetBytes();
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Security/KeyExchangeECCurve25519.cs b/src/Renci.SshNet/Security/KeyExchangeECCurve25519.cs
index b7a318bb9..c6c060bab 100644
--- a/src/Renci.SshNet/Security/KeyExchangeECCurve25519.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeECCurve25519.cs
@@ -6,7 +6,7 @@
namespace Renci.SshNet.Security
{
- internal class KeyExchangeECCurve25519 : KeyExchangeEC
+ internal sealed class KeyExchangeECCurve25519 : KeyExchangeEC
{
private byte[] _privateKey;
@@ -29,14 +29,10 @@ protected override int HashSize
get { return 256; }
}
- ///
- /// Starts key exchange algorithm
- ///
- /// The session.
- /// Key exchange init message.
- public override void Start(Session session, KeyExchangeInitMessage message)
+ ///
+ public override void Start(Session session, KeyExchangeInitMessage message, bool sendClientInitMessage)
{
- base.Start(session, message);
+ base.Start(session, message, sendClientInitMessage);
Session.RegisterMessage("SSH_MSG_KEX_ECDH_REPLY");
@@ -68,7 +64,7 @@ public override void Finish()
///
/// The hash data.
///
- /// Hashed bytes
+ /// The hash of the data.
///
protected override byte[] Hash(byte[] hashData)
{
@@ -82,12 +78,12 @@ private void Session_KeyExchangeEcdhReplyMessageReceived(object sender, MessageE
{
var message = e.Message;
- // Unregister message once received
+ // Unregister message once received
Session.UnRegisterMessage("SSH_MSG_KEX_ECDH_REPLY");
HandleServerEcdhReply(message.KS, message.QS, message.Signature);
- // When SSH_MSG_KEXDH_REPLY received key exchange is completed
+ // When SSH_MSG_KEXDH_REPLY received key exchange is completed
Finish();
}
diff --git a/src/Renci.SshNet/Security/KeyExchangeECDH.cs b/src/Renci.SshNet/Security/KeyExchangeECDH.cs
index f87a5c7e4..c756fb6cb 100644
--- a/src/Renci.SshNet/Security/KeyExchangeECDH.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeECDH.cs
@@ -2,12 +2,12 @@
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Transport;
+using Renci.SshNet.Security.Org.BouncyCastle.Asn1.X9;
+using Renci.SshNet.Security.Org.BouncyCastle.Crypto.Agreement;
using Renci.SshNet.Security.Org.BouncyCastle.Crypto.Generators;
using Renci.SshNet.Security.Org.BouncyCastle.Crypto.Parameters;
-using Renci.SshNet.Security.Org.BouncyCastle.Security;
using Renci.SshNet.Security.Org.BouncyCastle.Math.EC;
-using Renci.SshNet.Security.Org.BouncyCastle.Asn1.X9;
-using Renci.SshNet.Security.Org.BouncyCastle.Crypto.Agreement;
+using Renci.SshNet.Security.Org.BouncyCastle.Security;
namespace Renci.SshNet.Security
{
@@ -21,34 +21,30 @@ internal abstract class KeyExchangeECDH : KeyExchangeEC
///
protected abstract X9ECParameters CurveParameter { get; }
- protected ECDHCBasicAgreement KeyAgreement;
- protected ECDomainParameters DomainParameters;
+ private ECDHCBasicAgreement _keyAgreement;
+ private ECDomainParameters _domainParameters;
- ///
- /// Starts key exchange algorithm
- ///
- /// The session.
- /// Key exchange init message.
- public override void Start(Session session, KeyExchangeInitMessage message)
+ ///
+ public override void Start(Session session, KeyExchangeInitMessage message, bool sendClientInitMessage)
{
- base.Start(session, message);
+ base.Start(session, message, sendClientInitMessage);
Session.RegisterMessage("SSH_MSG_KEX_ECDH_REPLY");
Session.KeyExchangeEcdhReplyMessageReceived += Session_KeyExchangeEcdhReplyMessageReceived;
- DomainParameters = new ECDomainParameters(CurveParameter.Curve,
+ _domainParameters = new ECDomainParameters(CurveParameter.Curve,
CurveParameter.G,
CurveParameter.N,
CurveParameter.H,
CurveParameter.GetSeed());
var g = new ECKeyPairGenerator();
- g.Init(new ECKeyGenerationParameters(DomainParameters, new SecureRandom()));
+ g.Init(new ECKeyGenerationParameters(_domainParameters, new SecureRandom()));
var aKeyPair = g.GenerateKeyPair();
- KeyAgreement = new ECDHCBasicAgreement();
- KeyAgreement.Init(aKeyPair.Private);
+ _keyAgreement = new ECDHCBasicAgreement();
+ _keyAgreement.Init(aKeyPair.Private);
_clientExchangeValue = ((ECPublicKeyParameters)aKeyPair.Public).Q.GetEncoded();
SendMessage(new KeyExchangeEcdhInitMessage(_clientExchangeValue));
@@ -68,12 +64,12 @@ private void Session_KeyExchangeEcdhReplyMessageReceived(object sender, MessageE
{
var message = e.Message;
- // Unregister message once received
+ // Unregister message once received
Session.UnRegisterMessage("SSH_MSG_KEX_ECDH_REPLY");
HandleServerEcdhReply(message.KS, message.QS, message.Signature);
- // When SSH_MSG_KEXDH_REPLY received key exchange is completed
+ // When SSH_MSG_KEXDH_REPLY received key exchange is completed
Finish();
}
@@ -95,11 +91,11 @@ private void HandleServerEcdhReply(byte[] hostKey, byte[] serverExchangeValue, b
var y = new byte[cordSize];
Buffer.BlockCopy(serverExchangeValue, cordSize + 1, y, 0, y.Length);
- var c = (FpCurve)DomainParameters.Curve;
+ var c = (FpCurve)_domainParameters.Curve;
var q = c.CreatePoint(new Org.BouncyCastle.Math.BigInteger(1, x), new Org.BouncyCastle.Math.BigInteger(1, y));
- var publicKey = new ECPublicKeyParameters("ECDH", q, DomainParameters);
+ var publicKey = new ECPublicKeyParameters("ECDH", q, _domainParameters);
- var k1 = KeyAgreement.CalculateAgreement(publicKey);
+ var k1 = _keyAgreement.CalculateAgreement(publicKey);
SharedKey = k1.ToByteArray().ToBigInteger2().ToByteArray().Reverse();
}
}
diff --git a/src/Renci.SshNet/Security/KeyExchangeECDH256.cs b/src/Renci.SshNet/Security/KeyExchangeECDH256.cs
index 8f14d9bd4..b09652de8 100644
--- a/src/Renci.SshNet/Security/KeyExchangeECDH256.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeECDH256.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Security
{
- internal class KeyExchangeECDH256 : KeyExchangeECDH
+ internal sealed class KeyExchangeECDH256 : KeyExchangeECDH
{
///
/// Gets algorithm name.
@@ -41,7 +41,7 @@ protected override int HashSize
///
/// The hash data.
///
- /// Hashed bytes
+ /// The hash of the data.
///
protected override byte[] Hash(byte[] hashData)
{
@@ -51,4 +51,4 @@ protected override byte[] Hash(byte[] hashData)
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Security/KeyExchangeECDH384.cs b/src/Renci.SshNet/Security/KeyExchangeECDH384.cs
index bbd7ced51..cba304305 100644
--- a/src/Renci.SshNet/Security/KeyExchangeECDH384.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeECDH384.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Security
{
- internal class KeyExchangeECDH384 : KeyExchangeECDH
+ internal sealed class KeyExchangeECDH384 : KeyExchangeECDH
{
///
/// Gets algorithm name.
@@ -41,7 +41,7 @@ protected override int HashSize
///
/// The hash data.
///
- /// Hashed bytes
+ /// The hash of the data.
///
protected override byte[] Hash(byte[] hashData)
{
diff --git a/src/Renci.SshNet/Security/KeyExchangeECDH521.cs b/src/Renci.SshNet/Security/KeyExchangeECDH521.cs
index 920089c02..ce5b35515 100644
--- a/src/Renci.SshNet/Security/KeyExchangeECDH521.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeECDH521.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Security
{
- internal class KeyExchangeECDH521 : KeyExchangeECDH
+ internal sealed class KeyExchangeECDH521 : KeyExchangeECDH
{
///
/// Gets algorithm name.
@@ -41,7 +41,7 @@ protected override int HashSize
///
/// The hash data.
///
- /// Hashed bytes
+ /// The hash of the data.
///
protected override byte[] Hash(byte[] hashData)
{
@@ -51,4 +51,4 @@ protected override byte[] Hash(byte[] hashData)
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Security/KeyExchangeHash.cs b/src/Renci.SshNet/Security/KeyExchangeHashData.cs
similarity index 96%
rename from src/Renci.SshNet/Security/KeyExchangeHash.cs
rename to src/Renci.SshNet/Security/KeyExchangeHashData.cs
index e33cb14cc..f91946627 100644
--- a/src/Renci.SshNet/Security/KeyExchangeHash.cs
+++ b/src/Renci.SshNet/Security/KeyExchangeHashData.cs
@@ -1,9 +1,10 @@
-using Renci.SshNet.Common;
-using System;
+using System;
+
+using Renci.SshNet.Common;
namespace Renci.SshNet.Security
{
- internal class KeyExchangeHashData : SshData
+ internal sealed class KeyExchangeHashData : SshData
{
private byte[] _serverVersion;
private byte[] _clientVersion;
diff --git a/src/Renci.SshNet/Security/KeyHostAlgorithm.cs b/src/Renci.SshNet/Security/KeyHostAlgorithm.cs
index ca94fa70e..5611c9713 100644
--- a/src/Renci.SshNet/Security/KeyHostAlgorithm.cs
+++ b/src/Renci.SshNet/Security/KeyHostAlgorithm.cs
@@ -1,5 +1,7 @@
-using System.Collections.Generic;
+using System.Text;
+
using Renci.SshNet.Common;
+using Renci.SshNet.Security.Cryptography;
namespace Renci.SshNet.Security
{
@@ -9,169 +11,100 @@ namespace Renci.SshNet.Security
public class KeyHostAlgorithm : HostAlgorithm
{
///
- /// Gets the key.
+ /// Gets the key used in this host key algorithm.
///
public Key Key { get; private set; }
///
- /// Gets the public key data.
+ /// Gets the signature implementation used in this host key algorithm.
+ ///
+ public DigitalSignature DigitalSignature { get; private set; }
+
+ ///
+ /// Gets the encoded public key data.
///
+ ///
+ /// The encoded public key data.
+ ///
public override byte[] Data
{
get
{
- return new SshKeyData(Name, Key.Public).GetBytes();
+ var keyFormatIdentifier = Key is RsaKey ? "ssh-rsa" : Name;
+ return new SshKeyData(keyFormatIdentifier, Key.Public).GetBytes();
}
}
///
/// Initializes a new instance of the class.
///
- /// Host key name.
- /// Host key.
+ /// The signature format identifier.
+ /// The key used in this host key algorithm.
public KeyHostAlgorithm(string name, Key key)
: base(name)
{
Key = key;
+ DigitalSignature = key.DigitalSignature;
}
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
- /// Host key name.
- /// Host key.
- /// Host key encoded data.
- public KeyHostAlgorithm(string name, Key key, byte[] data)
+ /// The signature format identifier.
+ /// The key used in this host key algorithm.
+ /// The signature implementation used in this host key algorithm.
+ ///
+ /// The key used by is intended to be equal to .
+ /// This is not verified.
+ ///
+ public KeyHostAlgorithm(string name, Key key, DigitalSignature digitalSignature)
: base(name)
{
Key = key;
-
- var sshKey = new SshKeyData();
- sshKey.Load(data);
- Key.Public = sshKey.Keys;
+ DigitalSignature = digitalSignature;
}
///
- /// Signs the specified data.
+ /// Signs and encodes the specified data.
///
- /// The data.
+ /// The data to be signed.
///
- /// Signed data.
+ /// The encoded signature.
///
public override byte[] Sign(byte[] data)
{
- return new SignatureKeyData(Name, Key.Sign(data)).GetBytes();
+ return new SignatureKeyData(Name, DigitalSignature.Sign(data)).GetBytes();
}
///
/// Verifies the signature.
///
- /// The data.
- /// The signature.
+ /// The data to verify the signature against.
+ /// The encoded signature data.
///
- /// True is signature was successfully verifies; otherwise false.
+ /// if is the result of signing
+ /// with the corresponding private key to .
///
public override bool VerifySignature(byte[] data, byte[] signature)
{
var signatureData = new SignatureKeyData();
signatureData.Load(signature);
- return Key.VerifySignature(data, signatureData.Signature);
- }
-
- private class SshKeyData : SshData
- {
- private byte[] _name;
- private List _keys;
-
- public BigInteger[] Keys
- {
- get
- {
- var keys = new BigInteger[_keys.Count];
- for (var i = 0; i < _keys.Count; i++)
- {
- var key = _keys[i];
- keys[i] = key.ToBigInteger2();
- }
- return keys;
- }
- private set
- {
- _keys = new List(value.Length);
- foreach (var key in value)
- {
- _keys.Add(key.ToByteArray().Reverse());
- }
- }
- }
-
- private string Name
- {
- get { return Utf8.GetString(_name, 0, _name.Length); }
- set { _name = Utf8.GetBytes(value); }
- }
-
- protected override int BufferCapacity
- {
- get
- {
- var capacity = base.BufferCapacity;
- capacity += 4; // Name length
- capacity += _name.Length; // Name
- foreach (var key in _keys)
- {
- capacity += 4; // Key length
- capacity += key.Length; // Key
- }
- return capacity;
- }
- }
-
- public SshKeyData()
- {
- }
-
- public SshKeyData(string name, params BigInteger[] keys)
- {
- Name = name;
- Keys = keys;
- }
-
- protected override void LoadData()
- {
- _name = ReadBinary();
- _keys = new List();
-
- while (!IsEndOfData)
- {
- _keys.Add(ReadBinary());
- }
- }
-
- protected override void SaveData()
- {
- WriteBinaryString(_name);
-
- foreach (var key in _keys)
- {
- WriteBinaryString(key);
- }
- }
+ return DigitalSignature.Verify(data, signatureData.Signature);
}
- private class SignatureKeyData : SshData
+ internal sealed class SignatureKeyData : SshData
{
///
- /// Gets or sets the name of the algorithm as UTF-8 encoded byte array.
+ /// Gets or sets the signature format identifier.
///
///
- /// The name of the algorithm.
+ /// The signature format identifier.
///
- private byte[] AlgorithmName { get; set; }
+ public string AlgorithmName { get; set; }
///
- /// Gets or sets the signature.
+ /// Gets the signature.
///
///
/// The signature.
@@ -190,7 +123,7 @@ protected override int BufferCapacity
{
var capacity = base.BufferCapacity;
capacity += 4; // AlgorithmName length
- capacity += AlgorithmName.Length; // AlgorithmName
+ capacity += Encoding.UTF8.GetByteCount(AlgorithmName); // AlgorithmName
capacity += 4; // Signature length
capacity += Signature.Length; // Signature
return capacity;
@@ -203,7 +136,7 @@ public SignatureKeyData()
public SignatureKeyData(string name, byte[] signature)
{
- AlgorithmName = Utf8.GetBytes(name);
+ AlgorithmName = name;
Signature = signature;
}
@@ -212,7 +145,7 @@ public SignatureKeyData(string name, byte[] signature)
///
protected override void LoadData()
{
- AlgorithmName = ReadBinary();
+ AlgorithmName = ReadString();
Signature = ReadBinary();
}
@@ -221,7 +154,7 @@ protected override void LoadData()
///
protected override void SaveData()
{
- WriteBinaryString(AlgorithmName);
+ Write(AlgorithmName);
WriteBinaryString(Signature);
}
}
diff --git a/src/Renci.SshNet/Security/SshKeyData.cs b/src/Renci.SshNet/Security/SshKeyData.cs
new file mode 100644
index 000000000..6a3af835a
--- /dev/null
+++ b/src/Renci.SshNet/Security/SshKeyData.cs
@@ -0,0 +1,98 @@
+using System.Collections.Generic;
+using System.Text;
+
+using Renci.SshNet.Common;
+using Renci.SshNet.Security.Chaos.NaCl;
+
+namespace Renci.SshNet.Security
+{
+ ///
+ /// Facilitates (de)serializing encoded public key data in the format
+ /// specified by RFC 4253 section 6.6.
+ ///
+ ///
+ /// See https://datatracker.ietf.org/doc/html/rfc4253#section-6.6.
+ ///
+ public sealed class SshKeyData : SshData
+ {
+ ///
+ /// Gets the public key format identifier.
+ ///
+ public string Name { get; private set; }
+
+ ///
+ /// Gets the public key constituents.
+ ///
+ public BigInteger[] Keys { get; private set; }
+
+ ///
+ protected override int BufferCapacity
+ {
+ get
+ {
+ var capacity = base.BufferCapacity;
+ capacity += 4; // Name length
+ capacity += Encoding.UTF8.GetByteCount(Name); // Name
+
+ foreach (var key in Keys)
+ {
+ capacity += 4; // Key length
+ capacity += key.BitLength / 8; // Key
+ }
+
+ return capacity;
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The encoded public key data.
+ public SshKeyData(byte[] data)
+ {
+ Load(data);
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The public key format identifer.
+ /// The public key constituents.
+ public SshKeyData(string name, BigInteger[] keys)
+ {
+ Name = name;
+ Keys = keys;
+ }
+
+ ///
+ protected override void LoadData()
+ {
+ Name = ReadString();
+ var keys = new List();
+
+ while (!IsEndOfData)
+ {
+ keys.Add(ReadBinary().ToBigInteger2());
+ }
+
+ Keys = keys.ToArray();
+ }
+
+ ///
+ protected override void SaveData()
+ {
+ Write(Name);
+
+ foreach (var key in Keys)
+ {
+ var keyData = key.ToByteArray().Reverse();
+ if (Name == "ssh-ed25519")
+ {
+ keyData = keyData.TrimLeadingZeros().Pad(Ed25519.PublicKeySizeInBytes);
+ }
+
+ WriteBinaryString(keyData);
+ }
+ }
+ }
+}
diff --git a/src/Renci.SshNet/ServiceFactory.NET.cs b/src/Renci.SshNet/ServiceFactory.NET.cs
deleted file mode 100644
index 881d71ccf..000000000
--- a/src/Renci.SshNet/ServiceFactory.NET.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using Renci.SshNet.NetConf;
-
-namespace Renci.SshNet
-{
- internal partial class ServiceFactory
- {
- ///
- /// Creates a new in a given
- /// and with the specified operation timeout.
- ///
- /// The to create the in.
- /// The number of milliseconds to wait for an operation to complete, or -1 to wait indefinitely.
- ///
- /// An .
- ///
- public INetConfSession CreateNetConfSession(ISession session, int operationTimeout)
- {
- return new NetConfSession(session, operationTimeout);
- }
- }
-}
diff --git a/src/Renci.SshNet/ServiceFactory.cs b/src/Renci.SshNet/ServiceFactory.cs
index f04e6116d..af30f11c8 100644
--- a/src/Renci.SshNet/ServiceFactory.cs
+++ b/src/Renci.SshNet/ServiceFactory.cs
@@ -1,33 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Net.Sockets;
using System.Text;
+
+using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
+using Renci.SshNet.Connection;
using Renci.SshNet.Messages.Transport;
+using Renci.SshNet.NetConf;
using Renci.SshNet.Security;
using Renci.SshNet.Sftp;
-using Renci.SshNet.Abstractions;
-using Renci.SshNet.Connection;
-using System.Net.Sockets;
namespace Renci.SshNet
{
///
/// Basic factory for creating new services.
///
- internal partial class ServiceFactory : IServiceFactory
+ internal sealed partial class ServiceFactory : IServiceFactory
{
///
/// Defines the number of times an authentication attempt with any given
/// can result in before it is disregarded.
///
- private static int PartialSuccessLimit = 5;
+ private const int PartialSuccessLimit = 5;
///
- /// Creates a .
+ /// Creates an .
///
///
- /// A .
+ /// An .
///
public IClientAuthentication CreateClientAuthentication()
{
@@ -43,8 +45,8 @@ public IClientAuthentication CreateClientAuthentication()
///
/// An for the specified .
///
- /// is null.
- /// is null.
+ /// is .
+ /// is .
public ISession CreateSession(ConnectionInfo connectionInfo, ISocketFactory socketFactory)
{
return new Session(connectionInfo, this, socketFactory);
@@ -55,7 +57,7 @@ public ISession CreateSession(ConnectionInfo connectionInfo, ISocketFactory sock
/// the specified operation timeout and encoding.
///
/// The to create the in.
- /// The number of milliseconds to wait for an operation to complete, or -1 to wait indefinitely.
+ /// The number of milliseconds to wait for an operation to complete, or -1 to wait indefinitely.
/// The encoding.
/// The factory to use for creating SFTP messages.
///
@@ -86,15 +88,20 @@ public PipeStream CreatePipeStream()
///
/// A that was negotiated between client and server.
///
- /// is null.
- /// is null.
+ /// is .
+ /// is .
/// No key exchange algorithms are supported by both client and server.
public IKeyExchange CreateKeyExchange(IDictionary clientAlgorithms, string[] serverAlgorithms)
{
- if (clientAlgorithms == null)
- throw new ArgumentNullException("clientAlgorithms");
- if (serverAlgorithms == null)
- throw new ArgumentNullException("serverAlgorithms");
+ if (clientAlgorithms is null)
+ {
+ throw new ArgumentNullException(nameof(clientAlgorithms));
+ }
+
+ if (serverAlgorithms is null)
+ {
+ throw new ArgumentNullException(nameof(serverAlgorithms));
+ }
// find an algorithm that is supported by both client and server
var keyExchangeAlgorithmType = (from c in clientAlgorithms
@@ -102,7 +109,7 @@ from s in serverAlgorithms
where s == c.Key
select c.Value).FirstOrDefault();
- if (keyExchangeAlgorithmType == null)
+ if (keyExchangeAlgorithmType is null)
{
throw new SshConnectionException("Failed to negotiate key exchange algorithm.", DisconnectReason.KeyExchangeFailed);
}
@@ -110,16 +117,40 @@ from s in serverAlgorithms
return keyExchangeAlgorithmType.CreateInstance();
}
+ ///
+ /// Creates a new in a given
+ /// and with the specified operation timeout.
+ ///
+ /// The to create the in.
+ /// The number of milliseconds to wait for an operation to complete, or -1 to wait indefinitely.
+ ///
+ /// An .
+ ///
+ public INetConfSession CreateNetConfSession(ISession session, int operationTimeout)
+ {
+ return new NetConfSession(session, operationTimeout);
+ }
+
+ ///
+ /// Creates an for the specified file and with the specified
+ /// buffer size.
+ ///
+ /// The file to read.
+ /// The SFTP session to use.
+ /// The size of buffer.
+ ///
+ /// An .
+ ///
public ISftpFileReader CreateSftpFileReader(string fileName, ISftpSession sftpSession, uint bufferSize)
{
- const int defaultMaxPendingReads = 3;
+ const int defaultMaxPendingReads = 10;
// Issue #292: Avoid overlapping SSH_FXP_OPEN and SSH_FXP_LSTAT requests for the same file as this
// causes a performance degradation on Sun SSH
- var openAsyncResult = sftpSession.BeginOpen(fileName, Flags.Read, null, null);
+ var openAsyncResult = sftpSession.BeginOpen(fileName, Flags.Read, callback: null, state: null);
var handle = sftpSession.EndOpen(openAsyncResult);
- var statAsyncResult = sftpSession.BeginLStat(fileName, null, null);
+ var statAsyncResult = sftpSession.BeginLStat(fileName, callback: null, state: null);
long? fileSize;
int maxPendingReads;
@@ -132,7 +163,7 @@ public ISftpFileReader CreateSftpFileReader(string fileName, ISftpSession sftpSe
{
var fileAttributes = sftpSession.EndLStat(statAsyncResult);
fileSize = fileAttributes.Size;
- maxPendingReads = Math.Min(10, (int) Math.Ceiling((double) fileAttributes.Size / chunkSize) + 1);
+ maxPendingReads = Math.Min(100, (int)Math.Ceiling((double)fileAttributes.Size / chunkSize) + 1);
}
catch (SshException ex)
{
@@ -145,6 +176,12 @@ public ISftpFileReader CreateSftpFileReader(string fileName, ISftpSession sftpSe
return sftpSession.CreateFileReader(handle, sftpSession, chunkSize, maxPendingReads, fileSize);
}
+ ///
+ /// Creates a new instance.
+ ///
+ ///
+ /// An .
+ ///
public ISftpResponseFactory CreateSftpResponseFactory()
{
return new SftpResponseFactory();
@@ -157,7 +194,7 @@ public ISftpResponseFactory CreateSftpResponseFactory()
/// The TERM environment variable.
/// The terminal width in columns.
/// The terminal width in rows.
- /// The terminal height in pixels.
+ /// The terminal width in pixels.
/// The terminal height in pixels.
/// The terminal mode values.
/// The size of the buffer.
@@ -209,10 +246,15 @@ public IRemotePathTransformation CreateRemotePathDoubleQuoteTransformation()
/// The value of is not supported.
public IConnector CreateConnector(IConnectionInfo connectionInfo, ISocketFactory socketFactory)
{
- if (connectionInfo == null)
- throw new ArgumentNullException("connectionInfo");
- if (socketFactory == null)
- throw new ArgumentNullException("socketFactory");
+ if (connectionInfo is null)
+ {
+ throw new ArgumentNullException(nameof(connectionInfo));
+ }
+
+ if (socketFactory is null)
+ {
+ throw new ArgumentNullException(nameof(socketFactory));
+ }
switch (connectionInfo.ProxyType)
{
diff --git a/src/Renci.SshNet/Session.cs b/src/Renci.SshNet/Session.cs
index 0748b8dac..dab919552 100644
--- a/src/Renci.SshNet/Session.cs
+++ b/src/Renci.SshNet/Session.cs
@@ -1,8 +1,13 @@
using System;
+using System.Globalization;
+using System.Linq;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
+using System.Threading.Tasks;
+
+using Renci.SshNet.Abstractions;
using Renci.SshNet.Channels;
using Renci.SshNet.Common;
using Renci.SshNet.Compression;
@@ -12,9 +17,6 @@
using Renci.SshNet.Messages.Connection;
using Renci.SshNet.Messages.Transport;
using Renci.SshNet.Security;
-using System.Globalization;
-using System.Linq;
-using Renci.SshNet.Abstractions;
using Renci.SshNet.Security.Cryptography;
namespace Renci.SshNet
@@ -27,21 +29,13 @@ public class Session : ISession
internal const byte CarriageReturn = 0x0d;
internal const byte LineFeed = 0x0a;
- ///
- /// Specifies an infinite waiting period.
- ///
- ///
- /// The value of this field is -1 millisecond.
- ///
- internal static readonly TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, -1);
-
///
/// Specifies an infinite waiting period.
///
///
/// The value of this field is -1.
///
- internal static readonly int Infinite = -1;
+ internal const int Infinite = -1;
///
/// Specifies maximum packet size defined by the protocol.
@@ -77,68 +71,109 @@ public class Session : ISession
/// We currently do not enforce this limit.
///
///
- private const int LocalChannelDataPacketSize = 1024*64;
+ private const int LocalChannelDataPacketSize = 1024 * 64;
+
+ ///
+ /// Specifies an infinite waiting period.
+ ///
+ ///
+ /// The value of this field is -1 millisecond.
+ ///
+ internal static readonly TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, -1);
///
/// Controls how many authentication attempts can take place at the same time.
///
///
- /// Some server may restrict number to prevent authentication attacks
+ /// Some server may restrict number to prevent authentication attacks.
///
- private static readonly SemaphoreLight AuthenticationConnection = new SemaphoreLight(3);
+ private static readonly SemaphoreSlim AuthenticationConnection = new SemaphoreSlim(3);
+
+ ///
+ /// Holds the factory to use for creating new services.
+ ///
+ private readonly IServiceFactory _serviceFactory;
+ private readonly ISocketFactory _socketFactory;
///
- /// Holds metada about session messages
+ /// Holds an object that is used to ensure only a single thread can read from
+ /// at any given time.
+ ///
+ private readonly object _socketReadLock = new object();
+
+ ///
+ /// Holds an object that is used to ensure only a single thread can write to
+ /// at any given time.
+ ///
+ ///
+ /// This is also used to ensure that is
+ /// incremented atomatically.
+ ///
+ private readonly object _socketWriteLock = new object();
+
+ ///
+ /// Holds an object that is used to ensure only a single thread can dispose
+ /// at any given time.
+ ///
+ ///
+ /// This is also used to ensure that will not be disposed
+ /// while performing a given operation or set of operations on .
+ ///
+ private readonly object _socketDisposeLock = new object();
+
+ ///
+ /// Holds an object that is used to ensure only a single thread can connect
+ /// and lazy initialize the at any given time.
+ ///
+ private readonly object _connectAndLazySemaphoreInitLock = new object();
+
+ ///
+ /// Holds metadata about session messages.
///
private SshMessageFactory _sshMessageFactory;
///
/// Holds a that is signaled when the message listener loop has completed.
///
- private EventWaitHandle _messageListenerCompleted;
+ private ManualResetEvent _messageListenerCompleted;
///
- /// Specifies outbound packet number
+ /// Specifies outbound packet number.
///
private volatile uint _outboundPacketSequence;
///
- /// Specifies incoming packet number
+ /// Specifies incoming packet number.
///
private uint _inboundPacketSequence;
///
- /// WaitHandle to signal that last service request was accepted
+ /// WaitHandle to signal that last service request was accepted.
///
- private EventWaitHandle _serviceAccepted = new AutoResetEvent(false);
+ private EventWaitHandle _serviceAccepted = new AutoResetEvent(initialState: false);
///
/// WaitHandle to signal that exception was thrown by another thread.
///
- private EventWaitHandle _exceptionWaitHandle = new ManualResetEvent(false);
+ private EventWaitHandle _exceptionWaitHandle = new ManualResetEvent(initialState: false);
///
/// WaitHandle to signal that key exchange was completed.
///
- private EventWaitHandle _keyExchangeCompletedWaitHandle = new ManualResetEvent(false);
+ private ManualResetEventSlim _keyExchangeCompletedWaitHandle = new ManualResetEventSlim(initialState: false);
///
- /// WaitHandle to signal that key exchange is in progress.
- ///
- private bool _keyExchangeInProgress;
-
- ///
- /// Exception that need to be thrown by waiting thread
+ /// Exception that need to be thrown by waiting thread.
///
private Exception _exception;
///
- /// Specifies whether connection is authenticated
+ /// Specifies whether connection is authenticated.
///
private bool _isAuthenticated;
///
- /// Specifies whether user issued Disconnect command or not
+ /// Specifies whether user issued Disconnect command or not.
///
private bool _isDisconnecting;
@@ -156,65 +191,32 @@ public class Session : ISession
private Compressor _clientCompression;
- private SemaphoreLight _sessionSemaphore;
+ private SemaphoreSlim _sessionSemaphore;
- ///
- /// Holds the factory to use for creating new services.
- ///
- private readonly IServiceFactory _serviceFactory;
- private readonly ISocketFactory _socketFactory;
+ private bool _isDisconnectMessageSent;
+
+ private uint _nextChannelNumber;
///
/// Holds connection socket.
///
private Socket _socket;
-#if FEATURE_SOCKET_POLL
- ///
- /// Holds an object that is used to ensure only a single thread can read from
- /// at any given time.
- ///
- private readonly object _socketReadLock = new object();
-#endif // FEATURE_SOCKET_POLL
-
- ///
- /// Holds an object that is used to ensure only a single thread can write to
- /// at any given time.
- ///
- ///
- /// This is also used to ensure that is
- /// incremented atomatically.
- ///
- private readonly object _socketWriteLock = new object();
-
- ///
- /// Holds an object that is used to ensure only a single thread can dispose
- /// at any given time.
- ///
- ///
- /// This is also used to ensure that will not be disposed
- /// while performing a given operation or set of operations on .
- ///
- private readonly object _socketDisposeLock = new object();
-
///
/// Gets the session semaphore that controls session channels.
///
///
/// The session semaphore.
///
- public SemaphoreLight SessionSemaphore
+ public SemaphoreSlim SessionSemaphore
{
get
{
- if (_sessionSemaphore == null)
+ if (_sessionSemaphore is null)
{
- lock (this)
+ lock (_connectAndLazySemaphoreInitLock)
{
- if (_sessionSemaphore == null)
- {
- _sessionSemaphore = new SemaphoreLight(ConnectionInfo.MaxSessions);
- }
+ _sessionSemaphore ??= new SemaphoreSlim(ConnectionInfo.MaxSessions);
}
}
@@ -222,10 +224,6 @@ public SemaphoreLight SessionSemaphore
}
}
- private bool _isDisconnectMessageSent;
-
- private uint _nextChannelNumber;
-
///
/// Gets the next channel number.
///
@@ -238,7 +236,7 @@ private uint NextChannelNumber
{
uint result;
- lock (this)
+ lock (_connectAndLazySemaphoreInitLock)
{
result = _nextChannelNumber++;
}
@@ -251,10 +249,10 @@ private uint NextChannelNumber
/// Gets a value indicating whether the session is connected.
///
///
- /// true if the session is connected; otherwise, false.
+ /// if the session is connected; otherwise, .
///
///
- /// This methods returns true in all but the following cases:
+ /// This methods returns in all but the following cases:
///
/// -
/// The is disposed.
@@ -278,9 +276,14 @@ public bool IsConnected
get
{
if (_disposed || _isDisconnectMessageSent || !_isAuthenticated)
+ {
return false;
- if (_messageListenerCompleted == null || _messageListenerCompleted.WaitOne(0))
+ }
+
+ if (_messageListenerCompleted is null || _messageListenerCompleted.WaitOne(0))
+ {
return false;
+ }
return IsSocketConnected();
}
@@ -290,7 +293,7 @@ public bool IsConnected
/// Gets the session id.
///
///
- /// The session id, or null if the client has not been authenticated.
+ /// The session id, or if the client has not been authenticated.
///
public byte[] SessionId { get; private set; }
@@ -304,44 +307,48 @@ public Message ClientInitMessage
{
get
{
- if (_clientInitMessage == null)
- {
- _clientInitMessage = new KeyExchangeInitMessage
- {
- KeyExchangeAlgorithms = ConnectionInfo.KeyExchangeAlgorithms.Keys.ToArray(),
- ServerHostKeyAlgorithms = ConnectionInfo.HostKeyAlgorithms.Keys.ToArray(),
- EncryptionAlgorithmsClientToServer = ConnectionInfo.Encryptions.Keys.ToArray(),
- EncryptionAlgorithmsServerToClient = ConnectionInfo.Encryptions.Keys.ToArray(),
- MacAlgorithmsClientToServer = ConnectionInfo.HmacAlgorithms.Keys.ToArray(),
- MacAlgorithmsServerToClient = ConnectionInfo.HmacAlgorithms.Keys.ToArray(),
- CompressionAlgorithmsClientToServer = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(),
- CompressionAlgorithmsServerToClient = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(),
- LanguagesClientToServer = new[] {string.Empty},
- LanguagesServerToClient = new[] {string.Empty},
- FirstKexPacketFollows = false,
- Reserved = 0
- };
- }
+ _clientInitMessage ??= new KeyExchangeInitMessage
+ {
+ KeyExchangeAlgorithms = ConnectionInfo.KeyExchangeAlgorithms.Keys.ToArray(),
+ ServerHostKeyAlgorithms = ConnectionInfo.HostKeyAlgorithms.Keys.ToArray(),
+ EncryptionAlgorithmsClientToServer = ConnectionInfo.Encryptions.Keys.ToArray(),
+ EncryptionAlgorithmsServerToClient = ConnectionInfo.Encryptions.Keys.ToArray(),
+ MacAlgorithmsClientToServer = ConnectionInfo.HmacAlgorithms.Keys.ToArray(),
+ MacAlgorithmsServerToClient = ConnectionInfo.HmacAlgorithms.Keys.ToArray(),
+ CompressionAlgorithmsClientToServer = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(),
+ CompressionAlgorithmsServerToClient = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(),
+ LanguagesClientToServer = new[] { string.Empty },
+ LanguagesServerToClient = new[] { string.Empty },
+ FirstKexPacketFollows = false,
+ Reserved = 0
+ };
+
return _clientInitMessage;
}
}
///
- /// Gets or sets the server version string.
+ /// Gets the server version string.
///
- /// The server version.
+ ///
+ /// The server version.
+ ///
public string ServerVersion { get; private set; }
///
- /// Gets or sets the client version string.
+ /// Gets the client version string.
///
- /// The client version.
+ ///
+ /// The client version.
+ ///
public string ClientVersion { get; private set; }
///
- /// Gets or sets the connection info.
+ /// Gets the connection info.
///
- /// The connection info.
+ ///
+ /// The connection info.
+ ///
public ConnectionInfo ConnectionInfo { get; private set; }
///
@@ -354,6 +361,11 @@ public Message ClientInitMessage
///
public event EventHandler Disconnected;
+ ///
+ /// Occurs when server identification received.
+ ///
+ public event EventHandler ServerIdentificationReceived;
+
///
/// Occurs when host key received.
///
@@ -389,8 +401,6 @@ public Message ClientInitMessage
///
internal event EventHandler> KeyExchangeDhGroupExchangeReplyReceived;
- #region Message events
-
///
/// Occurs when message received
///
@@ -526,31 +536,37 @@ public Message ClientInitMessage
///
public event EventHandler> ChannelFailureReceived;
- #endregion
-
///
/// Initializes a new instance of the class.
///
/// The connection info.
/// The factory to use for creating new services.
/// A factory to create instances.
- /// is null.
- /// is null.
- /// is null.
+ /// is .
+ /// is .
+ /// is .
internal Session(ConnectionInfo connectionInfo, IServiceFactory serviceFactory, ISocketFactory socketFactory)
{
- if (connectionInfo == null)
- throw new ArgumentNullException("connectionInfo");
- if (serviceFactory == null)
- throw new ArgumentNullException("serviceFactory");
- if (socketFactory == null)
- throw new ArgumentNullException("socketFactory");
+ if (connectionInfo is null)
+ {
+ throw new ArgumentNullException(nameof(connectionInfo));
+ }
+
+ if (serviceFactory is null)
+ {
+ throw new ArgumentNullException(nameof(serviceFactory));
+ }
+
+ if (socketFactory is null)
+ {
+ throw new ArgumentNullException(nameof(socketFactory));
+ }
ClientVersion = "SSH-2.0-Renci.SshNet.SshClient.0.0.1";
ConnectionInfo = connectionInfo;
_serviceFactory = serviceFactory;
_socketFactory = socketFactory;
- _messageListenerCompleted = new ManualResetEvent(true);
+ _messageListenerCompleted = new ManualResetEvent(initialState: true);
}
///
@@ -563,20 +579,26 @@ internal Session(ConnectionInfo connectionInfo, IServiceFactory serviceFactory,
public void Connect()
{
if (IsConnected)
+ {
return;
+ }
try
{
AuthenticationConnection.Wait();
if (IsConnected)
+ {
return;
+ }
- lock (this)
+ lock (_connectAndLazySemaphoreInitLock)
{
// If connected don't connect again
if (IsConnected)
+ {
return;
+ }
// Reset connection specific information
Reset();
@@ -594,7 +616,7 @@ public void Connect()
ServerVersion = ConnectionInfo.ServerVersion = serverIdentification.ToString();
ConnectionInfo.ClientVersion = ClientVersion;
- DiagnosticAbstraction.Log(string.Format("Server version '{0}' on '{1}'.", serverIdentification.ProtocolVersion, serverIdentification.SoftwareVersion));
+ DiagnosticAbstraction.Log(string.Format("Server version '{0}'.", serverIdentification));
if (!(serverIdentification.ProtocolVersion.Equals("2.0") || serverIdentification.ProtocolVersion.Equals("1.99")))
{
@@ -602,6 +624,8 @@ public void Connect()
DisconnectReason.ProtocolVersionNotSupported);
}
+ ServerIdentificationReceived?.Invoke(this, new SshIdentificationEventArgs(serverIdentification));
+
// Register Transport response messages
RegisterMessage("SSH_MSG_DISCONNECT");
RegisterMessage("SSH_MSG_IGNORE");
@@ -614,17 +638,23 @@ public void Connect()
// Some server implementations might sent this message first, prior to establishing encryption algorithm
RegisterMessage("SSH_MSG_USERAUTH_BANNER");
+ // Send our key exchange init.
+ // We need to do this before starting the message listener to avoid the case where we receive the server
+ // key exchange init and we continue the key exchange before having sent our own init.
+ SendMessage(ClientInitMessage);
+
// Mark the message listener threads as started
- _messageListenerCompleted.Reset();
+ _ = _messageListenerCompleted.Reset();
// Start incoming request listener
- ThreadAbstraction.ExecuteThread(() => MessageListener());
+ // ToDo: Make message pump async, to not consume a thread for every session
+ _ = ThreadAbstraction.ExecuteThreadLongRunning(MessageListener);
// Wait for key exchange to be completed
- WaitOnHandle(_keyExchangeCompletedWaitHandle);
+ WaitOnHandle(_keyExchangeCompletedWaitHandle.WaitHandle);
// If sessionId is not set then its not connected
- if (SessionId == null)
+ if (SessionId is null)
{
Disconnect();
return;
@@ -665,10 +695,123 @@ public void Connect()
}
finally
{
- AuthenticationConnection.Release();
+ _ = AuthenticationConnection.Release();
}
}
+ ///
+ /// Asynchronously connects to the server.
+ ///
+ ///
+ /// Please note this function is NOT thread safe.
+ /// The caller SHOULD limit the number of simultaneous connection attempts to a server to a single connection attempt.
+ /// The to observe.
+ /// A that represents the asynchronous connect operation.
+ /// Socket connection to the SSH server or proxy server could not be established, or an error occurred while resolving the hostname.
+ /// SSH session could not be established.
+ /// Authentication of SSH session failed.
+ /// Failed to establish proxy connection.
+ public async Task ConnectAsync(CancellationToken cancellationToken)
+ {
+ // If connected don't connect again
+ if (IsConnected)
+ {
+ return;
+ }
+
+ // Reset connection specific information
+ Reset();
+
+ // Build list of available messages while connecting
+ _sshMessageFactory = new SshMessageFactory();
+
+ _socket = await _serviceFactory.CreateConnector(ConnectionInfo, _socketFactory)
+ .ConnectAsync(ConnectionInfo, cancellationToken).ConfigureAwait(false);
+
+ var serverIdentification = await _serviceFactory.CreateProtocolVersionExchange()
+ .StartAsync(ClientVersion, _socket, cancellationToken).ConfigureAwait(false);
+
+ // Set connection versions
+ ServerVersion = ConnectionInfo.ServerVersion = serverIdentification.ToString();
+ ConnectionInfo.ClientVersion = ClientVersion;
+
+ DiagnosticAbstraction.Log(string.Format("Server version '{0}'.", serverIdentification));
+
+ if (!(serverIdentification.ProtocolVersion.Equals("2.0") || serverIdentification.ProtocolVersion.Equals("1.99")))
+ {
+ throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Server version '{0}' is not supported.", serverIdentification.ProtocolVersion),
+ DisconnectReason.ProtocolVersionNotSupported);
+ }
+
+ ServerIdentificationReceived?.Invoke(this, new SshIdentificationEventArgs(serverIdentification));
+
+ // Register Transport response messages
+ RegisterMessage("SSH_MSG_DISCONNECT");
+ RegisterMessage("SSH_MSG_IGNORE");
+ RegisterMessage("SSH_MSG_UNIMPLEMENTED");
+ RegisterMessage("SSH_MSG_DEBUG");
+ RegisterMessage("SSH_MSG_SERVICE_ACCEPT");
+ RegisterMessage("SSH_MSG_KEXINIT");
+ RegisterMessage("SSH_MSG_NEWKEYS");
+
+ // Some server implementations might sent this message first, prior to establishing encryption algorithm
+ RegisterMessage("SSH_MSG_USERAUTH_BANNER");
+
+ // Send our key exchange init.
+ // We need to do this before starting the message listener to avoid the case where we receive the server
+ // key exchange init and we continue the key exchange before having sent our own init.
+ SendMessage(ClientInitMessage);
+
+ // Mark the message listener threads as started
+ _ = _messageListenerCompleted.Reset();
+
+ // Start incoming request listener
+ // ToDo: Make message pump async, to not consume a thread for every session
+ _ = ThreadAbstraction.ExecuteThreadLongRunning(MessageListener);
+
+ // Wait for key exchange to be completed
+ WaitOnHandle(_keyExchangeCompletedWaitHandle.WaitHandle);
+
+ // If sessionId is not set then its not connected
+ if (SessionId is null)
+ {
+ Disconnect();
+ return;
+ }
+
+ // Request user authorization service
+ SendMessage(new ServiceRequestMessage(ServiceName.UserAuthentication));
+
+ // Wait for service to be accepted
+ WaitOnHandle(_serviceAccepted);
+
+ if (string.IsNullOrEmpty(ConnectionInfo.Username))
+ {
+ throw new SshException("Username is not specified.");
+ }
+
+ // Some servers send a global request immediately after successful authentication
+ // Avoid race condition by already enabling SSH_MSG_GLOBAL_REQUEST before authentication
+ RegisterMessage("SSH_MSG_GLOBAL_REQUEST");
+
+ ConnectionInfo.Authenticate(this, _serviceFactory);
+ _isAuthenticated = true;
+
+ // Register Connection messages
+ RegisterMessage("SSH_MSG_REQUEST_SUCCESS");
+ RegisterMessage("SSH_MSG_REQUEST_FAILURE");
+ RegisterMessage("SSH_MSG_CHANNEL_OPEN_CONFIRMATION");
+ RegisterMessage("SSH_MSG_CHANNEL_OPEN_FAILURE");
+ RegisterMessage("SSH_MSG_CHANNEL_WINDOW_ADJUST");
+ RegisterMessage("SSH_MSG_CHANNEL_EXTENDED_DATA");
+ RegisterMessage("SSH_MSG_CHANNEL_REQUEST");
+ RegisterMessage("SSH_MSG_CHANNEL_SUCCESS");
+ RegisterMessage("SSH_MSG_CHANNEL_FAILURE");
+ RegisterMessage("SSH_MSG_CHANNEL_DATA");
+ RegisterMessage("SSH_MSG_CHANNEL_EOF");
+ RegisterMessage("SSH_MSG_CHANNEL_CLOSE");
+ }
+
///
/// Disconnects from the server.
///
@@ -688,7 +831,7 @@ public void Disconnect()
// has completed
if (_messageListenerCompleted != null)
{
- _messageListenerCompleted.WaitOne();
+ _ = _messageListenerCompleted.WaitOne();
}
}
@@ -747,23 +890,6 @@ void ISession.WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout)
WaitOnHandle(waitHandle, timeout);
}
- ///
- /// Waits for the specified handle or the exception handle for the receive thread
- /// to signal within the connection timeout.
- ///
- /// The wait handle.
- /// A received package was invalid or failed the message integrity check.
- /// None of the handles are signaled in time and the session is not disconnecting.
- /// A socket error was signaled while receiving messages from the server.
- ///
- /// When neither handles are signaled in time and the session is not closing, then the
- /// session is disconnected.
- ///
- internal void WaitOnHandle(WaitHandle waitHandle)
- {
- WaitOnHandle(waitHandle, ConnectionInfo.Timeout);
- }
-
///
/// Waits for the specified to receive a signal, using a
/// to specify the time interval.
@@ -775,8 +901,7 @@ internal void WaitOnHandle(WaitHandle waitHandle)
///
WaitResult ISession.TryWait(WaitHandle waitHandle, TimeSpan timeout)
{
- Exception exception;
- return TryWait(waitHandle, timeout, out exception);
+ return TryWait(waitHandle, timeout, out _);
}
///
@@ -806,8 +931,10 @@ WaitResult ISession.TryWait(WaitHandle waitHandle, TimeSpan timeout, out Excepti
///
private WaitResult TryWait(WaitHandle waitHandle, TimeSpan timeout, out Exception exception)
{
- if (waitHandle == null)
- throw new ArgumentNullException("waitHandle");
+ if (waitHandle is null)
+ {
+ throw new ArgumentNullException(nameof(waitHandle));
+ }
var waitHandles = new[]
{
@@ -824,6 +951,7 @@ private WaitResult TryWait(WaitHandle waitHandle, TimeSpan timeout, out Exceptio
exception = null;
return WaitResult.Disconnected;
}
+
exception = _exception;
return WaitResult.Failed;
case 1:
@@ -840,6 +968,23 @@ private WaitResult TryWait(WaitHandle waitHandle, TimeSpan timeout, out Exceptio
}
}
+ ///
+ /// Waits for the specified handle or the exception handle for the receive thread
+ /// to signal within the connection timeout.
+ ///
+ /// The wait handle.
+ /// A received package was invalid or failed the message integrity check.
+ /// None of the handles are signaled in time and the session is not disconnecting.
+ /// A socket error was signaled while receiving messages from the server.
+ ///
+ /// When neither handles are signaled in time and the session is not closing, then the
+ /// session is disconnected.
+ ///
+ internal void WaitOnHandle(WaitHandle waitHandle)
+ {
+ WaitOnHandle(waitHandle, ConnectionInfo.Timeout);
+ }
+
///
/// Waits for the specified handle or the exception handle for the receive thread
/// to signal within the specified timeout.
@@ -851,8 +996,10 @@ private WaitResult TryWait(WaitHandle waitHandle, TimeSpan timeout, out Exceptio
/// A socket error was signaled while receiving messages from the server.
internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout)
{
- if (waitHandle == null)
- throw new ArgumentNullException("waitHandle");
+ if (waitHandle is null)
+ {
+ throw new ArgumentNullException(nameof(waitHandle));
+ }
var waitHandles = new[]
{
@@ -861,12 +1008,17 @@ internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout)
waitHandle
};
- switch (WaitHandle.WaitAny(waitHandles, timeout))
+ var signaledElement = WaitHandle.WaitAny(waitHandles, timeout);
+ switch (signaledElement)
{
case 0:
- throw _exception;
+ System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(_exception).Throw();
+ break;
case 1:
throw new SshConnectionException("Client not connected.");
+ case 2:
+ // Specified waithandle was signaled
+ break;
case WaitHandle.WaitTimeout:
// when the session is disconnecting, a timeout is likely when no
// network connectivity is available; depending on the configured
@@ -878,7 +1030,10 @@ internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout)
{
throw new SshOperationTimeoutException("Session operation has timed out");
}
+
break;
+ default:
+ throw new SshException($"Unexpected element '{signaledElement.ToString(CultureInfo.InvariantCulture)}' signaled.");
}
}
@@ -892,17 +1047,19 @@ internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout)
internal void SendMessage(Message message)
{
if (!_socket.CanWrite())
+ {
throw new SshConnectionException("Client not connected.");
+ }
- if (_keyExchangeInProgress && !(message is IKeyExchangedAllowed))
+ if (!_keyExchangeCompletedWaitHandle.IsSet && message is not IKeyExchangedAllowed)
{
- // Wait for key exchange to be completed
- WaitOnHandle(_keyExchangeCompletedWaitHandle);
+ // Wait for key exchange to be completed
+ WaitOnHandle(_keyExchangeCompletedWaitHandle.WaitHandle);
}
DiagnosticAbstraction.Log(string.Format("[{0}] Sending message '{1}' to server: '{2}'.", ToHex(SessionId), message.GetType().Name, message));
- var paddingMultiplier = _clientCipher == null ? (byte) 8 : Math.Max((byte) 8, _serverCipher.MinimumSize);
+ var paddingMultiplier = _clientCipher is null ? (byte) 8 : Math.Max((byte) 8, _serverCipher.MinimumSize);
var packetData = message.GetPacket(paddingMultiplier, _clientCompression);
// take a write lock to ensure the outbound packet sequence number is incremented
@@ -916,14 +1073,15 @@ internal void SendMessage(Message message)
{
// write outbound packet sequence to start of packet data
Pack.UInt32ToBigEndian(_outboundPacketSequence, packetData);
- // calculate packet hash
+
+ // calculate packet hash
hash = _clientMac.ComputeHash(packetData);
}
// Encrypt packet data
if (_clientCipher != null)
{
- packetData = _clientCipher.Encrypt(packetData, packetDataOffset, (packetData.Length - packetDataOffset));
+ packetData = _clientCipher.Encrypt(packetData, packetDataOffset, packetData.Length - packetDataOffset);
packetDataOffset = 0;
}
@@ -933,7 +1091,7 @@ internal void SendMessage(Message message)
}
var packetLength = packetData.Length - packetDataOffset;
- if (hash == null)
+ if (hash is null)
{
SendPacket(packetData, packetDataOffset, packetLength);
}
@@ -948,7 +1106,7 @@ internal void SendMessage(Message message)
// increment the packet sequence number only after we're sure the packet has
// been sent; even though it's only used for the MAC, it needs to be incremented
// for each package sent.
- //
+ //
// the server will use it to verify the data integrity, and as such the order in
// which messages are sent must follow the outbound packet sequence number
_outboundPacketSequence++;
@@ -977,7 +1135,9 @@ private void SendPacket(byte[] packet, int offset, int length)
lock (_socketDisposeLock)
{
if (!_socket.IsConnected())
+ {
throw new SshConnectionException("Client not connected.");
+ }
SocketAbstraction.Send(_socket, packet, offset, length);
}
@@ -988,11 +1148,11 @@ private void SendPacket(byte[] packet, int offset, int length)
///
/// The message to send.
///
- /// true if the message was sent to the server; otherwise, false.
+ /// if the message was sent to the server; otherwise, .
///
/// The size of the packet exceeds the maximum size defined by the protocol.
///
- /// This methods returns false when the attempt to send the message results in a
+ /// This methods returns when the attempt to send the message results in a
/// or a .
///
private bool TrySendMessage(Message message)
@@ -1018,7 +1178,7 @@ private bool TrySendMessage(Message message)
/// Receives the message from the server.
///
///
- /// The incoming SSH message, or null if the connection with the SSH server was closed.
+ /// The incoming SSH message, or if the connection with the SSH server was closed.
///
///
/// We need no locking here since all messages are read by a single thread.
@@ -1027,27 +1187,27 @@ private Message ReceiveMessage(Socket socket)
{
// the length of the packet sequence field in bytes
const int inboundPacketSequenceLength = 4;
+
// The length of the "packet length" field in bytes
const int packetLengthFieldLength = 4;
+
// The length of the "padding length" field in bytes
const int paddingLengthFieldLength = 1;
// Determine the size of the first block, which is 8 or cipher block size (whichever is larger) bytes
- var blockSize = _serverCipher == null ? (byte) 8 : Math.Max((byte) 8, _serverCipher.MinimumSize);
+ var blockSize = _serverCipher is null ? (byte) 8 : Math.Max((byte) 8, _serverCipher.MinimumSize);
var serverMacLength = _serverMac != null ? _serverMac.HashSize/8 : 0;
byte[] data;
uint packetLength;
-#if FEATURE_SOCKET_POLL
// avoid reading from socket while IsSocketConnected is attempting to determine whether the
// socket is still connected by invoking Socket.Poll(...) and subsequently verifying value of
// Socket.Available
lock (_socketReadLock)
{
-#endif // FEATURE_SOCKET_POLL
- // Read first block - which starts with the packet length
+ // Read first block - which starts with the packet length
var firstBlock = new byte[blockSize];
if (TrySocketRead(socket, firstBlock, 0, blockSize) == 0)
{
@@ -1064,9 +1224,10 @@ private Message ReceiveMessage(Socket socket)
// Test packet minimum and maximum boundaries
if (packetLength < Math.Max((byte) 16, blockSize) - 4 || packetLength > MaximumSshPacketSize - 4)
- throw new SshConnectionException(
- string.Format(CultureInfo.CurrentCulture, "Bad packet length: {0}.", packetLength),
- DisconnectReason.ProtocolError);
+ {
+ throw new SshConnectionException(string.Format(CultureInfo.CurrentCulture, "Bad packet length: {0}.", packetLength),
+ DisconnectReason.ProtocolError);
+ }
// Determine the number of bytes left to read; We've already read "blockSize" bytes, but the
// "packet length" field itself - which is 4 bytes - is not included in the length of the packet
@@ -1074,12 +1235,12 @@ private Message ReceiveMessage(Socket socket)
// Construct buffer for holding the payload and the inbound packet sequence as we need both in order
// to generate the hash.
- //
+ //
// The total length of the "data" buffer is an addition of:
// - inboundPacketSequenceLength (4 bytes)
// - packetLength
// - serverMacLength
- //
+ //
// We include the inbound packet sequence to allow us to have the the full SSH packet in a single
// byte[] for the purpose of calculating the client hash. Room for the server MAC is foreseen
// to read the packet including server MAC in a single pass (except for the initial block).
@@ -1094,9 +1255,7 @@ private Message ReceiveMessage(Socket socket)
return null;
}
}
-#if FEATURE_SOCKET_POLL
}
-#endif // FEATURE_SOCKET_POLL
if (_serverCipher != null)
{
@@ -1118,8 +1277,8 @@ private Message ReceiveMessage(Socket socket)
var clientHash = _serverMac.ComputeHash(data, 0, data.Length - serverMacLength);
var serverHash = data.Take(data.Length - serverMacLength, serverMacLength);
- // TODO add IsEqualTo overload that takes left+right index and number of bytes to compare;
- // TODO that way we can eliminate the extra allocation of the Take above
+ // TODO Add IsEqualTo overload that takes left+right index and number of bytes to compare.
+ // TODO That way we can eliminate the extra allocation of the Take above.
if (!serverHash.IsEqualTo(clientHash))
{
throw new SshConnectionException("MAC error", DisconnectReason.MacError);
@@ -1130,9 +1289,10 @@ private Message ReceiveMessage(Socket socket)
{
data = _serverDecompression.Decompress(data, messagePayloadOffset, messagePayloadLength);
- // data now only contains the decompressed payload, and as such the offset is reset to zero
+ // Data now only contains the decompressed payload, and as such the offset is reset to zero
messagePayloadOffset = 0;
- // the length of the payload is now the complete decompressed content
+
+ // The length of the payload is now the complete decompressed content
messagePayloadLength = data.Length;
}
@@ -1145,15 +1305,13 @@ private void TrySendDisconnect(DisconnectReason reasonCode, string message)
{
var disconnectMessage = new DisconnectMessage(reasonCode, message);
- // send the disconnect message, but ignore the outcome
- TrySendMessage(disconnectMessage);
+ // Send the disconnect message, but ignore the outcome
+ _ = TrySendMessage(disconnectMessage);
- // mark disconnect message sent regardless of whether the send sctually succeeded
+ // Mark disconnect message sent regardless of whether the send sctually succeeded
_isDisconnectMessageSent = true;
}
- #region Handle received message events
-
///
/// Called when received.
///
@@ -1168,15 +1326,11 @@ internal void OnDisconnectReceived(DisconnectMessage message)
_isDisconnecting = true;
_exception = new SshConnectionException(string.Format(CultureInfo.InvariantCulture, "The connection was closed by the server: {0} ({1}).", message.Description, message.ReasonCode), message.ReasonCode);
- _exceptionWaitHandle.Set();
+ _ = _exceptionWaitHandle.Set();
- var disconnectReceived = DisconnectReceived;
- if (disconnectReceived != null)
- disconnectReceived(this, new MessageEventArgs(message));
+ DisconnectReceived?.Invoke(this, new MessageEventArgs(message));
- var disconnected = Disconnected;
- if (disconnected != null)
- disconnected(this, new EventArgs());
+ Disconnected?.Invoke(this, EventArgs.Empty);
// disconnect socket, and dispose it
SocketDisconnectAndDispose();
@@ -1188,9 +1342,7 @@ internal void OnDisconnectReceived(DisconnectMessage message)
/// message.
internal void OnIgnoreReceived(IgnoreMessage message)
{
- var handlers = IgnoreReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ IgnoreReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1199,9 +1351,7 @@ internal void OnIgnoreReceived(IgnoreMessage message)
/// message.
internal void OnUnimplementedReceived(UnimplementedMessage message)
{
- var handlers = UnimplementedReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ UnimplementedReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1210,9 +1360,7 @@ internal void OnUnimplementedReceived(UnimplementedMessage message)
/// message.
internal void OnDebugReceived(DebugMessage message)
{
- var handlers = DebugReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ DebugReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1221,9 +1369,7 @@ internal void OnDebugReceived(DebugMessage message)
/// message.
internal void OnServiceRequestReceived(ServiceRequestMessage message)
{
- var handlers = ServiceRequestReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ServiceRequestReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1232,25 +1378,19 @@ internal void OnServiceRequestReceived(ServiceRequestMessage message)
/// message.
internal void OnServiceAcceptReceived(ServiceAcceptMessage message)
{
- var handlers = ServiceAcceptReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ServiceAcceptReceived?.Invoke(this, new MessageEventArgs(message));
- _serviceAccepted.Set();
+ _ = _serviceAccepted.Set();
}
internal void OnKeyExchangeDhGroupExchangeGroupReceived(KeyExchangeDhGroupExchangeGroup message)
{
- var handlers = KeyExchangeDhGroupExchangeGroupReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ KeyExchangeDhGroupExchangeGroupReceived?.Invoke(this, new MessageEventArgs(message));
}
internal void OnKeyExchangeDhGroupExchangeReplyReceived(KeyExchangeDhGroupExchangeReply message)
{
- var handlers = KeyExchangeDhGroupExchangeReplyReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ KeyExchangeDhGroupExchangeReplyReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1259,7 +1399,13 @@ internal void OnKeyExchangeDhGroupExchangeReplyReceived(KeyExchangeDhGroupExchan
/// message.
internal void OnKeyExchangeInitReceived(KeyExchangeInitMessage message)
{
- _keyExchangeInProgress = true;
+ // If _keyExchangeCompletedWaitHandle is already set, then this is a key
+ // re-exchange initiated by the server, and we need to send our own init
+ // message.
+ // Otherwise, the wait handle is not set and this received init is part of the
+ // initial connection for which we have already sent our init, so we shouldn't
+ // send another one.
+ var sendClientInitMessage = _keyExchangeCompletedWaitHandle.IsSet;
_keyExchangeCompletedWaitHandle.Reset();
@@ -1271,28 +1417,24 @@ internal void OnKeyExchangeInitReceived(KeyExchangeInitMessage message)
ConnectionInfo.CurrentKeyExchangeAlgorithm = _keyExchange.Name;
+ DiagnosticAbstraction.Log(string.Format("[{0}] Performing {1} key exchange.", ToHex(SessionId), ConnectionInfo.CurrentKeyExchangeAlgorithm));
+
_keyExchange.HostKeyReceived += KeyExchange_HostKeyReceived;
- // Start the algorithm implementation
- _keyExchange.Start(this, message);
+ // Start the algorithm implementation
+ _keyExchange.Start(this, message, sendClientInitMessage);
- var keyExchangeInitReceived = KeyExchangeInitReceived;
- if (keyExchangeInitReceived != null)
- keyExchangeInitReceived(this, new MessageEventArgs(message));
+ KeyExchangeInitReceived?.Invoke(this, new MessageEventArgs(message));
}
internal void OnKeyExchangeDhReplyMessageReceived(KeyExchangeDhReplyMessage message)
{
- var handlers = KeyExchangeDhReplyMessageReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ KeyExchangeDhReplyMessageReceived?.Invoke(this, new MessageEventArgs(message));
}
internal void OnKeyExchangeEcdhReplyMessageReceived(KeyExchangeEcdhReplyMessage message)
{
- var handlers = KeyExchangeEcdhReplyMessageReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ KeyExchangeEcdhReplyMessageReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1301,13 +1443,20 @@ internal void OnKeyExchangeEcdhReplyMessageReceived(KeyExchangeEcdhReplyMessage
/// message.
internal void OnNewKeysReceived(NewKeysMessage message)
{
- // Update sessionId
- if (SessionId == null)
+ // Update sessionId
+ SessionId ??= _keyExchange.ExchangeHash;
+
+ // Dispose of old ciphers and hash algorithms
+ if (_serverCipher is IDisposable disposableServerCipher)
{
- SessionId = _keyExchange.ExchangeHash;
+ disposableServerCipher.Dispose();
+ }
+
+ if (_clientCipher is IDisposable disposableClientCipher)
+ {
+ disposableClientCipher.Dispose();
}
- // Dispose of old ciphers and hash algorithms
if (_serverMac != null)
{
_serverMac.Dispose();
@@ -1320,7 +1469,7 @@ internal void OnNewKeysReceived(NewKeysMessage message)
_clientMac = null;
}
- // Update negotiated algorithms
+ // Update negotiated algorithms
_serverCipher = _keyExchange.CreateServerCipher();
_clientCipher = _keyExchange.CreateClientCipher();
_serverMac = _keyExchange.CreateServerHash();
@@ -1328,25 +1477,18 @@ internal void OnNewKeysReceived(NewKeysMessage message)
_clientCompression = _keyExchange.CreateCompressor();
_serverDecompression = _keyExchange.CreateDecompressor();
- // Dispose of old KeyExchange object as it is no longer needed.
- if (_keyExchange != null)
- {
- _keyExchange.HostKeyReceived -= KeyExchange_HostKeyReceived;
- _keyExchange.Dispose();
- _keyExchange = null;
- }
+ // Dispose of old KeyExchange object as it is no longer needed.
+ _keyExchange.HostKeyReceived -= KeyExchange_HostKeyReceived;
+ _keyExchange.Dispose();
+ _keyExchange = null;
// Enable activated messages that are not key exchange related
_sshMessageFactory.EnableActivatedMessages();
- var newKeysReceived = NewKeysReceived;
- if (newKeysReceived != null)
- newKeysReceived(this, new MessageEventArgs(message));
+ NewKeysReceived?.Invoke(this, new MessageEventArgs(message));
- // Signal that key exchange completed
+ // Signal that key exchange completed
_keyExchangeCompletedWaitHandle.Set();
-
- _keyExchangeInProgress = false;
}
///
@@ -1363,9 +1505,7 @@ void ISession.OnDisconnecting()
/// message.
internal void OnUserAuthenticationRequestReceived(RequestMessage message)
{
- var handlers = UserAuthenticationRequestReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ UserAuthenticationRequestReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1374,9 +1514,7 @@ internal void OnUserAuthenticationRequestReceived(RequestMessage message)
/// message.
internal void OnUserAuthenticationFailureReceived(FailureMessage message)
{
- var handlers = UserAuthenticationFailureReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ UserAuthenticationFailureReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1385,9 +1523,7 @@ internal void OnUserAuthenticationFailureReceived(FailureMessage message)
/// message.
internal void OnUserAuthenticationSuccessReceived(SuccessMessage message)
{
- var handlers = UserAuthenticationSuccessReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ UserAuthenticationSuccessReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1396,35 +1532,26 @@ internal void OnUserAuthenticationSuccessReceived(SuccessMessage message)
/// message.
internal void OnUserAuthenticationBannerReceived(BannerMessage message)
{
- var handlers = UserAuthenticationBannerReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ UserAuthenticationBannerReceived?.Invoke(this, new MessageEventArgs(message));
}
-
///
/// Called when message received.
///
/// message.
internal void OnUserAuthenticationInformationRequestReceived(InformationRequestMessage message)
{
- var handlers = UserAuthenticationInformationRequestReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ UserAuthenticationInformationRequestReceived?.Invoke(this, new MessageEventArgs(message));
}
internal void OnUserAuthenticationPasswordChangeRequiredReceived(PasswordChangeRequiredMessage message)
{
- var handlers = UserAuthenticationPasswordChangeRequiredReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ UserAuthenticationPasswordChangeRequiredReceived?.Invoke(this, new MessageEventArgs(message));
}
internal void OnUserAuthenticationPublicKeyReceived(PublicKeyMessage message)
{
- var handlers = UserAuthenticationPublicKeyReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ UserAuthenticationPublicKeyReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1433,9 +1560,7 @@ internal void OnUserAuthenticationPublicKeyReceived(PublicKeyMessage message)
/// message.
internal void OnGlobalRequestReceived(GlobalRequestMessage message)
{
- var handlers = GlobalRequestReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ GlobalRequestReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1444,9 +1569,7 @@ internal void OnGlobalRequestReceived(GlobalRequestMessage message)
/// message.
internal void OnRequestSuccessReceived(RequestSuccessMessage message)
{
- var handlers = RequestSuccessReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ RequestSuccessReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1455,9 +1578,7 @@ internal void OnRequestSuccessReceived(RequestSuccessMessage message)
/// message.
internal void OnRequestFailureReceived(RequestFailureMessage message)
{
- var handlers = RequestFailureReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ RequestFailureReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1466,9 +1587,7 @@ internal void OnRequestFailureReceived(RequestFailureMessage message)
/// message.
internal void OnChannelOpenReceived(ChannelOpenMessage message)
{
- var handlers = ChannelOpenReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ChannelOpenReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1477,9 +1596,7 @@ internal void OnChannelOpenReceived(ChannelOpenMessage message)
/// message.
internal void OnChannelOpenConfirmationReceived(ChannelOpenConfirmationMessage message)
{
- var handlers = ChannelOpenConfirmationReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ChannelOpenConfirmationReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1488,9 +1605,7 @@ internal void OnChannelOpenConfirmationReceived(ChannelOpenConfirmationMessage m
/// message.
internal void OnChannelOpenFailureReceived(ChannelOpenFailureMessage message)
{
- var handlers = ChannelOpenFailureReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ChannelOpenFailureReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1499,9 +1614,7 @@ internal void OnChannelOpenFailureReceived(ChannelOpenFailureMessage message)
/// message.
internal void OnChannelWindowAdjustReceived(ChannelWindowAdjustMessage message)
{
- var handlers = ChannelWindowAdjustReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ChannelWindowAdjustReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1510,9 +1623,7 @@ internal void OnChannelWindowAdjustReceived(ChannelWindowAdjustMessage message)
/// message.
internal void OnChannelDataReceived(ChannelDataMessage message)
{
- var handlers = ChannelDataReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ChannelDataReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1521,9 +1632,7 @@ internal void OnChannelDataReceived(ChannelDataMessage message)
/// message.
internal void OnChannelExtendedDataReceived(ChannelExtendedDataMessage message)
{
- var handlers = ChannelExtendedDataReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ChannelExtendedDataReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1532,9 +1641,7 @@ internal void OnChannelExtendedDataReceived(ChannelExtendedDataMessage message)
/// message.
internal void OnChannelEofReceived(ChannelEofMessage message)
{
- var handlers = ChannelEofReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ChannelEofReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1543,9 +1650,7 @@ internal void OnChannelEofReceived(ChannelEofMessage message)
/// message.
internal void OnChannelCloseReceived(ChannelCloseMessage message)
{
- var handlers = ChannelCloseReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ChannelCloseReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1554,9 +1659,7 @@ internal void OnChannelCloseReceived(ChannelCloseMessage message)
/// message.
internal void OnChannelRequestReceived(ChannelRequestMessage message)
{
- var handlers = ChannelRequestReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ChannelRequestReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1565,9 +1668,7 @@ internal void OnChannelRequestReceived(ChannelRequestMessage message)
/// message.
internal void OnChannelSuccessReceived(ChannelSuccessMessage message)
{
- var handlers = ChannelSuccessReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ChannelSuccessReceived?.Invoke(this, new MessageEventArgs(message));
}
///
@@ -1576,22 +1677,14 @@ internal void OnChannelSuccessReceived(ChannelSuccessMessage message)
/// message.
internal void OnChannelFailureReceived(ChannelFailureMessage message)
{
- var handlers = ChannelFailureReceived;
- if (handlers != null)
- handlers(this, new MessageEventArgs(message));
+ ChannelFailureReceived?.Invoke(this, new MessageEventArgs(message));
}
- #endregion
-
private void KeyExchange_HostKeyReceived(object sender, HostKeyEventArgs e)
{
- var handlers = HostKeyReceived;
- if (handlers != null)
- handlers(this, e);
+ HostKeyReceived?.Invoke(this, e);
}
- #region Message loading functions
-
///
/// Registers SSH message with the session.
///
@@ -1641,7 +1734,7 @@ private static string ToHex(byte[] bytes, int offset)
for (var i = offset; i < byteCount; i++)
{
var b = bytes[i];
- builder.Append(b.ToString("X2"));
+ _ = builder.Append(b.ToString("X2"));
}
return builder.ToString();
@@ -1649,25 +1742,24 @@ private static string ToHex(byte[] bytes, int offset)
internal static string ToHex(byte[] bytes)
{
- if (bytes == null)
+ if (bytes is null)
+ {
return null;
+ }
return ToHex(bytes, 0);
}
- #endregion
-
-#if FEATURE_SOCKET_POLL
///
/// Gets a value indicating whether the socket is connected.
///
///
- /// true if the socket is connected; otherwise, false.
+ /// if the socket is connected; otherwise, .
///
///
///
/// As a first check we verify whether is
- /// true. However, this only returns the state of the socket as of
+ /// . However, this only returns the state of the socket as of
/// the last I/O operation.
///
///
@@ -1679,15 +1771,15 @@ internal static string ToHex(byte[] bytes)
/// with mode :
///
/// -
- /// true if data is available for reading;
+ /// if data is available for reading;
///
/// -
- /// true if the connection has been closed, reset, or terminated; otherwise, returns false.
+ /// if the connection has been closed, reset, or terminated; otherwise, returns .
///
///
///
///
- /// Conclusion: when the return value is true - but no data is available for reading - then
+ /// Conclusion: when the return value is - but no data is available for reading - then
/// the socket is no longer connected.
///
///
@@ -1696,38 +1788,40 @@ internal static string ToHex(byte[] bytes)
/// when the value of is obtained. To workaround this issue
/// we synchronize reads from the .
///
+ ///
+ /// We assume the socket is still connected if the read lock cannot be acquired immediately.
+ /// In this case, we just return without actually waiting to acquire
+ /// the lock. We don't want to wait for the read lock if another thread already has it because
+ /// there are cases where the other thread holding the lock can be waiting indefinitely for
+ /// a socket read operation to complete.
+ ///
///
-#else
- ///
- /// Gets a value indicating whether the socket is connected.
- ///
- ///
- /// true if the socket is connected; otherwise, false.
- ///
- ///
- /// We verify whether is true. However, this only returns the state
- /// of the socket as of the last I/O operation.
- ///
-#endif
private bool IsSocketConnected()
{
+#pragma warning disable S2222 // Locks should be released on all paths
lock (_socketDisposeLock)
{
-#if FEATURE_SOCKET_POLL
if (!_socket.IsConnected())
{
return false;
}
- lock (_socketReadLock)
+ if (!Monitor.TryEnter(_socketReadLock))
+ {
+ return true;
+ }
+
+ try
{
var connectionClosedOrDataAvailable = _socket.Poll(0, SelectMode.SelectRead);
return !(connectionClosedOrDataAvailable && _socket.Available == 0);
}
-#else
- return _socket.IsConnected();
-#endif // FEATURE_SOCKET_POLL
+ finally
+ {
+ Monitor.Exit(_socketReadLock);
+ }
}
+#pragma warning restore S2222 // Locks should be released on all paths
}
///
@@ -1800,15 +1894,13 @@ private void MessageListener()
{
var socket = _socket;
- if (socket == null || !socket.Connected)
+ if (socket is null || !socket.Connected)
{
break;
}
-#if FEATURE_SOCKET_POLL || FEATURE_SOCKET_SELECT
try
{
-#if FEATURE_SOCKET_POLL
// Block until either data is available or the socket is closed
var connectionClosedOrDataAvailable = socket.Poll(-1, SelectMode.SelectRead);
if (connectionClosedOrDataAvailable && socket.Available == 0)
@@ -1816,43 +1908,6 @@ private void MessageListener()
// connection with SSH server was closed or connection was reset
break;
}
-#elif FEATURE_SOCKET_SELECT
- var readSockets = new List { socket };
-
- // if the socket is already disposed when Select is invoked, then a SocketException
- // stating "An operation was attempted on something that is not a socket" is thrown;
- // we attempt to avoid this exception by having an IsConnected() that can break the
- // message loop
- //
- // note that there's no guarantee that the socket will not be disposed between the
- // IsConnected() check and the Select invocation; we can't take a "dispose" lock
- // that includes the Select invocation as we want Dispose() to be able to interrupt
- // the Select
-
- // perform a blocking select to determine whether there's is data available to be
- // read; we do not use a blocking read to allow us to use Socket.Poll to determine
- // if the connection is still available (in IsSocketConnected)
-
- Socket.Select(readSockets, null, null, -1);
-
- // the Select invocation will be interrupted in one of the following conditions:
- // * data is available to be read
- // => the socket will not be removed from "readSockets"
- // * the socket connection is closed during the Select invocation
- // => the socket will be removed from "readSockets"
- // * the socket is disposed during the Select invocation
- // => the socket will not be removed from "readSocket"
- //
- // since we handle the second and third condition the same way and Socket.Connected
- // allows us to check for both conditions, we use that instead of both checking for
- // the removal from "readSockets" and the Connection check
- if (!socket.IsConnected())
- {
- // connection with SSH server was closed or socket was disposed;
- // break out of the message loop
- break;
- }
-#endif // FEATURE_SOCKET_SELECT
}
catch (ObjectDisposedException)
{
@@ -1862,13 +1917,11 @@ private void MessageListener()
// * a SSH_MSG_DISCONNECT received from server
break;
}
-#endif // FEATURE_SOCKET_POLL || FEATURE_SOCKET_SELECT
var message = ReceiveMessage(socket);
- if (message == null)
+ if (message is null)
{
- // connection with SSH server was closed;
- // break out of the message loop
+ // Connection with SSH server was closed, so break out of the message loop
break;
}
@@ -1890,7 +1943,7 @@ private void MessageListener()
finally
{
// signal that the message listener thread has stopped
- _messageListenerCompleted.Set();
+ _ = _messageListenerCompleted.Set();
}
}
@@ -1906,25 +1959,26 @@ private void RaiseError(Exception exp)
if (_isDisconnecting)
{
- // a connection exception which is raised while isDisconnecting is normal and
- // should be ignored
+ // a connection exception which is raised while isDisconnecting is normal and
+ // should be ignored
if (connectionException != null)
+ {
return;
+ }
// any timeout while disconnecting can be caused by loss of connectivity
// altogether and should be ignored
- var socketException = exp as SocketException;
- if (socketException != null && socketException.SocketErrorCode == SocketError.TimedOut)
+ if (exp is SocketException socketException && socketException.SocketErrorCode == SocketError.TimedOut)
+ {
return;
+ }
}
// "save" exception and set exception wait handle to ensure any waits are interrupted
_exception = exp;
- _exceptionWaitHandle.Set();
+ _ = _exceptionWaitHandle.Set();
- var errorOccured = ErrorOccured;
- if (errorOccured != null)
- errorOccured(this, new ExceptionEventArgs(exp));
+ ErrorOccured?.Invoke(this, new ExceptionEventArgs(exp));
if (connectionException != null)
{
@@ -1939,19 +1993,15 @@ private void RaiseError(Exception exp)
///
private void Reset()
{
- if (_exceptionWaitHandle != null)
- _exceptionWaitHandle.Reset();
- if (_keyExchangeCompletedWaitHandle != null)
- _keyExchangeCompletedWaitHandle.Reset();
- if (_messageListenerCompleted != null)
- _messageListenerCompleted.Set();
+ _ = _exceptionWaitHandle?.Reset();
+ _keyExchangeCompletedWaitHandle?.Reset();
+ _ = _messageListenerCompleted?.Set();
SessionId = null;
_isDisconnectMessageSent = false;
_isDisconnecting = false;
_isAuthenticated = false;
_exception = null;
- _keyExchangeInProgress = false;
}
private static SshConnectionException CreateConnectionAbortedByServerException()
@@ -1960,8 +2010,6 @@ private static SshConnectionException CreateConnectionAbortedByServerException()
DisconnectReason.ConnectionLost);
}
-#region IDisposable implementation
-
private bool _disposed;
///
@@ -1969,18 +2017,20 @@ private static SshConnectionException CreateConnectionAbortedByServerException()
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_disposed)
+ {
return;
+ }
if (disposing)
{
@@ -2009,6 +2059,16 @@ protected virtual void Dispose(bool disposing)
_keyExchangeCompletedWaitHandle = null;
}
+ if (_serverCipher is IDisposable disposableServerCipher)
+ {
+ disposableServerCipher.Dispose();
+ }
+
+ if (_clientCipher is IDisposable disposableClientCipher)
+ {
+ disposableClientCipher.Dispose();
+ }
+
var serverMac = _serverMac;
if (serverMac != null)
{
@@ -2043,20 +2103,15 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~Session()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-#endregion IDisposable implementation
-
-#region ISession implementation
-
///
- /// Gets or sets the connection info.
+ /// Gets the connection info.
///
/// The connection info.
IConnectionInfo ISession.ConnectionInfo
@@ -2064,6 +2119,13 @@ IConnectionInfo ISession.ConnectionInfo
get { return ConnectionInfo; }
}
+ ///
+ /// Gets a that can be used to wait for the message listener loop to complete.
+ ///
+ ///
+ /// A that can be used to wait for the message listener loop to complete, or
+ /// when the session has not been connected.
+ ///
WaitHandle ISession.MessageListenerCompleted
{
get { return _messageListenerCompleted; }
@@ -2094,6 +2156,9 @@ IChannelDirectTcpip ISession.CreateChannelDirectTcpip()
///
/// Creates a "forwarded-tcpip" SSH channel.
///
+ /// The number of the remote channel.
+ /// The window size of the remote channel.
+ /// The data packet size of the remote channel.
///
/// A new "forwarded-tcpip" SSH channel.
///
@@ -2127,19 +2192,17 @@ void ISession.SendMessage(Message message)
///
/// The message to send.
///
- /// true if the message was sent to the server; otherwise, false.
+ /// if the message was sent to the server; otherwise, .
///
/// The size of the packet exceeds the maximum size defined by the protocol.
///
- /// This methods returns false when the attempt to send the message results in a
+ /// This methods returns when the attempt to send the message results in a
/// or a .
///
bool ISession.TrySendMessage(Message message)
{
return TrySendMessage(message);
}
-
-#endregion ISession implementation
}
///
@@ -2167,4 +2230,4 @@ internal enum WaitResult
///
Failed = 4
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Sftp/Flags.cs b/src/Renci.SshNet/Sftp/Flags.cs
index 68ae5b10b..6f0a0e6ca 100644
--- a/src/Renci.SshNet/Sftp/Flags.cs
+++ b/src/Renci.SshNet/Sftp/Flags.cs
@@ -3,31 +3,44 @@
namespace Renci.SshNet.Sftp
{
[Flags]
+#pragma warning disable S2344 // Enumeration type names should not have "Flags" or "Enum" suffixes
+#pragma warning disable MA0062 // Non-flags enums should not be marked with "FlagsAttribute"
internal enum Flags
+#pragma warning restore MA0062 // Non-flags enums should not be marked with "FlagsAttribute"
+#pragma warning restore S2344 // Enumeration type names should not have "Flags" or "Enum" suffixes
{
+ ///
+ /// None.
+ ///
None = 0x00000000,
+
///
- /// SSH_FXF_READ
+ /// SSH_FXF_READ.
///
Read = 0x00000001,
+
///
- /// SSH_FXF_WRITE
+ /// SSH_FXF_WRITE.
///
Write = 0x00000002,
+
///
- /// SSH_FXF_APPEND
+ /// SSH_FXF_APPEND.
///
Append = 0x00000004,
+
///
- /// SSH_FXF_CREAT
+ /// SSH_FXF_CREAT.
///
CreateNewOrOpen = 0x00000008,
+
///
- /// SSH_FXF_TRUNC
+ /// SSH_FXF_TRUNC.
///
Truncate = 0x00000010,
+
///
- /// SSH_FXF_EXCL
+ /// SSH_FXF_EXCL.
///
CreateNew = 0x00000028
}
diff --git a/src/Renci.SshNet/Sftp/ISftpFile.cs b/src/Renci.SshNet/Sftp/ISftpFile.cs
new file mode 100644
index 000000000..02dff7215
--- /dev/null
+++ b/src/Renci.SshNet/Sftp/ISftpFile.cs
@@ -0,0 +1,242 @@
+using System;
+
+namespace Renci.SshNet.Sftp
+{
+ ///
+ /// Represents SFTP file information.
+ ///
+ public interface ISftpFile
+ {
+ ///
+ /// Gets the file attributes.
+ ///
+ SftpFileAttributes Attributes { get; }
+
+ ///
+ /// Gets the full path of the file or directory.
+ ///
+ ///
+ /// The full path of the file or directory.
+ ///
+ string FullName { get; }
+
+ ///
+ /// Gets the name of the file or directory.
+ ///
+ ///
+ /// The name of the file or directory.
+ ///
+ ///
+ /// For directories, this is the name of the last directory in the hierarchy if a hierarchy exists;
+ /// otherwise, the name of the directory.
+ ///
+ string Name { get; }
+
+ ///
+ /// Gets or sets the time the current file or directory was last accessed.
+ ///
+ ///
+ /// The time that the current file or directory was last accessed.
+ ///
+ DateTime LastAccessTime { get; set; }
+
+ ///
+ /// Gets or sets the time when the current file or directory was last written to.
+ ///
+ ///
+ /// The time the current file was last written.
+ ///
+ DateTime LastWriteTime { get; set; }
+
+ ///
+ /// Gets or sets the time, in coordinated universal time (UTC), the current file or directory was last accessed.
+ ///
+ ///
+ /// The time that the current file or directory was last accessed.
+ ///
+ DateTime LastAccessTimeUtc { get; set; }
+
+ ///
+ /// Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to.
+ ///
+ ///
+ /// The time the current file was last written.
+ ///
+ DateTime LastWriteTimeUtc { get; set; }
+
+ ///
+ /// Gets the size, in bytes, of the current file.
+ ///
+ ///
+ /// The size of the current file in bytes.
+ ///
+ long Length { get; }
+
+ ///
+ /// Gets or sets file user id.
+ ///
+ ///
+ /// File user id.
+ ///
+ int UserId { get; set; }
+
+ ///
+ /// Gets or sets file group id.
+ ///
+ ///
+ /// File group id.
+ ///
+ int GroupId { get; set; }
+
+ ///
+ /// Gets a value indicating whether file represents a socket.
+ ///
+ ///
+ /// if file represents a socket; otherwise, .
+ ///
+ bool IsSocket { get; }
+
+ ///
+ /// Gets a value indicating whether file represents a symbolic link.
+ ///
+ ///
+ /// if file represents a symbolic link; otherwise, .
+ ///
+ bool IsSymbolicLink { get; }
+
+ ///
+ /// Gets a value indicating whether file represents a regular file.
+ ///
+ ///
+ /// if file represents a regular file; otherwise, .
+ ///
+ bool IsRegularFile { get; }
+
+ ///
+ /// Gets a value indicating whether file represents a block device.
+ ///
+ ///
+ /// if file represents a block device; otherwise, .
+ ///
+ bool IsBlockDevice { get; }
+
+ ///
+ /// Gets a value indicating whether file represents a directory.
+ ///
+ ///
+ /// if file represents a directory; otherwise, .
+ ///
+ bool IsDirectory { get; }
+
+ ///
+ /// Gets a value indicating whether file represents a character device.
+ ///
+ ///
+ /// if file represents a character device; otherwise, .
+ ///
+ bool IsCharacterDevice { get; }
+
+ ///
+ /// Gets a value indicating whether file represents a named pipe.
+ ///
+ ///
+ /// if file represents a named pipe; otherwise, .
+ ///
+ bool IsNamedPipe { get; }
+
+ ///
+ /// Gets or sets a value indicating whether the owner can read from this file.
+ ///
+ ///
+ /// if owner can read from this file; otherwise, .
+ ///
+ bool OwnerCanRead { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether the owner can write into this file.
+ ///
+ ///
+ /// if owner can write into this file; otherwise, .
+ ///
+ bool OwnerCanWrite { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether the owner can execute this file.
+ ///
+ ///
+ /// if owner can execute this file; otherwise, .
+ ///
+ bool OwnerCanExecute { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether the group members can read from this file.
+ ///
+ ///
+ /// if group members can read from this file; otherwise, .
+ ///
+ bool GroupCanRead { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether the group members can write into this file.
+ ///
+ ///
+ /// if group members can write into this file; otherwise, .
+ ///
+ bool GroupCanWrite { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether the group members can execute this file.
+ ///
+ ///
+ /// if group members can execute this file; otherwise, .
+ ///
+ bool GroupCanExecute { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether the others can read from this file.
+ ///
+ ///
+ /// if others can read from this file; otherwise, .
+ ///
+ bool OthersCanRead { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether the others can write into this file.
+ ///
+ ///
+ /// if others can write into this file; otherwise, .
+ ///
+ bool OthersCanWrite { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether the others can execute this file.
+ ///
+ ///
+ /// if others can execute this file; otherwise, .
+ ///
+ bool OthersCanExecute { get; set; }
+
+ ///
+ /// Sets file permissions.
+ ///
+ /// The mode.
+ void SetPermissions(short mode);
+
+ ///
+ /// Permanently deletes a file on remote machine.
+ ///
+ void Delete();
+
+ ///
+ /// Moves a specified file to a new location on remote machine, providing the option to specify a new file name.
+ ///
+ /// The path to move the file to, which can specify a different file name.
+ /// is .
+ void MoveTo(string destFileName);
+
+ ///
+ /// Updates file status on the server.
+ ///
+ void UpdateStatus();
+ }
+}
diff --git a/src/Renci.SshNet/Sftp/ISftpFileReader.cs b/src/Renci.SshNet/Sftp/ISftpFileReader.cs
index 684cc4187..823b2e23a 100644
--- a/src/Renci.SshNet/Sftp/ISftpFileReader.cs
+++ b/src/Renci.SshNet/Sftp/ISftpFileReader.cs
@@ -1,9 +1,23 @@
using System;
+using Renci.SshNet.Common;
+
namespace Renci.SshNet.Sftp
{
+ ///
+ /// Reads a given file.
+ ///
internal interface ISftpFileReader : IDisposable
{
+ ///
+ /// Reads a sequence of bytes from the current file and advances the position within the file by the number of bytes read.
+ ///
+ ///
+ /// The sequence of bytes read from the file, or a zero-length array if the end of the file
+ /// has been reached.
+ ///
+ /// The current is disposed.
+ /// Attempting to read beyond the end of the file.
byte[] Read();
}
}
diff --git a/src/Renci.SshNet/Sftp/ISftpResponseFactory.cs b/src/Renci.SshNet/Sftp/ISftpResponseFactory.cs
index afb440c10..ae57110fc 100644
--- a/src/Renci.SshNet/Sftp/ISftpResponseFactory.cs
+++ b/src/Renci.SshNet/Sftp/ISftpResponseFactory.cs
@@ -2,8 +2,21 @@
namespace Renci.SshNet.Sftp
{
+ ///
+ /// Represents a factory for creating SFTP response messages.
+ ///
internal interface ISftpResponseFactory
{
+ ///
+ /// Creates a SFTP response message for the specified protocol version and message type, and
+ /// with the specified .
+ ///
+ /// The protocol version.
+ /// The message type.
+ /// The .
+ ///
+ /// A .
+ ///
SftpMessage Create(uint protocolVersion, byte messageType, Encoding encoding);
}
}
diff --git a/src/Renci.SshNet/Sftp/ISftpSession.cs b/src/Renci.SshNet/Sftp/ISftpSession.cs
index 3d3993bbd..ed9b72369 100644
--- a/src/Renci.SshNet/Sftp/ISftpSession.cs
+++ b/src/Renci.SshNet/Sftp/ISftpSession.cs
@@ -1,10 +1,15 @@
using System;
using System.Collections.Generic;
using System.Threading;
+using System.Threading.Tasks;
+
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp
{
+ ///
+ /// Represents an SFTP session.
+ ///
internal interface ISftpSession : ISubsystemSession
{
///
@@ -39,27 +44,50 @@ internal interface ISftpSession : ISubsystemSession
string GetCanonicalPath(string path);
///
- /// Performs SSH_FXP_FSTAT request.
+ /// Asynchronously resolves a given path into an absolute path on the server.
+ ///
+ /// The path to resolve.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents an asynchronous operation to resolve into
+ /// an absolute path. The value of its contains the absolute
+ /// path of the specified path.
+ ///
+ Task GetCanonicalPathAsync(string path, CancellationToken cancellationToken);
+
+ ///
+ /// Asynchronously performs a SSH_FXP_FSTAT request.
///
/// The handle.
- /// if set to true returns null instead of throwing an exception.
+ /// If set to , is returned in case of an error.
///
- /// File attributes
+ /// The file attributes.
///
SftpFileAttributes RequestFStat(byte[] handle, bool nullOnError);
+ ///
+ /// Asynchronously performs a SSH_FXP_FSTAT request.
+ ///
+ /// The handle.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task the represents the asynchronous SSH_FXP_FSTAT request. The value of its
+ /// contains the file attributes of the specified handle.
+ ///
+ Task RequestFStatAsync(byte[] handle, CancellationToken cancellationToken);
+
///
/// Performs SSH_FXP_STAT request.
///
/// The path.
- /// if set to true returns null instead of throwing an exception.
+ /// If set to , is returned in case of an error.
///
- /// File attributes
+ /// File attributes.
///
SftpFileAttributes RequestStat(string path, bool nullOnError = false);
///
- /// Performs SSH_FXP_STAT request
+ /// Performs SSH_FXP_STAT request.
///
/// The path.
/// The delegate that is executed when completes.
@@ -76,7 +104,7 @@ internal interface ISftpSession : ISubsystemSession
///
/// The file attributes.
///
- /// is null.
+ /// is .
SftpFileAttributes EndStat(SFtpStatAsyncResult asyncResult);
///
@@ -84,7 +112,7 @@ internal interface ISftpSession : ISubsystemSession
///
/// The path.
///
- /// File attributes
+ /// File attributes.
///
SftpFileAttributes RequestLStat(string path);
@@ -106,7 +134,7 @@ internal interface ISftpSession : ISubsystemSession
///
/// The file attributes.
///
- /// is null.
+ /// is .
SftpFileAttributes EndLStat(SFtpStatAsyncResult asyncResult);
///
@@ -116,16 +144,30 @@ internal interface ISftpSession : ISubsystemSession
void RequestMkDir(string path);
///
- /// Performs SSH_FXP_OPEN request
+ /// Performs a SSH_FXP_OPEN request.
///
/// The path.
/// The flags.
- /// if set to true returns null instead of throwing an exception.
- /// File handle.
+ /// If set to , is returned in case of an error.
+ ///
+ /// The file handle for the specified path.
+ ///
byte[] RequestOpen(string path, Flags flags, bool nullOnError = false);
///
- /// Performs SSH_FXP_OPEN request
+ /// Asynchronously performs a SSH_FXP_OPEN request.
+ ///
+ /// The path.
+ /// The flags.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task the represents the asynchronous SSH_FXP_OPEN request. The value of its
+ /// contains the file handle of the specified path.
+ ///
+ Task RequestOpenAsync(string path, Flags flags, CancellationToken cancellationToken);
+
+ ///
+ /// Performs SSH_FXP_OPEN request.
///
/// The path.
/// The flags.
@@ -147,17 +189,30 @@ internal interface ISftpSession : ISubsystemSession
/// If all available data has been read, the method completes
/// immediately and returns zero bytes.
///
- /// is null.
+ /// is .
byte[] EndOpen(SftpOpenAsyncResult asyncResult);
///
- /// Performs SSH_FXP_OPENDIR request
+ /// Performs a SSH_FXP_OPENDIR request.
///
/// The path.
- /// if set to true returns null instead of throwing an exception.
- /// File handle.
+ /// If set to , is returned in case of an error.
+ ///
+ /// A file handle for the specified path.
+ ///
byte[] RequestOpenDir(string path, bool nullOnError = false);
+ ///
+ /// Asynchronously performs a SSH_FXP_OPENDIR request.
+ ///
+ /// The path.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_OPENDIR request. The value of its
+ /// contains the handle of the specified path.
+ ///
+ Task RequestOpenDirAsync(string path, CancellationToken cancellationToken);
+
///
/// Performs posix-rename@openssh.com extended request.
///
@@ -171,7 +226,7 @@ internal interface ISftpSession : ISubsystemSession
/// The handle.
/// The offset.
/// The length.
- /// data array; null if EOF
+ /// data array; null if EOF.
byte[] RequestRead(byte[] handle, ulong offset, uint length);
///
@@ -198,16 +253,46 @@ internal interface ISftpSession : ISubsystemSession
/// If all available data has been read, the method completes
/// immediately and returns zero bytes.
///
- /// is null.
+ /// is .
byte[] EndRead(SftpReadAsyncResult asyncResult);
///
- /// Performs SSH_FXP_READDIR request
+ /// Asynchronously performs a SSH_FXP_READ request.
///
- /// The handle.
- ///
+ /// The handle to the file to read from.
+ /// The offset in the file to start reading from.
+ /// The number of bytes to read.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_READ request. The value of
+ /// its contains the data read from the file, or an empty
+ /// array when the end of the file is reached.
+ ///
+ Task RequestReadAsync(byte[] handle, ulong offset, uint length, CancellationToken cancellationToken);
+
+ ///
+ /// Performs a SSH_FXP_READDIR request.
+ ///
+ /// The handle of the directory to read.
+ ///
+ /// A where the key is the name of a file in the directory
+ /// and the value is the of the file.
+ ///
KeyValuePair[] RequestReadDir(byte[] handle);
+ ///
+ /// Performs a SSH_FXP_READDIR request.
+ ///
+ /// The handle of the directory to read.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_READDIR request. The value of its
+ /// contains a where the
+ /// key is the name of a file in the directory and the value is the
+ /// of the file.
+ ///
+ Task[]> RequestReadDirAsync(byte[] handle, CancellationToken cancellationToken);
+
///
/// Performs SSH_FXP_REALPATH request.
///
@@ -226,22 +311,43 @@ internal interface ISftpSession : ISubsystemSession
///
/// The absolute path.
///
- /// is null.
+ /// is .
string EndRealPath(SftpRealPathAsyncResult asyncResult);
///
- /// Performs SSH_FXP_REMOVE request.
+ /// Performs a SSH_FXP_REMOVE request.
///
/// The path.
void RequestRemove(string path);
///
- /// Performs SSH_FXP_RENAME request.
+ /// Asynchronously performs a SSH_FXP_REMOVE request.
+ ///
+ /// The path.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_REMOVE request.
+ ///
+ Task RequestRemoveAsync(string path, CancellationToken cancellationToken);
+
+ ///
+ /// Performs a SSH_FXP_RENAME request.
///
/// The old path.
/// The new path.
void RequestRename(string oldPath, string newPath);
+ ///
+ /// Asynchronously performs a SSH_FXP_RENAME request.
+ ///
+ /// The old path.
+ /// The new path.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_RENAME request.
+ ///
+ Task RequestRenameAsync(string oldPath, string newPath, CancellationToken cancellationToken);
+
///
/// Performs SSH_FXP_RMDIR request.
///
@@ -256,13 +362,28 @@ internal interface ISftpSession : ISubsystemSession
void RequestSetStat(string path, SftpFileAttributes attributes);
///
- /// Performs statvfs@openssh.com extended request.
+ /// Performs a statvfs@openssh.com extended request.
///
/// The path.
- /// if set to true [null on error].
- ///
+ /// If set to , is returned in case of an error.
+ ///
+ /// The file system information for the specified path, or when
+ /// the request failed and is .
+ ///
SftpFileSytemInformation RequestStatVfs(string path, bool nullOnError = false);
+ ///
+ /// Asynchronously performs a statvfs@openssh.com extended request.
+ ///
+ /// The path.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the statvfs@openssh.com extended request. The value of its
+ /// contains the file system information for the specified
+ /// path.
+ ///
+ Task RequestStatVfsAsync(string path, CancellationToken cancellationToken);
+
///
/// Performs SSH_FXP_SYMLINK request.
///
@@ -296,11 +417,35 @@ void RequestWrite(byte[] handle,
Action writeCompleted = null);
///
- /// Performs SSH_FXP_CLOSE request.
+ /// Asynchronouly performs a SSH_FXP_WRITE request.
+ ///
+ /// The handle.
+ /// The the zero-based offset (in bytes) relative to the beginning of the file that the write must start at.
+ /// The buffer holding the data to write.
+ /// the zero-based offset in at which to begin taking bytes to write.
+ /// The length (in bytes) of the data to write.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_WRITE request.
+ ///
+ Task RequestWriteAsync(byte[] handle, ulong serverOffset, byte[] data, int offset, int length, CancellationToken cancellationToken);
+
+ ///
+ /// Performs a SSH_FXP_CLOSE request.
///
/// The handle.
void RequestClose(byte[] handle);
+ ///
+ /// Performs a SSH_FXP_CLOSE request.
+ ///
+ /// The handle.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_CLOSE request.
+ ///
+ Task RequestCloseAsync(byte[] handle, CancellationToken cancellationToken);
+
///
/// Performs SSH_FXP_CLOSE request.
///
@@ -316,7 +461,7 @@ void RequestWrite(byte[] handle,
/// Handles the end of an asynchronous close.
///
/// An that represents an asynchronous call.
- /// is null.
+ /// is .
void EndClose(SftpCloseAsyncResult asyncResult);
///
@@ -341,6 +486,18 @@ void RequestWrite(byte[] handle,
///
uint CalculateOptimalWriteLength(uint bufferSize, byte[] handle);
+ ///
+ /// Creates an for reading the content of the file represented by a given .
+ ///
+ /// The handle of the file to read.
+ /// The SFTP session.
+ /// The maximum number of bytes to read with each chunk.
+ /// The maximum number of pending reads.
+ /// The size of the file or when the size could not be determined.
+ ///
+ /// An for reading the content of the file represented by the
+ /// specified .
+ ///
ISftpFileReader CreateFileReader(byte[] handle, ISftpSession sftpSession, uint chunkSize, int maxPendingReads, long? fileSize);
}
}
diff --git a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/FStatVfsRequest.cs b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/FStatVfsRequest.cs
index 5b5b02ecd..685c03692 100644
--- a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/FStatVfsRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/FStatVfsRequest.cs
@@ -1,9 +1,10 @@
using System;
+
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp.Requests
{
- internal class FStatVfsRequest : SftpExtendedRequest
+ internal sealed class FStatVfsRequest : SftpExtendedRequest
{
private readonly Action _extendedReplyAction;
@@ -42,8 +43,7 @@ protected override void SaveData()
public override void Complete(SftpResponse response)
{
- var extendedReplyResponse = response as SftpExtendedReplyResponse;
- if (extendedReplyResponse != null)
+ if (response is SftpExtendedReplyResponse extendedReplyResponse)
{
_extendedReplyAction(extendedReplyResponse);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/HardLinkRequest.cs b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/HardLinkRequest.cs
index de7e06db4..cd744f0e2 100644
--- a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/HardLinkRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/HardLinkRequest.cs
@@ -1,9 +1,10 @@
using System;
+
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp.Requests
{
- internal class HardLinkRequest : SftpExtendedRequest
+ internal sealed class HardLinkRequest : SftpExtendedRequest
{
private byte[] _oldPath;
private byte[] _newPath;
@@ -53,4 +54,4 @@ protected override void SaveData()
WriteBinaryString(_newPath);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/PosixRenameRequest.cs b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/PosixRenameRequest.cs
index d0b530f08..5d996723b 100644
--- a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/PosixRenameRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/PosixRenameRequest.cs
@@ -1,10 +1,11 @@
using System;
-using Renci.SshNet.Sftp.Responses;
using System.Text;
+using Renci.SshNet.Sftp.Responses;
+
namespace Renci.SshNet.Sftp.Requests
{
- internal class PosixRenameRequest : SftpExtendedRequest
+ internal sealed class PosixRenameRequest : SftpExtendedRequest
{
private byte[] _oldPath;
private byte[] _newPath;
@@ -21,7 +22,7 @@ public string NewPath
private set { _newPath = Encoding.GetBytes(value); }
}
- public Encoding Encoding { get; private set; }
+ public Encoding Encoding { get; }
///
/// Gets the size of the message in bytes.
@@ -53,8 +54,9 @@ public PosixRenameRequest(uint protocolVersion, uint requestId, string oldPath,
protected override void SaveData()
{
base.SaveData();
+
WriteBinaryString(_oldPath);
WriteBinaryString(_newPath);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/StatVfsRequest.cs b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/StatVfsRequest.cs
index b1bda3c06..fe4373257 100644
--- a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/StatVfsRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/StatVfsRequest.cs
@@ -1,13 +1,14 @@
using System;
-using Renci.SshNet.Sftp.Responses;
using System.Text;
+using Renci.SshNet.Sftp.Responses;
+
namespace Renci.SshNet.Sftp.Requests
{
- internal class StatVfsRequest : SftpExtendedRequest
+ internal sealed class StatVfsRequest : SftpExtendedRequest
{
- private byte[] _path;
private readonly Action _extendedReplyAction;
+ private byte[] _path;
public string Path
{
@@ -51,8 +52,7 @@ protected override void SaveData()
public override void Complete(SftpResponse response)
{
- var extendedReplyResponse = response as SftpExtendedReplyResponse;
- if (extendedReplyResponse != null)
+ if (response is SftpExtendedReplyResponse extendedReplyResponse)
{
_extendedReplyAction(extendedReplyResponse);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpBlockRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpBlockRequest.cs
index 9414150c0..9c2ccd6ca 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpBlockRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpBlockRequest.cs
@@ -1,9 +1,10 @@
using System;
+
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpBlockRequest : SftpRequest
+ internal sealed class SftpBlockRequest : SftpRequest
{
public override SftpMessageTypes SftpMessageType
{
@@ -38,7 +39,7 @@ protected override int BufferCapacity
}
}
- public SftpBlockRequest(uint protocolVersion, uint requestId, byte[] handle, UInt64 offset, UInt64 length, UInt32 lockMask, Action statusAction)
+ public SftpBlockRequest(uint protocolVersion, uint requestId, byte[] handle, ulong offset, ulong length, uint lockMask, Action statusAction)
: base(protocolVersion, requestId, statusAction)
{
Handle = handle;
@@ -50,6 +51,7 @@ public SftpBlockRequest(uint protocolVersion, uint requestId, byte[] handle, UIn
protected override void LoadData()
{
base.LoadData();
+
Handle = ReadBinary();
Offset = ReadUInt64();
Length = ReadUInt64();
@@ -59,6 +61,7 @@ protected override void LoadData()
protected override void SaveData()
{
base.SaveData();
+
WriteBinaryString(Handle);
Write(Offset);
Write(Length);
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpCloseRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpCloseRequest.cs
index dd2dace1a..f17673f95 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpCloseRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpCloseRequest.cs
@@ -3,7 +3,7 @@
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpCloseRequest : SftpRequest
+ internal sealed class SftpCloseRequest : SftpRequest
{
public override SftpMessageTypes SftpMessageType
{
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpExtendedRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpExtendedRequest.cs
index 8693929d5..59da98af5 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpExtendedRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpExtendedRequest.cs
@@ -15,7 +15,10 @@ public override SftpMessageTypes SftpMessageType
public string Name
{
- get { return _name; }
+ get
+ {
+ return _name;
+ }
private set
{
_name = value;
@@ -52,4 +55,4 @@ protected override void SaveData()
WriteBinaryString(_nameBytes);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpFSetStatRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpFSetStatRequest.cs
index 5de45c5ae..d24f757b8 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpFSetStatRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpFSetStatRequest.cs
@@ -3,7 +3,7 @@
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpFSetStatRequest : SftpRequest
+ internal sealed class SftpFSetStatRequest : SftpRequest
{
private byte[] _attributesBytes;
@@ -20,10 +20,7 @@ private byte[] AttributesBytes
{
get
{
- if (_attributesBytes == null)
- {
- _attributesBytes = Attributes.GetBytes();
- }
+ _attributesBytes ??= Attributes.GetBytes();
return _attributesBytes;
}
}
@@ -56,6 +53,7 @@ public SftpFSetStatRequest(uint protocolVersion, uint requestId, byte[] handle,
protected override void LoadData()
{
base.LoadData();
+
Handle = ReadBinary();
Attributes = ReadAttributes();
}
@@ -63,6 +61,7 @@ protected override void LoadData()
protected override void SaveData()
{
base.SaveData();
+
WriteBinaryString(Handle);
Write(AttributesBytes);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpFStatRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpFStatRequest.cs
index da71a62ea..6fa4576f6 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpFStatRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpFStatRequest.cs
@@ -1,9 +1,10 @@
using System;
+
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpFStatRequest : SftpRequest
+ internal sealed class SftpFStatRequest : SftpRequest
{
private readonly Action _attrsAction;
@@ -52,8 +53,7 @@ protected override void SaveData()
public override void Complete(SftpResponse response)
{
- var attrsResponse = response as SftpAttrsResponse;
- if (attrsResponse != null)
+ if (response is SftpAttrsResponse attrsResponse)
{
_attrsAction(attrsResponse);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpInitRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpInitRequest.cs
index cb95c7c0e..25e21dabf 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpInitRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpInitRequest.cs
@@ -1,6 +1,6 @@
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpInitRequest : SftpMessage
+ internal sealed class SftpInitRequest : SftpMessage
{
public override SftpMessageTypes SftpMessageType
{
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpLStatRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpLStatRequest.cs
index 1edb9c695..950ef8f43 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpLStatRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpLStatRequest.cs
@@ -4,10 +4,10 @@
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpLStatRequest : SftpRequest
+ internal sealed class SftpLStatRequest : SftpRequest
{
- private byte[] _path;
private readonly Action _attrsAction;
+ private byte[] _path;
public override SftpMessageTypes SftpMessageType
{
@@ -61,8 +61,7 @@ protected override void SaveData()
public override void Complete(SftpResponse response)
{
- var attrsResponse = response as SftpAttrsResponse;
- if (attrsResponse != null)
+ if (response is SftpAttrsResponse attrsResponse)
{
_attrsAction(attrsResponse);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpLinkRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpLinkRequest.cs
index 04470b36f..b5b8a9efc 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpLinkRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpLinkRequest.cs
@@ -1,9 +1,10 @@
-using Renci.SshNet.Sftp.Responses;
-using System;
+using System;
+
+using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpLinkRequest : SftpRequest
+ internal sealed class SftpLinkRequest : SftpRequest
{
private byte[] _newLinkPath;
private byte[] _existingPath;
@@ -54,7 +55,7 @@ protected override int BufferCapacity
/// The request id.
/// Specifies the path name of the new link to create.
/// Specifies the path of a target object to which the newly created link will refer. In the case of a symbolic link, this path may not exist.
- /// if set to false the link should be a hard link, or a second directory entry referring to the same file or directory object.
+ /// if set to the link should be a hard link, or a second directory entry referring to the same file or directory object.
/// The status action.
public SftpLinkRequest(uint protocolVersion, uint requestId, string newLinkPath, string existingPath, bool isSymLink, Action statusAction)
: base(protocolVersion, requestId, statusAction)
@@ -67,6 +68,7 @@ public SftpLinkRequest(uint protocolVersion, uint requestId, string newLinkPath,
protected override void LoadData()
{
base.LoadData();
+
_newLinkPath = ReadBinary();
_existingPath = ReadBinary();
IsSymLink = ReadBoolean();
@@ -75,6 +77,7 @@ protected override void LoadData()
protected override void SaveData()
{
base.SaveData();
+
WriteBinaryString(_newLinkPath);
WriteBinaryString(_existingPath);
Write(IsSymLink);
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpMkDirRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpMkDirRequest.cs
index 9dc60edc8..126925b95 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpMkDirRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpMkDirRequest.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpMkDirRequest : SftpRequest
+ internal sealed class SftpMkDirRequest : SftpRequest
{
private byte[] _path;
private byte[] _attributesBytes;
@@ -28,10 +28,8 @@ private byte[] AttributesBytes
{
get
{
- if (_attributesBytes == null)
- {
- _attributesBytes = Attributes.GetBytes();
- }
+ _attributesBytes ??= Attributes.GetBytes();
+
return _attributesBytes;
}
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpOpenDirRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpOpenDirRequest.cs
index 81a54b62d..cde5a7af3 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpOpenDirRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpOpenDirRequest.cs
@@ -1,13 +1,14 @@
using System;
using System.Text;
+
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpOpenDirRequest : SftpRequest
+ internal sealed class SftpOpenDirRequest : SftpRequest
{
- private byte[] _path;
private readonly Action _handleAction;
+ private byte[] _path;
public override SftpMessageTypes SftpMessageType
{
@@ -64,8 +65,7 @@ protected override void SaveData()
public override void Complete(SftpResponse response)
{
- var handleResponse = response as SftpHandleResponse;
- if (handleResponse != null)
+ if (response is SftpHandleResponse handleResponse)
{
_handleAction(handleResponse);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpOpenRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpOpenRequest.cs
index da7a7a095..780552fbc 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpOpenRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpOpenRequest.cs
@@ -4,11 +4,11 @@
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpOpenRequest : SftpRequest
+ internal sealed class SftpOpenRequest : SftpRequest
{
+ private readonly Action _handleAction;
private byte[] _fileName;
private byte[] _attributes;
- private readonly Action _handleAction;
public override SftpMessageTypes SftpMessageType
{
@@ -21,7 +21,7 @@ public string Filename
private set { _fileName = Encoding.GetBytes(value); }
}
- public Flags Flags { get; private set; }
+ public Flags Flags { get; }
public SftpFileAttributes Attributes
{
@@ -29,7 +29,7 @@ public SftpFileAttributes Attributes
private set { _attributes = value.GetBytes(); }
}
- public Encoding Encoding { get; private set; }
+ public Encoding Encoding { get; }
///
/// Gets the size of the message in bytes.
@@ -83,8 +83,7 @@ protected override void SaveData()
public override void Complete(SftpResponse response)
{
- var handleResponse = response as SftpHandleResponse;
- if (handleResponse != null)
+ if (response is SftpHandleResponse handleResponse)
{
_handleAction(handleResponse);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpReadDirRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpReadDirRequest.cs
index 9d46c69bd..9eae83253 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpReadDirRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpReadDirRequest.cs
@@ -1,9 +1,10 @@
using System;
+
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpReadDirRequest : SftpRequest
+ internal sealed class SftpReadDirRequest : SftpRequest
{
private readonly Action _nameAction;
@@ -53,8 +54,7 @@ protected override void SaveData()
public override void Complete(SftpResponse response)
{
- var nameResponse = response as SftpNameResponse;
- if (nameResponse != null)
+ if (response is SftpNameResponse nameResponse)
{
_nameAction(nameResponse);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpReadLinkRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpReadLinkRequest.cs
index 90e36b69b..969eca564 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpReadLinkRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpReadLinkRequest.cs
@@ -1,13 +1,14 @@
using System;
using System.Text;
+
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpReadLinkRequest : SftpRequest
+ internal sealed class SftpReadLinkRequest : SftpRequest
{
- private byte[] _path;
private readonly Action _nameAction;
+ private byte[] _path;
public override SftpMessageTypes SftpMessageType
{
@@ -20,7 +21,7 @@ public string Path
private set { _path = Encoding.GetBytes(value); }
}
- public Encoding Encoding { get; private set; }
+ public Encoding Encoding { get; }
///
/// Gets the size of the message in bytes.
@@ -64,8 +65,7 @@ protected override void SaveData()
public override void Complete(SftpResponse response)
{
- var nameResponse = response as SftpNameResponse;
- if (nameResponse != null)
+ if (response is SftpNameResponse nameResponse)
{
_nameAction(nameResponse);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpReadRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpReadRequest.cs
index 72dc92877..b413b4a3a 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpReadRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpReadRequest.cs
@@ -1,9 +1,10 @@
using System;
+
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpReadRequest : SftpRequest
+ internal sealed class SftpReadRequest : SftpRequest
{
private readonly Action _dataAction;
@@ -37,7 +38,7 @@ protected override int BufferCapacity
}
}
- public SftpReadRequest(uint protocolVersion, uint requestId, byte[] handle, UInt64 offset, UInt32 length, Action dataAction, Action statusAction)
+ public SftpReadRequest(uint protocolVersion, uint requestId, byte[] handle, ulong offset, uint length, Action dataAction, Action statusAction)
: base(protocolVersion, requestId, statusAction)
{
Handle = handle;
@@ -49,6 +50,7 @@ public SftpReadRequest(uint protocolVersion, uint requestId, byte[] handle, UInt
protected override void LoadData()
{
base.LoadData();
+
Handle = ReadBinary();
Offset = ReadUInt64();
Length = ReadUInt32();
@@ -57,6 +59,7 @@ protected override void LoadData()
protected override void SaveData()
{
base.SaveData();
+
WriteBinaryString(Handle);
Write(Offset);
Write(Length);
@@ -64,8 +67,7 @@ protected override void SaveData()
public override void Complete(SftpResponse response)
{
- var dataResponse = response as SftpDataResponse;
- if (dataResponse != null)
+ if (response is SftpDataResponse dataResponse)
{
_dataAction(dataResponse);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpRealPathRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpRealPathRequest.cs
index 44b11e90b..d19497f0b 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpRealPathRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpRealPathRequest.cs
@@ -1,13 +1,14 @@
using System;
using System.Text;
+
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpRealPathRequest : SftpRequest
+ internal sealed class SftpRealPathRequest : SftpRequest
{
- private byte[] _path;
private readonly Action _nameAction;
+ private byte[] _path;
public override SftpMessageTypes SftpMessageType
{
@@ -20,7 +21,7 @@ public string Path
private set { _path = Encoding.GetBytes(value); }
}
- public Encoding Encoding { get; private set; }
+ public Encoding Encoding { get; }
///
/// Gets the size of the message in bytes.
@@ -42,12 +43,13 @@ protected override int BufferCapacity
public SftpRealPathRequest(uint protocolVersion, uint requestId, string path, Encoding encoding, Action nameAction, Action statusAction)
: base(protocolVersion, requestId, statusAction)
{
- if (nameAction == null)
- throw new ArgumentNullException("nameAction");
+ if (nameAction is null)
+ {
+ throw new ArgumentNullException(nameof(nameAction));
+ }
Encoding = encoding;
Path = path;
-
_nameAction = nameAction;
}
@@ -59,8 +61,7 @@ protected override void SaveData()
public override void Complete(SftpResponse response)
{
- var nameResponse = response as SftpNameResponse;
- if (nameResponse != null)
+ if (response is SftpNameResponse nameResponse)
{
_nameAction(nameResponse);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpRemoveRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpRemoveRequest.cs
index a527165c9..99d072f50 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpRemoveRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpRemoveRequest.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpRemoveRequest : SftpRequest
+ internal sealed class SftpRemoveRequest : SftpRequest
{
private byte[] _fileName;
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpRenameRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpRenameRequest.cs
index c6cf98f16..8d7fc91a2 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpRenameRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpRenameRequest.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpRenameRequest : SftpRequest
+ internal sealed class SftpRenameRequest : SftpRequest
{
private byte[] _oldPath;
private byte[] _newPath;
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpRequest.cs
index 88458e5fa..a3e4d0595 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpRequest.cs
@@ -7,9 +7,9 @@ internal abstract class SftpRequest : SftpMessage
{
private readonly Action _statusAction;
- public uint RequestId { get; private set; }
-
- public uint ProtocolVersion { get; private set; }
+ public uint RequestId { get; }
+
+ public uint ProtocolVersion { get; }
///
/// Gets the size of the message in bytes.
@@ -36,8 +36,7 @@ protected SftpRequest(uint protocolVersion, uint requestId, Action _attrsAction;
+ private byte[] _path;
public override SftpMessageTypes SftpMessageType
{
@@ -20,7 +20,7 @@ public string Path
private set { _path = Encoding.GetBytes(value); }
}
- public Encoding Encoding { get; private set; }
+ public Encoding Encoding { get; }
///
/// Gets the size of the message in bytes.
@@ -50,19 +50,20 @@ public SftpStatRequest(uint protocolVersion, uint requestId, string path, Encodi
protected override void LoadData()
{
base.LoadData();
+
_path = ReadBinary();
}
protected override void SaveData()
{
base.SaveData();
+
WriteBinaryString(_path);
}
public override void Complete(SftpResponse response)
{
- var attrsResponse = response as SftpAttrsResponse;
- if (attrsResponse != null)
+ if (response is SftpAttrsResponse attrsResponse)
{
_attrsAction(attrsResponse);
}
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpSymLinkRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpSymLinkRequest.cs
index b338923ee..63127cdd5 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpSymLinkRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpSymLinkRequest.cs
@@ -4,7 +4,7 @@
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpSymLinkRequest : SftpRequest
+ internal sealed class SftpSymLinkRequest : SftpRequest
{
private byte[] _newLinkPath;
private byte[] _existingPath;
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpUnblockRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpUnblockRequest.cs
index 7f4a2147a..6dff38360 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpUnblockRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpUnblockRequest.cs
@@ -3,7 +3,7 @@
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpUnblockRequest : SftpRequest
+ internal sealed class SftpUnblockRequest : SftpRequest
{
public override SftpMessageTypes SftpMessageType
{
@@ -35,7 +35,7 @@ protected override int BufferCapacity
}
}
- public SftpUnblockRequest(uint protocolVersion, uint requestId, byte[] handle, UInt64 offset, UInt64 length, Action statusAction)
+ public SftpUnblockRequest(uint protocolVersion, uint requestId, byte[] handle, ulong offset, ulong length, Action statusAction)
: base(protocolVersion, requestId, statusAction)
{
Handle = handle;
@@ -46,6 +46,7 @@ public SftpUnblockRequest(uint protocolVersion, uint requestId, byte[] handle, U
protected override void LoadData()
{
base.LoadData();
+
Handle = ReadBinary();
Offset = ReadUInt64();
Length = ReadUInt64();
@@ -54,6 +55,7 @@ protected override void LoadData()
protected override void SaveData()
{
base.SaveData();
+
WriteBinaryString(Handle);
Write(Offset);
Write(Length);
diff --git a/src/Renci.SshNet/Sftp/Requests/SftpWriteRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpWriteRequest.cs
index 6e8ca3166..be7f6da91 100644
--- a/src/Renci.SshNet/Sftp/Requests/SftpWriteRequest.cs
+++ b/src/Renci.SshNet/Sftp/Requests/SftpWriteRequest.cs
@@ -3,7 +3,7 @@
namespace Renci.SshNet.Sftp.Requests
{
- internal class SftpWriteRequest : SftpRequest
+ internal sealed class SftpWriteRequest : SftpRequest
{
public override SftpMessageTypes SftpMessageType
{
@@ -81,6 +81,7 @@ public SftpWriteRequest(uint protocolVersion,
protected override void LoadData()
{
base.LoadData();
+
Handle = ReadBinary();
ServerFileOffset = ReadUInt64();
Data = ReadBinary();
@@ -91,6 +92,7 @@ protected override void LoadData()
protected override void SaveData()
{
base.SaveData();
+
WriteBinaryString(Handle);
Write(ServerFileOffset);
WriteBinary(Data, Offset, Length);
diff --git a/src/Renci.SshNet/Sftp/Responses/ExtendedReplies/StatVfsReplyInfo.cs b/src/Renci.SshNet/Sftp/Responses/ExtendedReplies/StatVfsReplyInfo.cs
index 71c45dc15..d7cecf8f9 100644
--- a/src/Renci.SshNet/Sftp/Responses/ExtendedReplies/StatVfsReplyInfo.cs
+++ b/src/Renci.SshNet/Sftp/Responses/ExtendedReplies/StatVfsReplyInfo.cs
@@ -2,7 +2,7 @@
namespace Renci.SshNet.Sftp.Responses
{
- internal class StatVfsReplyInfo : ExtendedReplyInfo
+ internal sealed class StatVfsReplyInfo : ExtendedReplyInfo
{
public SftpFileSytemInformation Information { get; private set; }
@@ -18,8 +18,7 @@ public override void LoadData(SshDataStream stream)
stream.ReadUInt64(), // AvailableNodes
stream.ReadUInt64(), // Sid
stream.ReadUInt64(), // Flags
- stream.ReadUInt64() // MaxNameLenght
- );
+ stream.ReadUInt64()); // MaxNameLenght
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Sftp/Responses/SftpAttrsResponse.cs b/src/Renci.SshNet/Sftp/Responses/SftpAttrsResponse.cs
index fbf3250e9..f26aa5d33 100644
--- a/src/Renci.SshNet/Sftp/Responses/SftpAttrsResponse.cs
+++ b/src/Renci.SshNet/Sftp/Responses/SftpAttrsResponse.cs
@@ -1,6 +1,6 @@
namespace Renci.SshNet.Sftp.Responses
{
- internal class SftpAttrsResponse : SftpResponse
+ internal sealed class SftpAttrsResponse : SftpResponse
{
public override SftpMessageTypes SftpMessageType
{
@@ -17,6 +17,7 @@ public SftpAttrsResponse(uint protocolVersion)
protected override void LoadData()
{
base.LoadData();
+
Attributes = ReadAttributes();
}
}
diff --git a/src/Renci.SshNet/Sftp/Responses/SftpDataResponse.cs b/src/Renci.SshNet/Sftp/Responses/SftpDataResponse.cs
index f15a8dcc0..04a7d4d82 100644
--- a/src/Renci.SshNet/Sftp/Responses/SftpDataResponse.cs
+++ b/src/Renci.SshNet/Sftp/Responses/SftpDataResponse.cs
@@ -1,6 +1,6 @@
namespace Renci.SshNet.Sftp.Responses
{
- internal class SftpDataResponse : SftpResponse
+ internal sealed class SftpDataResponse : SftpResponse
{
public override SftpMessageTypes SftpMessageType
{
@@ -17,7 +17,7 @@ public SftpDataResponse(uint protocolVersion)
protected override void LoadData()
{
base.LoadData();
-
+
Data = ReadBinary();
}
diff --git a/src/Renci.SshNet/Sftp/Responses/SftpExtendedReplyResponse.cs b/src/Renci.SshNet/Sftp/Responses/SftpExtendedReplyResponse.cs
index 1a7048ec5..84fe93d35 100644
--- a/src/Renci.SshNet/Sftp/Responses/SftpExtendedReplyResponse.cs
+++ b/src/Renci.SshNet/Sftp/Responses/SftpExtendedReplyResponse.cs
@@ -1,6 +1,6 @@
namespace Renci.SshNet.Sftp.Responses
{
- internal class SftpExtendedReplyResponse : SftpResponse
+ internal sealed class SftpExtendedReplyResponse : SftpResponse
{
public override SftpMessageTypes SftpMessageType
{
@@ -12,7 +12,8 @@ public SftpExtendedReplyResponse(uint protocolVersion)
{
}
- public T GetReply() where T : ExtendedReplyInfo, new()
+ public T GetReply()
+ where T : ExtendedReplyInfo, new()
{
var result = new T();
result.LoadData(DataStream);
diff --git a/src/Renci.SshNet/Sftp/Responses/SftpHandleResponse.cs b/src/Renci.SshNet/Sftp/Responses/SftpHandleResponse.cs
index 233e3e371..21af8f835 100644
--- a/src/Renci.SshNet/Sftp/Responses/SftpHandleResponse.cs
+++ b/src/Renci.SshNet/Sftp/Responses/SftpHandleResponse.cs
@@ -1,6 +1,6 @@
namespace Renci.SshNet.Sftp.Responses
{
- internal class SftpHandleResponse : SftpResponse
+ internal sealed class SftpHandleResponse : SftpResponse
{
public override SftpMessageTypes SftpMessageType
{
@@ -17,7 +17,7 @@ public SftpHandleResponse(uint protocolVersion)
protected override void LoadData()
{
base.LoadData();
-
+
Handle = ReadBinary();
}
diff --git a/src/Renci.SshNet/Sftp/Responses/SftpNameResponse.cs b/src/Renci.SshNet/Sftp/Responses/SftpNameResponse.cs
index 3750119d4..2bdf67891 100644
--- a/src/Renci.SshNet/Sftp/Responses/SftpNameResponse.cs
+++ b/src/Renci.SshNet/Sftp/Responses/SftpNameResponse.cs
@@ -1,10 +1,10 @@
-using Renci.SshNet.Common;
+using System;
using System.Collections.Generic;
using System.Text;
namespace Renci.SshNet.Sftp.Responses
{
- internal class SftpNameResponse : SftpResponse
+ internal sealed class SftpNameResponse : SftpResponse
{
public override SftpMessageTypes SftpMessageType
{
@@ -20,14 +20,14 @@ public override SftpMessageTypes SftpMessageType
public SftpNameResponse(uint protocolVersion, Encoding encoding)
: base(protocolVersion)
{
- Files = Array>.Empty;
+ Files = Array.Empty>();
Encoding = encoding;
}
protected override void LoadData()
{
base.LoadData();
-
+
Count = ReadUInt32();
Files = new KeyValuePair[Count];
@@ -36,8 +36,9 @@ protected override void LoadData()
var fileName = ReadString(Encoding);
if (SupportsLongName(ProtocolVersion))
{
- ReadString(Encoding); // skip longname
+ _ = ReadString(Encoding); // skip longname
}
+
Files[i] = new KeyValuePair(fileName, ReadAttributes());
}
}
diff --git a/src/Renci.SshNet/Sftp/Responses/SftpResponse.cs b/src/Renci.SshNet/Sftp/Responses/SftpResponse.cs
index 3b784bf09..5e3ac145b 100644
--- a/src/Renci.SshNet/Sftp/Responses/SftpResponse.cs
+++ b/src/Renci.SshNet/Sftp/Responses/SftpResponse.cs
@@ -14,7 +14,7 @@ protected SftpResponse(uint protocolVersion)
protected override void LoadData()
{
base.LoadData();
-
+
ResponseId = ReadUInt32();
}
diff --git a/src/Renci.SshNet/Sftp/Responses/SftpStatusResponse.cs b/src/Renci.SshNet/Sftp/Responses/SftpStatusResponse.cs
index f41692f04..2f43cdc37 100644
--- a/src/Renci.SshNet/Sftp/Responses/SftpStatusResponse.cs
+++ b/src/Renci.SshNet/Sftp/Responses/SftpStatusResponse.cs
@@ -1,6 +1,6 @@
namespace Renci.SshNet.Sftp.Responses
{
- internal class SftpStatusResponse : SftpResponse
+ internal sealed class SftpStatusResponse : SftpResponse
{
public override SftpMessageTypes SftpMessageType
{
diff --git a/src/Renci.SshNet/Sftp/Responses/SftpVersionResponse.cs b/src/Renci.SshNet/Sftp/Responses/SftpVersionResponse.cs
index 87c9f13f3..1ae8e6d6a 100644
--- a/src/Renci.SshNet/Sftp/Responses/SftpVersionResponse.cs
+++ b/src/Renci.SshNet/Sftp/Responses/SftpVersionResponse.cs
@@ -2,7 +2,7 @@
namespace Renci.SshNet.Sftp.Responses
{
- internal class SftpVersionResponse : SftpMessage
+ internal sealed class SftpVersionResponse : SftpMessage
{
public override SftpMessageTypes SftpMessageType
{
@@ -16,6 +16,7 @@ public override SftpMessageTypes SftpMessageType
protected override void LoadData()
{
base.LoadData();
+
Version = ReadUInt32();
Extentions = ReadExtensionPair();
}
@@ -25,8 +26,11 @@ protected override void SaveData()
base.SaveData();
Write(Version);
+
if (Extentions != null)
+ {
Write(Extentions);
+ }
}
}
}
diff --git a/src/Renci.SshNet/Sftp/SFtpStatAsyncResult.cs b/src/Renci.SshNet/Sftp/SFtpStatAsyncResult.cs
index d3776ce21..41d915499 100644
--- a/src/Renci.SshNet/Sftp/SFtpStatAsyncResult.cs
+++ b/src/Renci.SshNet/Sftp/SFtpStatAsyncResult.cs
@@ -1,11 +1,13 @@
-using Renci.SshNet.Common;
-using System;
+using System;
+
+using Renci.SshNet.Common;
namespace Renci.SshNet.Sftp
{
- internal class SFtpStatAsyncResult : AsyncResult
+ internal sealed class SFtpStatAsyncResult : AsyncResult
{
- public SFtpStatAsyncResult(AsyncCallback asyncCallback, object state) : base(asyncCallback, state)
+ public SFtpStatAsyncResult(AsyncCallback asyncCallback, object state)
+ : base(asyncCallback, state)
{
}
}
diff --git a/src/Renci.SshNet/Sftp/SftpCloseAsyncResult.cs b/src/Renci.SshNet/Sftp/SftpCloseAsyncResult.cs
index 6349371f0..d4148e5c7 100644
--- a/src/Renci.SshNet/Sftp/SftpCloseAsyncResult.cs
+++ b/src/Renci.SshNet/Sftp/SftpCloseAsyncResult.cs
@@ -1,11 +1,13 @@
-using Renci.SshNet.Common;
-using System;
+using System;
+
+using Renci.SshNet.Common;
namespace Renci.SshNet.Sftp
{
- internal class SftpCloseAsyncResult : AsyncResult
+ internal sealed class SftpCloseAsyncResult : AsyncResult
{
- public SftpCloseAsyncResult(AsyncCallback asyncCallback, object state) : base(asyncCallback, state)
+ public SftpCloseAsyncResult(AsyncCallback asyncCallback, object state)
+ : base(asyncCallback, state)
{
}
}
diff --git a/src/Renci.SshNet/Sftp/SftpDownloadAsyncResult.cs b/src/Renci.SshNet/Sftp/SftpDownloadAsyncResult.cs
index 358f53776..9e706d9e0 100644
--- a/src/Renci.SshNet/Sftp/SftpDownloadAsyncResult.cs
+++ b/src/Renci.SshNet/Sftp/SftpDownloadAsyncResult.cs
@@ -6,13 +6,13 @@ namespace Renci.SshNet.Sftp
///
/// Encapsulates the results of an asynchronous download operation.
///
- public class SftpDownloadAsyncResult : AsyncResult
+ public class SftpDownloadAsyncResult : AsyncResult
{
///
/// Gets or sets a value indicating whether to cancel asynchronous download operation.
///
///
- /// true if download operation to be canceled; otherwise, false.
+ /// if download operation to be canceled; otherwise, .
///
///
/// Download operation will be canceled after finishing uploading current buffer.
diff --git a/src/Renci.SshNet/Sftp/SftpFile.cs b/src/Renci.SshNet/Sftp/SftpFile.cs
index cfcc37a2f..2122220be 100644
--- a/src/Renci.SshNet/Sftp/SftpFile.cs
+++ b/src/Renci.SshNet/Sftp/SftpFile.cs
@@ -5,9 +5,9 @@
namespace Renci.SshNet.Sftp
{
///
- /// Represents SFTP file information
+ /// Represents SFTP file information.
///
- public class SftpFile
+ public sealed class SftpFile : ISftpFile
{
private readonly ISftpSession _sftpSession;
@@ -22,35 +22,48 @@ public class SftpFile
/// The SFTP session.
/// Full path of the directory or file.
/// Attributes of the directory or file.
- /// or is null.
+ /// or is .
internal SftpFile(ISftpSession sftpSession, string fullName, SftpFileAttributes attributes)
{
- if (sftpSession == null)
+ if (sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
- if (attributes == null)
- throw new ArgumentNullException("attributes");
+ if (attributes is null)
+ {
+ throw new ArgumentNullException(nameof(attributes));
+ }
- if (fullName == null)
- throw new ArgumentNullException("fullName");
+ if (fullName is null)
+ {
+ throw new ArgumentNullException(nameof(fullName));
+ }
_sftpSession = sftpSession;
Attributes = attributes;
-
Name = fullName.Substring(fullName.LastIndexOf('/') + 1);
-
FullName = fullName;
}
///
- /// Gets the full path of the directory or file.
+ /// Gets the full path of the file or directory.
///
+ ///
+ /// The full path of the file or directory.
+ ///
public string FullName { get; private set; }
///
- /// For files, gets the name of the file. For directories, gets the name of the last directory in the hierarchy if a hierarchy exists.
- /// Otherwise, the Name property gets the name of the directory.
+ /// Gets the name of the file or directory.
///
+ ///
+ /// The name of the file or directory.
+ ///
+ ///
+ /// For directories, this is the name of the last directory in the hierarchy if a hierarchy exists;
+ /// otherwise, the name of the directory.
+ ///
public string Name { get; private set; }
///
@@ -126,7 +139,7 @@ public DateTime LastWriteTimeUtc
}
///
- /// Gets or sets the size, in bytes, of the current file.
+ /// Gets the size, in bytes, of the current file.
///
///
/// The size of the current file in bytes.
@@ -179,7 +192,7 @@ public int GroupId
/// Gets a value indicating whether file represents a socket.
///
///
- /// true if file represents a socket; otherwise, false.
+ /// if file represents a socket; otherwise, .
///
public bool IsSocket
{
@@ -193,7 +206,7 @@ public bool IsSocket
/// Gets a value indicating whether file represents a symbolic link.
///
///
- /// true if file represents a symbolic link; otherwise, false.
+ /// if file represents a symbolic link; otherwise, .
///
public bool IsSymbolicLink
{
@@ -207,7 +220,7 @@ public bool IsSymbolicLink
/// Gets a value indicating whether file represents a regular file.
///
///
- /// true if file represents a regular file; otherwise, false.
+ /// if file represents a regular file; otherwise, .
///
public bool IsRegularFile
{
@@ -221,7 +234,7 @@ public bool IsRegularFile
/// Gets a value indicating whether file represents a block device.
///
///
- /// true if file represents a block device; otherwise, false.
+ /// if file represents a block device; otherwise, .
///
public bool IsBlockDevice
{
@@ -235,7 +248,7 @@ public bool IsBlockDevice
/// Gets a value indicating whether file represents a directory.
///
///
- /// true if file represents a directory; otherwise, false.
+ /// if file represents a directory; otherwise, .
///
public bool IsDirectory
{
@@ -249,7 +262,7 @@ public bool IsDirectory
/// Gets a value indicating whether file represents a character device.
///
///
- /// true if file represents a character device; otherwise, false.
+ /// if file represents a character device; otherwise, .
///
public bool IsCharacterDevice
{
@@ -263,7 +276,7 @@ public bool IsCharacterDevice
/// Gets a value indicating whether file represents a named pipe.
///
///
- /// true if file represents a named pipe; otherwise, false.
+ /// if file represents a named pipe; otherwise, .
///
public bool IsNamedPipe
{
@@ -277,7 +290,7 @@ public bool IsNamedPipe
/// Gets or sets a value indicating whether the owner can read from this file.
///
///
- /// true if owner can read from this file; otherwise, false.
+ /// if owner can read from this file; otherwise, .
///
public bool OwnerCanRead
{
@@ -295,7 +308,7 @@ public bool OwnerCanRead
/// Gets or sets a value indicating whether the owner can write into this file.
///
///
- /// true if owner can write into this file; otherwise, false.
+ /// if owner can write into this file; otherwise, .
///
public bool OwnerCanWrite
{
@@ -313,7 +326,7 @@ public bool OwnerCanWrite
/// Gets or sets a value indicating whether the owner can execute this file.
///
///
- /// true if owner can execute this file; otherwise, false.
+ /// if owner can execute this file; otherwise, .
///
public bool OwnerCanExecute
{
@@ -331,7 +344,7 @@ public bool OwnerCanExecute
/// Gets or sets a value indicating whether the group members can read from this file.
///
///
- /// true if group members can read from this file; otherwise, false.
+ /// if group members can read from this file; otherwise, .
///
public bool GroupCanRead
{
@@ -349,7 +362,7 @@ public bool GroupCanRead
/// Gets or sets a value indicating whether the group members can write into this file.
///
///
- /// true if group members can write into this file; otherwise, false.
+ /// if group members can write into this file; otherwise, .
///
public bool GroupCanWrite
{
@@ -367,7 +380,7 @@ public bool GroupCanWrite
/// Gets or sets a value indicating whether the group members can execute this file.
///
///
- /// true if group members can execute this file; otherwise, false.
+ /// if group members can execute this file; otherwise, .
///
public bool GroupCanExecute
{
@@ -385,7 +398,7 @@ public bool GroupCanExecute
/// Gets or sets a value indicating whether the others can read from this file.
///
///
- /// true if others can read from this file; otherwise, false.
+ /// if others can read from this file; otherwise, .
///
public bool OthersCanRead
{
@@ -403,7 +416,7 @@ public bool OthersCanRead
/// Gets or sets a value indicating whether the others can write into this file.
///
///
- /// true if others can write into this file; otherwise, false.
+ /// if others can write into this file; otherwise, .
///
public bool OthersCanWrite
{
@@ -421,7 +434,7 @@ public bool OthersCanWrite
/// Gets or sets a value indicating whether the others can execute this file.
///
///
- /// true if others can execute this file; otherwise, false.
+ /// if others can execute this file; otherwise, .
///
public bool OthersCanExecute
{
@@ -436,7 +449,7 @@ public bool OthersCanExecute
}
///
- /// Sets file permissions.
+ /// Sets file permissions.
///
/// The mode.
public void SetPermissions(short mode)
@@ -465,11 +478,14 @@ public void Delete()
/// Moves a specified file to a new location on remote machine, providing the option to specify a new file name.
///
/// The path to move the file to, which can specify a different file name.
- /// is null.
+ /// is .
public void MoveTo(string destFileName)
{
- if (destFileName == null)
- throw new ArgumentNullException("destFileName");
+ if (destFileName is null)
+ {
+ throw new ArgumentNullException(nameof(destFileName));
+ }
+
_sftpSession.RequestRename(FullName, destFileName);
var fullPath = _sftpSession.GetCanonicalPath(destFileName);
@@ -488,14 +504,21 @@ public void UpdateStatus()
}
///
- /// Returns a that represents this instance.
+ /// Returns a that represents this instance.
///
///
- /// A that represents this instance.
+ /// A that represents this instance.
///
public override string ToString()
{
- return string.Format(CultureInfo.CurrentCulture, "Name {0}, Length {1}, User ID {2}, Group ID {3}, Accessed {4}, Modified {5}", Name, Length, UserId, GroupId, LastAccessTime, LastWriteTime);
+ return string.Format(CultureInfo.CurrentCulture,
+ "Name {0}, Length {1}, User ID {2}, Group ID {3}, Accessed {4}, Modified {5}",
+ Name,
+ Length,
+ UserId,
+ GroupId,
+ LastAccessTime,
+ LastWriteTime);
}
}
}
diff --git a/src/Renci.SshNet/Sftp/SftpFileAttributes.cs b/src/Renci.SshNet/Sftp/SftpFileAttributes.cs
index 573deb92a..2f32b4796 100644
--- a/src/Renci.SshNet/Sftp/SftpFileAttributes.cs
+++ b/src/Renci.SshNet/Sftp/SftpFileAttributes.cs
@@ -1,9 +1,9 @@
using System;
using System.Collections.Generic;
-using System.Linq;
using System.Globalization;
+using System.Linq;
+
using Renci.SshNet.Common;
-using System.Diagnostics;
namespace Renci.SshNet.Sftp
{
@@ -12,54 +12,30 @@ namespace Renci.SshNet.Sftp
///
public class SftpFileAttributes
{
- #region Bitmask constants
-
- private const uint S_IFMT = 0xF000; // bitmask for the file type bitfields
-
- private const uint S_IFSOCK = 0xC000; // socket
-
- private const uint S_IFLNK = 0xA000; // symbolic link
-
- private const uint S_IFREG = 0x8000; // regular file
-
- private const uint S_IFBLK = 0x6000; // block device
-
- private const uint S_IFDIR = 0x4000; // directory
-
- private const uint S_IFCHR = 0x2000; // character device
-
- private const uint S_IFIFO = 0x1000; // FIFO
-
- private const uint S_ISUID = 0x0800; // set UID bit
-
- private const uint S_ISGID = 0x0400; // set-group-ID bit (see below)
-
- private const uint S_ISVTX = 0x0200; // sticky bit (see below)
-
- private const uint S_IRUSR = 0x0100; // owner has read permission
-
- private const uint S_IWUSR = 0x0080; // owner has write permission
-
- private const uint S_IXUSR = 0x0040; // owner has execute permission
-
- private const uint S_IRGRP = 0x0020; // group has read permission
-
- private const uint S_IWGRP = 0x0010; // group has write permission
-
- private const uint S_IXGRP = 0x0008; // group has execute permission
-
- private const uint S_IROTH = 0x0004; // others have read permission
-
- private const uint S_IWOTH = 0x0002; // others have write permission
-
- private const uint S_IXOTH = 0x0001; // others have execute permission
-
- #endregion
-
- private bool _isBitFiledsBitSet;
- private bool _isUIDBitSet;
- private bool _isGroupIDBitSet;
- private bool _isStickyBitSet;
+#pragma warning disable IDE1006 // Naming Styles
+#pragma warning disable SA1310 // Field names should not contain underscore
+ private const uint S_IFMT = 0xF000; // bitmask for the file type bitfields
+ private const uint S_IFSOCK = 0xC000; // socket
+ private const uint S_IFLNK = 0xA000; // symbolic link
+ private const uint S_IFREG = 0x8000; // regular file
+ private const uint S_IFBLK = 0x6000; // block device
+ private const uint S_IFDIR = 0x4000; // directory
+ private const uint S_IFCHR = 0x2000; // character device
+ private const uint S_IFIFO = 0x1000; // FIFO
+ private const uint S_ISUID = 0x0800; // set UID bit
+ private const uint S_ISGID = 0x0400; // set-group-ID bit (see below)
+ private const uint S_ISVTX = 0x0200; // sticky bit (see below)
+ private const uint S_IRUSR = 0x0100; // owner has read permission
+ private const uint S_IWUSR = 0x0080; // owner has write permission
+ private const uint S_IXUSR = 0x0040; // owner has execute permission
+ private const uint S_IRGRP = 0x0020; // group has read permission
+ private const uint S_IWGRP = 0x0010; // group has write permission
+ private const uint S_IXGRP = 0x0008; // group has execute permission
+ private const uint S_IROTH = 0x0004; // others have read permission
+ private const uint S_IWOTH = 0x0002; // others have write permission
+ private const uint S_IXOTH = 0x0001; // others have execute permission
+#pragma warning restore SA1310 // Field names should not contain underscore
+#pragma warning restore IDE1006 // Naming Styles
private readonly DateTime _originalLastAccessTimeUtc;
private readonly DateTime _originalLastWriteTimeUtc;
@@ -69,6 +45,11 @@ public class SftpFileAttributes
private readonly uint _originalPermissions;
private readonly IDictionary _originalExtensions;
+ private bool _isBitFiledsBitSet;
+ private bool _isUIDBitSet;
+ private bool _isGroupIDBitSet;
+ private bool _isStickyBitSet;
+
internal bool IsLastAccessTimeChanged
{
get { return _originalLastAccessTimeUtc != LastAccessTimeUtc; }
@@ -114,12 +95,12 @@ public DateTime LastAccessTime
{
get
{
- return ToLocalTime(this.LastAccessTimeUtc);
+ return ToLocalTime(LastAccessTimeUtc);
}
set
{
- this.LastAccessTimeUtc = ToUniversalTime(value);
+ LastAccessTimeUtc = ToUniversalTime(value);
}
}
@@ -133,12 +114,12 @@ public DateTime LastWriteTime
{
get
{
- return ToLocalTime(this.LastWriteTimeUtc);
+ return ToLocalTime(LastWriteTimeUtc);
}
set
{
- this.LastWriteTimeUtc = ToUniversalTime(value);
+ LastWriteTimeUtc = ToUniversalTime(value);
}
}
@@ -186,7 +167,7 @@ public DateTime LastWriteTime
/// Gets a value indicating whether file represents a socket.
///
///
- /// true if file represents a socket; otherwise, false.
+ /// if file represents a socket; otherwise, .
///
public bool IsSocket { get; private set; }
@@ -194,7 +175,7 @@ public DateTime LastWriteTime
/// Gets a value indicating whether file represents a symbolic link.
///
///
- /// true if file represents a symbolic link; otherwise, false.
+ /// if file represents a symbolic link; otherwise, .
///
public bool IsSymbolicLink { get; private set; }
@@ -202,7 +183,7 @@ public DateTime LastWriteTime
/// Gets a value indicating whether file represents a regular file.
///
///
- /// true if file represents a regular file; otherwise, false.
+ /// if file represents a regular file; otherwise, .
///
public bool IsRegularFile { get; private set; }
@@ -210,7 +191,7 @@ public DateTime LastWriteTime
/// Gets a value indicating whether file represents a block device.
///
///
- /// true if file represents a block device; otherwise, false.
+ /// if file represents a block device; otherwise, .
///
public bool IsBlockDevice { get; private set; }
@@ -218,7 +199,7 @@ public DateTime LastWriteTime
/// Gets a value indicating whether file represents a directory.
///
///
- /// true if file represents a directory; otherwise, false.
+ /// if file represents a directory; otherwise, .
///
public bool IsDirectory { get; private set; }
@@ -226,7 +207,7 @@ public DateTime LastWriteTime
/// Gets a value indicating whether file represents a character device.
///
///
- /// true if file represents a character device; otherwise, false.
+ /// if file represents a character device; otherwise, .
///
public bool IsCharacterDevice { get; private set; }
@@ -234,84 +215,84 @@ public DateTime LastWriteTime
/// Gets a value indicating whether file represents a named pipe.
///
///
- /// true if file represents a named pipe; otherwise, false.
+ /// if file represents a named pipe; otherwise, .
///
public bool IsNamedPipe { get; private set; }
///
- /// Gets a value indicating whether the owner can read from this file.
+ /// Gets or sets a value indicating whether the owner can read from this file.
///
///
- /// true if owner can read from this file; otherwise, false.
+ /// if owner can read from this file; otherwise, .
///
public bool OwnerCanRead { get; set; }
///
- /// Gets a value indicating whether the owner can write into this file.
+ /// Gets or sets a value indicating whether the owner can write into this file.
///
///
- /// true if owner can write into this file; otherwise, false.
+ /// if owner can write into this file; otherwise, .
///
public bool OwnerCanWrite { get; set; }
///
- /// Gets a value indicating whether the owner can execute this file.
+ /// Gets or sets a value indicating whether the owner can execute this file.
///
///
- /// true if owner can execute this file; otherwise, false.
+ /// if owner can execute this file; otherwise, .
///
public bool OwnerCanExecute { get; set; }
///
- /// Gets a value indicating whether the group members can read from this file.
+ /// Gets or sets a value indicating whether the group members can read from this file.
///
///
- /// true if group members can read from this file; otherwise, false.
+ /// if group members can read from this file; otherwise, .
///
public bool GroupCanRead { get; set; }
///
- /// Gets a value indicating whether the group members can write into this file.
+ /// Gets or sets a value indicating whether the group members can write into this file.
///
///
- /// true if group members can write into this file; otherwise, false.
+ /// if group members can write into this file; otherwise, .
///
public bool GroupCanWrite { get; set; }
///
- /// Gets a value indicating whether the group members can execute this file.
+ /// Gets or sets a value indicating whether the group members can execute this file.
///
///
- /// true if group members can execute this file; otherwise, false.
+ /// if group members can execute this file; otherwise, .
///
public bool GroupCanExecute { get; set; }
///
- /// Gets a value indicating whether the others can read from this file.
+ /// Gets or sets a value indicating whether the others can read from this file.
///
///
- /// true if others can read from this file; otherwise, false.
+ /// if others can read from this file; otherwise, .
///
public bool OthersCanRead { get; set; }
///
- /// Gets a value indicating whether the others can write into this file.
+ /// Gets or sets a value indicating whether the others can write into this file.
///
///
- /// true if others can write into this file; otherwise, false.
+ /// if others can write into this file; otherwise, .
///
public bool OthersCanWrite { get; set; }
///
- /// Gets a value indicating whether the others can execute this file.
+ /// Gets or sets a value indicating whether the others can execute this file.
///
///
- /// true if others can execute this file; otherwise, false.
+ /// if others can execute this file; otherwise, .
///
public bool OthersCanExecute { get; set; }
///
- /// Gets or sets the extensions.
+ /// Gets the extensions.
///
///
/// The extensions.
@@ -325,108 +306,148 @@ internal uint Permissions
uint permission = 0;
if (_isBitFiledsBitSet)
- permission = permission | S_IFMT;
+ {
+ permission |= S_IFMT;
+ }
if (IsSocket)
- permission = permission | S_IFSOCK;
+ {
+ permission |= S_IFSOCK;
+ }
if (IsSymbolicLink)
- permission = permission | S_IFLNK;
+ {
+ permission |= S_IFLNK;
+ }
if (IsRegularFile)
- permission = permission | S_IFREG;
+ {
+ permission |= S_IFREG;
+ }
if (IsBlockDevice)
- permission = permission | S_IFBLK;
+ {
+ permission |= S_IFBLK;
+ }
if (IsDirectory)
- permission = permission | S_IFDIR;
+ {
+ permission |= S_IFDIR;
+ }
if (IsCharacterDevice)
- permission = permission | S_IFCHR;
+ {
+ permission |= S_IFCHR;
+ }
if (IsNamedPipe)
- permission = permission | S_IFIFO;
+ {
+ permission |= S_IFIFO;
+ }
if (_isUIDBitSet)
- permission = permission | S_ISUID;
+ {
+ permission |= S_ISUID;
+ }
if (_isGroupIDBitSet)
- permission = permission | S_ISGID;
+ {
+ permission |= S_ISGID;
+ }
if (_isStickyBitSet)
- permission = permission | S_ISVTX;
+ {
+ permission |= S_ISVTX;
+ }
if (OwnerCanRead)
- permission = permission | S_IRUSR;
+ {
+ permission |= S_IRUSR;
+ }
if (OwnerCanWrite)
- permission = permission | S_IWUSR;
+ {
+ permission |= S_IWUSR;
+ }
if (OwnerCanExecute)
- permission = permission | S_IXUSR;
+ {
+ permission |= S_IXUSR;
+ }
if (GroupCanRead)
- permission = permission | S_IRGRP;
+ {
+ permission |= S_IRGRP;
+ }
if (GroupCanWrite)
- permission = permission | S_IWGRP;
+ {
+ permission |= S_IWGRP;
+ }
if (GroupCanExecute)
- permission = permission | S_IXGRP;
+ {
+ permission |= S_IXGRP;
+ }
if (OthersCanRead)
- permission = permission | S_IROTH;
+ {
+ permission |= S_IROTH;
+ }
if (OthersCanWrite)
- permission = permission | S_IWOTH;
+ {
+ permission |= S_IWOTH;
+ }
if (OthersCanExecute)
- permission = permission | S_IXOTH;
+ {
+ permission |= S_IXOTH;
+ }
return permission;
}
private set
{
- _isBitFiledsBitSet = ((value & S_IFMT) == S_IFMT);
+ _isBitFiledsBitSet = (value & S_IFMT) == S_IFMT;
- IsSocket = ((value & S_IFSOCK) == S_IFSOCK);
+ IsSocket = (value & S_IFSOCK) == S_IFSOCK;
- IsSymbolicLink = ((value & S_IFLNK) == S_IFLNK);
+ IsSymbolicLink = (value & S_IFLNK) == S_IFLNK;
- IsRegularFile = ((value & S_IFREG) == S_IFREG);
+ IsRegularFile = (value & S_IFREG) == S_IFREG;
- IsBlockDevice = ((value & S_IFBLK) == S_IFBLK);
+ IsBlockDevice = (value & S_IFBLK) == S_IFBLK;
- IsDirectory = ((value & S_IFDIR) == S_IFDIR);
+ IsDirectory = (value & S_IFDIR) == S_IFDIR;
- IsCharacterDevice = ((value & S_IFCHR) == S_IFCHR);
+ IsCharacterDevice = (value & S_IFCHR) == S_IFCHR;
- IsNamedPipe = ((value & S_IFIFO) == S_IFIFO);
+ IsNamedPipe = (value & S_IFIFO) == S_IFIFO;
- _isUIDBitSet = ((value & S_ISUID) == S_ISUID);
+ _isUIDBitSet = (value & S_ISUID) == S_ISUID;
- _isGroupIDBitSet = ((value & S_ISGID) == S_ISGID);
+ _isGroupIDBitSet = (value & S_ISGID) == S_ISGID;
- _isStickyBitSet = ((value & S_ISVTX) == S_ISVTX);
+ _isStickyBitSet = (value & S_ISVTX) == S_ISVTX;
- OwnerCanRead = ((value & S_IRUSR) == S_IRUSR);
+ OwnerCanRead = (value & S_IRUSR) == S_IRUSR;
- OwnerCanWrite = ((value & S_IWUSR) == S_IWUSR);
+ OwnerCanWrite = (value & S_IWUSR) == S_IWUSR;
- OwnerCanExecute = ((value & S_IXUSR) == S_IXUSR);
+ OwnerCanExecute = (value & S_IXUSR) == S_IXUSR;
- GroupCanRead = ((value & S_IRGRP) == S_IRGRP);
+ GroupCanRead = (value & S_IRGRP) == S_IRGRP;
- GroupCanWrite = ((value & S_IWGRP) == S_IWGRP);
+ GroupCanWrite = (value & S_IWGRP) == S_IWGRP;
- GroupCanExecute = ((value & S_IXGRP) == S_IXGRP);
+ GroupCanExecute = (value & S_IXGRP) == S_IXGRP;
- OthersCanRead = ((value & S_IROTH) == S_IROTH);
+ OthersCanRead = (value & S_IROTH) == S_IROTH;
- OthersCanWrite = ((value & S_IWOTH) == S_IWOTH);
+ OthersCanWrite = (value & S_IWOTH) == S_IWOTH;
- OthersCanExecute = ((value & S_IXOTH) == S_IXOTH);
+ OthersCanExecute = (value & S_IXOTH) == S_IXOTH;
}
}
@@ -451,14 +472,14 @@ internal SftpFileAttributes(DateTime lastAccessTimeUtc, DateTime lastWriteTimeUt
/// The mode.
public void SetPermissions(short mode)
{
- if (mode < 0 || mode > 999)
+ if (mode is < 0 or > 999)
{
- throw new ArgumentOutOfRangeException("mode");
+ throw new ArgumentOutOfRangeException(nameof(mode));
}
var modeBytes = mode.ToString(CultureInfo.InvariantCulture).PadLeft(3, '0').ToCharArray();
- var permission = (modeBytes[0] & 0x0F) * 8 * 8 + (modeBytes[1] & 0x0F) * 8 + (modeBytes[2] & 0x0F);
+ var permission = ((modeBytes[0] & 0x0F) * 8 * 8) + ((modeBytes[1] & 0x0F) * 8) + (modeBytes[2] & 0x0F);
OwnerCanRead = (permission & S_IRUSR) == S_IRUSR;
OwnerCanWrite = (permission & S_IWUSR) == S_IWUSR;
@@ -481,79 +502,88 @@ public void SetPermissions(short mode)
///
public byte[] GetBytes()
{
- var stream = new SshDataStream(4);
-
- uint flag = 0;
-
- if (IsSizeChanged && IsRegularFile)
+ using (var stream = new SshDataStream(4))
{
- flag |= 0x00000001;
- }
+ uint flag = 0;
- if (IsUserIdChanged || IsGroupIdChanged)
- {
- flag |= 0x00000002;
- }
+ if (IsSizeChanged && IsRegularFile)
+ {
+ flag |= 0x00000001;
+ }
- if (IsPermissionsChanged)
- {
- flag |= 0x00000004;
- }
+ if (IsUserIdChanged || IsGroupIdChanged)
+ {
+ flag |= 0x00000002;
+ }
- if (IsLastAccessTimeChanged || IsLastWriteTimeChanged)
- {
- flag |= 0x00000008;
- }
+ if (IsPermissionsChanged)
+ {
+ flag |= 0x00000004;
+ }
- if (IsExtensionsChanged)
- {
- flag |= 0x80000000;
- }
+ if (IsLastAccessTimeChanged || IsLastWriteTimeChanged)
+ {
+ flag |= 0x00000008;
+ }
- stream.Write(flag);
+ if (IsExtensionsChanged)
+ {
+ flag |= 0x80000000;
+ }
- if (IsSizeChanged && IsRegularFile)
- {
- stream.Write((ulong) Size);
- }
+ stream.Write(flag);
- if (IsUserIdChanged || IsGroupIdChanged)
- {
- stream.Write((uint) UserId);
- stream.Write((uint) GroupId);
- }
+ if (IsSizeChanged && IsRegularFile)
+ {
+ stream.Write((ulong) Size);
+ }
- if (IsPermissionsChanged)
- {
- stream.Write(Permissions);
- }
+ if (IsUserIdChanged || IsGroupIdChanged)
+ {
+ stream.Write((uint) UserId);
+ stream.Write((uint) GroupId);
+ }
- if (IsLastAccessTimeChanged || IsLastWriteTimeChanged)
- {
- var time = (uint)(LastAccessTimeUtc.ToFileTimeUtc() / 10000000 - 11644473600);
- stream.Write(time);
- time = (uint)(LastWriteTimeUtc.ToFileTimeUtc() / 10000000 - 11644473600);
- stream.Write(time);
- }
+ if (IsPermissionsChanged)
+ {
+ stream.Write(Permissions);
+ }
- if (IsExtensionsChanged)
- {
- foreach (var item in Extensions)
+ if (IsLastAccessTimeChanged || IsLastWriteTimeChanged)
{
- // TODO: we write as ASCII but read as UTF8 !!!
+ var time = (uint) ((LastAccessTimeUtc.ToFileTimeUtc() / 10000000) - 11644473600);
+ stream.Write(time);
+ time = (uint) ((LastWriteTimeUtc.ToFileTimeUtc() / 10000000) - 11644473600);
+ stream.Write(time);
+ }
- stream.Write(item.Key, SshData.Ascii);
- stream.Write(item.Value, SshData.Ascii);
+ if (IsExtensionsChanged)
+ {
+ foreach (var item in Extensions)
+ {
+ /*
+ * TODO: we write as ASCII but read as UTF8 !!!
+ */
+
+ stream.Write(item.Key, SshData.Ascii);
+ stream.Write(item.Value, SshData.Ascii);
+ }
}
- }
- return stream.ToArray();
+ return stream.ToArray();
+ }
}
internal static readonly SftpFileAttributes Empty = new SftpFileAttributes();
internal static SftpFileAttributes FromBytes(SshDataStream stream)
{
+ const uint SSH_FILEXFER_ATTR_SIZE = 0x00000001;
+ const uint SSH_FILEXFER_ATTR_UIDGID = 0x00000002;
+ const uint SSH_FILEXFER_ATTR_PERMISSIONS = 0x00000004;
+ const uint SSH_FILEXFER_ATTR_ACMODTIME = 0x00000008;
+ const uint SSH_FILEXFER_ATTR_EXTENDED = 0x80000000;
+
var flag = stream.ReadUInt32();
long size = -1;
@@ -562,26 +592,26 @@ internal static SftpFileAttributes FromBytes(SshDataStream stream)
uint permissions = 0;
DateTime accessTime;
DateTime modifyTime;
- IDictionary extensions = null;
+ Dictionary extensions = null;
- if ((flag & 0x00000001) == 0x00000001) // SSH_FILEXFER_ATTR_SIZE
+ if ((flag & SSH_FILEXFER_ATTR_SIZE) == SSH_FILEXFER_ATTR_SIZE)
{
size = (long) stream.ReadUInt64();
}
- if ((flag & 0x00000002) == 0x00000002) // SSH_FILEXFER_ATTR_UIDGID
+ if ((flag & SSH_FILEXFER_ATTR_UIDGID) == SSH_FILEXFER_ATTR_UIDGID)
{
userId = (int) stream.ReadUInt32();
groupId = (int) stream.ReadUInt32();
}
- if ((flag & 0x00000004) == 0x00000004) // SSH_FILEXFER_ATTR_PERMISSIONS
+ if ((flag & SSH_FILEXFER_ATTR_PERMISSIONS) == SSH_FILEXFER_ATTR_PERMISSIONS)
{
permissions = stream.ReadUInt32();
}
- if ((flag & 0x00000008) == 0x00000008) // SSH_FILEXFER_ATTR_ACMODTIME
+ if ((flag & SSH_FILEXFER_ATTR_ACMODTIME) == SSH_FILEXFER_ATTR_ACMODTIME)
{
// The incoming times are "Unix times", so they're already in UTC. We need to preserve that
// to avoid losing information in a local time conversion during the "fall back" hour in DST.
@@ -596,7 +626,7 @@ internal static SftpFileAttributes FromBytes(SshDataStream stream)
modifyTime = DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
}
- if ((flag & 0x80000000) == 0x80000000) // SSH_FILEXFER_ATTR_EXTENDED
+ if ((flag & SSH_FILEXFER_ATTR_EXTENDED) == SSH_FILEXFER_ATTR_EXTENDED)
{
var extendedCount = (int) stream.ReadUInt32();
extensions = new Dictionary(extendedCount);
diff --git a/src/Renci.SshNet/Sftp/SftpFileReader.cs b/src/Renci.SshNet/Sftp/SftpFileReader.cs
index 3aed4f535..8d3ef211f 100644
--- a/src/Renci.SshNet/Sftp/SftpFileReader.cs
+++ b/src/Renci.SshNet/Sftp/SftpFileReader.cs
@@ -1,69 +1,72 @@
-using Renci.SshNet.Abstractions;
-using Renci.SshNet.Common;
-using System;
+using System;
using System.Collections.Generic;
using System.Globalization;
+using System.Runtime.ExceptionServices;
using System.Threading;
+using Renci.SshNet.Abstractions;
+using Renci.SshNet.Common;
+
namespace Renci.SshNet.Sftp
{
- internal class SftpFileReader : ISftpFileReader
+ internal sealed class SftpFileReader : ISftpFileReader
{
private const int ReadAheadWaitTimeoutInMilliseconds = 1000;
private readonly byte[] _handle;
private readonly ISftpSession _sftpSession;
private readonly uint _chunkSize;
- private ulong _offset;
+ private readonly SemaphoreSlim _semaphore;
+ private readonly object _readLock;
+ private readonly ManualResetEvent _disposingWaitHandle;
+ private readonly ManualResetEvent _readAheadCompleted;
+ private readonly Dictionary _queue;
+ private readonly WaitHandle[] _waitHandles;
///
/// Holds the size of the file, when available.
///
private readonly long? _fileSize;
- private readonly Dictionary _queue;
- private readonly WaitHandle[] _waitHandles;
+ private ulong _offset;
private int _readAheadChunkIndex;
private ulong _readAheadOffset;
- private readonly ManualResetEvent _readAheadCompleted;
private int _nextChunkIndex;
///
/// Holds a value indicating whether EOF has already been signaled by the SSH server.
///
private bool _endOfFileReceived;
+
///
/// Holds a value indicating whether the client has read up to the end of the file.
///
private bool _isEndOfFileRead;
- private readonly SemaphoreLight _semaphore;
- private readonly object _readLock;
- private readonly ManualResetEvent _disposingWaitHandle;
private bool _disposingOrDisposed;
private Exception _exception;
///
- /// Initializes a new instance with the specified handle,
+ /// Initializes a new instance of the class with the specified handle,
/// and the maximum number of pending reads.
///
- ///
- ///
+ /// The file handle.
+ /// The SFT session.
/// The size of a individual read-ahead chunk.
/// The maximum number of pending reads.
- /// The size of the file, if known; otherwise, null.
+ /// The size of the file, if known; otherwise, .
public SftpFileReader(byte[] handle, ISftpSession sftpSession, uint chunkSize, int maxPendingReads, long? fileSize)
{
_handle = handle;
_sftpSession = sftpSession;
_chunkSize = chunkSize;
_fileSize = fileSize;
- _semaphore = new SemaphoreLight(maxPendingReads);
+ _semaphore = new SemaphoreSlim(maxPendingReads);
_queue = new Dictionary(maxPendingReads);
_readLock = new object();
- _readAheadCompleted = new ManualResetEvent(false);
- _disposingWaitHandle = new ManualResetEvent(false);
+ _readAheadCompleted = new ManualResetEvent(initialState: false);
+ _disposingWaitHandle = new ManualResetEvent(initialState: false);
_waitHandles = _sftpSession.CreateWaitHandleArray(_disposingWaitHandle, _semaphore.AvailableWaitHandle);
StartReadAhead();
@@ -71,27 +74,41 @@ public SftpFileReader(byte[] handle, ISftpSession sftpSession, uint chunkSize, i
public byte[] Read()
{
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_disposingOrDisposed, this);
+#else
if (_disposingOrDisposed)
+ {
throw new ObjectDisposedException(GetType().FullName);
- if (_exception != null)
- throw _exception;
+ }
+#endif // NET7_0_OR_GREATER
+
+ if (_exception is not null)
+ {
+ ExceptionDispatchInfo.Capture(_exception).Throw();
+ }
+
if (_isEndOfFileRead)
+ {
throw new SshException("Attempting to read beyond the end of the file.");
+ }
BufferedRead nextChunk;
lock (_readLock)
{
- // wait until either the next chunk is avalable, an exception has occurred or the current
+ // wait until either the next chunk is available, an exception has occurred or the current
// instance is already disposed
- while (!_queue.TryGetValue(_nextChunkIndex, out nextChunk) && _exception == null)
+ while (!_queue.TryGetValue(_nextChunkIndex, out nextChunk) && _exception is null)
{
- Monitor.Wait(_readLock);
+ _ =Monitor.Wait(_readLock);
}
// throw when exception occured in read-ahead, or the current instance is already disposed
if (_exception != null)
- throw _exception;
+ {
+ ExceptionDispatchInfo.Capture(_exception).Throw();
+ }
var data = nextChunk.Data;
@@ -101,55 +118,63 @@ public byte[] Read()
if (data.Length == 0)
{
// PERF: we do not bother updating all of the internal state when we've reached EOF
-
_isEndOfFileRead = true;
}
else
{
// remove processed chunk
- _queue.Remove(_nextChunkIndex);
+ _ = _queue.Remove(_nextChunkIndex);
+
// update offset
_offset += (ulong) data.Length;
+
// move to next chunk
_nextChunkIndex++;
}
+
// unblock wait in read-ahead
- _semaphore.Release();
+ _ = _semaphore.Release();
return data;
}
- // when we received an EOF for the next chunk and the size of the file is known, then
- // we only complete the current chunk if we haven't already read up to the file size;
- // this way we save an extra round-trip to the server
+ // When we received an EOF for the next chunk and the size of the file is known, then
+ // we only complete the current chunk if we haven't already read up to the file size.
+ // This way we save an extra round-trip to the server.
if (data.Length == 0 && _fileSize.HasValue && _offset == (ulong) _fileSize.Value)
{
// avoid future reads
_isEndOfFileRead = true;
+
// unblock wait in read-ahead
- _semaphore.Release();
+ _ = _semaphore.Release();
+
// signal EOF to caller
return nextChunk.Data;
}
}
- // When the server returned less bytes than requested (for the previous chunk)
- // we'll synchronously request the remaining data.
- //
- // Due to the optimization above, we'll only get here in one of the following cases:
- // - an EOF situation for files for which we were unable to obtain the file size
- // - fewer bytes that requested were returned
- //
- // According to the SSH specification, this last case should never happen for normal
- // disk files (but can happen for device files). In practice, OpenSSH - for example -
- // returns less bytes than requested when requesting more than 64 KB.
- //
- // Important:
- // To avoid a deadlock, this read must be done outside of the read lock
+ /*
+ * When the server returned less bytes than requested (for the previous chunk)
+ * we'll synchronously request the remaining data.
+ *
+ * Due to the optimization above, we'll only get here in one of the following cases:
+ * - an EOF situation for files for which we were unable to obtain the file size
+ * - fewer bytes that requested were returned
+ *
+ * According to the SSH specification, this last case should never happen for normal
+ * disk files (but can happen for device files). In practice, OpenSSH - for example -
+ * returns less bytes than requested when requesting more than 64 KB.
+ *
+ * Important:
+ * To avoid a deadlock, this read must be done outside of the read lock.
+ */
var bytesToCatchUp = nextChunk.Offset - _offset;
- // TODO: break loop and interrupt blocking wait in case of exception
+ /*
+ * TODO: break loop and interrupt blocking wait in case of exception
+ */
var read = _sftpSession.RequestRead(_handle, _offset, (uint) bytesToCatchUp);
if (read.Length == 0)
@@ -162,24 +187,28 @@ public byte[] Read()
if (nextChunk.Data.Length == 0)
{
_isEndOfFileRead = true;
+
// ensure we've not yet disposed the current instance
if (!_disposingOrDisposed)
{
// unblock wait in read-ahead
- _semaphore.Release();
+ _ = _semaphore.Release();
}
+
// signal EOF to caller
return read;
}
// move reader to error state
_exception = new SshException("Unexpectedly reached end of file.");
+
// ensure we've not yet disposed the current instance
if (!_disposingOrDisposed)
{
// unblock wait in read-ahead
- _semaphore.Release();
+ _ = _semaphore.Release();
}
+
// notify caller of error
throw _exception;
}
@@ -192,23 +221,25 @@ public byte[] Read()
~SftpFileReader()
{
- Dispose(false);
+ Dispose(disposing: false);
}
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
- protected void Dispose(bool disposing)
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
+ private void Dispose(bool disposing)
{
if (_disposingOrDisposed)
+ {
return;
+ }
// transition to disposing state
_disposingOrDisposed = true;
@@ -219,10 +250,10 @@ protected void Dispose(bool disposing)
_exception = new ObjectDisposedException(GetType().FullName);
// signal that we're disposing to interrupt wait in read-ahead
- _disposingWaitHandle.Set();
+ _ = _disposingWaitHandle.Set();
// wait until the read-ahead thread has completed
- _readAheadCompleted.WaitOne();
+ _ = _readAheadCompleted.WaitOne();
// unblock the Read()
lock (_readLock)
@@ -230,6 +261,7 @@ protected void Dispose(bool disposing)
// dispose semaphore in read lock to ensure we don't run into an ObjectDisposedException
// in Read()
_semaphore.Dispose();
+
// awake Read
Monitor.PulseAll(_readLock);
}
@@ -241,7 +273,7 @@ protected void Dispose(bool disposing)
{
try
{
- var closeAsyncResult = _sftpSession.BeginClose(_handle, null, null);
+ var closeAsyncResult = _sftpSession.BeginClose(_handle, callback: null, state: null);
_sftpSession.EndClose(closeAsyncResult);
}
catch (Exception ex)
@@ -256,7 +288,7 @@ private void StartReadAhead()
{
ThreadAbstraction.ExecuteThread(() =>
{
- while (!_endOfFileReceived && _exception == null)
+ while (!_endOfFileReceived && _exception is null)
{
// check if we should continue with the read-ahead loop
// note that the EOF and exception check are not included
@@ -269,6 +301,7 @@ private void StartReadAhead()
{
Monitor.PulseAll(_readLock);
}
+
// break the read-ahead loop
break;
}
@@ -285,7 +318,9 @@ private void StartReadAhead()
// don't bother reading any more chunks if we received EOF, an exception has occurred
// or the current instance is disposed
if (_endOfFileReceived || _exception != null)
+ {
break;
+ }
// start reading next chunk
var bufferedRead = new BufferedRead(_readAheadChunkIndex, _readAheadOffset);
@@ -301,14 +336,13 @@ private void StartReadAhead()
// mode to avoid having multiple read-aheads that read beyond EOF
if (_fileSize != null && (long) _readAheadOffset > _fileSize.Value)
{
- var asyncResult = _sftpSession.BeginRead(_handle, _readAheadOffset, _chunkSize, null,
- bufferedRead);
+ var asyncResult = _sftpSession.BeginRead(_handle, _readAheadOffset, _chunkSize, callback: null, bufferedRead);
var data = _sftpSession.EndRead(asyncResult);
ReadCompletedCore(bufferedRead, data);
}
else
{
- _sftpSession.BeginRead(_handle, _readAheadOffset, _chunkSize, ReadCompleted, bufferedRead);
+ _ = _sftpSession.BeginRead(_handle, _readAheadOffset, _chunkSize, ReadCompleted, bufferedRead);
}
}
catch (Exception ex)
@@ -319,11 +353,12 @@ private void StartReadAhead()
// advance read-ahead offset
_readAheadOffset += _chunkSize;
+
// increment index of read-ahead chunk
_readAheadChunkIndex++;
}
- _readAheadCompleted.Set();
+ _ = _readAheadCompleted.Set();
});
}
@@ -331,7 +366,7 @@ private void StartReadAhead()
/// Returns a value indicating whether the read-ahead loop should be continued.
///
///
- /// true if the read-ahead loop should be continued; otherwise, false.
+ /// if the read-ahead loop should be continued; otherwise, .
///
private bool ContinueReadAhead()
{
@@ -350,7 +385,7 @@ private bool ContinueReadAhead()
}
catch (Exception ex)
{
- Interlocked.CompareExchange(ref _exception, ex, null);
+ _ = Interlocked.CompareExchange(ref _exception, ex, comparand: null);
return false;
}
}
@@ -392,8 +427,9 @@ private void ReadCompletedCore(BufferedRead bufferedRead, byte[] data)
{
// add item to queue
_queue.Add(bufferedRead.ChunkIndex, bufferedRead);
- // signal that a chunk has been read or EOF has been reached;
- // in both cases, Read() will eventually also unblock the "read-ahead" thread
+
+ // Signal that a chunk has been read or EOF has been reached.
+ // In both cases, Read() will eventually also unblock the "read-ahead" thread.
Monitor.PulseAll(_readLock);
}
@@ -407,10 +443,10 @@ private void ReadCompletedCore(BufferedRead bufferedRead, byte[] data)
private void HandleFailure(Exception cause)
{
- Interlocked.CompareExchange(ref _exception, cause, null);
+ _ = Interlocked.CompareExchange(ref _exception, cause, comparand: null);
// unblock read-ahead
- _semaphore.Release();
+ _ = _semaphore.Release();
// unblock Read()
lock (_readLock)
@@ -419,13 +455,13 @@ private void HandleFailure(Exception cause)
}
}
- internal class BufferedRead
+ internal sealed class BufferedRead
{
- public int ChunkIndex { get; private set; }
+ public int ChunkIndex { get; }
public byte[] Data { get; private set; }
- public ulong Offset { get; private set; }
+ public ulong Offset { get; }
public BufferedRead(int chunkIndex, ulong offset)
{
diff --git a/src/Renci.SshNet/Sftp/SftpFileStream.cs b/src/Renci.SshNet/Sftp/SftpFileStream.cs
index 8f51250ce..7880ffbbd 100644
--- a/src/Renci.SshNet/Sftp/SftpFileStream.cs
+++ b/src/Renci.SshNet/Sftp/SftpFileStream.cs
@@ -1,7 +1,10 @@
using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
using System.IO;
using System.Threading;
-using System.Diagnostics.CodeAnalysis;
+using System.Threading.Tasks;
+
using Renci.SshNet.Common;
namespace Renci.SshNet.Sftp
@@ -9,17 +12,21 @@ namespace Renci.SshNet.Sftp
///
/// Exposes a around a remote SFTP file, supporting both synchronous and asynchronous read and write operations.
///
+ ///
+#pragma warning disable CA1844 // Provide memory-based overrides of async methods when subclassing 'Stream'
public class SftpFileStream : Stream
+#pragma warning restore CA1844 // Provide memory-based overrides of async methods when subclassing 'Stream'
{
- // TODO: Add security method to set userid, groupid and other permission settings
+ private readonly object _lock = new object();
+ private readonly int _readBufferSize;
+ private readonly int _writeBufferSize;
+
// Internal state.
private byte[] _handle;
private ISftpSession _session;
// Buffer information.
- private readonly int _readBufferSize;
private byte[] _readBuffer;
- private readonly int _writeBufferSize;
private byte[] _writeBuffer;
private int _bufferPosition;
private int _bufferLen;
@@ -29,13 +36,11 @@ public class SftpFileStream : Stream
private bool _canSeek;
private bool _canWrite;
- private readonly object _lock = new object();
-
///
/// Gets a value indicating whether the current stream supports reading.
///
///
- /// true if the stream supports reading; otherwise, false.
+ /// if the stream supports reading; otherwise, .
///
public override bool CanRead
{
@@ -46,7 +51,7 @@ public override bool CanRead
/// Gets a value indicating whether the current stream supports seeking.
///
///
- /// true if the stream supports seeking; otherwise, false.
+ /// if the stream supports seeking; otherwise, .
///
public override bool CanSeek
{
@@ -57,7 +62,7 @@ public override bool CanSeek
/// Gets a value indicating whether the current stream supports writing.
///
///
- /// true if the stream supports writing; otherwise, false.
+ /// if the stream supports writing; otherwise, .
///
public override bool CanWrite
{
@@ -65,10 +70,10 @@ public override bool CanWrite
}
///
- /// Indicates whether timeout properties are usable for .
+ /// Gets a value indicating whether timeout properties are usable for .
///
///
- /// true in all cases.
+ /// in all cases.
///
public override bool CanTimeout
{
@@ -93,7 +98,9 @@ public override long Length
CheckSessionIsOpen();
if (!CanSeek)
+ {
throw new NotSupportedException("Seek operation is not supported.");
+ }
// Flush the write buffer, because it may
// affect the length of the stream.
@@ -103,11 +110,12 @@ public override long Length
}
// obtain file attributes
- var attributes = _session.RequestFStat(_handle, true);
+ var attributes = _session.RequestFStat(_handle, nullOnError: true);
if (attributes != null)
{
return attributes.Size;
}
+
throw new IOException("Seek operation failed.");
}
}
@@ -125,13 +133,17 @@ public override long Position
get
{
CheckSessionIsOpen();
+
if (!CanSeek)
+ {
throw new NotSupportedException("Seek operation not supported.");
+ }
+
return _position;
}
set
{
- Seek(value, SeekOrigin.Begin);
+ _ = Seek(value, SeekOrigin.Begin);
}
}
@@ -166,23 +178,55 @@ public virtual byte[] Handle
///
public TimeSpan Timeout { get; set; }
+ private SftpFileStream(ISftpSession session, string path, FileAccess access, int bufferSize, byte[] handle, long position)
+ {
+ Timeout = TimeSpan.FromSeconds(30);
+ Name = path;
+
+ _session = session;
+ _canRead = (access & FileAccess.Read) == FileAccess.Read;
+ _canSeek = true;
+ _canWrite = (access & FileAccess.Write) == FileAccess.Write;
+
+ _handle = handle;
+
+ /*
+ * Instead of using the specified buffer size as is, we use it to calculate a buffer size
+ * that ensures we always receive or send the max. number of bytes in a single SSH_FXP_READ
+ * or SSH_FXP_WRITE message.
+ */
+
+ _readBufferSize = (int) session.CalculateOptimalReadLength((uint) bufferSize);
+ _writeBufferSize = (int) session.CalculateOptimalWriteLength((uint) bufferSize, _handle);
+
+ _position = position;
+ }
+
internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAccess access, int bufferSize)
{
- if (session == null)
+ if (session is null)
+ {
throw new SshConnectionException("Client not connected.");
- if (path == null)
- throw new ArgumentNullException("path");
+ }
+
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
+
if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException("bufferSize");
+ {
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), "Cannot be less than or equal to zero.");
+ }
Timeout = TimeSpan.FromSeconds(30);
Name = path;
// Initialize the object state.
_session = session;
- _canRead = (access & FileAccess.Read) != 0;
+ _canRead = (access & FileAccess.Read) == FileAccess.Read;
_canSeek = true;
- _canWrite = (access & FileAccess.Write) != 0;
+ _canWrite = (access & FileAccess.Write) == FileAccess.Write;
var flags = Flags.None;
@@ -199,23 +243,28 @@ internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAc
flags |= Flags.Write;
break;
default:
- throw new ArgumentOutOfRangeException("access");
+ throw new ArgumentOutOfRangeException(nameof(access));
}
- if ((access & FileAccess.Read) != 0 && mode == FileMode.Append)
+ if ((access & FileAccess.Read) == FileAccess.Read && mode == FileMode.Append)
{
- throw new ArgumentException(string.Format("{0} mode can be requested only when combined with write-only access.", mode.ToString("G")));
+ throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
+ "{0} mode can be requested only when combined with write-only access.",
+ mode.ToString("G")),
+ nameof(mode));
}
- if ((access & FileAccess.Write) == 0)
+ if ((access & FileAccess.Write) != FileAccess.Write)
{
- if (mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate || mode == FileMode.Append)
+ if (mode is FileMode.Create or FileMode.CreateNew or FileMode.Truncate or FileMode.Append)
{
- throw new ArgumentException(string.Format("Combining {0}: {1} with {2}: {3} is invalid.",
- typeof(FileMode).Name,
- mode,
- typeof(FileAccess).Name,
- access));
+ throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
+ "Combining {0}: {1} with {2}: {3} is invalid.",
+ nameof(FileMode),
+ mode,
+ nameof(FileAccess),
+ access),
+ nameof(mode));
}
}
@@ -225,8 +274,8 @@ internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAc
flags |= Flags.Append | Flags.CreateNewOrOpen;
break;
case FileMode.Create:
- _handle = _session.RequestOpen(path, flags | Flags.Truncate, true);
- if (_handle == null)
+ _handle = _session.RequestOpen(path, flags | Flags.Truncate, nullOnError: true);
+ if (_handle is null)
{
flags |= Flags.CreateNew;
}
@@ -234,6 +283,7 @@ internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAc
{
flags |= Flags.Truncate;
}
+
break;
case FileMode.CreateNew:
flags |= Flags.CreateNew;
@@ -247,33 +297,141 @@ internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAc
flags |= Flags.Truncate;
break;
default:
- throw new ArgumentOutOfRangeException("mode");
+ throw new ArgumentOutOfRangeException(nameof(mode));
}
- if (_handle == null)
- _handle = _session.RequestOpen(path, flags);
+ _handle ??= _session.RequestOpen(path, flags);
- // instead of using the specified buffer size as is, we use it to calculate a buffer size
- // that ensures we always receive or send the max. number of bytes in a single SSH_FXP_READ
- // or SSH_FXP_WRITE message
+ /*
+ * Instead of using the specified buffer size as is, we use it to calculate a buffer size
+ * that ensures we always receive or send the max. number of bytes in a single SSH_FXP_READ
+ * or SSH_FXP_WRITE message.
+ */
_readBufferSize = (int) session.CalculateOptimalReadLength((uint) bufferSize);
_writeBufferSize = (int) session.CalculateOptimalWriteLength((uint) bufferSize, _handle);
if (mode == FileMode.Append)
{
- var attributes = _session.RequestFStat(_handle, false);
+ var attributes = _session.RequestFStat(_handle, nullOnError: false);
_position = attributes.Size;
}
}
+ internal static async Task OpenAsync(ISftpSession session, string path, FileMode mode, FileAccess access, int bufferSize, CancellationToken cancellationToken)
+ {
+ if (session is null)
+ {
+ throw new SshConnectionException("Client not connected.");
+ }
+
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
+
+ if (bufferSize <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), "Cannot be less than or equal to zero.");
+ }
+
+ var flags = Flags.None;
+
+ switch (access)
+ {
+ case FileAccess.Read:
+ flags |= Flags.Read;
+ break;
+ case FileAccess.Write:
+ flags |= Flags.Write;
+ break;
+ case FileAccess.ReadWrite:
+ flags |= Flags.Read;
+ flags |= Flags.Write;
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(access));
+ }
+
+ if ((access & FileAccess.Read) == FileAccess.Read && mode == FileMode.Append)
+ {
+ throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
+ "{0} mode can be requested only when combined with write-only access.",
+ mode.ToString("G")),
+ nameof(mode));
+ }
+
+ if ((access & FileAccess.Write) != FileAccess.Write)
+ {
+ if (mode is FileMode.Create or FileMode.CreateNew or FileMode.Truncate or FileMode.Append)
+ {
+ throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
+ "Combining {0}: {1} with {2}: {3} is invalid.",
+ nameof(FileMode),
+ mode,
+ nameof(FileAccess),
+ access),
+ nameof(mode));
+ }
+ }
+
+ switch (mode)
+ {
+ case FileMode.Append:
+ flags |= Flags.Append | Flags.CreateNewOrOpen;
+ break;
+ case FileMode.Create:
+ flags |= Flags.CreateNewOrOpen | Flags.Truncate;
+ break;
+ case FileMode.CreateNew:
+ flags |= Flags.CreateNew;
+ break;
+ case FileMode.Open:
+ break;
+ case FileMode.OpenOrCreate:
+ flags |= Flags.CreateNewOrOpen;
+ break;
+ case FileMode.Truncate:
+ flags |= Flags.Truncate;
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(mode));
+ }
+
+ var handle = await session.RequestOpenAsync(path, flags, cancellationToken).ConfigureAwait(false);
+
+ long position = 0;
+ if (mode == FileMode.Append)
+ {
+ try
+ {
+ var attributes = await session.RequestFStatAsync(handle, cancellationToken).ConfigureAwait(false);
+ position = attributes.Size;
+ }
+ catch
+ {
+ try
+ {
+ await session.RequestCloseAsync(handle, cancellationToken).ConfigureAwait(false);
+ }
+ catch
+ {
+ // The original exception is presumably more informative, so we just ignore this one.
+ }
+
+ throw;
+ }
+ }
+
+ return new SftpFileStream(session, path, access, bufferSize, handle, position);
+ }
+
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~SftpFileStream()
{
- Dispose(false);
+ Dispose(disposing: false);
}
///
@@ -298,6 +456,27 @@ public override void Flush()
}
}
+ ///
+ /// Asynchronously clears all buffers for this stream and causes any buffered data to be written to the file.
+ ///
+ /// The to observe.
+ /// A that represents the asynchronous flush operation.
+ /// An I/O error occurs.
+ /// Stream is closed.
+ public override Task FlushAsync(CancellationToken cancellationToken)
+ {
+ CheckSessionIsOpen();
+
+ if (_bufferOwnedByWrite)
+ {
+ return FlushWriteBufferAsync(cancellationToken);
+ }
+
+ FlushReadBuffer();
+
+ return Task.CompletedTask;
+ }
+
///
/// Reads a sequence of bytes from the current stream and advances the position within the stream by the
/// number of bytes read.
@@ -310,7 +489,7 @@ public override void Flush()
/// if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
///
/// The sum of and is larger than the buffer length.
- /// is null.
+ /// is .
/// or is negative.
/// An I/O error occurs.
/// The stream does not support reading.
@@ -335,14 +514,29 @@ public override int Read(byte[] buffer, int offset, int count)
{
var readLen = 0;
- if (buffer == null)
- throw new ArgumentNullException("buffer");
+ if (buffer is null)
+ {
+ throw new ArgumentNullException(nameof(buffer));
+ }
+
+#if NET8_0_OR_GREATER
+ ArgumentOutOfRangeException.ThrowIfNegative(offset);
+ ArgumentOutOfRangeException.ThrowIfNegative(count);
+#else
if (offset < 0)
- throw new ArgumentOutOfRangeException("offset");
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset));
+ }
+
if (count < 0)
- throw new ArgumentOutOfRangeException("count");
+ {
+ throw new ArgumentOutOfRangeException(nameof(count));
+ }
+#endif
if ((buffer.Length - offset) < count)
+ {
throw new ArgumentException("Invalid array range.");
+ }
// Lock down the file stream while we do this.
lock (_lock)
@@ -374,6 +568,7 @@ public override int Read(byte[] buffer, int offset, int count)
{
// write all data read to caller-provided buffer
bytesToWriteToCallerBuffer = data.Length;
+
// reset buffer since we will skip buffering
_bufferPosition = 0;
_bufferLen = 0;
@@ -382,18 +577,23 @@ public override int Read(byte[] buffer, int offset, int count)
{
// determine number of bytes that we should write into read buffer
var bytesToWriteToReadBuffer = data.Length - bytesToWriteToCallerBuffer;
+
// write remaining bytes to read buffer
Buffer.BlockCopy(data, count, GetOrCreateReadBuffer(), 0, bytesToWriteToReadBuffer);
+
// update position in read buffer
_bufferPosition = 0;
+
// update number of bytes in read buffer
_bufferLen = bytesToWriteToReadBuffer;
}
// write bytes to caller-provided buffer
Buffer.BlockCopy(data, 0, buffer, offset, bytesToWriteToCallerBuffer);
+
// update stream position
_position += bytesToWriteToCallerBuffer;
+
// record total number of bytes read into caller-provided buffer
readLen += bytesToWriteToCallerBuffer;
@@ -409,6 +609,7 @@ public override int Read(byte[] buffer, int offset, int count)
// advance offset to start writing bytes into caller-provided buffer
offset += bytesToWriteToCallerBuffer;
+
// update number of bytes left to read into caller-provided buffer
count -= bytesToWriteToCallerBuffer;
}
@@ -416,18 +617,25 @@ public override int Read(byte[] buffer, int offset, int count)
{
// limit the number of bytes to use from read buffer to the caller-request number of bytes
if (bytesAvailableInBuffer > count)
+ {
bytesAvailableInBuffer = count;
+ }
// copy data from read buffer to the caller-provided buffer
Buffer.BlockCopy(GetOrCreateReadBuffer(), _bufferPosition, buffer, offset, bytesAvailableInBuffer);
+
// update position in read buffer
_bufferPosition += bytesAvailableInBuffer;
+
// update stream position
_position += bytesAvailableInBuffer;
+
// record total number of bytes read into caller-provided buffer
readLen += bytesAvailableInBuffer;
+
// advance offset to start writing bytes into caller-provided buffer
offset += bytesAvailableInBuffer;
+
// update number of bytes left to read
count -= bytesAvailableInBuffer;
}
@@ -438,6 +646,147 @@ public override int Read(byte[] buffer, int offset, int count)
return readLen;
}
+ ///
+ /// Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the
+ /// number of bytes read.
+ ///
+ /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between and ( + - 1) replaced by the bytes read from the current source.
+ /// The zero-based byte offset in at which to begin storing the data read from the current stream.
+ /// The maximum number of bytes to be read from the current stream.
+ /// The to observe.
+ /// A that represents the asynchronous read operation.
+ public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ var readLen = 0;
+
+ if (buffer is null)
+ {
+ throw new ArgumentNullException(nameof(buffer));
+ }
+
+#if NET8_0_OR_GREATER
+ ArgumentOutOfRangeException.ThrowIfNegative(offset);
+ ArgumentOutOfRangeException.ThrowIfNegative(count);
+#else
+ if (offset < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset));
+ }
+
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count));
+ }
+#endif
+ if ((buffer.Length - offset) < count)
+ {
+ throw new ArgumentException("Invalid array range.");
+ }
+
+ CheckSessionIsOpen();
+
+ // Set up for the read operation.
+ SetupRead();
+
+ // Read data into the caller's buffer.
+ while (count > 0)
+ {
+ // How much data do we have available in the buffer?
+ var bytesAvailableInBuffer = _bufferLen - _bufferPosition;
+ if (bytesAvailableInBuffer <= 0)
+ {
+ var data = await _session.RequestReadAsync(_handle, (ulong)_position, (uint)_readBufferSize, cancellationToken).ConfigureAwait(false);
+
+ if (data.Length == 0)
+ {
+ _bufferPosition = 0;
+ _bufferLen = 0;
+
+ break;
+ }
+
+ var bytesToWriteToCallerBuffer = count;
+ if (bytesToWriteToCallerBuffer >= data.Length)
+ {
+ // write all data read to caller-provided buffer
+ bytesToWriteToCallerBuffer = data.Length;
+
+ // reset buffer since we will skip buffering
+ _bufferPosition = 0;
+ _bufferLen = 0;
+ }
+ else
+ {
+ // determine number of bytes that we should write into read buffer
+ var bytesToWriteToReadBuffer = data.Length - bytesToWriteToCallerBuffer;
+
+ // write remaining bytes to read buffer
+ Buffer.BlockCopy(data, count, GetOrCreateReadBuffer(), 0, bytesToWriteToReadBuffer);
+
+ // update position in read buffer
+ _bufferPosition = 0;
+
+ // update number of bytes in read buffer
+ _bufferLen = bytesToWriteToReadBuffer;
+ }
+
+ // write bytes to caller-provided buffer
+ Buffer.BlockCopy(data, 0, buffer, offset, bytesToWriteToCallerBuffer);
+
+ // update stream position
+ _position += bytesToWriteToCallerBuffer;
+
+ // record total number of bytes read into caller-provided buffer
+ readLen += bytesToWriteToCallerBuffer;
+
+ // break out of the read loop when the server returned less than the request number of bytes
+ // as that *may* indicate that we've reached EOF
+ //
+ // doing this avoids reading from server twice to determine EOF: once in the read loop, and
+ // once upon the next Read or ReadByte invocation by the caller
+ if (data.Length < _readBufferSize)
+ {
+ break;
+ }
+
+ // advance offset to start writing bytes into caller-provided buffer
+ offset += bytesToWriteToCallerBuffer;
+
+ // update number of bytes left to read into caller-provided buffer
+ count -= bytesToWriteToCallerBuffer;
+ }
+ else
+ {
+ // limit the number of bytes to use from read buffer to the caller-request number of bytes
+ if (bytesAvailableInBuffer > count)
+ {
+ bytesAvailableInBuffer = count;
+ }
+
+ // copy data from read buffer to the caller-provided buffer
+ Buffer.BlockCopy(GetOrCreateReadBuffer(), _bufferPosition, buffer, offset, bytesAvailableInBuffer);
+
+ // update position in read buffer
+ _bufferPosition += bytesAvailableInBuffer;
+
+ // update stream position
+ _position += bytesAvailableInBuffer;
+
+ // record total number of bytes read into caller-provided buffer
+ readLen += bytesAvailableInBuffer;
+
+ // advance offset to start writing bytes into caller-provided buffer
+ offset += bytesAvailableInBuffer;
+
+ // update number of bytes left to read
+ count -= bytesAvailableInBuffer;
+ }
+ }
+
+ // return the number of bytes that were read to the caller.
+ return readLen;
+ }
+
///
/// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
///
@@ -482,6 +831,7 @@ public override int ReadByte()
// Extract the next byte from the buffer.
++_position;
+
return readBuffer[_bufferPosition++];
}
}
@@ -499,7 +849,7 @@ public override int ReadByte()
/// Methods were called after the stream was closed.
public override long Seek(long offset, SeekOrigin origin)
{
- long newPosn = -1;
+ long newPosn;
// Lock down the file stream while we do this.
lock (_lock)
@@ -507,13 +857,16 @@ public override long Seek(long offset, SeekOrigin origin)
CheckSessionIsOpen();
if (!CanSeek)
+ {
throw new NotSupportedException("Seek is not supported.");
+ }
// Don't do anything if the position won't be moving.
if (origin == SeekOrigin.Begin && offset == _position)
{
return offset;
}
+
if (origin == SeekOrigin.Current && offset == 0)
{
return _position;
@@ -524,26 +877,6 @@ public override long Seek(long offset, SeekOrigin origin)
{
// Flush the write buffer and then seek.
FlushWriteBuffer();
-
- switch (origin)
- {
- case SeekOrigin.Begin:
- newPosn = offset;
- break;
- case SeekOrigin.Current:
- newPosn = _position + offset;
- break;
- case SeekOrigin.End:
- var attributes = _session.RequestFStat(_handle, false);
- newPosn = attributes.Size - offset;
- break;
- }
-
- if (newPosn == -1)
- {
- throw new EndOfStreamException("End of stream.");
- }
- _position = newPosn;
}
else
{
@@ -574,29 +907,31 @@ public override long Seek(long offset, SeekOrigin origin)
// Abandon the read buffer.
_bufferPosition = 0;
_bufferLen = 0;
+ }
- // Seek to the new position.
- switch (origin)
- {
- case SeekOrigin.Begin:
- newPosn = offset;
- break;
- case SeekOrigin.Current:
- newPosn = _position + offset;
- break;
- case SeekOrigin.End:
- var attributes = _session.RequestFStat(_handle, false);
- newPosn = attributes.Size - offset;
- break;
- }
-
- if (newPosn < 0)
- {
- throw new EndOfStreamException();
- }
+ // Seek to the new position.
+ switch (origin)
+ {
+ case SeekOrigin.Begin:
+ newPosn = offset;
+ break;
+ case SeekOrigin.Current:
+ newPosn = _position + offset;
+ break;
+ case SeekOrigin.End:
+ var attributes = _session.RequestFStat(_handle, nullOnError: false);
+ newPosn = attributes.Size + offset;
+ break;
+ default:
+ throw new ArgumentException("Invalid seek origin.", nameof(origin));
+ }
- _position = newPosn;
+ if (newPosn < 0)
+ {
+ throw new EndOfStreamException();
}
+
+ _position = newPosn;
return _position;
}
}
@@ -624,8 +959,14 @@ public override long Seek(long offset, SeekOrigin origin)
///
public override void SetLength(long value)
{
+#if NET8_0_OR_GREATER
+ ArgumentOutOfRangeException.ThrowIfNegative(value);
+#else
if (value < 0)
- throw new ArgumentOutOfRangeException("value");
+ {
+ throw new ArgumentOutOfRangeException(nameof(value));
+ }
+#endif
// Lock down the file stream while we do this.
lock (_lock)
@@ -633,7 +974,9 @@ public override void SetLength(long value)
CheckSessionIsOpen();
if (!CanSeek)
+ {
throw new NotSupportedException("Seek is not supported.");
+ }
if (_bufferOwnedByWrite)
{
@@ -644,7 +987,7 @@ public override void SetLength(long value)
SetupWrite();
}
- var attributes = _session.RequestFStat(_handle, false);
+ var attributes = _session.RequestFStat(_handle, nullOnError: false);
attributes.Size = value;
_session.RequestFSetStat(_handle, attributes);
@@ -662,21 +1005,36 @@ public override void SetLength(long value)
/// The zero-based byte offset in at which to begin copying bytes to the current stream.
/// The number of bytes to be written to the current stream.
/// The sum of and is greater than the buffer length.
- /// is null.
+ /// is .
/// or is negative.
/// An I/O error occurs.
/// The stream does not support writing.
/// Methods were called after the stream was closed.
public override void Write(byte[] buffer, int offset, int count)
{
- if (buffer == null)
- throw new ArgumentNullException("buffer");
+ if (buffer is null)
+ {
+ throw new ArgumentNullException(nameof(buffer));
+ }
+
+#if NET8_0_OR_GREATER
+ ArgumentOutOfRangeException.ThrowIfNegative(offset);
+ ArgumentOutOfRangeException.ThrowIfNegative(count);
+#else
if (offset < 0)
- throw new ArgumentOutOfRangeException("offset");
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset));
+ }
+
if (count < 0)
- throw new ArgumentOutOfRangeException("count");
+ {
+ throw new ArgumentOutOfRangeException(nameof(count));
+ }
+#endif
if ((buffer.Length - offset) < count)
+ {
throw new ArgumentException("Invalid array range.");
+ }
// Lock down the file stream while we do this.
lock (_lock)
@@ -695,6 +1053,7 @@ public override void Write(byte[] buffer, int offset, int count)
{
// flush write buffer, and mark it empty
FlushWriteBuffer();
+
// we can now write or buffer the full buffer size
tempLen = _writeBufferSize;
}
@@ -708,7 +1067,7 @@ public override void Write(byte[] buffer, int offset, int count)
// Can we short-cut the internal buffer?
if (_bufferPosition == 0 && tempLen == _writeBufferSize)
{
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
_session.RequestWrite(_handle, (ulong) _position, buffer, offset, tempLen, wait);
}
@@ -730,7 +1089,7 @@ public override void Write(byte[] buffer, int offset, int count)
// rather than waiting for the next call to this method.
if (_bufferPosition >= _writeBufferSize)
{
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
_session.RequestWrite(_handle, (ulong) (_position - _bufferPosition), GetOrCreateWriteBuffer(), 0, _bufferPosition, wait);
}
@@ -740,6 +1099,98 @@ public override void Write(byte[] buffer, int offset, int count)
}
}
+ ///
+ /// Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
+ ///
+ /// An array of bytes. This method copies bytes from to the current stream.
+ /// The zero-based byte offset in at which to begin copying bytes to the current stream.
+ /// The number of bytes to be written to the current stream.
+ /// The to observe.
+ /// A that represents the asynchronous write operation.
+ /// The sum of and is greater than the buffer length.
+ /// is .
+ /// or is negative.
+ /// An I/O error occurs.
+ /// The stream does not support writing.
+ /// Methods were called after the stream was closed.
+ public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ if (buffer is null)
+ {
+ throw new ArgumentNullException(nameof(buffer));
+ }
+
+#if NET8_0_OR_GREATER
+ ArgumentOutOfRangeException.ThrowIfNegative(offset);
+ ArgumentOutOfRangeException.ThrowIfNegative(count);
+#else
+ if (offset < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset));
+ }
+
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count));
+ }
+#endif
+ if ((buffer.Length - offset) < count)
+ {
+ throw new ArgumentException("Invalid array range.");
+ }
+
+ CheckSessionIsOpen();
+
+ // Setup this object for writing.
+ SetupWrite();
+
+ // Write data to the file stream.
+ while (count > 0)
+ {
+ // Determine how many bytes we can write to the buffer.
+ var tempLen = _writeBufferSize - _bufferPosition;
+ if (tempLen <= 0)
+ {
+ // flush write buffer, and mark it empty
+ await FlushWriteBufferAsync(cancellationToken).ConfigureAwait(false);
+
+ // we can now write or buffer the full buffer size
+ tempLen = _writeBufferSize;
+ }
+
+ // limit the number of bytes to write to the actual number of bytes requested
+ if (tempLen > count)
+ {
+ tempLen = count;
+ }
+
+ // Can we short-cut the internal buffer?
+ if (_bufferPosition == 0 && tempLen == _writeBufferSize)
+ {
+ await _session.RequestWriteAsync(_handle, (ulong)_position, buffer, offset, tempLen, cancellationToken).ConfigureAwait(false);
+ }
+ else
+ {
+ // No: copy the data to the write buffer first.
+ Buffer.BlockCopy(buffer, offset, GetOrCreateWriteBuffer(), _bufferPosition, tempLen);
+ _bufferPosition += tempLen;
+ }
+
+ // Advance the buffer and stream positions.
+ _position += tempLen;
+ offset += tempLen;
+ count -= tempLen;
+ }
+
+ // If the buffer is full, then do a speculative flush now,
+ // rather than waiting for the next call to this method.
+ if (_bufferPosition >= _writeBufferSize)
+ {
+ await _session.RequestWriteAsync(_handle, (ulong)(_position - _bufferPosition), GetOrCreateWriteBuffer(), 0, _bufferPosition, cancellationToken).ConfigureAwait(false);
+ _bufferPosition = 0;
+ }
+ }
+
///
/// Writes a byte to the current position in the stream and advances the position within the stream by one byte.
///
@@ -762,7 +1213,7 @@ public override void WriteByte(byte value)
// Flush the current buffer if it is full.
if (_bufferPosition >= _writeBufferSize)
{
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
_session.RequestWrite(_handle, (ulong) (_position - _bufferPosition), writeBuffer, 0, _bufferPosition, wait);
}
@@ -779,7 +1230,7 @@ public override void WriteByte(byte value)
///
/// Releases the unmanaged resources used by the and optionally releases the managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
@@ -820,15 +1271,13 @@ protected override void Dispose(bool disposing)
private byte[] GetOrCreateReadBuffer()
{
- if (_readBuffer == null)
- _readBuffer = new byte[_readBufferSize];
+ _readBuffer ??= new byte[_readBufferSize];
return _readBuffer;
}
private byte[] GetOrCreateWriteBuffer()
{
- if (_writeBuffer == null)
- _writeBuffer = new byte[_writeBufferSize];
+ _writeBuffer ??= new byte[_writeBufferSize];
return _writeBuffer;
}
@@ -848,7 +1297,7 @@ private void FlushWriteBuffer()
{
if (_bufferPosition > 0)
{
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
_session.RequestWrite(_handle, (ulong) (_position - _bufferPosition), _writeBuffer, 0, _bufferPosition, wait);
}
@@ -857,13 +1306,24 @@ private void FlushWriteBuffer()
}
}
+ private async Task FlushWriteBufferAsync(CancellationToken cancellationToken)
+ {
+ if (_bufferPosition > 0)
+ {
+ await _session.RequestWriteAsync(_handle, (ulong)(_position - _bufferPosition), _writeBuffer, 0, _bufferPosition, cancellationToken).ConfigureAwait(false);
+ _bufferPosition = 0;
+ }
+ }
+
///
/// Setups the read.
///
private void SetupRead()
{
if (!CanRead)
+ {
throw new NotSupportedException("Read not supported.");
+ }
if (_bufferOwnedByWrite)
{
@@ -877,8 +1337,10 @@ private void SetupRead()
///
private void SetupWrite()
{
- if ((!CanWrite))
+ if (!CanWrite)
+ {
throw new NotSupportedException("Write not supported.");
+ }
if (!_bufferOwnedByWrite)
{
@@ -889,10 +1351,19 @@ private void SetupWrite()
private void CheckSessionIsOpen()
{
- if (_session == null)
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_session is null, this);
+#else
+ if (_session is null)
+ {
throw new ObjectDisposedException(GetType().FullName);
+ }
+#endif // NET7_0_OR_GREATER
+
if (!_session.IsOpen)
+ {
throw new ObjectDisposedException(GetType().FullName, "Cannot access a closed SFTP session.");
+ }
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Sftp/SftpFileSystemInformation.cs b/src/Renci.SshNet/Sftp/SftpFileSystemInformation.cs
index bff9295be..89d24a727 100644
--- a/src/Renci.SshNet/Sftp/SftpFileSystemInformation.cs
+++ b/src/Renci.SshNet/Sftp/SftpFileSystemInformation.cs
@@ -5,10 +5,14 @@ namespace Renci.SshNet.Sftp
///
/// Contains File system information exposed by statvfs@openssh.com request.
///
+#pragma warning disable SA1649 // File name should match first type name
public class SftpFileSytemInformation
+#pragma warning restore SA1649 // File name should match first type name
{
+#pragma warning disable SA1310 // Field names should not contain underscore
internal const ulong SSH_FXE_STATVFS_ST_RDONLY = 0x1;
internal const ulong SSH_FXE_STATVFS_ST_NOSUID = 0x2;
+#pragma warning restore SA1310 // Field names should not contain underscore
private readonly ulong _flag;
@@ -88,7 +92,7 @@ public class SftpFileSytemInformation
/// Gets a value indicating whether this instance is read only.
///
///
- /// true if this instance is read only; otherwise, false.
+ /// if this instance is read only; otherwise, .
///
public bool IsReadOnly
{
@@ -99,7 +103,7 @@ public bool IsReadOnly
/// Gets a value indicating whether [supports set uid].
///
///
- /// true if [supports set uid]; otherwise, false.
+ /// if [supports set uid]; otherwise, .
///
public bool SupportsSetUid
{
@@ -158,4 +162,4 @@ internal void SaveData(SshDataStream stream)
stream.Write(MaxNameLenght);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet/Sftp/SftpListDirectoryAsyncResult.cs b/src/Renci.SshNet/Sftp/SftpListDirectoryAsyncResult.cs
index cb7b60132..b69c05b27 100644
--- a/src/Renci.SshNet/Sftp/SftpListDirectoryAsyncResult.cs
+++ b/src/Renci.SshNet/Sftp/SftpListDirectoryAsyncResult.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+
using Renci.SshNet.Common;
namespace Renci.SshNet.Sftp
@@ -7,22 +8,21 @@ namespace Renci.SshNet.Sftp
///
/// Encapsulates the results of an asynchronous directory list operation.
///
- public class SftpListDirectoryAsyncResult : AsyncResult>
+ public class SftpListDirectoryAsyncResult : AsyncResult>
{
///
/// Gets the number of files read so far.
///
public int FilesRead { get; private set; }
-
+
///
/// Initializes a new instance of the class.
///
/// The async callback.
/// The state.
- public SftpListDirectoryAsyncResult(AsyncCallback asyncCallback, Object state)
+ public SftpListDirectoryAsyncResult(AsyncCallback asyncCallback, object state)
: base(asyncCallback, state)
{
-
}
///
diff --git a/src/Renci.SshNet/Sftp/SftpMessage.cs b/src/Renci.SshNet/Sftp/SftpMessage.cs
index 8f131fa79..5ecb69bc8 100644
--- a/src/Renci.SshNet/Sftp/SftpMessage.cs
+++ b/src/Renci.SshNet/Sftp/SftpMessage.cs
@@ -1,6 +1,7 @@
-using System.IO;
+using System.Globalization;
+using System.IO;
+
using Renci.SshNet.Common;
-using System.Globalization;
namespace Renci.SshNet.Sftp
{
@@ -44,7 +45,7 @@ protected override void WriteBytes(SshDataStream stream)
var startPosition = stream.Position;
// skip 4 bytes for the length of the SFTP message data
- stream.Seek(sizeOfDataLengthBytes, SeekOrigin.Current);
+ _ = stream.Seek(sizeOfDataLengthBytes, SeekOrigin.Current);
// write the SFTP message data to the stream
base.WriteBytes(stream);
diff --git a/src/Renci.SshNet/Sftp/SftpMessageTypes.cs b/src/Renci.SshNet/Sftp/SftpMessageTypes.cs
index d74fc6ccd..25ea00eac 100644
--- a/src/Renci.SshNet/Sftp/SftpMessageTypes.cs
+++ b/src/Renci.SshNet/Sftp/SftpMessageTypes.cs
@@ -1,130 +1,155 @@
-
-namespace Renci.SshNet.Sftp
+namespace Renci.SshNet.Sftp
{
internal enum SftpMessageTypes : byte
{
///
- /// SSH_FXP_INIT
+ /// SSH_FXP_INIT.
///
Init = 1,
+
///
- /// SSH_FXP_VERSION
+ /// SSH_FXP_VERSION.
///
Version = 2,
+
///
- /// SSH_FXP_OPEN
+ /// SSH_FXP_OPEN.
///
Open = 3,
+
///
- /// SSH_FXP_CLOSE
+ /// SSH_FXP_CLOSE.
///
Close = 4,
+
///
- /// SSH_FXP_READ
+ /// SSH_FXP_READ.
///
Read = 5,
+
///
- /// SSH_FXP_WRITE
+ /// SSH_FXP_WRITE.
///
Write = 6,
+
///
- /// SSH_FXP_LSTAT
+ /// SSH_FXP_LSTAT.
///
LStat = 7,
+
///
- /// SSH_FXP_FSTAT
+ /// SSH_FXP_FSTAT.
///
FStat = 8,
+
///
- /// SSH_FXP_SETSTAT
+ /// SSH_FXP_SETSTAT.
///
SetStat = 9,
+
///
- /// SSH_FXP_FSETSTAT
+ /// SSH_FXP_FSETSTAT.
///
FSetStat = 10,
+
///
- /// SSH_FXP_OPENDIR
+ /// SSH_FXP_OPENDIR.
///
OpenDir = 11,
+
///
- /// SSH_FXP_READDIR
+ /// SSH_FXP_READDIR.
///
ReadDir = 12,
+
///
- /// SSH_FXP_REMOVE
+ /// SSH_FXP_REMOVE.
///
Remove = 13,
+
///
- /// SSH_FXP_MKDIR
+ /// SSH_FXP_MKDIR.
///
MkDir = 14,
+
///
- /// SSH_FXP_RMDIR
+ /// SSH_FXP_RMDIR.
///
RmDir = 15,
+
///
- /// SSH_FXP_REALPATH
+ /// SSH_FXP_REALPATH.
///
RealPath = 16,
+
///
- /// SSH_FXP_STAT
+ /// SSH_FXP_STAT.
///
Stat = 17,
+
///
- /// SSH_FXP_RENAME
+ /// SSH_FXP_RENAME.
///
Rename = 18,
+
///
- /// SSH_FXP_READLINK
+ /// SSH_FXP_READLINK.
///
ReadLink = 19,
+
///
- /// SSH_FXP_SYMLINK
+ /// SSH_FXP_SYMLINK.
///
SymLink = 20,
+
///
- /// SSH_FXP_LINK
+ /// SSH_FXP_LINK.
///
Link = 21,
+
///
- /// SSH_FXP_BLOCK
+ /// SSH_FXP_BLOCK.
///
Block = 22,
+
///
- /// SSH_FXP_UNBLOCK
+ /// SSH_FXP_UNBLOCK.
///
Unblock = 23,
///
- /// SSH_FXP_STATUS
+ /// SSH_FXP_STATUS.
///
Status = 101,
+
///
- /// SSH_FXP_HANDLE
+ /// SSH_FXP_HANDLE.
///
Handle = 102,
+
///
- /// SSH_FXP_DATA
+ /// SSH_FXP_DATA.
///
Data = 103,
+
///
- /// SSH_FXP_NAME
+ /// SSH_FXP_NAME.
///
Name = 104,
+
///
- /// SSH_FXP_ATTRS
+ /// SSH_FXP_ATTRS.
///
Attrs = 105,
///
- /// SSH_FXP_EXTENDED
+ /// SSH_FXP_EXTENDED.
///
Extended = 200,
+
///
- /// SSH_FXP_EXTENDED_REPLY
+ /// SSH_FXP_EXTENDED_REPLY.
///
ExtendedReply = 201
-
}
}
diff --git a/src/Renci.SshNet/Sftp/SftpOpenAsyncResult.cs b/src/Renci.SshNet/Sftp/SftpOpenAsyncResult.cs
index b19de7e79..a239172e4 100644
--- a/src/Renci.SshNet/Sftp/SftpOpenAsyncResult.cs
+++ b/src/Renci.SshNet/Sftp/SftpOpenAsyncResult.cs
@@ -1,11 +1,13 @@
-using Renci.SshNet.Common;
-using System;
+using System;
+
+using Renci.SshNet.Common;
namespace Renci.SshNet.Sftp
{
- internal class SftpOpenAsyncResult : AsyncResult
+ internal sealed class SftpOpenAsyncResult : AsyncResult
{
- public SftpOpenAsyncResult(AsyncCallback asyncCallback, object state) : base(asyncCallback, state)
+ public SftpOpenAsyncResult(AsyncCallback asyncCallback, object state)
+ : base(asyncCallback, state)
{
}
}
diff --git a/src/Renci.SshNet/Sftp/SftpReadAsyncResult.cs b/src/Renci.SshNet/Sftp/SftpReadAsyncResult.cs
index 65911d222..9814f0e8f 100644
--- a/src/Renci.SshNet/Sftp/SftpReadAsyncResult.cs
+++ b/src/Renci.SshNet/Sftp/SftpReadAsyncResult.cs
@@ -1,11 +1,13 @@
-using Renci.SshNet.Common;
-using System;
+using System;
+
+using Renci.SshNet.Common;
namespace Renci.SshNet.Sftp
{
- internal class SftpReadAsyncResult : AsyncResult
+ internal sealed class SftpReadAsyncResult : AsyncResult
{
- public SftpReadAsyncResult(AsyncCallback asyncCallback, object state) : base(asyncCallback, state)
+ public SftpReadAsyncResult(AsyncCallback asyncCallback, object state)
+ : base(asyncCallback, state)
{
}
}
diff --git a/src/Renci.SshNet/Sftp/SftpRealPathAsyncResult.cs b/src/Renci.SshNet/Sftp/SftpRealPathAsyncResult.cs
index e1f1fbf95..ab8600320 100644
--- a/src/Renci.SshNet/Sftp/SftpRealPathAsyncResult.cs
+++ b/src/Renci.SshNet/Sftp/SftpRealPathAsyncResult.cs
@@ -1,11 +1,13 @@
-using Renci.SshNet.Common;
-using System;
+using System;
+
+using Renci.SshNet.Common;
namespace Renci.SshNet.Sftp
{
- internal class SftpRealPathAsyncResult : AsyncResult
+ internal sealed class SftpRealPathAsyncResult : AsyncResult
{
- public SftpRealPathAsyncResult(AsyncCallback asyncCallback, object state) : base(asyncCallback, state)
+ public SftpRealPathAsyncResult(AsyncCallback asyncCallback, object state)
+ : base(asyncCallback, state)
{
}
}
diff --git a/src/Renci.SshNet/Sftp/SftpResponseFactory.cs b/src/Renci.SshNet/Sftp/SftpResponseFactory.cs
index ad6b22913..1d5b4ad50 100644
--- a/src/Renci.SshNet/Sftp/SftpResponseFactory.cs
+++ b/src/Renci.SshNet/Sftp/SftpResponseFactory.cs
@@ -1,7 +1,8 @@
using System;
+using System.Globalization;
using System.Text;
+
using Renci.SshNet.Sftp.Responses;
-using System.Globalization;
namespace Renci.SshNet.Sftp
{
@@ -13,6 +14,7 @@ public SftpMessage Create(uint protocolVersion, byte messageType, Encoding encod
SftpMessage message;
+#pragma warning disable IDE0010 // Add missing cases
switch (sftpMessageType)
{
case SftpMessageTypes.Version:
@@ -39,6 +41,7 @@ public SftpMessage Create(uint protocolVersion, byte messageType, Encoding encod
default:
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Message type '{0}' is not supported.", sftpMessageType));
}
+#pragma warning restore IDE0010 // Add missing cases
return message;
}
diff --git a/src/Renci.SshNet/Sftp/SftpSession.cs b/src/Renci.SshNet/Sftp/SftpSession.cs
index 283ff6179..0fec92230 100644
--- a/src/Renci.SshNet/Sftp/SftpSession.cs
+++ b/src/Renci.SshNet/Sftp/SftpSession.cs
@@ -1,31 +1,31 @@
using System;
+using System.Collections.Generic;
+using System.Globalization;
using System.Text;
using System.Threading;
+using System.Threading.Tasks;
+
using Renci.SshNet.Common;
-using System.Collections.Generic;
-using System.Globalization;
-using Renci.SshNet.Sftp.Responses;
using Renci.SshNet.Sftp.Requests;
+using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp
{
- internal class SftpSession : SubsystemSession, ISftpSession
+ ///
+ /// Represents an SFTP session.
+ ///
+ internal sealed class SftpSession : SubsystemSession, ISftpSession
{
internal const int MaximumSupportedVersion = 3;
private const int MinimumSupportedVersion = 0;
private readonly Dictionary _requests = new Dictionary();
private readonly ISftpResponseFactory _sftpResponseFactory;
- //FIXME: obtain from SftpClient!
private readonly List _data = new List(32 * 1024);
- private EventWaitHandle _sftpVersionConfirmed = new AutoResetEvent(false);
+ private readonly Encoding _encoding;
+ private EventWaitHandle _sftpVersionConfirmed = new AutoResetEvent(initialState: false);
private IDictionary _supportedExtensions;
- ///
- /// Gets the character encoding to use.
- ///
- protected Encoding Encoding { get; private set; }
-
///
/// Gets the remote working directory.
///
@@ -55,10 +55,17 @@ public uint NextRequestId
}
}
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The SSH session.
+ /// The operation timeout.
+ /// The character encoding to use.
+ /// The factory to create SFTP responses.
public SftpSession(ISession session, int operationTimeout, Encoding encoding, ISftpResponseFactory sftpResponseFactory)
: base(session, "sftp", operationTimeout)
{
- Encoding = encoding;
+ _encoding = encoding;
_sftpResponseFactory = sftpResponseFactory;
}
@@ -94,7 +101,7 @@ public string GetCanonicalPath(string path)
var canonizedPath = string.Empty;
- var realPathFiles = RequestRealPath(fullPath, true);
+ var realPathFiles = RequestRealPath(fullPath, nullOnError: true);
if (realPathFiles != null)
{
@@ -102,23 +109,37 @@ public string GetCanonicalPath(string path)
}
if (!string.IsNullOrEmpty(canonizedPath))
+ {
return canonizedPath;
+ }
- // Check for special cases
+ // Check for special cases
if (fullPath.EndsWith("/.", StringComparison.OrdinalIgnoreCase) ||
fullPath.EndsWith("/..", StringComparison.OrdinalIgnoreCase) ||
fullPath.Equals("/", StringComparison.OrdinalIgnoreCase) ||
+#if NET || NETSTANDARD2_1_OR_GREATER
+ fullPath.IndexOf('/', StringComparison.OrdinalIgnoreCase) < 0)
+#else
fullPath.IndexOf('/') < 0)
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
return fullPath;
+ }
var pathParts = fullPath.Split('/');
+#if NET || NETSTANDARD2_1_OR_GREATER
+ var partialFullPath = string.Join('/', pathParts, 0, pathParts.Length - 1);
+#else
var partialFullPath = string.Join("/", pathParts, 0, pathParts.Length - 1);
+#endif // NET || NETSTANDARD2_1_OR_GREATER
if (string.IsNullOrEmpty(partialFullPath))
+ {
partialFullPath = "/";
+ }
- realPathFiles = RequestRealPath(partialFullPath, true);
+ realPathFiles = RequestRealPath(partialFullPath, nullOnError: true);
if (realPathFiles != null)
{
@@ -132,10 +153,96 @@ public string GetCanonicalPath(string path)
var slash = string.Empty;
if (canonizedPath[canonizedPath.Length - 1] != '/')
+ {
slash = "/";
+ }
+
return string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", canonizedPath, slash, pathParts[pathParts.Length - 1]);
}
+ ///
+ /// Asynchronously resolves a given path into an absolute path on the server.
+ ///
+ /// The path to resolve.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task representing the absolute path.
+ ///
+ public async Task GetCanonicalPathAsync(string path, CancellationToken cancellationToken)
+ {
+ var fullPath = GetFullRemotePath(path);
+
+ var canonizedPath = string.Empty;
+ var realPathFiles = await RequestRealPathAsync(fullPath, nullOnError: true, cancellationToken).ConfigureAwait(false);
+ if (realPathFiles != null)
+ {
+ canonizedPath = realPathFiles[0].Key;
+ }
+
+ if (!string.IsNullOrEmpty(canonizedPath))
+ {
+ return canonizedPath;
+ }
+
+ // Check for special cases
+ if (fullPath.EndsWith("/.", StringComparison.Ordinal) ||
+ fullPath.EndsWith("/..", StringComparison.Ordinal) ||
+ fullPath.Equals("/", StringComparison.Ordinal) ||
+#if NET || NETSTANDARD2_1_OR_GREATER
+ fullPath.IndexOf('/', StringComparison.Ordinal) < 0)
+#else
+ fullPath.IndexOf('/') < 0)
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ return fullPath;
+ }
+
+ var pathParts = fullPath.Split('/');
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ var partialFullPath = string.Join('/', pathParts);
+#else
+ var partialFullPath = string.Join("/", pathParts);
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+
+ if (string.IsNullOrEmpty(partialFullPath))
+ {
+ partialFullPath = "/";
+ }
+
+ realPathFiles = await RequestRealPathAsync(partialFullPath, nullOnError: true, cancellationToken).ConfigureAwait(false);
+
+ if (realPathFiles != null)
+ {
+ canonizedPath = realPathFiles[0].Key;
+ }
+
+ if (string.IsNullOrEmpty(canonizedPath))
+ {
+ return fullPath;
+ }
+
+ var slash = string.Empty;
+ if (canonizedPath[canonizedPath.Length - 1] != '/')
+ {
+ slash = "/";
+ }
+
+ return canonizedPath + slash + pathParts[pathParts.Length - 1];
+ }
+
+ ///
+ /// Creates an for reading the content of the file represented by a given .
+ ///
+ /// The handle of the file to read.
+ /// The SFTP session.
+ /// The maximum number of bytes to read with each chunk.
+ /// The maximum number of pending reads.
+ /// The size of the file or when the size could not be determined.
+ ///
+ /// An for reading the content of the file represented by the
+ /// specified .
+ ///
public ISftpFileReader CreateFileReader(byte[] handle, ISftpSession sftpSession, uint chunkSize, int maxPendingReads, long? fileSize)
{
return new SftpFileReader(handle, sftpSession, chunkSize, maxPendingReads, fileSize);
@@ -149,13 +256,14 @@ internal string GetFullRemotePath(string path)
{
if (WorkingDirectory[WorkingDirectory.Length - 1] == '/')
{
- fullPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", WorkingDirectory, path);
+ fullPath = WorkingDirectory + path;
}
else
{
- fullPath = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", WorkingDirectory, path);
+ fullPath = WorkingDirectory + '/' + path;
}
}
+
return fullPath;
}
@@ -165,12 +273,12 @@ protected override void OnChannelOpen()
WaitOnHandle(_sftpVersionConfirmed, OperationTimeout);
- if (ProtocolVersion > MaximumSupportedVersion || ProtocolVersion < MinimumSupportedVersion)
+ if (ProtocolVersion is > MaximumSupportedVersion or < MinimumSupportedVersion)
{
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Server SFTP version {0} is not supported.", ProtocolVersion));
}
- // Resolve current directory
+ // Resolve current directory
WorkingDirectory = RequestRealPath(".")[0].Key;
}
@@ -291,19 +399,19 @@ protected override void OnDataReceived(byte[] data)
private bool TryLoadSftpMessage(byte[] packetData, int offset, int count)
{
// Create SFTP message
- var response = _sftpResponseFactory.Create(ProtocolVersion, packetData[offset], Encoding);
+ var response = _sftpResponseFactory.Create(ProtocolVersion, packetData[offset], _encoding);
+
// Load message data into it
response.Load(packetData, offset + 1, count - 1);
try
{
- var versionResponse = response as SftpVersionResponse;
- if (versionResponse != null)
+ if (response is SftpVersionResponse versionResponse)
{
ProtocolVersion = versionResponse.Version;
_supportedExtensions = versionResponse.Extentions;
- _sftpVersionConfirmed.Set();
+ _ = _sftpVersionConfirmed.Set();
}
else
{
@@ -344,49 +452,88 @@ private void SendRequest(SftpRequest request)
SendMessage(request);
}
- #region SFTP API functions
-
///
- /// Performs SSH_FXP_OPEN request
+ /// Performs SSH_FXP_OPEN request.
///
/// The path.
/// The flags.
- /// if set to true returns null instead of throwing an exception.
+ /// If set to returns instead of throwing an exception.
/// File handle.
public byte[] RequestOpen(string path, Flags flags, bool nullOnError = false)
{
byte[] handle = null;
SshException exception = null;
- using (var wait = new AutoResetEvent(false))
- {
- var request = new SftpOpenRequest(ProtocolVersion, NextRequestId, path, Encoding, flags,
- response =>
- {
- handle = response.Handle;
- wait.Set();
- },
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ using (var wait = new AutoResetEvent(initialState: false))
+ {
+ var request = new SftpOpenRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ flags,
+ response =>
+ {
+ handle = response.Handle;
+ _ = wait.Set();
+ },
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (!nullOnError && exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (!nullOnError && exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
+#pragma warning restore CA1508 // Avoid dead conditional code
return handle;
}
///
- /// Performs SSH_FXP_OPEN request
+ /// Asynchronously performs a SSH_FXP_OPEN request.
+ ///
+ /// The path.
+ /// The flags.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_OPEN request. The value of its
+ /// contains the file handle of the specified path.
+ ///
+ public async Task RequestOpenAsync(string path, Flags flags, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ SendRequest(new SftpOpenRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ flags,
+ response => tcs.TrySetResult(response.Handle),
+ response => tcs.TrySetException(GetSftpException(response))));
+
+ return await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
+ ///
+ /// Performs SSH_FXP_OPEN request.
///
/// The path.
/// The flags.
@@ -399,15 +546,19 @@ public SftpOpenAsyncResult BeginOpen(string path, Flags flags, AsyncCallback cal
{
var asyncResult = new SftpOpenAsyncResult(callback, state);
- var request = new SftpOpenRequest(ProtocolVersion, NextRequestId, path, Encoding, flags,
- response =>
- {
- asyncResult.SetAsCompleted(response.Handle, false);
- },
- response =>
- {
- asyncResult.SetAsCompleted(GetSftpException(response), false);
- });
+ var request = new SftpOpenRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ flags,
+ response =>
+ {
+ asyncResult.SetAsCompleted(response.Handle, completedSynchronously: false);
+ },
+ response =>
+ {
+ asyncResult.SetAsCompleted(GetSftpException(response), completedSynchronously: false);
+ });
SendRequest(request);
@@ -425,17 +576,23 @@ public SftpOpenAsyncResult BeginOpen(string path, Flags flags, AsyncCallback cal
/// If all available data has been read, the method completes
/// immediately and returns zero bytes.
///
- /// is null.
+ /// is .
public byte[] EndOpen(SftpOpenAsyncResult asyncResult)
{
- if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ if (asyncResult is null)
+ {
+ throw new ArgumentNullException(nameof(asyncResult));
+ }
if (asyncResult.EndInvokeCalled)
+ {
throw new InvalidOperationException("EndOpen has already been called.");
+ }
if (asyncResult.IsCompleted)
+ {
return asyncResult.EndInvoke();
+ }
using (var waitHandle = asyncResult.AsyncWaitHandle)
{
@@ -452,26 +609,70 @@ public void RequestClose(byte[] handle)
{
SshException exception = null;
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
- var request = new SftpCloseRequest(ProtocolVersion, NextRequestId, handle,
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ var request = new SftpCloseRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
}
+ ///
+ /// Performs a SSH_FXP_CLOSE request.
+ ///
+ /// The handle.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_CLOSE request.
+ ///
+ public async Task RequestCloseAsync(byte[] handle, CancellationToken cancellationToken)
+ {
+ var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ SendRequest(new SftpCloseRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ response =>
+ {
+ if (response.StatusCode == StatusCodes.Ok)
+ {
+ _ = tcs.TrySetResult(true);
+ }
+ else
+ {
+ _ = tcs.TrySetException(GetSftpException(response));
+ }
+ }));
+
+ // Only check for cancellation after the SftpCloseRequest was sent
+ cancellationToken.ThrowIfCancellationRequested();
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ _ = await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
///
/// Performs SSH_FXP_CLOSE request.
///
@@ -485,11 +686,13 @@ public SftpCloseAsyncResult BeginClose(byte[] handle, AsyncCallback callback, ob
{
var asyncResult = new SftpCloseAsyncResult(callback, state);
- var request = new SftpCloseRequest(ProtocolVersion, NextRequestId, handle,
- response =>
- {
- asyncResult.SetAsCompleted(GetSftpException(response), false);
- });
+ var request = new SftpCloseRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ response =>
+ {
+ asyncResult.SetAsCompleted(GetSftpException(response), completedSynchronously: false);
+ });
SendRequest(request);
return asyncResult;
@@ -499,14 +702,18 @@ public SftpCloseAsyncResult BeginClose(byte[] handle, AsyncCallback callback, ob
/// Handles the end of an asynchronous close.
///
/// An that represents an asynchronous call.
- /// is null.
+ /// is .
public void EndClose(SftpCloseAsyncResult asyncResult)
{
- if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ if (asyncResult is null)
+ {
+ throw new ArgumentNullException(nameof(asyncResult));
+ }
if (asyncResult.EndInvokeCalled)
+ {
throw new InvalidOperationException("EndClose has already been called.");
+ }
if (asyncResult.IsCompleted)
{
@@ -537,22 +744,26 @@ public SftpReadAsyncResult BeginRead(byte[] handle, ulong offset, uint length, A
{
var asyncResult = new SftpReadAsyncResult(callback, state);
- var request = new SftpReadRequest(ProtocolVersion, NextRequestId, handle, offset, length,
- response =>
- {
- asyncResult.SetAsCompleted(response.Data, false);
- },
- response =>
- {
- if (response.StatusCode != StatusCodes.Eof)
- {
- asyncResult.SetAsCompleted(GetSftpException(response), false);
- }
- else
- {
- asyncResult.SetAsCompleted(Array.Empty, false);
- }
- });
+ var request = new SftpReadRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ offset,
+ length,
+ response =>
+ {
+ asyncResult.SetAsCompleted(response.Data, completedSynchronously: false);
+ },
+ response =>
+ {
+ if (response.StatusCode != StatusCodes.Eof)
+ {
+ asyncResult.SetAsCompleted(GetSftpException(response), completedSynchronously: false);
+ }
+ else
+ {
+ asyncResult.SetAsCompleted(Array.Empty(), completedSynchronously: false);
+ }
+ });
SendRequest(request);
return asyncResult;
@@ -569,17 +780,23 @@ public SftpReadAsyncResult BeginRead(byte[] handle, ulong offset, uint length, A
/// If all available data has been read, the method completes
/// immediately and returns zero bytes.
///
- /// is null.
+ /// is .
public byte[] EndRead(SftpReadAsyncResult asyncResult)
{
- if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ if (asyncResult is null)
+ {
+ throw new ArgumentNullException(nameof(asyncResult));
+ }
if (asyncResult.EndInvokeCalled)
+ {
throw new InvalidOperationException("EndRead has already been called.");
+ }
if (asyncResult.IsCompleted)
+ {
return asyncResult.EndInvoke();
+ }
using (var waitHandle = asyncResult.AsyncWaitHandle)
{
@@ -594,40 +811,49 @@ public byte[] EndRead(SftpReadAsyncResult asyncResult)
/// The handle.
/// The offset.
/// The length.
- /// data array; null if EOF
+ ///
+ /// The data that was read, or an empty array when the end of the file was reached.
+ ///
public byte[] RequestRead(byte[] handle, ulong offset, uint length)
{
SshException exception = null;
byte[] data = null;
- using (var wait = new AutoResetEvent(false))
- {
- var request = new SftpReadRequest(ProtocolVersion, NextRequestId, handle, offset, length,
- response =>
- {
- data = response.Data;
- wait.Set();
- },
- response =>
- {
- if (response.StatusCode != StatusCodes.Eof)
- {
- exception = GetSftpException(response);
- }
- else
- {
- data = Array.Empty;
- }
- wait.Set();
- });
+ using (var wait = new AutoResetEvent(initialState: false))
+ {
+ var request = new SftpReadRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ offset,
+ length,
+ response =>
+ {
+ data = response.Data;
+ _ = wait.Set();
+ },
+ response =>
+ {
+ if (response.StatusCode != StatusCodes.Eof)
+ {
+ exception = GetSftpException(response);
+ }
+ else
+ {
+ data = Array.Empty();
+ }
+
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -635,6 +861,52 @@ public byte[] RequestRead(byte[] handle, ulong offset, uint length)
return data;
}
+ ///
+ /// Asynchronously performs a SSH_FXP_READ request.
+ ///
+ /// The handle to the file to read from.
+ /// The offset in the file to start reading from.
+ /// The number of bytes to read.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_READ request. The value of
+ /// its contains the data read from the file, or an empty
+ /// array when the end of the file is reached.
+ ///
+ public async Task RequestReadAsync(byte[] handle, ulong offset, uint length, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ SendRequest(new SftpReadRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ offset,
+ length,
+ response => tcs.TrySetResult(response.Data),
+ response =>
+ {
+ if (response.StatusCode == StatusCodes.Eof)
+ {
+ _ = tcs.TrySetResult(Array.Empty());
+ }
+ else
+ {
+ _ = tcs.TrySetException(GetSftpException(response));
+ }
+ }));
+
+ return await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
///
/// Performs SSH_FXP_WRITE request.
///
@@ -655,62 +927,123 @@ public void RequestWrite(byte[] handle,
{
SshException exception = null;
- var request = new SftpWriteRequest(ProtocolVersion, NextRequestId, handle, serverOffset, data, offset,
- length, response =>
- {
- if (writeCompleted != null)
- {
- writeCompleted(response);
- }
-
- exception = GetSftpException(response);
- if (wait != null)
- wait.Set();
- });
+ var request = new SftpWriteRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ serverOffset,
+ data,
+ offset,
+ length,
+ response =>
+ {
+ writeCompleted?.Invoke(response);
+
+ exception = GetSftpException(response);
+ if (wait != null)
+ {
+ _ = wait.Set();
+ }
+ });
SendRequest(request);
- if (wait != null)
+ if (wait is not null)
+ {
WaitOnHandle(wait, OperationTimeout);
+ }
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
}
+ ///
+ /// Asynchronouly performs a SSH_FXP_WRITE request.
+ ///
+ /// The handle.
+ /// The the zero-based offset (in bytes) relative to the beginning of the file that the write must start at.
+ /// The buffer holding the data to write.
+ /// the zero-based offset in at which to begin taking bytes to write.
+ /// The length (in bytes) of the data to write.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_WRITE request.
+ ///
+ public async Task RequestWriteAsync(byte[] handle, ulong serverOffset, byte[] data, int offset, int length, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ SendRequest(new SftpWriteRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ serverOffset,
+ data,
+ offset,
+ length,
+ response =>
+ {
+ if (response.StatusCode == StatusCodes.Ok)
+ {
+ _ = tcs.TrySetResult(true);
+ }
+ else
+ {
+ _ = tcs.TrySetException(GetSftpException(response));
+ }
+ }));
+
+ _ = await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
///
/// Performs SSH_FXP_LSTAT request.
///
/// The path.
///
- /// File attributes
+ /// File attributes.
///
public SftpFileAttributes RequestLStat(string path)
{
SshException exception = null;
SftpFileAttributes attributes = null;
- using (var wait = new AutoResetEvent(false))
- {
- var request = new SftpLStatRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- attributes = response.Attributes;
- wait.Set();
- },
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ using (var wait = new AutoResetEvent(initialState: false))
+ {
+ var request = new SftpLStatRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response =>
+ {
+ attributes = response.Attributes;
+ _ = wait.Set();
+ },
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -731,15 +1064,18 @@ public SFtpStatAsyncResult BeginLStat(string path, AsyncCallback callback, objec
{
var asyncResult = new SFtpStatAsyncResult(callback, state);
- var request = new SftpLStatRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- asyncResult.SetAsCompleted(response.Attributes, false);
- },
- response =>
- {
- asyncResult.SetAsCompleted(GetSftpException(response), false);
- });
+ var request = new SftpLStatRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response =>
+ {
+ asyncResult.SetAsCompleted(response.Attributes, completedSynchronously: false);
+ },
+ response =>
+ {
+ asyncResult.SetAsCompleted(GetSftpException(response), completedSynchronously: false);
+ });
SendRequest(request);
return asyncResult;
@@ -752,17 +1088,23 @@ public SFtpStatAsyncResult BeginLStat(string path, AsyncCallback callback, objec
///
/// The file attributes.
///
- /// is null.
+ /// is .
public SftpFileAttributes EndLStat(SFtpStatAsyncResult asyncResult)
{
- if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ if (asyncResult is null)
+ {
+ throw new ArgumentNullException(nameof(asyncResult));
+ }
if (asyncResult.EndInvokeCalled)
+ {
throw new InvalidOperationException("EndLStat has already been called.");
+ }
if (asyncResult.IsCompleted)
+ {
return asyncResult.EndInvoke();
+ }
using (var waitHandle = asyncResult.AsyncWaitHandle)
{
@@ -775,35 +1117,39 @@ public SftpFileAttributes EndLStat(SFtpStatAsyncResult asyncResult)
/// Performs SSH_FXP_FSTAT request.
///
/// The handle.
- /// if set to true returns null instead of throwing an exception.
+ /// If set to , returns instead of throwing an exception.
///
- /// File attributes
+ /// File attributes.
///
public SftpFileAttributes RequestFStat(byte[] handle, bool nullOnError)
{
SshException exception = null;
SftpFileAttributes attributes = null;
- using (var wait = new AutoResetEvent(false))
- {
- var request = new SftpFStatRequest(ProtocolVersion, NextRequestId, handle,
- response =>
- {
- attributes = response.Attributes;
- wait.Set();
- },
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ using (var wait = new AutoResetEvent(initialState: false))
+ {
+ var request = new SftpFStatRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ response =>
+ {
+ attributes = response.Attributes;
+ _ = wait.Set();
+ },
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null && !nullOnError)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (!nullOnError && exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -811,6 +1157,37 @@ public SftpFileAttributes RequestFStat(byte[] handle, bool nullOnError)
return attributes;
}
+ ///
+ /// Asynchronously performs a SSH_FXP_FSTAT request.
+ ///
+ /// The handle.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_FSTAT request. The value of its
+ /// contains the file attributes of the specified handle.
+ ///
+ public async Task RequestFStatAsync(byte[] handle, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ SendRequest(new SftpFStatRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ response => tcs.TrySetResult(response.Attributes),
+ response => tcs.TrySetException(GetSftpException(response))));
+
+ return await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
///
/// Performs SSH_FXP_SETSTAT request.
///
@@ -820,21 +1197,27 @@ public void RequestSetStat(string path, SftpFileAttributes attributes)
{
SshException exception = null;
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
- var request = new SftpSetStatRequest(ProtocolVersion, NextRequestId, path, Encoding, attributes,
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ var request = new SftpSetStatRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ attributes,
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -849,31 +1232,36 @@ public void RequestFSetStat(byte[] handle, SftpFileAttributes attributes)
{
SshException exception = null;
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
- var request = new SftpFSetStatRequest(ProtocolVersion, NextRequestId, handle, attributes,
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ var request = new SftpFSetStatRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ attributes,
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
}
///
- /// Performs SSH_FXP_OPENDIR request
+ /// Performs SSH_FXP_OPENDIR request.
///
/// The path.
- /// if set to true returns null instead of throwing an exception.
+ /// If set to , returns instead of throwing an exception.
/// File handle.
public byte[] RequestOpenDir(string path, bool nullOnError = false)
{
@@ -881,26 +1269,31 @@ public byte[] RequestOpenDir(string path, bool nullOnError = false)
byte[] handle = null;
- using (var wait = new AutoResetEvent(false))
- {
- var request = new SftpOpenDirRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- handle = response.Handle;
- wait.Set();
- },
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ using (var wait = new AutoResetEvent(initialState: false))
+ {
+ var request = new SftpOpenDirRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response =>
+ {
+ handle = response.Handle;
+ _ = wait.Set();
+ },
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (!nullOnError && exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (!nullOnError && exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -909,39 +1302,79 @@ public byte[] RequestOpenDir(string path, bool nullOnError = false)
}
///
- /// Performs SSH_FXP_READDIR request
+ /// Asynchronously performs a SSH_FXP_OPENDIR request.
///
- /// The handle.
- ///
+ /// The path.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_OPENDIR request. The value of its
+ /// contains the handle of the specified path.
+ ///
+ public async Task RequestOpenDirAsync(string path, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ SendRequest(new SftpOpenDirRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response => tcs.TrySetResult(response.Handle),
+ response => tcs.TrySetException(GetSftpException(response))));
+
+ return await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
+ ///
+ /// Performs SSH_FXP_READDIR request.
+ ///
+ /// The handle of the directory to read.
+ ///
+ /// A where the key is the name of a file in
+ /// the directory and the value is the of the file.
+ ///
public KeyValuePair[] RequestReadDir(byte[] handle)
{
SshException exception = null;
KeyValuePair[] result = null;
- using (var wait = new AutoResetEvent(false))
- {
- var request = new SftpReadDirRequest(ProtocolVersion, NextRequestId, handle,
- response =>
- {
- result = response.Files;
- wait.Set();
- },
- response =>
- {
- if (response.StatusCode != StatusCodes.Eof)
- {
- exception = GetSftpException(response);
- }
- wait.Set();
- });
+ using (var wait = new AutoResetEvent(initialState: false))
+ {
+ var request = new SftpReadDirRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ response =>
+ {
+ result = response.Files;
+ _ = wait.Set();
+ },
+ response =>
+ {
+ if (response.StatusCode != StatusCodes.Eof)
+ {
+ exception = GetSftpException(response);
+ }
+
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -949,6 +1382,49 @@ public KeyValuePair[] RequestReadDir(byte[] handle)
return result;
}
+ ///
+ /// Performs a SSH_FXP_READDIR request.
+ ///
+ /// The handle of the directory to read.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_READDIR request. The value of its
+ /// contains a where the
+ /// key is the name of a file in the directory and the value is the
+ /// of the file.
+ ///
+ public async Task[]> RequestReadDirAsync(byte[] handle, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tcs = new TaskCompletionSource[]>(TaskCreationOptions.RunContinuationsAsynchronously);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(s => ((TaskCompletionSource[]>) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(s => ((TaskCompletionSource[]>) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ SendRequest(new SftpReadDirRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ response => tcs.TrySetResult(response.Files),
+ response =>
+ {
+ if (response.StatusCode == StatusCodes.Eof)
+ {
+ _ = tcs.TrySetResult(null);
+ }
+ else
+ {
+ _ = tcs.TrySetException(GetSftpException(response));
+ }
+ }));
+
+ return await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
///
/// Performs SSH_FXP_REMOVE request.
///
@@ -957,26 +1433,71 @@ public void RequestRemove(string path)
{
SshException exception = null;
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
- var request = new SftpRemoveRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ var request = new SftpRemoveRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
}
+ ///
+ /// Asynchronously performs a SSH_FXP_REMOVE request.
+ ///
+ /// The path.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_REMOVE request.
+ ///
+ public async Task RequestRemoveAsync(string path, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ SendRequest(new SftpRemoveRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response =>
+ {
+ if (response.StatusCode == StatusCodes.Ok)
+ {
+ _ = tcs.TrySetResult(true);
+ }
+ else
+ {
+ _ = tcs.TrySetException(GetSftpException(response));
+ }
+ }));
+
+ _ = await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
///
/// Performs SSH_FXP_MKDIR request.
///
@@ -985,21 +1506,26 @@ public void RequestMkDir(string path)
{
SshException exception = null;
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
- var request = new SftpMkDirRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ var request = new SftpMkDirRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -1013,31 +1539,36 @@ public void RequestRmDir(string path)
{
SshException exception = null;
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
- var request = new SftpRmDirRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ var request = new SftpRmDirRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
}
///
- /// Performs SSH_FXP_REALPATH request
+ /// Performs SSH_FXP_REALPATH request.
///
/// The path.
- /// if set to true returns null instead of throwing an exception.
+ /// if set to returns null instead of throwing an exception.
///
/// The absolute path.
///
@@ -1047,33 +1578,71 @@ internal KeyValuePair[] RequestRealPath(string path,
KeyValuePair[] result = null;
- using (var wait = new AutoResetEvent(false))
- {
- var request = new SftpRealPathRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- result = response.Files;
- wait.Set();
- },
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ using (var wait = new AutoResetEvent(initialState: false))
+ {
+ var request = new SftpRealPathRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response =>
+ {
+ result = response.Files;
+ _ = wait.Set();
+ },
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (!nullOnError && exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (!nullOnError && exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
-
+
return result;
}
+ internal async Task[]> RequestRealPathAsync(string path, bool nullOnError, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tcs = new TaskCompletionSource[]>(TaskCreationOptions.RunContinuationsAsynchronously);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(s => ((TaskCompletionSource[]>) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(s => ((TaskCompletionSource[]>) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ SendRequest(new SftpRealPathRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response => tcs.TrySetResult(response.Files),
+ response =>
+ {
+ if (nullOnError)
+ {
+ _ = tcs.TrySetResult(null);
+ }
+ else
+ {
+ _ = tcs.TrySetException(GetSftpException(response));
+ }
+ }));
+
+ return await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
///
/// Performs SSH_FXP_REALPATH request.
///
@@ -1087,15 +1656,12 @@ public SftpRealPathAsyncResult BeginRealPath(string path, AsyncCallback callback
{
var asyncResult = new SftpRealPathAsyncResult(callback, state);
- var request = new SftpRealPathRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- asyncResult.SetAsCompleted(response.Files[0].Key, false);
- },
- response =>
- {
- asyncResult.SetAsCompleted(GetSftpException(response), false);
- });
+ var request = new SftpRealPathRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response => asyncResult.SetAsCompleted(response.Files[0].Key, completedSynchronously: false),
+ response => asyncResult.SetAsCompleted(GetSftpException(response), completedSynchronously: false));
SendRequest(request);
return asyncResult;
@@ -1108,17 +1674,23 @@ public SftpRealPathAsyncResult BeginRealPath(string path, AsyncCallback callback
///
/// The absolute path.
///
- /// is null.
+ /// is .
public string EndRealPath(SftpRealPathAsyncResult asyncResult)
{
- if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ if (asyncResult is null)
+ {
+ throw new ArgumentNullException(nameof(asyncResult));
+ }
if (asyncResult.EndInvokeCalled)
+ {
throw new InvalidOperationException("EndRealPath has already been called.");
+ }
if (asyncResult.IsCompleted)
+ {
return asyncResult.EndInvoke();
+ }
using (var waitHandle = asyncResult.AsyncWaitHandle)
{
@@ -1131,9 +1703,9 @@ public string EndRealPath(SftpRealPathAsyncResult asyncResult)
/// Performs SSH_FXP_STAT request.
///
/// The path.
- /// if set to true returns null instead of throwing an exception.
+ /// if set to returns null instead of throwing an exception.
///
- /// File attributes
+ /// File attributes.
///
public SftpFileAttributes RequestStat(string path, bool nullOnError = false)
{
@@ -1141,26 +1713,31 @@ public SftpFileAttributes RequestStat(string path, bool nullOnError = false)
SftpFileAttributes attributes = null;
- using (var wait = new AutoResetEvent(false))
- {
- var request = new SftpStatRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- attributes = response.Attributes;
- wait.Set();
- },
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ using (var wait = new AutoResetEvent(initialState: false))
+ {
+ var request = new SftpStatRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response =>
+ {
+ attributes = response.Attributes;
+ _ = wait.Set();
+ },
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (!nullOnError && exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (!nullOnError && exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -1169,7 +1746,7 @@ public SftpFileAttributes RequestStat(string path, bool nullOnError = false)
}
///
- /// Performs SSH_FXP_STAT request
+ /// Performs SSH_FXP_STAT request.
///
/// The path.
/// The delegate that is executed when completes.
@@ -1181,15 +1758,12 @@ public SFtpStatAsyncResult BeginStat(string path, AsyncCallback callback, object
{
var asyncResult = new SFtpStatAsyncResult(callback, state);
- var request = new SftpStatRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- asyncResult.SetAsCompleted(response.Attributes, false);
- },
- response =>
- {
- asyncResult.SetAsCompleted(GetSftpException(response), false);
- });
+ var request = new SftpStatRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response => asyncResult.SetAsCompleted(response.Attributes, completedSynchronously: false),
+ response => asyncResult.SetAsCompleted(GetSftpException(response), completedSynchronously: false));
SendRequest(request);
return asyncResult;
@@ -1202,17 +1776,23 @@ public SFtpStatAsyncResult BeginStat(string path, AsyncCallback callback, object
///
/// The file attributes.
///
- /// is null.
+ /// is .
public SftpFileAttributes EndStat(SFtpStatAsyncResult asyncResult)
{
- if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ if (asyncResult is null)
+ {
+ throw new ArgumentNullException(nameof(asyncResult));
+ }
if (asyncResult.EndInvokeCalled)
+ {
throw new InvalidOperationException("EndStat has already been called.");
+ }
if (asyncResult.IsCompleted)
+ {
return asyncResult.EndInvoke();
+ }
using (var waitHandle = asyncResult.AsyncWaitHandle)
{
@@ -1235,32 +1815,83 @@ public void RequestRename(string oldPath, string newPath)
SshException exception = null;
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
- var request = new SftpRenameRequest(ProtocolVersion, NextRequestId, oldPath, newPath, Encoding,
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ var request = new SftpRenameRequest(ProtocolVersion,
+ NextRequestId,
+ oldPath,
+ newPath,
+ _encoding,
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
}
+ ///
+ /// Asynchronously performs a SSH_FXP_RENAME request.
+ ///
+ /// The old path.
+ /// The new path.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the asynchronous SSH_FXP_RENAME request.
+ ///
+ public async Task RequestRenameAsync(string oldPath, string newPath, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ SendRequest(new SftpRenameRequest(ProtocolVersion,
+ NextRequestId,
+ oldPath,
+ newPath,
+ _encoding,
+ response =>
+ {
+ if (response.StatusCode == StatusCodes.Ok)
+ {
+ _ = tcs.TrySetResult(true);
+ }
+ else
+ {
+ _ = tcs.TrySetException(GetSftpException(response));
+ }
+ }));
+
+ _ = await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
///
/// Performs SSH_FXP_READLINK request.
///
/// The path.
- /// if set to true returns null instead of throwing an exception.
- ///
+ /// if set to returns instead of throwing an exception.
+ ///
+ /// An array of where the key is the name of
+ /// a file and the value is the of the file.
+ ///
internal KeyValuePair[] RequestReadLink(string path, bool nullOnError = false)
{
if (ProtocolVersion < 3)
@@ -1272,26 +1903,31 @@ internal KeyValuePair[] RequestReadLink(string path,
KeyValuePair[] result = null;
- using (var wait = new AutoResetEvent(false))
- {
- var request = new SftpReadLinkRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- result = response.Files;
- wait.Set();
- },
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ using (var wait = new AutoResetEvent(initialState: false))
+ {
+ var request = new SftpReadLinkRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response =>
+ {
+ result = response.Files;
+ _ = wait.Set();
+ },
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (!nullOnError && exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (!nullOnError && exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -1313,30 +1949,32 @@ public void RequestSymLink(string linkpath, string targetpath)
SshException exception = null;
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
- var request = new SftpSymLinkRequest(ProtocolVersion, NextRequestId, linkpath, targetpath, Encoding,
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ var request = new SftpSymLinkRequest(ProtocolVersion,
+ NextRequestId,
+ linkpath,
+ targetpath,
+ _encoding,
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
}
- #endregion
-
- #region SFTP Extended API functions
-
///
/// Performs posix-rename@openssh.com extended request.
///
@@ -1351,24 +1989,32 @@ public void RequestPosixRename(string oldPath, string newPath)
SshException exception = null;
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
- var request = new PosixRenameRequest(ProtocolVersion, NextRequestId, oldPath, newPath, Encoding,
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ var request = new PosixRenameRequest(ProtocolVersion,
+ NextRequestId,
+ oldPath,
+ newPath,
+ _encoding,
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
if (!_supportedExtensions.ContainsKey(request.Name))
+ {
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
+ }
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -1378,8 +2024,10 @@ public void RequestPosixRename(string oldPath, string newPath)
/// Performs statvfs@openssh.com extended request.
///
/// The path.
- /// if set to true [null on error].
- ///
+ /// if set to [null on error].
+ ///
+ /// A for the specified path.
+ ///
public SftpFileSytemInformation RequestStatVfs(string path, bool nullOnError = false)
{
if (ProtocolVersion < 3)
@@ -1391,29 +2039,36 @@ public SftpFileSytemInformation RequestStatVfs(string path, bool nullOnError = f
SftpFileSytemInformation information = null;
- using (var wait = new AutoResetEvent(false))
- {
- var request = new StatVfsRequest(ProtocolVersion, NextRequestId, path, Encoding,
- response =>
- {
- information = response.GetReply().Information;
- wait.Set();
- },
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ using (var wait = new AutoResetEvent(initialState: false))
+ {
+ var request = new StatVfsRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response =>
+ {
+ information = response.GetReply().Information;
+ _ = wait.Set();
+ },
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
if (!_supportedExtensions.ContainsKey(request.Name))
+ {
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
+ }
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (!nullOnError && exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (!nullOnError && exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -1421,13 +2076,53 @@ public SftpFileSytemInformation RequestStatVfs(string path, bool nullOnError = f
return information;
}
+ ///
+ /// Asynchronously performs a statvfs@openssh.com extended request.
+ ///
+ /// The path.
+ /// The token to monitor for cancellation requests.
+ ///
+ /// A task that represents the statvfs@openssh.com extended request. The value of its
+ /// contains the file system information for the specified
+ /// path.
+ ///
+ public async Task RequestStatVfsAsync(string path, CancellationToken cancellationToken)
+ {
+ if (ProtocolVersion < 3)
+ {
+ throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", ProtocolVersion));
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+
+#if NET || NETSTANDARD2_1_OR_GREATER
+ await using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
+#else
+ using (cancellationToken.Register(s => ((TaskCompletionSource) s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
+ SendRequest(new StatVfsRequest(ProtocolVersion,
+ NextRequestId,
+ path,
+ _encoding,
+ response => tcs.TrySetResult(response.GetReply().Information),
+ response => tcs.TrySetException(GetSftpException(response))));
+
+ return await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
///
/// Performs fstatvfs@openssh.com extended request.
///
/// The file handle.
- /// if set to true [null on error].
- ///
- ///
+ /// if set to [null on error].
+ ///
+ /// A for the specified path.
+ ///
+ /// This operation is not supported for the current SFTP protocol version.
internal SftpFileSytemInformation RequestFStatVfs(byte[] handle, bool nullOnError = false)
{
if (ProtocolVersion < 3)
@@ -1439,29 +2134,35 @@ internal SftpFileSytemInformation RequestFStatVfs(byte[] handle, bool nullOnErro
SftpFileSytemInformation information = null;
- using (var wait = new AutoResetEvent(false))
- {
- var request = new FStatVfsRequest(ProtocolVersion, NextRequestId, handle,
- response =>
- {
- information = response.GetReply().Information;
- wait.Set();
- },
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ using (var wait = new AutoResetEvent(initialState: false))
+ {
+ var request = new FStatVfsRequest(ProtocolVersion,
+ NextRequestId,
+ handle,
+ response =>
+ {
+ information = response.GetReply().Information;
+ _ = wait.Set();
+ },
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
if (!_supportedExtensions.ContainsKey(request.Name))
+ {
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
+ }
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
-
- if (!nullOnError && exception != null)
+
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (!nullOnError && exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
@@ -1483,31 +2184,36 @@ internal void HardLink(string oldPath, string newPath)
SshException exception = null;
- using (var wait = new AutoResetEvent(false))
+ using (var wait = new AutoResetEvent(initialState: false))
{
- var request = new HardLinkRequest(ProtocolVersion, NextRequestId, oldPath, newPath,
- response =>
- {
- exception = GetSftpException(response);
- wait.Set();
- });
+ var request = new HardLinkRequest(ProtocolVersion,
+ NextRequestId,
+ oldPath,
+ newPath,
+ response =>
+ {
+ exception = GetSftpException(response);
+ _ = wait.Set();
+ });
if (!_supportedExtensions.ContainsKey(request.Name))
+ {
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
+ }
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
- if (exception != null)
+#pragma warning disable CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
+ if (exception is not null)
+#pragma warning restore CA1508 // Avoid dead conditional code; Remove when we upgrade to newer SDK in which bug is fixed
{
throw exception;
}
}
- #endregion
-
///
/// Calculates the optimal size of the buffer to read data from the channel.
///
@@ -1521,7 +2227,7 @@ public uint CalculateOptimalReadLength(uint bufferSize)
// bytes 1 to 4: packet length
// byte 5: message type
// bytes 6 to 9: response id
- // bytes 10 to 13: length of payload
+ // bytes 10 to 13: length of payload
//
// WinSCP uses a payload length of 32755 bytes
//
@@ -1557,16 +2263,19 @@ public uint CalculateOptimalWriteLength(uint bufferSize, byte[] handle)
// 14-21: offset
// 22-25: data length
- // Putty uses data length of 4096 bytes
- // WinSCP uses data length of 32739 bytes (total 32768 bytes; 32739 + 25 + 4 bytes for handle)
+ /*
+ * Putty uses data length of 4096 bytes
+ * WinSCP uses data length of 32739 bytes (total 32768 bytes; 32739 + 25 + 4 bytes for handle)
+ */
- var lengthOfNonDataProtocolFields = 25u + (uint)handle.Length;
+ var lengthOfNonDataProtocolFields = 25u + (uint) handle.Length;
var maximumPacketSize = Channel.RemotePacketSize;
return Math.Min(bufferSize, maximumPacketSize) - lengthOfNonDataProtocolFields;
}
private static SshException GetSftpException(SftpStatusResponse response)
{
+#pragma warning disable IDE0010 // Add missing cases
switch (response.StatusCode)
{
case StatusCodes.Ok:
@@ -1578,6 +2287,7 @@ private static SshException GetSftpException(SftpStatusResponse response)
default:
return new SshException(response.ErrorMessage);
}
+#pragma warning restore IDE0010 // Add missing cases
}
private void HandleResponse(SftpResponse response)
@@ -1585,15 +2295,17 @@ private void HandleResponse(SftpResponse response)
SftpRequest request;
lock (_requests)
{
- _requests.TryGetValue(response.ResponseId, out request);
- if (request != null)
+ _ = _requests.TryGetValue(response.ResponseId, out request);
+ if (request is not null)
{
- _requests.Remove(response.ResponseId);
+ _ = _requests.Remove(response.ResponseId);
}
}
- if (request == null)
+ if (request is null)
+ {
throw new InvalidOperationException("Invalid response.");
+ }
request.Complete(response);
}
diff --git a/src/Renci.SshNet/Sftp/SftpSynchronizeDirectoriesAsyncResult.cs b/src/Renci.SshNet/Sftp/SftpSynchronizeDirectoriesAsyncResult.cs
index 0d2644de5..35aacd200 100644
--- a/src/Renci.SshNet/Sftp/SftpSynchronizeDirectoriesAsyncResult.cs
+++ b/src/Renci.SshNet/Sftp/SftpSynchronizeDirectoriesAsyncResult.cs
@@ -1,8 +1,9 @@
using System;
using System.Collections.Generic;
-using Renci.SshNet.Common;
using System.IO;
+using Renci.SshNet.Common;
+
namespace Renci.SshNet.Sftp
{
///
@@ -16,11 +17,11 @@ public class SftpSynchronizeDirectoriesAsyncResult : AsyncResult
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The async callback.
/// The state.
- public SftpSynchronizeDirectoriesAsyncResult(AsyncCallback asyncCallback, Object state)
+ public SftpSynchronizeDirectoriesAsyncResult(AsyncCallback asyncCallback, object state)
: base(asyncCallback, state)
{
}
diff --git a/src/Renci.SshNet/Sftp/SftpUploadAsyncResult.cs b/src/Renci.SshNet/Sftp/SftpUploadAsyncResult.cs
index 5f586daf5..efd1e2342 100644
--- a/src/Renci.SshNet/Sftp/SftpUploadAsyncResult.cs
+++ b/src/Renci.SshNet/Sftp/SftpUploadAsyncResult.cs
@@ -1,4 +1,5 @@
using System;
+
using Renci.SshNet.Common;
namespace Renci.SshNet.Sftp
@@ -9,10 +10,10 @@ namespace Renci.SshNet.Sftp
public class SftpUploadAsyncResult : AsyncResult
{
///
- /// Gets or sets a value indicating whether to cancel asynchronous upload operation
+ /// Gets or sets a value indicating whether to cancel asynchronous upload operation.
///
///
- /// true if upload operation to be canceled; otherwise, false.
+ /// if upload operation to be canceled; otherwise, .
///
///
/// Upload operation will be canceled after finishing uploading current buffer.
@@ -29,7 +30,7 @@ public class SftpUploadAsyncResult : AsyncResult
///
/// The async callback.
/// The state.
- public SftpUploadAsyncResult(AsyncCallback asyncCallback, Object state)
+ public SftpUploadAsyncResult(AsyncCallback asyncCallback, object state)
: base(asyncCallback, state)
{
}
diff --git a/src/Renci.SshNet/Sftp/StatusCodes.cs b/src/Renci.SshNet/Sftp/StatusCodes.cs
index 101b8c0bc..12997a47e 100644
--- a/src/Renci.SshNet/Sftp/StatusCodes.cs
+++ b/src/Renci.SshNet/Sftp/StatusCodes.cs
@@ -1,135 +1,165 @@
-
-namespace Renci.SshNet.Sftp
+namespace Renci.SshNet.Sftp
{
internal enum StatusCodes : uint
{
///
- /// SSH_FX_OK
+ /// SSH_FX_OK.
///
Ok = 0,
+
///
- /// SSH_FX_EOF
+ /// SSH_FX_EOF.
///
Eof = 1,
+
///
- /// SSH_FX_NO_SUCH_FILE
+ /// SSH_FX_NO_SUCH_FILE.
///
NoSuchFile = 2,
+
///
- /// SSH_FX_PERMISSION_DENIED
+ /// SSH_FX_PERMISSION_DENIED.
///
PermissionDenied = 3,
+
///
- /// SSH_FX_FAILURE
+ /// SSH_FX_FAILURE.
///
Failure = 4,
+
///
- /// SSH_FX_BAD_MESSAGE
+ /// SSH_FX_BAD_MESSAGE.
///
BadMessage = 5,
+
///
- /// SSH_FX_NO_CONNECTION
+ /// SSH_FX_NO_CONNECTION.
///
NoConnection = 6,
+
///
- /// SSH_FX_CONNECTION_LOST
+ /// SSH_FX_CONNECTION_LOST.
///
ConnectionLost = 7,
+
///
- /// SSH_FX_OP_UNSUPPORTED
+ /// SSH_FX_OP_UNSUPPORTED.
///
OperationUnsupported = 8,
+
///
- /// SSH_FX_INVALID_HANDLE
+ /// SSH_FX_INVALID_HANDLE.
///
InvalidHandle = 9,
+
///
- /// SSH_FX_NO_SUCH_PATH
+ /// SSH_FX_NO_SUCH_PATH.
///
NoSuchPath = 10,
+
///
- /// SSH_FX_FILE_ALREADY_EXISTS
+ /// SSH_FX_FILE_ALREADY_EXISTS.
///
FileAlreadyExists = 11,
+
///
- /// SSH_FX_WRITE_PROTECT
+ /// SSH_FX_WRITE_PROTECT.
///
WriteProtect = 12,
+
///
- /// SSH_FX_NO_MEDIA
+ /// SSH_FX_NO_MEDIA.
///
NoMedia = 13,
+
///
- /// SSH_FX_NO_SPACE_ON_FILESYSTEM
+ /// SSH_FX_NO_SPACE_ON_FILESYSTEM.
///
NoSpaceOnFilesystem = 14,
+
///
- /// SSH_FX_QUOTA_EXCEEDED
+ /// SSH_FX_QUOTA_EXCEEDED.
///
QuotaExceeded = 15,
+
///
- /// SSH_FX_UNKNOWN_PRINCIPAL
+ /// SSH_FX_UNKNOWN_PRINCIPAL.
///
UnknownPrincipal = 16,
+
///
- /// SSH_FX_LOCK_CONFLICT
+ /// SSH_FX_LOCK_CONFLICT.
///
LockConflict = 17,
+
///
- /// SSH_FX_DIR_NOT_EMPTY
+ /// SSH_FX_DIR_NOT_EMPTY.
///
DirNotEmpty = 18,
+
///
- /// SSH_FX_NOT_A_DIRECTORY
+ /// SSH_FX_NOT_A_DIRECTORY.
///
NotDirectory = 19,
+
///
- /// SSH_FX_INVALID_FILENAME
+ /// SSH_FX_INVALID_FILENAME.
///
InvalidFilename = 20,
+
///
- /// SSH_FX_LINK_LOOP
+ /// SSH_FX_LINK_LOOP.
///
LinkLoop = 21,
+
///
- /// SSH_FX_CANNOT_DELETE
+ /// SSH_FX_CANNOT_DELETE.
///
CannotDelete = 22,
+
///
- /// SSH_FX_INVALID_PARAMETER
+ /// SSH_FX_INVALID_PARAMETER.
///
InvalidParameter = 23,
+
///
- /// SSH_FX_FILE_IS_A_DIRECTORY
+ /// SSH_FX_FILE_IS_A_DIRECTORY.
///
FileIsADirectory = 24,
+
///
- /// SSH_FX_BYTE_RANGE_LOCK_CONFLICT
+ /// SSH_FX_BYTE_RANGE_LOCK_CONFLICT.
///
ByteRangeLockConflict = 25,
+
///
- /// SSH_FX_BYTE_RANGE_LOCK_REFUSED
+ /// SSH_FX_BYTE_RANGE_LOCK_REFUSED.
///
ByteRangeLockRefused = 26,
+
///
- /// SSH_FX_DELETE_PENDING
+ /// SSH_FX_DELETE_PENDING.
///
DeletePending = 27,
+
///
- /// SSH_FX_FILE_CORRUPT
+ /// SSH_FX_FILE_CORRUPT.
///
FileCorrupt = 28,
+
///
- /// SSH_FX_OWNER_INVALID
+ /// SSH_FX_OWNER_INVALID.
///
OwnerInvalid = 29,
+
///
- /// SSH_FX_GROUP_INVALID
+ /// SSH_FX_GROUP_INVALID.
///
GroupInvalid = 30,
+
///
- /// SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK
+ /// SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK.
///
- NoMatchingByteRangeLock = 31,
+ NoMatchingByteRangeLock = 31
}
}
diff --git a/src/Renci.SshNet/SftpClient.cs b/src/Renci.SshNet/SftpClient.cs
index 3c22290d0..01472dbff 100644
--- a/src/Renci.SshNet/SftpClient.cs
+++ b/src/Renci.SshNet/SftpClient.cs
@@ -1,12 +1,14 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
-using System.IO;
using System.Globalization;
-using System.Linq;
+using System.IO;
using System.Net;
+using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
+using System.Threading.Tasks;
+
using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
using Renci.SshNet.Sftp;
@@ -18,7 +20,7 @@ namespace Renci.SshNet
///
public class SftpClient : BaseClient, ISftpClient
{
- private static readonly Encoding Utf8NoBOM = new UTF8Encoding(false, true);
+ private static readonly Encoding Utf8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
///
/// Holds the instance that is used to communicate to the
@@ -44,7 +46,7 @@ public class SftpClient : BaseClient, ISftpClient
/// one (-1) milliseconds, which indicates an infinite timeout period.
///
/// The method was called after the client was disposed.
- /// represents a value that is less than -1 or greater than milliseconds.
+ /// represents a value that is less than -1 or greater than milliseconds.
public TimeSpan OperationTimeout
{
get
@@ -58,8 +60,10 @@ public TimeSpan OperationTimeout
CheckDisposed();
var timeoutInMilliseconds = value.TotalMilliseconds;
- if (timeoutInMilliseconds < -1d || timeoutInMilliseconds > int.MaxValue)
- throw new ArgumentOutOfRangeException("value", "The timeout must represent a value between -1 and Int32.MaxValue, inclusive.");
+ if (timeoutInMilliseconds is < -1d or > int.MaxValue)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), "The timeout must represent a value between -1 and Int32.MaxValue, inclusive.");
+ }
_operationTimeout = (int) timeoutInMilliseconds;
}
@@ -90,7 +94,7 @@ public TimeSpan OperationTimeout
/// SSH_FXP_DATA protocol fields.
///
///
- /// The size of the each indivual SSH_FXP_DATA message is limited to the
+ /// The size of the each individual SSH_FXP_DATA message is limited to the
/// local maximum packet size of the channel, which is set to 64 KB
/// for SSH.NET. However, the peer can limit this even further.
///
@@ -120,8 +124,12 @@ public string WorkingDirectory
get
{
CheckDisposed();
- if (_sftpSession == null)
+
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
+
return _sftpSession.WorkingDirectory;
}
}
@@ -136,8 +144,12 @@ public int ProtocolVersion
get
{
CheckDisposed();
- if (_sftpSession == null)
+
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
+
return (int) _sftpSession.ProtocolVersion;
}
}
@@ -159,9 +171,9 @@ internal ISftpSession SftpSession
/// Initializes a new instance of the class.
///
/// The connection info.
- /// is null.
+ /// is .
public SftpClient(ConnectionInfo connectionInfo)
- : this(connectionInfo, false)
+ : this(connectionInfo, ownsConnectionInfo: false)
{
}
@@ -172,12 +184,12 @@ public SftpClient(ConnectionInfo connectionInfo)
/// Connection port.
/// Authentication username.
/// Authentication password.
- /// is null.
- /// is invalid. -or- is null or contains only whitespace characters.
+ /// is .
+ /// is invalid. -or- is or contains only whitespace characters.
/// is not within and .
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
public SftpClient(string host, int port, string username, string password)
- : this(new PasswordConnectionInfo(host, port, username, password), true)
+ : this(new PasswordConnectionInfo(host, port, username, password), ownsConnectionInfo: true)
{
}
@@ -187,8 +199,8 @@ public SftpClient(string host, int port, string username, string password)
/// Connection host.
/// Authentication username.
/// Authentication password.
- /// is null.
- /// is invalid. -or- is null contains only whitespace characters.
+ /// is .
+ /// is invalid. -or- is contains only whitespace characters.
public SftpClient(string host, string username, string password)
: this(host, ConnectionInfo.DefaultPort, username, password)
{
@@ -201,12 +213,12 @@ public SftpClient(string host, string username, string password)
/// Connection port.
/// Authentication username.
/// Authentication private key file(s) .
- /// is null.
- /// is invalid. -or- is nunullll or contains only whitespace characters.
+ /// is .
+ /// is invalid. -or- is or contains only whitespace characters.
/// is not within and .
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
- public SftpClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)
- : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), true)
+ public SftpClient(string host, int port, string username, params IPrivateKeySource[] keyFiles)
+ : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), ownsConnectionInfo: true)
{
}
@@ -216,9 +228,9 @@ public SftpClient(string host, int port, string username, params PrivateKeyFile[
/// Connection host.
/// Authentication username.
/// Authentication private key file(s) .
- /// is null.
- /// is invalid. -or- is null or contains only whitespace characters.
- public SftpClient(string host, string username, params PrivateKeyFile[] keyFiles)
+ /// is .
+ /// is invalid. -or- is or contains only whitespace characters.
+ public SftpClient(string host, string username, params IPrivateKeySource[] keyFiles)
: this(host, ConnectionInfo.DefaultPort, username, keyFiles)
{
}
@@ -228,9 +240,9 @@ public SftpClient(string host, string username, params PrivateKeyFile[] keyFiles
///
/// The connection info.
/// Specified whether this instance owns the connection info.
- /// is null.
+ /// is .
///
- /// If is true, the connection info will be disposed when this
+ /// If is , the connection info will be disposed when this
/// instance is disposed.
///
private SftpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
@@ -244,10 +256,10 @@ private SftpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
/// The connection info.
/// Specified whether this instance owns the connection info.
/// The factory to use for creating new services.
- /// is null.
- /// is null.
+ /// is .
+ /// is .
///
- /// If is true, the connection info will be disposed when this
+ /// If is , the connection info will be disposed when this
/// instance is disposed.
///
internal SftpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
@@ -263,7 +275,7 @@ internal SftpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, ISer
/// Changes remote directory to path.
///
/// New directory path.
- /// is null.
+ /// is .
/// Client is not connected.
/// Permission to change directory denied by remote host. -or- A SSH command was denied by the server.
/// was not found on the remote host.
@@ -273,11 +285,15 @@ public void ChangeDirectory(string path)
{
CheckDisposed();
- if (path == null)
- throw new ArgumentNullException("path");
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
_sftpSession.ChangeDirectory(path);
}
@@ -287,7 +303,7 @@ public void ChangeDirectory(string path)
///
/// File(s) path, may match multiple files.
/// The mode.
- /// is null.
+ /// is .
/// Client is not connected.
/// Permission to change permission on the path(s) was denied by the remote host. -or- A SSH command was denied by the server.
/// was not found on the remote host.
@@ -303,7 +319,7 @@ public void ChangePermissions(string path, short mode)
/// Creates remote directory specified by path.
///
/// Directory path to create.
- /// is null or contains only whitespace characters.
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to create the directory was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -312,11 +328,15 @@ public void CreateDirectory(string path)
{
CheckDisposed();
- if (path.IsNullOrWhiteSpace())
+ if (string.IsNullOrWhiteSpace(path))
+ {
throw new ArgumentException(path);
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
@@ -327,7 +347,7 @@ public void CreateDirectory(string path)
/// Deletes remote directory specified by path.
///
/// Directory to be deleted path.
- /// is null or contains only whitespace characters.
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// was not found on the remote host.
/// Permission to delete the directory was denied by the remote host. -or- A SSH command was denied by the server.
@@ -337,11 +357,15 @@ public void DeleteDirectory(string path)
{
CheckDisposed();
- if (path.IsNullOrWhiteSpace())
+ if (string.IsNullOrWhiteSpace(path))
+ {
throw new ArgumentException("path");
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
@@ -352,7 +376,7 @@ public void DeleteDirectory(string path)
/// Deletes remote file specified by path.
///
/// File to be deleted path.
- /// is null or contains only whitespace characters.
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// was not found on the remote host.
/// Permission to delete the file was denied by the remote host. -or- A SSH command was denied by the server.
@@ -362,30 +386,66 @@ public void DeleteFile(string path)
{
CheckDisposed();
- if (path.IsNullOrWhiteSpace())
+ if (string.IsNullOrWhiteSpace(path))
+ {
throw new ArgumentException("path");
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
_sftpSession.RequestRemove(fullPath);
}
+ ///
+ /// Asynchronously deletes remote file specified by path.
+ ///
+ /// File to be deleted path.
+ /// The to observe.
+ /// A that represents the asynchronous delete operation.
+ /// is or contains only whitespace characters.
+ /// Client is not connected.
+ /// was not found on the remote host.
+ /// Permission to delete the file was denied by the remote host. -or- A SSH command was denied by the server.
+ /// A SSH error where is the message from the remote host.
+ /// The method was called after the client was disposed.
+ public async Task DeleteFileAsync(string path, CancellationToken cancellationToken)
+ {
+ CheckDisposed();
+
+ if (string.IsNullOrWhiteSpace(path))
+ {
+ throw new ArgumentException("path");
+ }
+
+ if (_sftpSession is null)
+ {
+ throw new SshConnectionException("Client not connected.");
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
+ await _sftpSession.RequestRemoveAsync(fullPath, cancellationToken).ConfigureAwait(false);
+ }
+
///
/// Renames remote file from old path to new path.
///
/// Path to the old file location.
/// Path to the new file location.
- /// is null. -or- or is null.
+ /// is . -or- or is .
/// Client is not connected.
/// Permission to rename the file was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
/// The method was called after the client was disposed.
public void RenameFile(string oldPath, string newPath)
{
- RenameFile(oldPath, newPath, false);
+ RenameFile(oldPath, newPath, isPosix: false);
}
///
@@ -393,8 +453,8 @@ public void RenameFile(string oldPath, string newPath)
///
/// Path to the old file location.
/// Path to the new file location.
- /// if set to true then perform a posix rename.
- /// is null. -or- or is null.
+ /// if set to then perform a posix rename.
+ /// is . -or- or is .
/// Client is not connected.
/// Permission to rename the file was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -403,14 +463,20 @@ public void RenameFile(string oldPath, string newPath, bool isPosix)
{
CheckDisposed();
- if (oldPath == null)
- throw new ArgumentNullException("oldPath");
+ if (oldPath is null)
+ {
+ throw new ArgumentNullException(nameof(oldPath));
+ }
- if (newPath == null)
- throw new ArgumentNullException("newPath");
+ if (newPath is null)
+ {
+ throw new ArgumentNullException(nameof(newPath));
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var oldFullPath = _sftpSession.GetCanonicalPath(oldPath);
@@ -426,12 +492,50 @@ public void RenameFile(string oldPath, string newPath, bool isPosix)
}
}
+ ///
+ /// Asynchronously renames remote file from old path to new path.
+ ///
+ /// Path to the old file location.
+ /// Path to the new file location.
+ /// The to observe.
+ /// A that represents the asynchronous rename operation.
+ /// is . -or- or is .
+ /// Client is not connected.
+ /// Permission to rename the file was denied by the remote host. -or- A SSH command was denied by the server.
+ /// A SSH error where is the message from the remote host.
+ /// The method was called after the client was disposed.
+ public async Task RenameFileAsync(string oldPath, string newPath, CancellationToken cancellationToken)
+ {
+ CheckDisposed();
+
+ if (oldPath is null)
+ {
+ throw new ArgumentNullException(nameof(oldPath));
+ }
+
+ if (newPath is null)
+ {
+ throw new ArgumentNullException(nameof(newPath));
+ }
+
+ if (_sftpSession is null)
+ {
+ throw new SshConnectionException("Client not connected.");
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var oldFullPath = await _sftpSession.GetCanonicalPathAsync(oldPath, cancellationToken).ConfigureAwait(false);
+ var newFullPath = await _sftpSession.GetCanonicalPathAsync(newPath, cancellationToken).ConfigureAwait(false);
+ await _sftpSession.RequestRenameAsync(oldFullPath, newFullPath, cancellationToken).ConfigureAwait(false);
+ }
+
///
/// Creates a symbolic link from old path to new path.
///
/// The old path.
/// The new path.
- /// is null. -or- is null or contains only whitespace characters.
+ /// is . -or- is or contains only whitespace characters.
/// Client is not connected.
/// Permission to create the symbolic link was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -440,14 +544,20 @@ public void SymbolicLink(string path, string linkPath)
{
CheckDisposed();
- if (path.IsNullOrWhiteSpace())
+ if (string.IsNullOrWhiteSpace(path))
+ {
throw new ArgumentException("path");
+ }
- if (linkPath.IsNullOrWhiteSpace())
+ if (string.IsNullOrWhiteSpace(linkPath))
+ {
throw new ArgumentException("linkPath");
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
@@ -464,16 +574,75 @@ public void SymbolicLink(string path, string linkPath)
///
/// A list of files.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// Permission to list the contents of the directory was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
/// The method was called after the client was disposed.
- public IEnumerable ListDirectory(string path, Action listCallback = null)
+ public IEnumerable ListDirectory(string path, Action listCallback = null)
{
CheckDisposed();
- return InternalListDirectory(path, listCallback);
+ return InternalListDirectory(path, asyncResult: null, listCallback);
+ }
+
+ ///
+ /// Asynchronously enumerates the files in remote directory.
+ ///
+ /// The path.
+ /// The to observe.
+ ///
+ /// An of that represents the asynchronous enumeration operation.
+ /// The enumeration contains an async stream of for the files in the directory specified by .
+ ///
+ /// is .
+ /// Client is not connected.
+ /// Permission to list the contents of the directory was denied by the remote host. -or- A SSH command was denied by the server.
+ /// A SSH error where is the message from the remote host.
+ /// The method was called after the client was disposed.
+ public async IAsyncEnumerable ListDirectoryAsync(string path, [EnumeratorCancellation] CancellationToken cancellationToken)
+ {
+ CheckDisposed();
+
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
+
+ if (_sftpSession is null)
+ {
+ throw new SshConnectionException("Client not connected.");
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
+
+ var handle = await _sftpSession.RequestOpenDirAsync(fullPath, cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var basePath = (fullPath[fullPath.Length - 1] == '/') ?
+ fullPath :
+ fullPath + '/';
+
+ while (true)
+ {
+ var files = await _sftpSession.RequestReadDirAsync(handle, cancellationToken).ConfigureAwait(false);
+ if (files is null)
+ {
+ break;
+ }
+
+ foreach (var file in files)
+ {
+ yield return new SftpFile(_sftpSession, basePath + file.Key, file.Value);
+ }
+ }
+ }
+ finally
+ {
+ await _sftpSession.RequestCloseAsync(handle, cancellationToken).ConfigureAwait(false);
+ }
}
///
@@ -497,21 +666,13 @@ public IAsyncResult BeginListDirectory(string path, AsyncCallback asyncCallback,
{
try
{
- var result = InternalListDirectory(path, count =>
- {
- asyncResult.Update(count);
-
- if (listCallback != null)
- {
- listCallback(count);
- }
- });
+ var result = InternalListDirectory(path, asyncResult, listCallback);
- asyncResult.SetAsCompleted(result, false);
+ asyncResult.SetAsCompleted(result, completedSynchronously: false);
}
catch (Exception exp)
{
- asyncResult.SetAsCompleted(exp, false);
+ asyncResult.SetAsCompleted(exp, completedSynchronously: false);
}
});
@@ -526,12 +687,12 @@ public IAsyncResult BeginListDirectory(string path, AsyncCallback asyncCallback,
/// A list of files.
///
/// The object did not come from the corresponding async method on this type.-or- was called multiple times with the same .
- public IEnumerable EndListDirectory(IAsyncResult asyncResult)
+ public IEnumerable EndListDirectory(IAsyncResult asyncResult)
{
- var ar = asyncResult as SftpListDirectoryAsyncResult;
-
- if (ar == null || ar.EndInvokeCalled)
+ if (asyncResult is not SftpListDirectoryAsyncResult ar || ar.EndInvokeCalled)
+ {
throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
+ }
// Wait for operation to complete, then return result or throw exception
return ar.EndInvoke();
@@ -542,21 +703,25 @@ public IEnumerable EndListDirectory(IAsyncResult asyncResult)
///
/// The path.
///
- /// A reference to file object.
+ /// A reference to file object.
///
/// Client is not connected.
/// was not found on the remote host.
- /// is null.
+ /// is .
/// The method was called after the client was disposed.
- public SftpFile Get(string path)
+ public ISftpFile Get(string path)
{
CheckDisposed();
- if (path == null)
- throw new ArgumentNullException("path");
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
@@ -566,13 +731,13 @@ public SftpFile Get(string path)
}
///
- /// Checks whether file or directory exists;
+ /// Checks whether file or directory exists.
///
/// The path.
///
- /// true if directory or file exists; otherwise false.
+ /// if directory or file exists; otherwise .
///
- /// is null or contains only whitespace characters.
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to perform the operation was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -581,34 +746,40 @@ public bool Exists(string path)
{
CheckDisposed();
- if (path.IsNullOrWhiteSpace())
+ if (string.IsNullOrWhiteSpace(path))
+ {
throw new ArgumentException("path");
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
- // using SSH_FXP_REALPATH is not an alternative as the SFTP specification has not always
- // been clear on how the server should respond when the specified path is not present on
- // the server:
- //
- // SSH 1 to 4:
- // No mention of how the server should respond if the path is not present on the server.
- //
- // SSH 5:
- // The server SHOULD fail the request if the path is not present on the server.
- //
- // SSH 6:
- // Draft 06: The server SHOULD fail the request if the path is not present on the server.
- // Draft 07 to 13: The server MUST NOT fail the request if the path does not exist.
- //
- // Note that SSH 6 (draft 06 and forward) allows for more control options, but we
- // currently only support up to v3.
+ /*
+ * Using SSH_FXP_REALPATH is not an alternative as the SFTP specification has not always
+ * been clear on how the server should respond when the specified path is not present on
+ * the server:
+ *
+ * SSH 1 to 4:
+ * No mention of how the server should respond if the path is not present on the server.
+ *
+ * SSH 5:
+ * The server SHOULD fail the request if the path is not present on the server.
+ *
+ * SSH 6:
+ * Draft 06: The server SHOULD fail the request if the path is not present on the server.
+ * Draft 07 to 13: The server MUST NOT fail the request if the path does not exist.
+ *
+ * Note that SSH 6 (draft 06 and forward) allows for more control options, but we
+ * currently only support up to v3.
+ */
try
{
- _sftpSession.RequestLStat(fullPath);
+ _ = _sftpSession.RequestLStat(fullPath);
return true;
}
catch (SftpPathNotFoundException)
@@ -623,11 +794,11 @@ public bool Exists(string path)
/// File to download.
/// Stream to write the file into.
/// The download callback.
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to perform the operation was denied by the remote host. -or- A SSH command was denied by the server.
- /// was not found on the remote host.///
+ /// was not found on the remote host.///
/// A SSH error where is the message from the remote host.
/// The method was called after the client was disposed.
///
@@ -637,7 +808,7 @@ public void DownloadFile(string path, Stream output, Action downloadCallb
{
CheckDisposed();
- InternalDownloadFile(path, output, null, downloadCallback);
+ InternalDownloadFile(path, output, asyncResult: null, downloadCallback);
}
///
@@ -648,8 +819,8 @@ public void DownloadFile(string path, Stream output, Action downloadCallb
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to perform the operation was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -659,7 +830,7 @@ public void DownloadFile(string path, Stream output, Action downloadCallb
///
public IAsyncResult BeginDownloadFile(string path, Stream output)
{
- return BeginDownloadFile(path, output, null, null);
+ return BeginDownloadFile(path, output, asyncCallback: null, state: null);
}
///
@@ -671,8 +842,8 @@ public IAsyncResult BeginDownloadFile(string path, Stream output)
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to perform the operation was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -682,7 +853,7 @@ public IAsyncResult BeginDownloadFile(string path, Stream output)
///
public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback asyncCallback)
{
- return BeginDownloadFile(path, output, asyncCallback, null);
+ return BeginDownloadFile(path, output, asyncCallback, state: null);
}
///
@@ -696,8 +867,8 @@ public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// The method was called after the client was disposed.
///
/// Method calls made by this method to , may under certain conditions result in exceptions thrown by the stream.
@@ -706,11 +877,15 @@ public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback
{
CheckDisposed();
- if (path.IsNullOrWhiteSpace())
+ if (string.IsNullOrWhiteSpace(path))
+ {
throw new ArgumentException("path");
+ }
- if (output == null)
- throw new ArgumentNullException("output");
+ if (output is null)
+ {
+ throw new ArgumentNullException(nameof(output));
+ }
var asyncResult = new SftpDownloadAsyncResult(asyncCallback, state);
@@ -718,21 +893,13 @@ public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback
{
try
{
- InternalDownloadFile(path, output, asyncResult, offset =>
- {
- asyncResult.Update(offset);
-
- if (downloadCallback != null)
- {
- downloadCallback(offset);
- }
- });
+ InternalDownloadFile(path, output, asyncResult, downloadCallback);
- asyncResult.SetAsCompleted(null, false);
+ asyncResult.SetAsCompleted(exception: null, completedSynchronously: false);
}
catch (Exception exp)
{
- asyncResult.SetAsCompleted(exp, false);
+ asyncResult.SetAsCompleted(exp, completedSynchronously: false);
}
});
@@ -750,10 +917,10 @@ public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback
/// A SSH error where is the message from the remote host.
public void EndDownloadFile(IAsyncResult asyncResult)
{
- var ar = asyncResult as SftpDownloadAsyncResult;
-
- if (ar == null || ar.EndInvokeCalled)
+ if (asyncResult is not SftpDownloadAsyncResult ar || ar.EndInvokeCalled)
+ {
throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
+ }
// Wait for operation to complete, then return result or throw exception
ar.EndInvoke();
@@ -765,8 +932,8 @@ public void EndDownloadFile(IAsyncResult asyncResult)
/// Data input stream.
/// Remote file path.
/// The upload callback.
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to upload the file was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -776,7 +943,7 @@ public void EndDownloadFile(IAsyncResult asyncResult)
///
public void UploadFile(Stream input, string path, Action uploadCallback = null)
{
- UploadFile(input, path, true, uploadCallback);
+ UploadFile(input, path, canOverride: true, uploadCallback);
}
///
@@ -784,10 +951,10 @@ public void UploadFile(Stream input, string path, Action uploadCallback =
///
/// Data input stream.
/// Remote file path.
- /// if set to true then existing file will be overwritten.
+ /// if set to then existing file will be overwritten.
/// The upload callback.
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to upload the file was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -802,11 +969,15 @@ public void UploadFile(Stream input, string path, bool canOverride, Action
@@ -817,8 +988,8 @@ public void UploadFile(Stream input, string path, bool canOverride, Action
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to list the contents of the directory was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -833,7 +1004,7 @@ public void UploadFile(Stream input, string path, bool canOverride, Action
public IAsyncResult BeginUploadFile(Stream input, string path)
{
- return BeginUploadFile(input, path, true, null, null);
+ return BeginUploadFile(input, path, canOverride: true, asyncCallback: null, state: null);
}
///
@@ -845,8 +1016,8 @@ public IAsyncResult BeginUploadFile(Stream input, string path)
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to list the contents of the directory was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -861,7 +1032,7 @@ public IAsyncResult BeginUploadFile(Stream input, string path)
///
public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asyncCallback)
{
- return BeginUploadFile(input, path, true, asyncCallback, null);
+ return BeginUploadFile(input, path, canOverride: true, asyncCallback, state: null);
}
///
@@ -875,8 +1046,8 @@ public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asy
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// Client is not connected.
/// Permission to list the contents of the directory was denied by the remote host. -or- A SSH command was denied by the server.
/// A SSH error where is the message from the remote host.
@@ -891,7 +1062,7 @@ public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asy
///
public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asyncCallback, object state, Action uploadCallback = null)
{
- return BeginUploadFile(input, path, true, asyncCallback, state, uploadCallback);
+ return BeginUploadFile(input, path, canOverride: true, asyncCallback, state, uploadCallback);
}
///
@@ -906,16 +1077,16 @@ public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asy
///
/// An that references the asynchronous operation.
///
- /// is null.
- /// is null or contains only whitespace characters.
+ /// is .
+ /// is or contains only whitespace characters.
/// The method was called after the client was disposed.
///
///
/// Method calls made by this method to , may under certain conditions result in exceptions thrown by the stream.
///
///
- /// When refers to an existing file, set to true to overwrite and truncate that file.
- /// If is false, the upload will fail and will throw an
+ /// When refers to an existing file, set to to overwrite and truncate that file.
+ /// If is , the upload will fail and will throw an
/// .
///
///
@@ -923,18 +1094,26 @@ public IAsyncResult BeginUploadFile(Stream input, string path, bool canOverride,
{
CheckDisposed();
- if (input == null)
- throw new ArgumentNullException("input");
+ if (input is null)
+ {
+ throw new ArgumentNullException(nameof(input));
+ }
- if (path.IsNullOrWhiteSpace())
+ if (string.IsNullOrWhiteSpace(path))
+ {
throw new ArgumentException("path");
+ }
var flags = Flags.Write | Flags.Truncate;
if (canOverride)
+ {
flags |= Flags.CreateNewOrOpen;
+ }
else
+ {
flags |= Flags.CreateNew;
+ }
var asyncResult = new SftpUploadAsyncResult(asyncCallback, state);
@@ -942,22 +1121,13 @@ public IAsyncResult BeginUploadFile(Stream input, string path, bool canOverride,
{
try
{
- InternalUploadFile(input, path, flags, asyncResult, offset =>
- {
- asyncResult.Update(offset);
-
- if (uploadCallback != null)
- {
- uploadCallback(offset);
- }
+ InternalUploadFile(input, path, flags, asyncResult, uploadCallback);
- });
-
- asyncResult.SetAsCompleted(null, false);
+ asyncResult.SetAsCompleted(exception: null, completedSynchronously: false);
}
catch (Exception exp)
{
- asyncResult.SetAsCompleted(exp, false);
+ asyncResult.SetAsCompleted(exception: exp, completedSynchronously: false);
}
});
@@ -975,10 +1145,10 @@ public IAsyncResult BeginUploadFile(Stream input, string path, bool canOverride,
/// A SSH error where is the message from the remote host.
public void EndUploadFile(IAsyncResult asyncResult)
{
- var ar = asyncResult as SftpUploadAsyncResult;
-
- if (ar == null || ar.EndInvokeCalled)
+ if (asyncResult is not SftpUploadAsyncResult ar || ar.EndInvokeCalled)
+ {
throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
+ }
// Wait for operation to complete, then return result or throw exception
ar.EndInvoke();
@@ -992,23 +1162,59 @@ public void EndUploadFile(IAsyncResult asyncResult)
/// A instance that contains file status information.
///
/// Client is not connected.
- /// is null.
+ /// is .
/// The method was called after the client was disposed.
public SftpFileSytemInformation GetStatus(string path)
{
CheckDisposed();
- if (path == null)
- throw new ArgumentNullException("path");
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
return _sftpSession.RequestStatVfs(fullPath);
}
+ ///
+ /// Asynchronously gets status using statvfs@openssh.com request.
+ ///
+ /// The path.
+ /// The to observe.
+ ///
+ /// A that represents the status operation.
+ /// The task result contains the instance that contains file status information.
+ ///
+ /// Client is not connected.
+ /// is .
+ /// The method was called after the client was disposed.
+ public async Task GetStatusAsync(string path, CancellationToken cancellationToken)
+ {
+ CheckDisposed();
+
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
+
+ if (_sftpSession is null)
+ {
+ throw new SshConnectionException("Client not connected.");
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
+ return await _sftpSession.RequestStatVfsAsync(fullPath, cancellationToken).ConfigureAwait(false);
+ }
+
#region File Methods
///
@@ -1016,19 +1222,21 @@ public SftpFileSytemInformation GetStatus(string path)
///
/// The file to append the lines to. The file is created if it does not already exist.
/// The lines to append to the file.
- /// isnull -or- is null.
+ /// is . -or- is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
///
- /// The characters are written to the file using UTF-8 encoding without a Byte-Order Mark (BOM)
+ /// The characters are written to the file using UTF-8 encoding without a byte-order mark (BOM).
///
public void AppendAllLines(string path, IEnumerable contents)
{
CheckDisposed();
- if (contents == null)
- throw new ArgumentNullException("contents");
+ if (contents is null)
+ {
+ throw new ArgumentNullException(nameof(contents));
+ }
using (var stream = AppendText(path))
{
@@ -1045,7 +1253,7 @@ public void AppendAllLines(string path, IEnumerable contents)
/// The file to append the lines to. The file is created if it does not already exist.
/// The lines to append to the file.
/// The character encoding to use.
- /// is null. -or- is null. -or- is null.
+ /// is . -or- is . -or- is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1053,8 +1261,10 @@ public void AppendAllLines(string path, IEnumerable contents, Encoding e
{
CheckDisposed();
- if (contents == null)
- throw new ArgumentNullException("contents");
+ if (contents is null)
+ {
+ throw new ArgumentNullException(nameof(contents));
+ }
using (var stream = AppendText(path, encoding))
{
@@ -1070,7 +1280,7 @@ public void AppendAllLines(string path, IEnumerable contents, Encoding e
///
/// The file to append the specified string to.
/// The string to append to the file.
- /// is null. -or- is null.
+ /// is . -or- is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1091,7 +1301,7 @@ public void AppendAllText(string path, string contents)
/// The file to append the specified string to.
/// The string to append to the file.
/// The character encoding to use.
- /// is null. -or- is null. -or- is null.
+ /// is . -or- is . -or- is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1112,7 +1322,7 @@ public void AppendAllText(string path, string contents, Encoding encoding)
/// A that appends text to a file using UTF-8 encoding without a
/// Byte-Order Mark (BOM).
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1130,7 +1340,7 @@ public StreamWriter AppendText(string path)
///
/// A that appends text to a file using the specified encoding.
///
- /// is null. -or- is null.
+ /// is . -or- is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1138,8 +1348,10 @@ public StreamWriter AppendText(string path, Encoding encoding)
{
CheckDisposed();
- if (encoding == null)
- throw new ArgumentNullException("encoding");
+ if (encoding is null)
+ {
+ throw new ArgumentNullException(nameof(encoding));
+ }
return new StreamWriter(new SftpFileStream(_sftpSession, path, FileMode.Append, FileAccess.Write, (int) _bufferSize), encoding);
}
@@ -1151,7 +1363,7 @@ public StreamWriter AppendText(string path, Encoding encoding)
///
/// A that provides read/write access to the file specified in path.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1173,7 +1385,7 @@ public SftpFileStream Create(string path)
///
/// A that provides read/write access to the file specified in path.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1195,7 +1407,7 @@ public SftpFileStream Create(string path, int bufferSize)
/// A that writes text to a file using UTF-8 encoding without
/// a Byte-Order Mark (BOM).
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1220,7 +1432,7 @@ public StreamWriter CreateText(string path)
///
/// A that writes to a file using the specified encoding.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1243,7 +1455,7 @@ public StreamWriter CreateText(string path, Encoding encoding)
/// Deletes the specified file or directory.
///
/// The name of the file or directory to be deleted. Wildcard characters are not supported.
- /// is null.
+ /// is .
/// Client is not connected.
/// was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1261,7 +1473,7 @@ public void Delete(string path)
/// A structure set to the date and time that the specified file or directory was last accessed.
/// This value is expressed in local time.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public DateTime GetLastAccessTime(string path)
@@ -1278,7 +1490,7 @@ public DateTime GetLastAccessTime(string path)
/// A structure set to the date and time that the specified file or directory was last accessed.
/// This value is expressed in UTC time.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public DateTime GetLastAccessTimeUtc(string path)
@@ -1295,7 +1507,7 @@ public DateTime GetLastAccessTimeUtc(string path)
/// A structure set to the date and time that the specified file or directory was last written to.
/// This value is expressed in local time.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public DateTime GetLastWriteTime(string path)
@@ -1312,7 +1524,7 @@ public DateTime GetLastWriteTime(string path)
/// A structure set to the date and time that the specified file or directory was last written to.
/// This value is expressed in UTC time.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public DateTime GetLastWriteTimeUtc(string path)
@@ -1329,7 +1541,7 @@ public DateTime GetLastWriteTimeUtc(string path)
///
/// An unshared that provides access to the specified file, with the specified mode and read/write access.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public SftpFileStream Open(string path, FileMode mode)
@@ -1346,7 +1558,7 @@ public SftpFileStream Open(string path, FileMode mode)
///
/// An unshared that provides access to the specified file, with the specified mode and access.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public SftpFileStream Open(string path, FileMode mode, FileAccess access)
@@ -1356,6 +1568,39 @@ public SftpFileStream Open(string path, FileMode mode, FileAccess access)
return new SftpFileStream(_sftpSession, path, mode, access, (int) _bufferSize);
}
+ ///
+ /// Asynchronously opens a on the specified path, with the specified mode and access.
+ ///
+ /// The file to open.
+ /// A value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.
+ /// A value that specifies the operations that can be performed on the file.
+ /// The to observe.
+ ///
+ /// A that represents the asynchronous open operation.
+ /// The task result contains the that provides access to the specified file, with the specified mode and access.
+ ///
+ /// is .
+ /// Client is not connected.
+ /// The method was called after the client was disposed.
+ public Task OpenAsync(string path, FileMode mode, FileAccess access, CancellationToken cancellationToken)
+ {
+ CheckDisposed();
+
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
+
+ if (_sftpSession is null)
+ {
+ throw new SshConnectionException("Client not connected.");
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ return SftpFileStream.OpenAsync(_sftpSession, path, mode, access, (int) _bufferSize, cancellationToken);
+ }
+
///
/// Opens an existing file for reading.
///
@@ -1363,7 +1608,7 @@ public SftpFileStream Open(string path, FileMode mode, FileAccess access)
///
/// A read-only on the specified path.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public SftpFileStream OpenRead(string path)
@@ -1378,7 +1623,7 @@ public SftpFileStream OpenRead(string path)
///
/// A on the specified path.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public StreamReader OpenText(string path)
@@ -1393,7 +1638,7 @@ public StreamReader OpenText(string path)
///
/// An unshared object on the specified path with access.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
///
@@ -1413,7 +1658,7 @@ public SftpFileStream OpenWrite(string path)
///
/// A byte array containing the contents of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public byte[] ReadAllBytes(string path)
@@ -1421,7 +1666,7 @@ public byte[] ReadAllBytes(string path)
using (var stream = OpenRead(path))
{
var buffer = new byte[stream.Length];
- stream.Read(buffer, 0, buffer.Length);
+ _ = stream.Read(buffer, 0, buffer.Length);
return buffer;
}
}
@@ -1433,7 +1678,7 @@ public byte[] ReadAllBytes(string path)
///
/// A string array containing all lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public string[] ReadAllLines(string path)
@@ -1449,15 +1694,18 @@ public string[] ReadAllLines(string path)
///
/// A string array containing all lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public string[] ReadAllLines(string path, Encoding encoding)
{
- // we use the default buffer size for StreamReader - which is 1024 bytes - and the configured buffer size
- // for the SftpFileStream; may want to revisit this later
+ /*
+ * We use the default buffer size for StreamReader - which is 1024 bytes - and the configured buffer size
+ * for the SftpFileStream. We may want to revisit this later.
+ */
var lines = new List();
+
using (var stream = new StreamReader(OpenRead(path), encoding))
{
while (!stream.EndOfStream)
@@ -1465,6 +1713,7 @@ public string[] ReadAllLines(string path, Encoding encoding)
lines.Add(stream.ReadLine());
}
}
+
return lines.ToArray();
}
@@ -1475,7 +1724,7 @@ public string[] ReadAllLines(string path, Encoding encoding)
///
/// A string containing all lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public string ReadAllText(string path)
@@ -1491,13 +1740,15 @@ public string ReadAllText(string path)
///
/// A string containing all lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public string ReadAllText(string path, Encoding encoding)
{
- // we use the default buffer size for StreamReader - which is 1024 bytes - and the configured buffer size
- // for the SftpFileStream; may want to revisit this later
+ /*
+ * We use the default buffer size for StreamReader - which is 1024 bytes - and the configured buffer size
+ * for the SftpFileStream. We may want to revisit this later.
+ */
using (var stream = new StreamReader(OpenRead(path), encoding))
{
@@ -1512,7 +1763,7 @@ public string ReadAllText(string path, Encoding encoding)
///
/// The lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public IEnumerable ReadLines(string path)
@@ -1528,7 +1779,7 @@ public IEnumerable ReadLines(string path)
///
/// The lines of the file.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public IEnumerable ReadLines(string path, Encoding encoding)
@@ -1541,10 +1792,11 @@ public IEnumerable ReadLines(string path, Encoding encoding)
///
/// The file for which to set the access date and time information.
/// A containing the value to set for the last access date and time of path. This value is expressed in local time.
- [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
public void SetLastAccessTime(string path, DateTime lastAccessTime)
{
- throw new NotImplementedException();
+ var attributes = GetAttributes(path);
+ attributes.LastAccessTime = lastAccessTime;
+ SetAttributes(path, attributes);
}
///
@@ -1552,10 +1804,11 @@ public void SetLastAccessTime(string path, DateTime lastAccessTime)
///
/// The file for which to set the access date and time information.
/// A containing the value to set for the last access date and time of path. This value is expressed in UTC time.
- [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
public void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
{
- throw new NotImplementedException();
+ var attributes = GetAttributes(path);
+ attributes.LastAccessTimeUtc = lastAccessTimeUtc;
+ SetAttributes(path, attributes);
}
///
@@ -1563,10 +1816,11 @@ public void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
///
/// The file for which to set the date and time information.
/// A containing the value to set for the last write date and time of path. This value is expressed in local time.
- [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
public void SetLastWriteTime(string path, DateTime lastWriteTime)
{
- throw new NotImplementedException();
+ var attributes = GetAttributes(path);
+ attributes.LastWriteTime = lastWriteTime;
+ SetAttributes(path, attributes);
}
///
@@ -1574,10 +1828,11 @@ public void SetLastWriteTime(string path, DateTime lastWriteTime)
///
/// The file for which to set the date and time information.
/// A containing the value to set for the last write date and time of path. This value is expressed in UTC time.
- [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
public void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
{
- throw new NotImplementedException();
+ var attributes = GetAttributes(path);
+ attributes.LastWriteTimeUtc = lastWriteTimeUtc;
+ SetAttributes(path, attributes);
}
///
@@ -1585,7 +1840,7 @@ public void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
///
/// The file to write to.
/// The bytes to write to the file.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1610,7 +1865,7 @@ public void WriteAllBytes(string path, byte[] bytes)
///
/// The file to write to.
/// The lines to write to the file.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1635,7 +1890,7 @@ public void WriteAllLines(string path, IEnumerable contents)
///
/// The file to write to.
/// The string array to write to the file.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1661,7 +1916,7 @@ public void WriteAllLines(string path, string[] contents)
/// The file to write to.
/// The lines to write to the file.
/// The character encoding to use.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1690,7 +1945,7 @@ public void WriteAllLines(string path, IEnumerable contents, Encoding en
/// The file to write to.
/// The string array to write to the file.
/// An object that represents the character encoding applied to the string array.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1718,7 +1973,7 @@ public void WriteAllLines(string path, string[] contents, Encoding encoding)
///
/// The file to write to.
/// The string to write to the file.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1747,7 +2002,7 @@ public void WriteAllText(string path, string contents)
/// The file to write to.
/// The string to write to the file.
/// The encoding to apply to the string.
- /// is null.
+ /// is .
/// Client is not connected.
/// The specified path is invalid, or its directory was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1774,7 +2029,7 @@ public void WriteAllText(string path, string contents, Encoding encoding)
///
/// The of the file on the path.
///
- /// is null.
+ /// is .
/// Client is not connected.
/// was not found on the remote host.
/// The method was called after the client was disposed.
@@ -1782,8 +2037,10 @@ public SftpFileAttributes GetAttributes(string path)
{
CheckDisposed();
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
@@ -1795,30 +2052,23 @@ public SftpFileAttributes GetAttributes(string path)
///
/// The path to the file.
/// The desired .
- /// is null.
+ /// is .
/// Client is not connected.
/// The method was called after the client was disposed.
public void SetAttributes(string path, SftpFileAttributes fileAttributes)
{
CheckDisposed();
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
_sftpSession.RequestSetStat(fullPath, fileAttributes);
}
- // Please don't forget this when you implement these methods: is null.
- //public FileSecurity GetAccessControl(string path);
- //public FileSecurity GetAccessControl(string path, AccessControlSections includeSections);
- //public DateTime GetCreationTime(string path);
- //public DateTime GetCreationTimeUtc(string path);
- //public void SetAccessControl(string path, FileSecurity fileSecurity);
- //public void SetCreationTime(string path, DateTime creationTime);
- //public void SetCreationTimeUtc(string path, DateTime creationTimeUtc);
-
#endregion // File Methods
#region SynchronizeDirectories
@@ -1832,17 +2082,23 @@ public void SetAttributes(string path, SftpFileAttributes fileAttributes)
///
/// A list of uploaded files.
///
- /// is null.
- /// is null or contains only whitespace.
+ /// is .
+ /// is or contains only whitespace.
/// was not found on the remote host.
+ /// If a problem occurs while copying the file.
public IEnumerable SynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern)
{
- if (sourcePath == null)
- throw new ArgumentNullException("sourcePath");
- if (destinationPath.IsNullOrWhiteSpace())
+ if (sourcePath is null)
+ {
+ throw new ArgumentNullException(nameof(sourcePath));
+ }
+
+ if (string.IsNullOrWhiteSpace(destinationPath))
+ {
throw new ArgumentException("destinationPath");
+ }
- return InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, null);
+ return InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, asynchResult: null);
}
///
@@ -1856,30 +2112,36 @@ public IEnumerable SynchronizeDirectories(string sourcePath, string de
///
/// An that represents the asynchronous directory synchronization.
///
- /// is null.
- /// is null or contains only whitespace.
+ /// is .
+ /// is or contains only whitespace.
+ /// If a problem occurs while copying the file.
public IAsyncResult BeginSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, AsyncCallback asyncCallback, object state)
{
- if (sourcePath == null)
- throw new ArgumentNullException("sourcePath");
- if (destinationPath.IsNullOrWhiteSpace())
+ if (sourcePath is null)
+ {
+ throw new ArgumentNullException(nameof(sourcePath));
+ }
+
+ if (string.IsNullOrWhiteSpace(destinationPath))
+ {
throw new ArgumentException("destDir");
+ }
var asyncResult = new SftpSynchronizeDirectoriesAsyncResult(asyncCallback, state);
ThreadAbstraction.ExecuteThread(() =>
- {
- try
{
- var result = InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, asyncResult);
+ try
+ {
+ var result = InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, asyncResult);
- asyncResult.SetAsCompleted(result, false);
- }
- catch (Exception exp)
- {
- asyncResult.SetAsCompleted(exp, false);
- }
- });
+ asyncResult.SetAsCompleted(result, completedSynchronously: false);
+ }
+ catch (Exception exp)
+ {
+ asyncResult.SetAsCompleted(exp, completedSynchronously: false);
+ }
+ });
return asyncResult;
}
@@ -1895,78 +2157,90 @@ public IAsyncResult BeginSynchronizeDirectories(string sourcePath, string destin
/// The destination path was not found on the remote host.
public IEnumerable EndSynchronizeDirectories(IAsyncResult asyncResult)
{
- var ar = asyncResult as SftpSynchronizeDirectoriesAsyncResult;
-
- if (ar == null || ar.EndInvokeCalled)
+ if (asyncResult is not SftpSynchronizeDirectoriesAsyncResult ar || ar.EndInvokeCalled)
+ {
throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
+ }
// Wait for operation to complete, then return result or throw exception
return ar.EndInvoke();
}
- private IEnumerable InternalSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, SftpSynchronizeDirectoriesAsyncResult asynchResult)
+ private List InternalSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, SftpSynchronizeDirectoriesAsyncResult asynchResult)
{
if (!Directory.Exists(sourcePath))
+ {
throw new FileNotFoundException(string.Format("Source directory not found: {0}", sourcePath));
+ }
var uploadedFiles = new List();
var sourceDirectory = new DirectoryInfo(sourcePath);
- var sourceFiles = FileSystemAbstraction.EnumerateFiles(sourceDirectory, searchPattern).ToList();
- if (sourceFiles.Count == 0)
- return uploadedFiles;
+ using (var sourceFiles = sourceDirectory.EnumerateFiles(searchPattern).GetEnumerator())
+ {
+ if (!sourceFiles.MoveNext())
+ {
+ return uploadedFiles;
+ }
- #region Existing Files at The Destination
+ #region Existing Files at The Destination
- var destFiles = InternalListDirectory(destinationPath, null);
- var destDict = new Dictionary();
- foreach (var destFile in destFiles)
- {
- if (destFile.IsDirectory)
- continue;
- destDict.Add(destFile.Name, destFile);
- }
+ var destFiles = InternalListDirectory(destinationPath, asyncResult: null, listCallback: null);
+ var destDict = new Dictionary();
+ foreach (var destFile in destFiles)
+ {
+ if (destFile.IsDirectory)
+ {
+ continue;
+ }
- #endregion
+ destDict.Add(destFile.Name, destFile);
+ }
- #region Upload the difference
+ #endregion
- const Flags uploadFlag = Flags.Write | Flags.Truncate | Flags.CreateNewOrOpen;
- foreach (var localFile in sourceFiles)
- {
- var isDifferent = !destDict.ContainsKey(localFile.Name);
+ #region Upload the difference
- if (!isDifferent)
+ const Flags uploadFlag = Flags.Write | Flags.Truncate | Flags.CreateNewOrOpen;
+ do
{
- var temp = destDict[localFile.Name];
- // TODO: Use md5 to detect a difference
- //ltang: File exists at the destination => Using filesize to detect the difference
- isDifferent = localFile.Length != temp.Length;
- }
+ var localFile = sourceFiles.Current;
+ if (localFile is null)
+ {
+ continue;
+ }
- if (isDifferent)
- {
- var remoteFileName = string.Format(CultureInfo.InvariantCulture, @"{0}/{1}", destinationPath, localFile.Name);
- try
+ var isDifferent = true;
+ if (destDict.TryGetValue(localFile.Name, out var remoteFile))
+ {
+ // File exists at the destination, use filesize to detect if there's a difference
+ isDifferent = localFile.Length != remoteFile.Length;
+ }
+
+ if (isDifferent)
{
- using (var file = File.OpenRead(localFile.FullName))
+ var remoteFileName = string.Format(CultureInfo.InvariantCulture, @"{0}/{1}", destinationPath, localFile.Name);
+ try
{
- InternalUploadFile(file, remoteFileName, uploadFlag, null, null);
- }
+#pragma warning disable CA2000 // Dispose objects before losing scope; false positive
+ using (var file = File.OpenRead(localFile.FullName))
+#pragma warning restore CA2000 // Dispose objects before losing scope; false positive
+ {
+ InternalUploadFile(file, remoteFileName, uploadFlag, asyncResult: null, uploadCallback: null);
+ }
- uploadedFiles.Add(localFile);
+ uploadedFiles.Add(localFile);
- if (asynchResult != null)
+ asynchResult?.Update(uploadedFiles.Count);
+ }
+ catch (Exception ex)
{
- asynchResult.Update(uploadedFiles.Count);
+ throw new SshException($"Failed to upload {localFile.FullName} to {remoteFileName}", ex);
}
}
- catch (Exception ex)
- {
- throw new Exception(string.Format("Failed to upload {0} to {1}", localFile.FullName, remoteFileName), ex);
- }
}
+ while (sourceFiles.MoveNext());
}
#endregion
@@ -1980,19 +2254,24 @@ private IEnumerable InternalSynchronizeDirectories(string sourcePath,
/// Internals the list directory.
///
/// The path.
+ /// An that references the asynchronous request.
/// The list callback.
///
/// A list of files in the specfied directory.
///
- /// is null.
+ /// is .
/// Client not connected.
- private IEnumerable InternalListDirectory(string path, Action listCallback)
+ private List InternalListDirectory(string path, SftpListDirectoryAsyncResult asyncResult, Action listCallback)
{
- if (path == null)
- throw new ArgumentNullException("path");
+ if (path is null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
@@ -2000,22 +2279,34 @@ private IEnumerable InternalListDirectory(string path, Action lis
var basePath = fullPath;
- if (!basePath.EndsWith("/"))
+#if NET || NETSTANDARD2_1_OR_GREATER
+ if (!basePath.EndsWith('/'))
+#else
+ if (!basePath.EndsWith("/", StringComparison.Ordinal))
+#endif // NET || NETSTANDARD2_1_OR_GREATER
+ {
basePath = string.Format("{0}/", fullPath);
+ }
- var result = new List();
+ var result = new List();
var files = _sftpSession.RequestReadDir(handle);
- while (files != null)
+ while (files is not null)
{
- result.AddRange(from f in files
- select new SftpFile(_sftpSession, string.Format(CultureInfo.InvariantCulture, "{0}{1}", basePath, f.Key), f.Value));
+ foreach (var f in files)
+ {
+ result.Add(new SftpFile(_sftpSession,
+ string.Format(CultureInfo.InvariantCulture, "{0}{1}", basePath, f.Key),
+ f.Value));
+ }
+
+ asyncResult?.Update(result.Count);
- // Call callback to report number of files read
- if (listCallback != null)
+ // Call callback to report number of files read
+ if (listCallback is not null)
{
- // Execute callback on different thread
+ // Execute callback on different thread
ThreadAbstraction.ExecuteThread(() => listCallback(result.Count));
}
@@ -2034,19 +2325,25 @@ private IEnumerable InternalListDirectory(string path, Action lis
/// The output.
/// An that references the asynchronous request.
/// The download callback.
- /// is null.
- /// is null or contains whitespace.
+ /// is .
+ /// is or contains whitespace.
/// Client not connected.
private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncResult asyncResult, Action downloadCallback)
{
- if (output == null)
- throw new ArgumentNullException("output");
+ if (output is null)
+ {
+ throw new ArgumentNullException(nameof(output));
+ }
- if (path.IsNullOrWhiteSpace())
+ if (string.IsNullOrWhiteSpace(path))
+ {
throw new ArgumentException("path");
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
@@ -2056,24 +2353,30 @@ private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncR
while (true)
{
- // Cancel download
- if (asyncResult != null && asyncResult.IsDownloadCanceled)
+ // Cancel download
+ if (asyncResult is not null && asyncResult.IsDownloadCanceled)
+ {
break;
+ }
var data = fileReader.Read();
if (data.Length == 0)
+ {
break;
+ }
output.Write(data, 0, data.Length);
totalBytesRead += (ulong) data.Length;
- if (downloadCallback != null)
+ asyncResult?.Update(totalBytesRead);
+
+ if (downloadCallback is not null)
{
- // copy offset to ensure it's not modified between now and execution of callback
+ // Copy offset to ensure it's not modified between now and execution of callback
var downloadOffset = totalBytesRead;
- // Execute callback on different thread
+ // Execute callback on different thread
ThreadAbstraction.ExecuteThread(() => { downloadCallback(downloadOffset); });
}
}
@@ -2088,19 +2391,25 @@ private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncR
/// The flags.
/// An that references the asynchronous request.
/// The upload callback.
- /// is null.
- /// is null or contains whitespace.
+ /// is .
+ /// is or contains whitespace.
/// Client not connected.
private void InternalUploadFile(Stream input, string path, Flags flags, SftpUploadAsyncResult asyncResult, Action uploadCallback)
{
- if (input == null)
- throw new ArgumentNullException("input");
+ if (input is null)
+ {
+ throw new ArgumentNullException(nameof(input));
+ }
- if (path.IsNullOrWhiteSpace())
+ if (string.IsNullOrWhiteSpace(path))
+ {
throw new ArgumentException("path");
+ }
- if (_sftpSession == null)
+ if (_sftpSession is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
var fullPath = _sftpSession.GetCanonicalPath(path);
@@ -2113,34 +2422,39 @@ private void InternalUploadFile(Stream input, string path, Flags flags, SftpUplo
var bytesRead = input.Read(buffer, 0, buffer.Length);
var expectedResponses = 0;
- var responseReceivedWaitHandle = new AutoResetEvent(false);
+ var responseReceivedWaitHandle = new AutoResetEvent(initialState: false);
do
{
- // Cancel upload
- if (asyncResult != null && asyncResult.IsUploadCanceled)
+ // Cancel upload
+ if (asyncResult is not null && asyncResult.IsUploadCanceled)
+ {
break;
+ }
if (bytesRead > 0)
{
var writtenBytes = offset + (ulong) bytesRead;
- _sftpSession.RequestWrite(handle, offset, buffer, 0, bytesRead, null, s =>
+ _sftpSession.RequestWrite(handle, offset, buffer, offset: 0, bytesRead, wait: null, s =>
{
if (s.StatusCode == StatusCodes.Ok)
{
- Interlocked.Decrement(ref expectedResponses);
- responseReceivedWaitHandle.Set();
+ _ = Interlocked.Decrement(ref expectedResponses);
+ _ = responseReceivedWaitHandle.Set();
+
+ asyncResult?.Update(writtenBytes);
- // Call callback to report number of bytes written
- if (uploadCallback != null)
+ // Call callback to report number of bytes written
+ if (uploadCallback is not null)
{
- // Execute callback on different thread
+ // Execute callback on different thread
ThreadAbstraction.ExecuteThread(() => uploadCallback(writtenBytes));
}
}
});
- Interlocked.Increment(ref expectedResponses);
+
+ _ = Interlocked.Increment(ref expectedResponses);
offset += (ulong) bytesRead;
@@ -2148,12 +2462,14 @@ private void InternalUploadFile(Stream input, string path, Flags flags, SftpUplo
}
else if (expectedResponses > 0)
{
- // Wait for expectedResponses to change
+ // Wait for expectedResponses to change
_sftpSession.WaitOnHandle(responseReceivedWaitHandle, _operationTimeout);
}
- } while (expectedResponses > 0 || bytesRead > 0);
+ }
+ while (expectedResponses > 0 || bytesRead > 0);
_sftpSession.RequestClose(handle);
+ responseReceivedWaitHandle.Dispose();
}
///
@@ -2176,7 +2492,7 @@ protected override void OnDisconnecting()
// disconnect, dispose and dereference the SFTP session since we create a new SFTP session
// on each connect
var sftpSession = _sftpSession;
- if (sftpSession != null)
+ if (sftpSession is not null)
{
_sftpSession = null;
sftpSession.Dispose();
@@ -2184,9 +2500,9 @@ protected override void OnDisconnecting()
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
@@ -2194,7 +2510,7 @@ protected override void Dispose(bool disposing)
if (disposing)
{
var sftpSession = _sftpSession;
- if (sftpSession != null)
+ if (sftpSession is not null)
{
_sftpSession = null;
sftpSession.Dispose();
diff --git a/src/Renci.SshNet/Shell.cs b/src/Renci.SshNet/Shell.cs
index c508be896..4a73e58fb 100644
--- a/src/Renci.SshNet/Shell.cs
+++ b/src/Renci.SshNet/Shell.cs
@@ -1,38 +1,39 @@
using System;
+using System.Collections.Generic;
using System.IO;
using System.Threading;
+
+using Renci.SshNet.Abstractions;
using Renci.SshNet.Channels;
using Renci.SshNet.Common;
-using System.Collections.Generic;
-using Renci.SshNet.Abstractions;
namespace Renci.SshNet
{
///
- /// Represents instance of the SSH shell object
+ /// Represents instance of the SSH shell object.
///
public class Shell : IDisposable
{
private readonly ISession _session;
- private IChannelSession _channel;
- private EventWaitHandle _channelClosedWaitHandle;
- private Stream _input;
private readonly string _terminalName;
private readonly uint _columns;
private readonly uint _rows;
private readonly uint _width;
private readonly uint _height;
private readonly IDictionary _terminalModes;
- private EventWaitHandle _dataReaderTaskCompleted;
private readonly Stream _outputStream;
private readonly Stream _extendedOutputStream;
private readonly int _bufferSize;
+ private ManualResetEvent _dataReaderTaskCompleted;
+ private IChannelSession _channel;
+ private AutoResetEvent _channelClosedWaitHandle;
+ private Stream _input;
///
/// Gets a value indicating whether this shell is started.
///
///
- /// true if started is started; otherwise, false.
+ /// if started is started; otherwise, .
///
public bool IsStarted { get; private set; }
@@ -101,10 +102,7 @@ public void Start()
throw new SshException("Shell is started.");
}
- if (Starting != null)
- {
- Starting(this, new EventArgs());
- }
+ Starting?.Invoke(this, EventArgs.Empty);
_channel = _session.CreateChannelSession();
_channel.DataReceived += Channel_DataReceived;
@@ -114,13 +112,13 @@ public void Start()
_session.ErrorOccured += Session_ErrorOccured;
_channel.Open();
- _channel.SendPseudoTerminalRequest(_terminalName, _columns, _rows, _width, _height, _terminalModes);
- _channel.SendShellRequest();
+ _ = _channel.SendPseudoTerminalRequest(_terminalName, _columns, _rows, _width, _height, _terminalModes);
+ _ = _channel.SendShellRequest();
- _channelClosedWaitHandle = new AutoResetEvent(false);
+ _channelClosedWaitHandle = new AutoResetEvent(initialState: false);
- // Start input stream listener
- _dataReaderTaskCompleted = new ManualResetEvent(false);
+ // Start input stream listener
+ _dataReaderTaskCompleted = new ManualResetEvent(initialState: false);
ThreadAbstraction.ExecuteThread(() =>
{
try
@@ -129,34 +127,16 @@ public void Start()
while (_channel.IsOpen)
{
-#if FEATURE_STREAM_TAP
var readTask = _input.ReadAsync(buffer, 0, buffer.Length);
var readWaitHandle = ((IAsyncResult) readTask).AsyncWaitHandle;
- if (WaitHandle.WaitAny(new[] {readWaitHandle, _channelClosedWaitHandle}) == 0)
+ if (WaitHandle.WaitAny(new[] { readWaitHandle, _channelClosedWaitHandle }) == 0)
{
var read = readTask.GetAwaiter().GetResult();
_channel.SendData(buffer, 0, read);
continue;
}
-#elif FEATURE_STREAM_APM
- var asyncResult = _input.BeginRead(buffer, 0, buffer.Length, result =>
- {
- // If input stream is closed and disposed already don't finish reading the stream
- if (_input == null)
- return;
-
- var read = _input.EndRead(result);
- _channel.SendData(buffer, 0, read);
- }, null);
- WaitHandle.WaitAny(new[] { asyncResult.AsyncWaitHandle, _channelClosedWaitHandle });
-
- if (asyncResult.IsCompleted)
- continue;
-#else
- #error Async receive is not implemented.
-#endif
break;
}
}
@@ -166,16 +146,13 @@ public void Start()
}
finally
{
- _dataReaderTaskCompleted.Set();
+ _ = _dataReaderTaskCompleted.Set();
}
});
IsStarted = true;
- if (Started != null)
- {
- Started(this, new EventArgs());
- }
+ Started?.Invoke(this, EventArgs.Empty);
}
///
@@ -189,10 +166,7 @@ public void Stop()
throw new SshException("Shell is not started.");
}
- if (_channel != null)
- {
- _channel.Dispose();
- }
+ _channel?.Dispose();
}
private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
@@ -202,11 +176,7 @@ private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
private void RaiseError(ExceptionEventArgs e)
{
- var handler = ErrorOccurred;
- if (handler != null)
- {
- handler(this, e);
- }
+ ErrorOccurred?.Invoke(this, e);
}
private void Session_Disconnected(object sender, EventArgs e)
@@ -216,35 +186,29 @@ private void Session_Disconnected(object sender, EventArgs e)
private void Channel_ExtendedDataReceived(object sender, ChannelExtendedDataEventArgs e)
{
- if (_extendedOutputStream != null)
- {
- _extendedOutputStream.Write(e.Data, 0, e.Data.Length);
- }
+ _extendedOutputStream?.Write(e.Data, 0, e.Data.Length);
}
private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
{
- if (_outputStream != null)
- {
- _outputStream.Write(e.Data, 0, e.Data.Length);
- }
+ _outputStream?.Write(e.Data, 0, e.Data.Length);
}
private void Channel_Closed(object sender, ChannelEventArgs e)
{
- if (Stopping != null)
+ if (Stopping is not null)
{
- // Handle event on different thread
- ThreadAbstraction.ExecuteThread(() => Stopping(this, new EventArgs()));
+ // Handle event on different thread
+ ThreadAbstraction.ExecuteThread(() => Stopping(this, EventArgs.Empty));
}
_channel.Dispose();
- _channelClosedWaitHandle.Set();
+ _ = _channelClosedWaitHandle.Set();
_input.Dispose();
_input = null;
- _dataReaderTaskCompleted.WaitOne(_session.ConnectionInfo.Timeout);
+ _ = _dataReaderTaskCompleted.WaitOne(_session.ConnectionInfo.Timeout);
_dataReaderTaskCompleted.Dispose();
_dataReaderTaskCompleted = null;
@@ -256,8 +220,8 @@ private void Channel_Closed(object sender, ChannelEventArgs e)
if (Stopped != null)
{
- // Handle event on different thread
- ThreadAbstraction.ExecuteThread(() => Stopped(this, new EventArgs()));
+ // Handle event on different thread
+ ThreadAbstraction.ExecuteThread(() => Stopped(this, EventArgs.Empty));
}
_channel = null;
@@ -268,19 +232,19 @@ private void Channel_Closed(object sender, ChannelEventArgs e)
///
/// The session.
///
- /// Does nothing when is null.
+ /// Does nothing when is .
///
private void UnsubscribeFromSessionEvents(ISession session)
{
- if (session == null)
+ if (session is null)
+ {
return;
+ }
session.Disconnected -= Session_Disconnected;
session.ErrorOccured -= Session_ErrorOccured;
}
- #region IDisposable Members
-
private bool _disposed;
///
@@ -288,39 +252,41 @@ private void UnsubscribeFromSessionEvents(ISession session)
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_disposed)
+ {
return;
+ }
if (disposing)
{
UnsubscribeFromSessionEvents(_session);
var channelClosedWaitHandle = _channelClosedWaitHandle;
- if (channelClosedWaitHandle != null)
+ if (channelClosedWaitHandle is not null)
{
channelClosedWaitHandle.Dispose();
_channelClosedWaitHandle = null;
}
var channel = _channel;
- if (channel != null)
+ if (channel is not null)
{
channel.Dispose();
_channel = null;
}
var dataReaderTaskCompleted = _dataReaderTaskCompleted;
- if (dataReaderTaskCompleted != null)
+ if (dataReaderTaskCompleted is not null)
{
dataReaderTaskCompleted.Dispose();
_dataReaderTaskCompleted = null;
@@ -331,15 +297,11 @@ protected virtual void Dispose(bool disposing)
}
///
- /// Releases unmanaged resources and performs other cleanup operations before the
- /// is reclaimed by garbage collection.
+ /// Finalizes an instance of the class.
///
~Shell()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
-
}
}
diff --git a/src/Renci.SshNet/ShellStream.cs b/src/Renci.SshNet/ShellStream.cs
index 3274fe19c..ce57072d5 100644
--- a/src/Renci.SshNet/ShellStream.cs
+++ b/src/Renci.SshNet/ShellStream.cs
@@ -1,12 +1,13 @@
using System;
using System.Collections.Generic;
-using System.Text;
using System.IO;
-using Renci.SshNet.Channels;
-using Renci.SshNet.Common;
-using System.Threading;
+using System.Text;
using System.Text.RegularExpressions;
+using System.Threading;
+
using Renci.SshNet.Abstractions;
+using Renci.SshNet.Channels;
+using Renci.SshNet.Common;
namespace Renci.SshNet
{
@@ -23,7 +24,7 @@ public class ShellStream : Stream
private readonly Queue _incoming;
private readonly Queue _outgoing;
private IChannelSession _channel;
- private AutoResetEvent _dataReceived = new AutoResetEvent(false);
+ private AutoResetEvent _dataReceived = new AutoResetEvent(initialState: false);
private bool _isDisposed;
///
@@ -37,10 +38,10 @@ public class ShellStream : Stream
public event EventHandler ErrorOccurred;
///
- /// Gets a value that indicates whether data is available on the to be read.
+ /// Gets a value indicating whether data is available on the to be read.
///
///
- /// true if data is available to be read; otherwise, false.
+ /// if data is available to be read; otherwise, .
///
public bool DataAvailable
{
@@ -65,13 +66,13 @@ internal int BufferSize
}
///
- /// Initializes a new instance.
+ /// Initializes a new instance of the class.
///
/// The SSH session.
/// The TERM environment variable.
/// The terminal width in columns.
/// The terminal width in rows.
- /// The terminal height in pixels.
+ /// The terminal width in pixels.
/// The terminal height in pixels.
/// The terminal mode values.
/// The size of the buffer.
@@ -95,10 +96,12 @@ internal ShellStream(ISession session, string terminalName, uint columns, uint r
try
{
_channel.Open();
+
if (!_channel.SendPseudoTerminalRequest(terminalName, columns, rows, width, height, terminalModeValues))
{
throw new SshException("The pseudo-terminal request was not accepted by the server. Consult the server log for more information.");
}
+
if (!_channel.SendShellRequest())
{
throw new SshException("The request to start a shell was not accepted by the server. Consult the server log for more information.");
@@ -112,13 +115,11 @@ internal ShellStream(ISession session, string terminalName, uint columns, uint r
}
}
- #region Stream overide methods
-
///
/// Gets a value indicating whether the current stream supports reading.
///
///
- /// true if the stream supports reading; otherwise, false.
+ /// if the stream supports reading; otherwise, .
///
public override bool CanRead
{
@@ -129,7 +130,7 @@ public override bool CanRead
/// Gets a value indicating whether the current stream supports seeking.
///
///
- /// true if the stream supports seeking; otherwise, false.
+ /// if the stream supports seeking; otherwise, .
///
public override bool CanSeek
{
@@ -140,7 +141,7 @@ public override bool CanSeek
/// Gets a value indicating whether the current stream supports writing.
///
///
- /// true if the stream supports writing; otherwise, false.
+ /// if the stream supports writing; otherwise, .
///
public override bool CanWrite
{
@@ -150,14 +151,18 @@ public override bool CanWrite
///
/// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
///
- /// An I/O error occurs.
+ /// An I/O error occurs.
/// Methods were called after the stream was closed.
public override void Flush()
{
- if (_channel == null)
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_channel is null, this);
+#else
+ if (_channel is null)
{
- throw new ObjectDisposedException("ShellStream");
+ throw new ObjectDisposedException(GetType().FullName);
}
+#endif // NET7_0_OR_GREATER
if (_outgoing.Count > 0)
{
@@ -189,56 +194,26 @@ public override long Length
///
/// The current position within the stream.
///
- /// An I/O error occurs.
- /// The stream does not support seeking.
- /// Methods were called after the stream was closed.
+ /// An I/O error occurs.
+ /// The stream does not support seeking.
+ /// Methods were called after the stream was closed.
public override long Position
{
get { return 0; }
set { throw new NotSupportedException(); }
}
- ///
- /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
- ///
- /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between and ( + - 1) replaced by the bytes read from the current source.
- /// The zero-based byte offset in at which to begin storing the data read from the current stream.
- /// The maximum number of bytes to be read from the current stream.
- ///
- /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
- ///
- /// The sum of and is larger than the buffer length.
- /// is null.
- /// or is negative.
- /// An I/O error occurs.
- /// The stream does not support reading.
- /// Methods were called after the stream was closed.
- public override int Read(byte[] buffer, int offset, int count)
- {
- var i = 0;
-
- lock (_incoming)
- {
- for (; i < count && _incoming.Count > 0; i++)
- {
- buffer[offset + i] = _incoming.Dequeue();
- }
- }
-
- return i;
- }
-
///
/// This method is not supported.
///
/// A byte offset relative to the parameter.
- /// A value of type indicating the reference point used to obtain the new position.
+ /// A value of type indicating the reference point used to obtain the new position.
///
/// The new position within the current stream.
///
- /// An I/O error occurs.
- /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output.
- /// Methods were called after the stream was closed.
+ /// An I/O error occurs.
+ /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output.
+ /// Methods were called after the stream was closed.
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
@@ -248,41 +223,14 @@ public override long Seek(long offset, SeekOrigin origin)
/// This method is not supported.
///
/// The desired length of the current stream in bytes.
- /// An I/O error occurs.
- /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output.
- /// Methods were called after the stream was closed.
+ /// An I/O error occurs.
+ /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output.
+ /// Methods were called after the stream was closed.
public override void SetLength(long value)
{
throw new NotSupportedException();
}
- ///
- /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
- ///
- /// An array of bytes. This method copies bytes from to the current stream.
- /// The zero-based byte offset in at which to begin copying bytes to the current stream.
- /// The number of bytes to be written to the current stream.
- /// The sum of and is greater than the buffer length.
- /// is null.
- /// or is negative.
- /// An I/O error occurs.
- /// The stream does not support writing.
- /// Methods were called after the stream was closed.
- public override void Write(byte[] buffer, int offset, int count)
- {
- foreach (var b in buffer.Take(offset, count))
- {
- if (_outgoing.Count == _bufferSize)
- {
- Flush();
- }
-
- _outgoing.Enqueue(b);
- }
- }
-
- #endregion
-
///
/// Expects the specified expression and performs action when one is found.
///
@@ -323,8 +271,8 @@ public void Expect(TimeSpan timeout, params ExpectAction[] expectActions)
for (var i = 0; i < match.Index + match.Length && _incoming.Count > 0; i++)
{
- // Remove processed items from the queue
- _incoming.Dequeue();
+ // Remove processed items from the queue
+ _ = _incoming.Dequeue();
}
expectAction.Action(result);
@@ -345,13 +293,102 @@ public void Expect(TimeSpan timeout, params ExpectAction[] expectActions)
}
else
{
- _dataReceived.WaitOne();
+ _ = _dataReceived.WaitOne();
}
}
}
while (!expectedFound);
}
+ ///
+ /// Expects the expression specified by text.
+ ///
+ /// The text to expect.
+ ///
+ /// Text available in the shell that ends with expected text.
+ ///
+ public string Expect(string text)
+ {
+ return Expect(new Regex(Regex.Escape(text)), Session.InfiniteTimeSpan);
+ }
+
+ ///
+ /// Expects the expression specified by text.
+ ///
+ /// The text to expect.
+ /// Time to wait for input.
+ ///
+ /// The text available in the shell that ends with expected text, or if the specified time has elapsed.
+ ///
+ public string Expect(string text, TimeSpan timeout)
+ {
+ return Expect(new Regex(Regex.Escape(text)), timeout);
+ }
+
+ ///
+ /// Expects the expression specified by regular expression.
+ ///
+ /// The regular expression to expect.
+ ///
+ /// The text available in the shell that contains all the text that ends with expected expression.
+ ///
+ public string Expect(Regex regex)
+ {
+ return Expect(regex, TimeSpan.Zero);
+ }
+
+ ///
+ /// Expects the expression specified by regular expression.
+ ///
+ /// The regular expression to expect.
+ /// Time to wait for input.
+ ///
+ /// The text available in the shell that contains all the text that ends with expected expression,
+ /// or if the specified time has elapsed.
+ ///
+ public string Expect(Regex regex, TimeSpan timeout)
+ {
+ var text = string.Empty;
+
+ while (true)
+ {
+ lock (_incoming)
+ {
+ if (_incoming.Count > 0)
+ {
+ text = _encoding.GetString(_incoming.ToArray(), 0, _incoming.Count);
+ }
+
+ var match = regex.Match(text);
+
+ if (match.Success)
+ {
+ // Remove processed items from the queue
+ for (var i = 0; i < match.Index + match.Length && _incoming.Count > 0; i++)
+ {
+ _ = _incoming.Dequeue();
+ }
+
+ break;
+ }
+ }
+
+ if (timeout.Ticks > 0)
+ {
+ if (!_dataReceived.WaitOne(timeout))
+ {
+ return null;
+ }
+ }
+ else
+ {
+ _ = _dataReceived.WaitOne();
+ }
+ }
+
+ return text;
+ }
+
///
/// Begins the expect.
///
@@ -361,7 +398,7 @@ public void Expect(TimeSpan timeout, params ExpectAction[] expectActions)
///
public IAsyncResult BeginExpect(params ExpectAction[] expectActions)
{
- return BeginExpect(TimeSpan.Zero, null, null, expectActions);
+ return BeginExpect(TimeSpan.Zero, callback: null, state: null, expectActions);
}
///
@@ -374,7 +411,7 @@ public IAsyncResult BeginExpect(params ExpectAction[] expectActions)
///
public IAsyncResult BeginExpect(AsyncCallback callback, params ExpectAction[] expectActions)
{
- return BeginExpect(TimeSpan.Zero, callback, null, expectActions);
+ return BeginExpect(TimeSpan.Zero, callback, state: null, expectActions);
}
///
@@ -401,25 +438,25 @@ public IAsyncResult BeginExpect(AsyncCallback callback, object state, params Exp
///
/// An that references the asynchronous operation.
///
+#pragma warning disable CA1859 // Use concrete types when possible for improved performance
public IAsyncResult BeginExpect(TimeSpan timeout, AsyncCallback callback, object state, params ExpectAction[] expectActions)
+#pragma warning restore CA1859 // Use concrete types when possible for improved performance
{
var text = string.Empty;
- // Create new AsyncResult object
+ // Create new AsyncResult object
var asyncResult = new ExpectAsyncResult(callback, state);
- // Execute callback on different thread
+ // Execute callback on different thread
ThreadAbstraction.ExecuteThread(() =>
{
string expectActionResult = null;
try
{
-
do
{
lock (_incoming)
{
-
if (_incoming.Count > 0)
{
text = _encoding.GetString(_incoming.ToArray(), 0, _incoming.Count);
@@ -437,16 +474,12 @@ public IAsyncResult BeginExpect(TimeSpan timeout, AsyncCallback callback, object
for (var i = 0; i < match.Index + match.Length && _incoming.Count > 0; i++)
{
- // Remove processed items from the queue
- _incoming.Dequeue();
+ // Remove processed items from the queue
+ _ = _incoming.Dequeue();
}
expectAction.Action(result);
-
- if (callback != null)
- {
- callback(asyncResult);
- }
+ callback?.Invoke(asyncResult);
expectActionResult = result;
}
}
@@ -454,30 +487,30 @@ public IAsyncResult BeginExpect(TimeSpan timeout, AsyncCallback callback, object
}
if (expectActionResult != null)
+ {
break;
+ }
if (timeout.Ticks > 0)
{
if (!_dataReceived.WaitOne(timeout))
{
- if (callback != null)
- {
- callback(asyncResult);
- }
+ callback?.Invoke(asyncResult);
break;
}
}
else
{
- _dataReceived.WaitOne();
+ _ = _dataReceived.WaitOne();
}
- } while (true);
+ }
+ while (true);
- asyncResult.SetAsCompleted(expectActionResult, true);
+ asyncResult.SetAsCompleted(expectActionResult, completedSynchronously: true);
}
catch (Exception exp)
{
- asyncResult.SetAsCompleted(exp, true);
+ asyncResult.SetAsCompleted(exp, completedSynchronously: true);
}
});
@@ -488,105 +521,19 @@ public IAsyncResult BeginExpect(TimeSpan timeout, AsyncCallback callback, object
/// Ends the execute.
///
/// The async result.
- /// Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.
- public string EndExpect(IAsyncResult asyncResult)
- {
- var ar = asyncResult as ExpectAsyncResult;
-
- if (ar == null || ar.EndInvokeCalled)
- throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
-
- // Wait for operation to complete, then return result or throw exception
- return ar.EndInvoke();
- }
-
- ///
- /// Expects the expression specified by text.
- ///
- /// The text to expect.
///
/// Text available in the shell that ends with expected text.
///
- public string Expect(string text)
- {
- return Expect(new Regex(Regex.Escape(text)), Session.InfiniteTimeSpan);
- }
-
- ///
- /// Expects the expression specified by text.
- ///
- /// The text to expect.
- /// Time to wait for input.
- ///
- /// The text available in the shell that ends with expected text, or null if the specified time has elapsed.
- ///
- public string Expect(string text, TimeSpan timeout)
- {
- return Expect(new Regex(Regex.Escape(text)), timeout);
- }
-
- ///
- /// Expects the expression specified by regular expression.
- ///
- /// The regular expression to expect.
- ///
- /// The text available in the shell that contains all the text that ends with expected expression.
- ///
- public string Expect(Regex regex)
- {
- return Expect(regex, TimeSpan.Zero);
- }
-
- ///
- /// Expects the expression specified by regular expression.
- ///
- /// The regular expression to expect.
- /// Time to wait for input.
- ///
- /// The text available in the shell that contains all the text that ends with expected expression,
- /// or null if the specified time has elapsed.
- ///
- public string Expect(Regex regex, TimeSpan timeout)
+ /// Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.
+ public string EndExpect(IAsyncResult asyncResult)
{
- var text = string.Empty;
-
- while (true)
+ if (asyncResult is not ExpectAsyncResult ar || ar.EndInvokeCalled)
{
- lock (_incoming)
- {
- if (_incoming.Count > 0)
- {
- text = _encoding.GetString(_incoming.ToArray(), 0, _incoming.Count);
- }
-
- var match = regex.Match(text);
-
- if (match.Success)
- {
- // Remove processed items from the queue
- for (var i = 0; i < match.Index + match.Length && _incoming.Count > 0; i++)
- {
- _incoming.Dequeue();
- }
- break;
- }
- }
-
- if (timeout.Ticks > 0)
- {
- if (!_dataReceived.WaitOne(timeout))
- {
- return null;
- }
- }
- else
- {
- _dataReceived.WaitOne();
- }
-
+ throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
}
- return text;
+ // Wait for operation to complete, then return result or throw exception
+ return ar.EndInvoke();
}
///
@@ -605,7 +552,7 @@ public string ReadLine()
///
/// Time to wait for input.
///
- /// The line read from the shell, or null when no input is received for the specified timeout.
+ /// The line read from the shell, or when no input is received for the specified timeout.
///
public string ReadLine(TimeSpan timeout)
{
@@ -631,7 +578,9 @@ public string ReadLine(TimeSpan timeout)
// remove processed bytes from the queue
for (var i = 0; i < bytesProcessed; i++)
- _incoming.Dequeue();
+ {
+ _ = _incoming.Dequeue();
+ }
break;
}
@@ -646,9 +595,8 @@ public string ReadLine(TimeSpan timeout)
}
else
{
- _dataReceived.WaitOne();
+ _ = _dataReceived.WaitOne();
}
-
}
return text;
@@ -673,33 +621,94 @@ public string Read()
return text;
}
+ ///
+ /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
+ ///
+ /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between and ( + - 1) replaced by the bytes read from the current source.
+ /// The zero-based byte offset in at which to begin storing the data read from the current stream.
+ /// The maximum number of bytes to be read from the current stream.
+ ///
+ /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
+ ///
+ /// The sum of and is larger than the buffer length.
+ /// is .
+ /// or is negative.
+ /// An I/O error occurs.
+ /// The stream does not support reading.
+ /// Methods were called after the stream was closed.
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ var i = 0;
+
+ lock (_incoming)
+ {
+ for (; i < count && _incoming.Count > 0; i++)
+ {
+ buffer[offset + i] = _incoming.Dequeue();
+ }
+ }
+
+ return i;
+ }
+
///
/// Writes the specified text to the shell.
///
/// The text to be written to the shell.
///
- /// If is null, nothing is written.
+ /// If is , nothing is written.
///
public void Write(string text)
{
- if (text == null)
+ if (text is null)
+ {
return;
+ }
- if (_channel == null)
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_channel is null, this);
+#else
+ if (_channel is null)
{
- throw new ObjectDisposedException("ShellStream");
+ throw new ObjectDisposedException(GetType().FullName);
}
+#endif // NET7_0_OR_GREATER
var data = _encoding.GetBytes(text);
_channel.SendData(data);
}
+ ///
+ /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
+ ///
+ /// An array of bytes. This method copies bytes from to the current stream.
+ /// The zero-based byte offset in at which to begin copying bytes to the current stream.
+ /// The number of bytes to be written to the current stream.
+ /// The sum of and is greater than the buffer length.
+ /// is .
+ /// or is negative.
+ /// An I/O error occurs.
+ /// The stream does not support writing.
+ /// Methods were called after the stream was closed.
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ foreach (var b in buffer.Take(offset, count))
+ {
+ if (_outgoing.Count == _bufferSize)
+ {
+ Flush();
+ }
+
+ _outgoing.Enqueue(b);
+ }
+ }
+
///
/// Writes the line to the shell.
///
/// The line to be written to the shell.
///
- /// If is null, only the line terminator is written.
+ /// If is , only the line terminator is written.
///
public void WriteLine(string line)
{
@@ -709,13 +718,15 @@ public void WriteLine(string line)
///
/// Releases the unmanaged resources used by the and optionally releases the managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -748,12 +759,14 @@ protected override void Dispose(bool disposing)
///
/// The session.
///
- /// Does nothing when is null.
+ /// Does nothing when is .
///
private void UnsubscribeFromSessionEvents(ISession session)
{
- if (session == null)
+ if (session is null)
+ {
return;
+ }
session.Disconnected -= Session_Disconnected;
session.ErrorOccured -= Session_ErrorOccured;
@@ -766,13 +779,12 @@ private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
private void Session_Disconnected(object sender, EventArgs e)
{
- if (_channel != null)
- _channel.Dispose();
+ _channel?.Dispose();
}
private void Channel_Closed(object sender, ChannelEventArgs e)
{
- // TODO: Do we need to call dispose here ??
+ // TODO: Do we need to call dispose here ??
Dispose();
}
@@ -781,31 +793,27 @@ private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
lock (_incoming)
{
foreach (var b in e.Data)
+ {
_incoming.Enqueue(b);
+ }
}
if (_dataReceived != null)
- _dataReceived.Set();
+ {
+ _ = _dataReceived.Set();
+ }
OnDataReceived(e.Data);
}
private void OnRaiseError(ExceptionEventArgs e)
{
- var handler = ErrorOccurred;
- if (handler != null)
- {
- handler(this, e);
- }
+ ErrorOccurred?.Invoke(this, e);
}
private void OnDataReceived(byte[] data)
{
- var handler = DataReceived;
- if (handler != null)
- {
- handler(this, new ShellDataEventArgs(data));
- }
+ DataReceived?.Invoke(this, new ShellDataEventArgs(data));
}
}
}
diff --git a/src/Renci.SshNet/SshClient.cs b/src/Renci.SshNet/SshClient.cs
index 49c9ff84b..2e1103553 100644
--- a/src/Renci.SshNet/SshClient.cs
+++ b/src/Renci.SshNet/SshClient.cs
@@ -1,9 +1,10 @@
using System;
using System.Collections.Generic;
-using System.IO;
-using System.Text;
using System.Diagnostics.CodeAnalysis;
+using System.IO;
using System.Net;
+using System.Text;
+
using Renci.SshNet.Common;
namespace Renci.SshNet
@@ -14,7 +15,7 @@ namespace Renci.SshNet
public class SshClient : BaseClient
{
///
- /// Holds the list of forwarded ports
+ /// Holds the list of forwarded ports.
///
private readonly List _forwardedPorts;
@@ -22,11 +23,11 @@ public class SshClient : BaseClient
/// Holds a value indicating whether the current instance is disposed.
///
///
- /// true if the current instance is disposed; otherwise, false.
+ /// if the current instance is disposed; otherwise, .
///
private bool _isDisposed;
- private Stream _inputStream;
+ private MemoryStream _inputStream;
///
/// Gets the list of forwarded ports.
@@ -39,21 +40,13 @@ public IEnumerable ForwardedPorts
}
}
- #region Constructors
-
///
/// Initializes a new instance of the class.
///
/// The connection info.
- ///
- ///
- ///
- ///
- ///
- ///
- /// is null.
+ /// is .
public SshClient(ConnectionInfo connectionInfo)
- : this(connectionInfo, false)
+ : this(connectionInfo, ownsConnectionInfo: false)
{
}
@@ -64,12 +57,14 @@ public SshClient(ConnectionInfo connectionInfo)
/// Connection port.
/// Authentication username.
/// Authentication password.
- /// is null.
- /// is invalid, or is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, or is or contains only whitespace characters.
/// is not within and .
[SuppressMessage("Microsoft.Reliability", "C2A000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
public SshClient(string host, int port, string username, string password)
- : this(new PasswordConnectionInfo(host, port, username, password), true)
+#pragma warning disable CA2000 // Dispose objects before losing scope
+ : this(new PasswordConnectionInfo(host, port, username, password), ownsConnectionInfo: true)
+#pragma warning restore CA2000 // Dispose objects before losing scope
{
}
@@ -79,11 +74,8 @@ public SshClient(string host, int port, string username, string password)
/// Connection host.
/// Authentication username.
/// Authentication password.
- ///
- ///
- ///
- /// is null.
- /// is invalid, or is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, or is or contains only whitespace characters.
public SshClient(string host, string username, string password)
: this(host, ConnectionInfo.DefaultPort, username, password)
{
@@ -96,16 +88,12 @@ public SshClient(string host, string username, string password)
/// Connection port.
/// Authentication username.
/// Authentication private key file(s) .
- ///
- ///
- ///
- ///
- /// is null.
- /// is invalid, -or- is null or contains only whitespace characters.
+ /// is .
+ /// is invalid, -or- is or contains only whitespace characters.
/// is not within and .
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
- public SshClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)
- : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), true)
+ public SshClient(string host, int port, string username, params IPrivateKeySource[] keyFiles)
+ : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), ownsConnectionInfo: true)
{
}
@@ -115,13 +103,9 @@ public SshClient(string host, int port, string username, params PrivateKeyFile[]
/// Connection host.
/// Authentication username.
/// Authentication private key file(s) .
- ///
- ///
- ///
- ///
- /// is null.
- /// is invalid, -or- is null or contains only whitespace characters.
- public SshClient(string host, string username, params PrivateKeyFile[] keyFiles)
+ /// is .
+ /// is invalid, -or- is or contains only whitespace characters.
+ public SshClient(string host, string username, params IPrivateKeySource[] keyFiles)
: this(host, ConnectionInfo.DefaultPort, username, keyFiles)
{
}
@@ -131,9 +115,9 @@ public SshClient(string host, string username, params PrivateKeyFile[] keyFiles)
///
/// The connection info.
/// Specified whether this instance owns the connection info.
- /// is null.
+ /// is .
///
- /// If is true, then the
+ /// If is , then the
/// connection info will be disposed when this instance is disposed.
///
private SshClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
@@ -147,10 +131,10 @@ private SshClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
/// The connection info.
/// Specified whether this instance owns the connection info.
/// The factory to use for creating new services.
- /// is null.
- /// is null.
+ /// is .
+ /// is .
///
- /// If is true, then the
+ /// If is , then the
/// connection info will be disposed when this instance is disposed.
///
internal SshClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
@@ -159,8 +143,6 @@ internal SshClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServ
_forwardedPorts = new List();
}
- #endregion
-
///
/// Called when client is disconnecting from the server.
///
@@ -178,17 +160,16 @@ protected override void OnDisconnecting()
/// Adds the forwarded port.
///
/// The port.
- ///
- ///
- ///
- ///
/// Forwarded port is already added to a different client.
- /// is null.
+ /// is .
/// Client is not connected.
public void AddForwardedPort(ForwardedPort port)
{
- if (port == null)
- throw new ArgumentNullException("port");
+ if (port is null)
+ {
+ throw new ArgumentNullException(nameof(port));
+ }
+
EnsureSessionIsOpen();
AttachForwardedPort(port);
@@ -199,23 +180,27 @@ public void AddForwardedPort(ForwardedPort port)
/// Stops and removes the forwarded port from the list.
///
/// Forwarded port.
- /// is null.
+ /// is .
public void RemoveForwardedPort(ForwardedPort port)
{
- if (port == null)
- throw new ArgumentNullException("port");
+ if (port is null)
+ {
+ throw new ArgumentNullException(nameof(port));
+ }
- // Stop port forwarding before removing it
+ // Stop port forwarding before removing it
port.Stop();
DetachForwardedPort(port);
- _forwardedPorts.Remove(port);
+ _ = _forwardedPorts.Remove(port);
}
private void AttachForwardedPort(ForwardedPort port)
{
if (port.Session != null && port.Session != Session)
+ {
throw new InvalidOperationException("Forwarded port is already added to a different client.");
+ }
port.Session = Session;
}
@@ -244,7 +229,7 @@ public SshCommand CreateCommand(string commandText)
/// object which uses specified encoding.
/// This method will change current default encoding.
/// Client is not connected.
- /// or is null.
+ /// or is .
public SshCommand CreateCommand(string commandText, Encoding encoding)
{
EnsureSessionIsOpen();
@@ -259,19 +244,15 @@ public SshCommand CreateCommand(string commandText, Encoding encoding)
/// The command text.
/// Returns an instance of with execution results.
/// This method internally uses asynchronous calls.
- ///
- ///
- ///
- ///
/// CommandText property is empty.
- /// Invalid Operation - An existing channel was used to execute this command.
+ /// Invalid Operation - An existing channel was used to execute this command.
/// Asynchronous operation is already in progress.
/// Client is not connected.
- /// is null.
+ /// is .
public SshCommand RunCommand(string commandText)
{
var cmd = CreateCommand(commandText);
- cmd.Execute();
+ _ = cmd.Execute();
return cmd;
}
@@ -332,7 +313,7 @@ public Shell CreateShell(Stream input, Stream output, Stream extendedOutput, str
/// Client is not connected.
public Shell CreateShell(Stream input, Stream output, Stream extendedOutput)
{
- return CreateShell(input, output, extendedOutput, string.Empty, 0, 0, 0, 0, null, 1024);
+ return CreateShell(input, output, extendedOutput, string.Empty, 0, 0, 0, 0, terminalModes: null, 1024);
}
///
@@ -355,13 +336,19 @@ public Shell CreateShell(Stream input, Stream output, Stream extendedOutput)
/// Client is not connected.
public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary terminalModes, int bufferSize)
{
- // TODO let shell dispose of input stream when we own the stream!
+ /*
+ * TODO Issue #1224: let shell dispose of input stream when we own the stream!
+ */
_inputStream = new MemoryStream();
- var writer = new StreamWriter(_inputStream, encoding);
- writer.Write(input);
- writer.Flush();
- _inputStream.Seek(0, SeekOrigin.Begin);
+
+ using (var writer = new StreamWriter(_inputStream, encoding, bufferSize: 1024, leaveOpen: true))
+ {
+ writer.Write(input);
+ writer.Flush();
+ }
+
+ _ = _inputStream.Seek(0, SeekOrigin.Begin);
return CreateShell(_inputStream, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize);
}
@@ -401,7 +388,7 @@ public Shell CreateShell(Encoding encoding, string input, Stream output, Stream
/// Client is not connected.
public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput)
{
- return CreateShell(encoding, input, output, extendedOutput, string.Empty, 0, 0, 0, 0, null, 1024);
+ return CreateShell(encoding, input, output, extendedOutput, string.Empty, 0, 0, 0, 0, terminalModes: null, 1024);
}
///
@@ -410,7 +397,7 @@ public Shell CreateShell(Encoding encoding, string input, Stream output, Stream
/// The TERM environment variable.
/// The terminal width in columns.
/// The terminal width in rows.
- /// The terminal height in pixels.
+ /// The terminal width in pixels.
/// The terminal height in pixels.
/// The size of the buffer.
///
@@ -429,7 +416,7 @@ public Shell CreateShell(Encoding encoding, string input, Stream output, Stream
///
public ShellStream CreateShellStream(string terminalName, uint columns, uint rows, uint width, uint height, int bufferSize)
{
- return CreateShellStream(terminalName, columns, rows, width, height, bufferSize, null);
+ return CreateShellStream(terminalName, columns, rows, width, height, bufferSize, terminalModeValues: null);
}
///
@@ -438,7 +425,7 @@ public ShellStream CreateShellStream(string terminalName, uint columns, uint row
/// The TERM environment variable.
/// The terminal width in columns.
/// The terminal width in rows.
- /// The terminal height in pixels.
+ /// The terminal width in pixels.
/// The terminal height in pixels.
/// The size of the buffer.
/// The terminal mode values.
@@ -479,15 +466,17 @@ protected override void OnDisconnected()
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -503,8 +492,10 @@ protected override void Dispose(bool disposing)
private void EnsureSessionIsOpen()
{
- if (Session == null)
+ if (Session is null)
+ {
throw new SshConnectionException("Client not connected.");
+ }
}
}
}
diff --git a/src/Renci.SshNet/SshCommand.cs b/src/Renci.SshNet/SshCommand.cs
index 37e91da08..a7769ab2c 100644
--- a/src/Renci.SshNet/SshCommand.cs
+++ b/src/Renci.SshNet/SshCommand.cs
@@ -1,13 +1,15 @@
using System;
+using System.Globalization;
using System.IO;
+using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
+
+using Renci.SshNet.Abstractions;
using Renci.SshNet.Channels;
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Connection;
using Renci.SshNet.Messages.Transport;
-using System.Globalization;
-using Renci.SshNet.Abstractions;
namespace Renci.SshNet
{
@@ -16,15 +18,19 @@ namespace Renci.SshNet
///
public class SshCommand : IDisposable
{
- private ISession _session;
private readonly Encoding _encoding;
+ private readonly object _endExecuteLock = new object();
+
+ private ISession _session;
private IChannelSession _channel;
private CommandAsyncResult _asyncResult;
private AsyncCallback _callback;
private EventWaitHandle _sessionErrorOccuredWaitHandle;
private Exception _exception;
+ private StringBuilder _result;
+ private StringBuilder _error;
private bool _hasError;
- private readonly object _endExecuteLock = new object();
+ private bool _isDisposed;
///
/// Gets the command text.
@@ -37,89 +43,78 @@ public class SshCommand : IDisposable
///
/// The command timeout.
///
- ///
- ///
- ///
public TimeSpan CommandTimeout { get; set; }
///
/// Gets the command exit status.
///
- ///
- ///
- ///
public int ExitStatus { get; private set; }
///
/// Gets the output stream.
///
- ///
- ///
- ///
+#pragma warning disable CA1859 // Use concrete types when possible for improved performance
public Stream OutputStream { get; private set; }
+#pragma warning restore CA1859 // Use concrete types when possible for improved performance
///
/// Gets the extended output stream.
///
- ///
- ///
- ///
+#pragma warning disable CA1859 // Use concrete types when possible for improved performance
public Stream ExtendedOutputStream { get; private set; }
+#pragma warning restore CA1859 // Use concrete types when possible for improved performance
- private StringBuilder _result;
///
/// Gets the command execution result.
///
- ///
- ///
- ///
public string Result
{
get
{
- if (_result == null)
- {
- _result = new StringBuilder();
- }
+ _result ??= new StringBuilder();
if (OutputStream != null && OutputStream.Length > 0)
{
- // do not dispose the StreamReader, as it would also dispose the stream
- var sr = new StreamReader(OutputStream, _encoding);
- _result.Append(sr.ReadToEnd());
+ using (var sr = new StreamReader(OutputStream,
+ _encoding,
+ detectEncodingFromByteOrderMarks: true,
+ bufferSize: 1024,
+ leaveOpen: true))
+ {
+ _ = _result.Append(sr.ReadToEnd());
+ }
}
return _result.ToString();
}
}
- private StringBuilder _error;
///
/// Gets the command execution error.
///
- ///
- ///
- ///
public string Error
{
get
{
if (_hasError)
{
- if (_error == null)
- {
- _error = new StringBuilder();
- }
+ _error ??= new StringBuilder();
if (ExtendedOutputStream != null && ExtendedOutputStream.Length > 0)
{
- // do not dispose the StreamReader, as it would also dispose the stream
- var sr = new StreamReader(ExtendedOutputStream, _encoding);
- _error.Append(sr.ReadToEnd());
+ using (var sr = new StreamReader(ExtendedOutputStream,
+ _encoding,
+ detectEncodingFromByteOrderMarks: true,
+ bufferSize: 1024,
+ leaveOpen: true))
+ {
+ _ = _error.Append(sr.ReadToEnd());
+ }
}
return _error.ToString();
}
+
return string.Empty;
}
}
@@ -130,21 +125,29 @@ public string Error
/// The session.
/// The command text.
/// The encoding to use for the results.
- /// Either , is null.
+ /// Either , is .
internal SshCommand(ISession session, string commandText, Encoding encoding)
{
- if (session == null)
- throw new ArgumentNullException("session");
- if (commandText == null)
- throw new ArgumentNullException("commandText");
- if (encoding == null)
- throw new ArgumentNullException("encoding");
+ if (session is null)
+ {
+ throw new ArgumentNullException(nameof(session));
+ }
+
+ if (commandText is null)
+ {
+ throw new ArgumentNullException(nameof(commandText));
+ }
+
+ if (encoding is null)
+ {
+ throw new ArgumentNullException(nameof(encoding));
+ }
_session = session;
CommandText = commandText;
_encoding = encoding;
CommandTimeout = Session.InfiniteTimeSpan;
- _sessionErrorOccuredWaitHandle = new AutoResetEvent(false);
+ _sessionErrorOccuredWaitHandle = new AutoResetEvent(initialState: false);
_session.Disconnected += Session_Disconnected;
_session.ErrorOccured += Session_ErrorOccured;
@@ -154,21 +157,16 @@ internal SshCommand(ISession session, string commandText, Encoding encoding)
/// Begins an asynchronous command execution.
///
///
- /// An that represents the asynchronous command execution, which could still be pending.
+ /// An that represents the asynchronous command execution, which could still be pending.
///
- ///
- ///
- ///
/// Asynchronous operation is already in progress.
/// Invalid operation.
/// CommandText property is empty.
/// Client is not connected.
/// Operation has timed out.
- /// Asynchronous operation is already in progress.
- /// CommandText property is empty.
public IAsyncResult BeginExecute()
{
- return BeginExecute(null, null);
+ return BeginExecute(callback: null, state: null);
}
///
@@ -176,18 +174,16 @@ public IAsyncResult BeginExecute()
///
/// An optional asynchronous callback, to be called when the command execution is complete.
///
- /// An that represents the asynchronous command execution, which could still be pending.
+ /// An that represents the asynchronous command execution, which could still be pending.
///
/// Asynchronous operation is already in progress.
/// Invalid operation.
/// CommandText property is empty.
/// Client is not connected.
/// Operation has timed out.
- /// Asynchronous operation is already in progress.
- /// CommandText property is empty.
public IAsyncResult BeginExecute(AsyncCallback callback)
{
- return BeginExecute(callback, null);
+ return BeginExecute(callback, state: null);
}
///
@@ -203,48 +199,50 @@ public IAsyncResult BeginExecute(AsyncCallback callback)
/// CommandText property is empty.
/// Client is not connected.
/// Operation has timed out.
- /// Asynchronous operation is already in progress.
- /// CommandText property is empty.
+#pragma warning disable CA1859 // Use concrete types when possible for improved performance
public IAsyncResult BeginExecute(AsyncCallback callback, object state)
+#pragma warning restore CA1859 // Use concrete types when possible for improved performance
{
- // Prevent from executing BeginExecute before calling EndExecute
+ // Prevent from executing BeginExecute before calling EndExecute
if (_asyncResult != null && !_asyncResult.EndCalled)
{
throw new InvalidOperationException("Asynchronous operation is already in progress.");
}
- // Create new AsyncResult object
+ // Create new AsyncResult object
_asyncResult = new CommandAsyncResult
{
- AsyncWaitHandle = new ManualResetEvent(false),
+ AsyncWaitHandle = new ManualResetEvent(initialState: false),
IsCompleted = false,
AsyncState = state,
};
- // When command re-executed again, create a new channel
- if (_channel != null)
+ // When command re-executed again, create a new channel
+ if (_channel is not null)
{
throw new SshException("Invalid operation.");
}
if (string.IsNullOrEmpty(CommandText))
+ {
throw new ArgumentException("CommandText property is empty.");
+ }
var outputStream = OutputStream;
- if (outputStream != null)
+ if (outputStream is not null)
{
outputStream.Dispose();
OutputStream = null;
}
var extendedOutputStream = ExtendedOutputStream;
- if (extendedOutputStream != null)
+ if (extendedOutputStream is not null)
{
extendedOutputStream.Dispose();
ExtendedOutputStream = null;
}
- // Initialize output streams
+ // Initialize output streams
OutputStream = new PipeStream();
ExtendedOutputStream = new PipeStream();
@@ -254,7 +252,7 @@ public IAsyncResult BeginExecute(AsyncCallback callback, object state)
_channel = CreateChannel();
_channel.Open();
- _channel.SendExecRequest(CommandText);
+ _ = _channel.SendExecRequest(CommandText);
return _asyncResult;
}
@@ -266,10 +264,10 @@ public IAsyncResult BeginExecute(AsyncCallback callback, object state)
/// An optional asynchronous callback, to be called when the command execution is complete.
/// A user-provided object that distinguishes this particular asynchronous read request from other requests.
///
- /// An that represents the asynchronous command execution, which could still be pending.
+ /// An that represents the asynchronous command execution, which could still be pending.
///
- /// Client is not connected.
- /// Operation has timed out.
+ /// Client is not connected.
+ /// Operation has timed out.
public IAsyncResult BeginExecute(string commandText, AsyncCallback callback, object state)
{
CommandText = commandText;
@@ -282,22 +280,18 @@ public IAsyncResult BeginExecute(string commandText, AsyncCallback callback, obj
///
/// The reference to the pending asynchronous request to finish.
/// Command execution result.
- ///
- ///
- ///
/// Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.
- /// is null.
+ /// is .
public string EndExecute(IAsyncResult asyncResult)
{
- if (asyncResult == null)
+ if (asyncResult is null)
{
- throw new ArgumentNullException("asyncResult");
+ throw new ArgumentNullException(nameof(asyncResult));
}
- var commandAsyncResult = asyncResult as CommandAsyncResult;
- if (commandAsyncResult == null || _asyncResult != commandAsyncResult)
+ if (asyncResult is not CommandAsyncResult commandAsyncResult || _asyncResult != commandAsyncResult)
{
- throw new ArgumentException(string.Format("The {0} object was not returned from the corresponding asynchronous method on this class.", typeof(IAsyncResult).Name));
+ throw new ArgumentException(string.Format("The {0} object was not returned from the corresponding asynchronous method on this class.", nameof(IAsyncResult)));
}
lock (_endExecuteLock)
@@ -307,7 +301,7 @@ public string EndExecute(IAsyncResult asyncResult)
throw new ArgumentException("EndExecute can only be called once for each asynchronous operation.");
}
- // wait for operation to complete (or time out)
+ // wait for operation to complete (or time out)
WaitOnHandle(_asyncResult.AsyncWaitHandle);
UnsubscribeFromEventsAndDisposeChannel(_channel);
@@ -320,40 +314,39 @@ public string EndExecute(IAsyncResult asyncResult)
}
///
- /// Executes command specified by property.
- ///
- /// Command execution result
- ///
- ///
- ///
- ///
- ///
- /// Client is not connected.
- /// Operation has timed out.
- public string Execute()
- {
- return EndExecute(BeginExecute(null, null));
- }
-
- ///
- /// Cancels command execution in asynchronous scenarios.
+ /// Cancels command execution in asynchronous scenarios.
///
public void CancelAsync()
{
- if (_channel != null && _channel.IsOpen && _asyncResult != null)
+ if (_channel is not null && _channel.IsOpen && _asyncResult is not null)
{
// TODO: check with Oleg if we shouldn't dispose the channel and uninitialize it ?
_channel.Dispose();
}
}
+ ///
+ /// Executes command specified by property.
+ ///
+ ///
+ /// Command execution result.
+ ///
+ /// Client is not connected.
+ /// Operation has timed out.
+ public string Execute()
+ {
+ return EndExecute(BeginExecute(callback: null, state: null));
+ }
+
///
/// Executes the specified command text.
///
/// The command text.
- /// Command execution result
- /// Client is not connected.
- /// Operation has timed out.
+ ///
+ /// The result of the command execution.
+ ///
+ /// Client is not connected.
+ /// Operation has timed out.
public string Execute(string commandText)
{
CommandText = commandText;
@@ -373,54 +366,49 @@ private IChannelSession CreateChannel()
private void Session_Disconnected(object sender, EventArgs e)
{
- // If objected is disposed or being disposed don't handle this event
+ // If objected is disposed or being disposed don't handle this event
if (_isDisposed)
+ {
return;
+ }
_exception = new SshConnectionException("An established connection was aborted by the software in your host machine.", DisconnectReason.ConnectionLost);
- _sessionErrorOccuredWaitHandle.Set();
+ _ = _sessionErrorOccuredWaitHandle.Set();
}
private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
{
- // If objected is disposed or being disposed don't handle this event
+ // If objected is disposed or being disposed don't handle this event
if (_isDisposed)
+ {
return;
+ }
_exception = e.Exception;
- _sessionErrorOccuredWaitHandle.Set();
+ _ = _sessionErrorOccuredWaitHandle.Set();
}
private void Channel_Closed(object sender, ChannelEventArgs e)
{
- var outputStream = OutputStream;
- if (outputStream != null)
- {
- outputStream.Flush();
- }
-
- var extendedOutputStream = ExtendedOutputStream;
- if (extendedOutputStream != null)
- {
- extendedOutputStream.Flush();
- }
+ OutputStream?.Flush();
+ ExtendedOutputStream?.Flush();
_asyncResult.IsCompleted = true;
- if (_callback != null)
+ if (_callback is not null)
{
- // Execute callback on different thread
+ // Execute callback on different thread
ThreadAbstraction.ExecuteThread(() => _callback(_asyncResult));
}
- ((EventWaitHandle) _asyncResult.AsyncWaitHandle).Set();
+
+ _ = ((EventWaitHandle) _asyncResult.AsyncWaitHandle).Set();
}
private void Channel_RequestReceived(object sender, ChannelRequestEventArgs e)
{
- var exitStatusInfo = e.Info as ExitStatusRequestInfo;
- if (exitStatusInfo != null)
+ if (e.Info is ExitStatusRequestInfo exitStatusInfo)
{
ExitStatus = (int) exitStatusInfo.ExitStatus;
@@ -481,12 +469,19 @@ private void WaitOnHandle(WaitHandle waitHandle)
waitHandle
};
- switch (WaitHandle.WaitAny(waitHandles, CommandTimeout))
+ var signaledElement = WaitHandle.WaitAny(waitHandles, CommandTimeout);
+ switch (signaledElement)
{
case 0:
- throw _exception;
+ ExceptionDispatchInfo.Capture(_exception).Throw();
+ break;
+ case 1:
+ // Specified waithandle was signaled
+ break;
case WaitHandle.WaitTimeout:
throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Command '{0}' has timed out.", CommandText));
+ default:
+ throw new SshException($"Unexpected element '{signaledElement.ToString(CultureInfo.InvariantCulture)}' signaled.");
}
}
@@ -496,12 +491,14 @@ private void WaitOnHandle(WaitHandle waitHandle)
///
/// The channel.
///
- /// Does nothing when is null.
+ /// Does nothing when is .
///
private void UnsubscribeFromEventsAndDisposeChannel(IChannel channel)
{
- if (channel == null)
+ if (channel is null)
+ {
return;
+ }
// unsubscribe from events as we do not want to be signaled should these get fired
// during the dispose of the channel
@@ -514,27 +511,25 @@ private void UnsubscribeFromEventsAndDisposeChannel(IChannel channel)
channel.Dispose();
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -583,14 +578,13 @@ protected virtual void Dispose(bool disposing)
}
///
+ /// Finalizes an instance of the class.
/// Releases unmanaged resources and performs other cleanup operations before the
/// is reclaimed by garbage collection.
///
~SshCommand()
{
- Dispose(false);
+ Dispose(disposing: false);
}
-
- #endregion
}
}
diff --git a/src/Renci.SshNet/SshMessageFactory.cs b/src/Renci.SshNet/SshMessageFactory.cs
index 153024dbf..efa861256 100644
--- a/src/Renci.SshNet/SshMessageFactory.cs
+++ b/src/Renci.SshNet/SshMessageFactory.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
+
using Renci.SshNet.Common;
using Renci.SshNet.Messages;
using Renci.SshNet.Messages.Authentication;
@@ -9,13 +10,48 @@
namespace Renci.SshNet
{
- internal class SshMessageFactory
+ internal sealed class SshMessageFactory
{
private readonly MessageMetadata[] _enabledMessagesByNumber;
private readonly bool[] _activatedMessagesById;
+ private readonly object _lock = new object();
- internal static readonly MessageMetadata[] AllMessages;
- private static readonly IDictionary MessagesByName;
+ private static readonly MessageMetadata[] AllMessages = new MessageMetadata[]
+ {
+ new MessageMetadata(0, "SSH_MSG_KEXINIT", 20),
+ new MessageMetadata(1, "SSH_MSG_NEWKEYS", 21),
+ new MessageMetadata(2, "SSH_MSG_REQUEST_FAILURE", 82),
+ new MessageMetadata(3, "SSH_MSG_CHANNEL_OPEN_FAILURE", 92),
+ new MessageMetadata(4, "SSH_MSG_CHANNEL_FAILURE", 100),
+ new MessageMetadata(5, "SSH_MSG_CHANNEL_EXTENDED_DATA", 95),
+ new MessageMetadata(6, "SSH_MSG_CHANNEL_DATA", 94),
+ new MessageMetadata(7, "SSH_MSG_CHANNEL_REQUEST", 98),
+ new MessageMetadata(8, "SSH_MSG_USERAUTH_BANNER", 53),
+ new MessageMetadata(9, "SSH_MSG_USERAUTH_INFO_RESPONSE", 61),
+ new MessageMetadata(10, "SSH_MSG_USERAUTH_FAILURE", 51),
+ new MessageMetadata(11, "SSH_MSG_DEBUG", 4),
+ new MessageMetadata(12, "SSH_MSG_GLOBAL_REQUEST", 80),
+ new MessageMetadata(13, "SSH_MSG_CHANNEL_OPEN", 90),
+ new MessageMetadata(14, "SSH_MSG_CHANNEL_OPEN_CONFIRMATION", 91),
+ new MessageMetadata(15, "SSH_MSG_USERAUTH_INFO_REQUEST", 60),
+ new MessageMetadata(16, "SSH_MSG_UNIMPLEMENTED", 3),
+ new MessageMetadata(17, "SSH_MSG_REQUEST_SUCCESS", 81),
+ new MessageMetadata(18, "SSH_MSG_CHANNEL_SUCCESS", 99),
+ new MessageMetadata(19, "SSH_MSG_USERAUTH_PASSWD_CHANGEREQ", 60),
+ new MessageMetadata(20, "SSH_MSG_DISCONNECT", 1),
+ new MessageMetadata(21, "SSH_MSG_USERAUTH_SUCCESS", 52),
+ new MessageMetadata(22, "SSH_MSG_USERAUTH_PK_OK", 60),
+ new MessageMetadata(23, "SSH_MSG_IGNORE", 2),
+ new MessageMetadata(24, "SSH_MSG_CHANNEL_WINDOW_ADJUST", 93),
+ new MessageMetadata(25, "SSH_MSG_CHANNEL_EOF", 96),
+ new MessageMetadata(26, "SSH_MSG_CHANNEL_CLOSE", 97),
+ new MessageMetadata(27, "SSH_MSG_SERVICE_ACCEPT", 6),
+ new MessageMetadata(28, "SSH_MSG_KEX_DH_GEX_GROUP", 31),
+ new MessageMetadata(29, "SSH_MSG_KEXDH_REPLY", 31),
+ new MessageMetadata(30, "SSH_MSG_KEX_DH_GEX_REPLY", 33),
+ new MessageMetadata(31, "SSH_MSG_KEX_ECDH_REPLY", 31)
+ };
+ private static readonly Dictionary MessagesByName = CreateMessagesByNameMapping();
///
/// Defines the highest message number that is currently supported.
@@ -27,52 +63,9 @@ internal class SshMessageFactory
///
internal const int TotalMessageCount = 32;
- static SshMessageFactory()
- {
- AllMessages = new MessageMetadata[]
- {
- new MessageMetadata(0, "SSH_MSG_KEXINIT", 20),
- new MessageMetadata (1, "SSH_MSG_NEWKEYS", 21),
- new MessageMetadata (2, "SSH_MSG_REQUEST_FAILURE", 82),
- new MessageMetadata (3, "SSH_MSG_CHANNEL_OPEN_FAILURE", 92),
- new MessageMetadata (4, "SSH_MSG_CHANNEL_FAILURE", 100),
- new MessageMetadata (5, "SSH_MSG_CHANNEL_EXTENDED_DATA", 95),
- new MessageMetadata (6, "SSH_MSG_CHANNEL_DATA", 94),
- new MessageMetadata (7, "SSH_MSG_CHANNEL_REQUEST", 98),
- new MessageMetadata (8, "SSH_MSG_USERAUTH_BANNER", 53),
- new MessageMetadata (9, "SSH_MSG_USERAUTH_INFO_RESPONSE", 61),
- new MessageMetadata (10, "SSH_MSG_USERAUTH_FAILURE", 51),
- new MessageMetadata (11, "SSH_MSG_DEBUG", 4),
- new MessageMetadata (12, "SSH_MSG_GLOBAL_REQUEST", 80),
- new MessageMetadata (13, "SSH_MSG_CHANNEL_OPEN", 90),
- new MessageMetadata (14, "SSH_MSG_CHANNEL_OPEN_CONFIRMATION", 91),
- new MessageMetadata (15, "SSH_MSG_USERAUTH_INFO_REQUEST", 60),
- new MessageMetadata (16, "SSH_MSG_UNIMPLEMENTED", 3),
- new MessageMetadata (17, "SSH_MSG_REQUEST_SUCCESS", 81),
- new MessageMetadata (18, "SSH_MSG_CHANNEL_SUCCESS", 99),
- new MessageMetadata (19, "SSH_MSG_USERAUTH_PASSWD_CHANGEREQ", 60),
- new MessageMetadata (20, "SSH_MSG_DISCONNECT", 1),
- new MessageMetadata (21, "SSH_MSG_USERAUTH_SUCCESS", 52),
- new MessageMetadata (22, "SSH_MSG_USERAUTH_PK_OK", 60),
- new MessageMetadata (23, "SSH_MSG_IGNORE", 2),
- new MessageMetadata (24, "SSH_MSG_CHANNEL_WINDOW_ADJUST", 93),
- new MessageMetadata (25, "SSH_MSG_CHANNEL_EOF", 96),
- new MessageMetadata (26, "SSH_MSG_CHANNEL_CLOSE", 97),
- new MessageMetadata (27, "SSH_MSG_SERVICE_ACCEPT", 6),
- new MessageMetadata (28, "SSH_MSG_KEX_DH_GEX_GROUP", 31),
- new MessageMetadata (29, "SSH_MSG_KEXDH_REPLY", 31),
- new MessageMetadata (30, "SSH_MSG_KEX_DH_GEX_REPLY", 33),
- new MessageMetadata (31, "SSH_MSG_KEX_ECDH_REPLY", 31)
- };
-
- MessagesByName = new Dictionary(AllMessages.Length);
- for (var i = 0; i < AllMessages.Length; i++)
- {
- var messageMetadata = AllMessages[i];
- MessagesByName.Add(messageMetadata.Name, messageMetadata);
- }
- }
-
+ ///
+ /// Initializes a new instance of the class.
+ ///
public SshMessageFactory()
{
_activatedMessagesById = new bool[TotalMessageCount];
@@ -96,7 +89,7 @@ public Message Create(byte messageNumber)
}
var enabledMessageMetadata = _enabledMessagesByNumber[messageNumber];
- if (enabledMessageMetadata == null)
+ if (enabledMessageMetadata is null)
{
MessageMetadata definedMessageMetadata = null;
@@ -111,7 +104,7 @@ public Message Create(byte messageNumber)
}
}
- if (definedMessageMetadata == null)
+ if (definedMessageMetadata is null)
{
throw CreateMessageTypeNotSupportedException(messageNumber);
}
@@ -129,7 +122,7 @@ public void DisableNonKeyExchangeMessages()
var messageMetadata = AllMessages[i];
var messageNumber = messageMetadata.Number;
- if ((messageNumber > 2 && messageNumber < 20) || messageNumber > 30)
+ if (messageNumber is (> 2 and < 20) or > 30)
{
_enabledMessagesByNumber[messageNumber] = null;
}
@@ -143,29 +136,32 @@ public void EnableActivatedMessages()
var messageMetadata = AllMessages[i];
if (!_activatedMessagesById[messageMetadata.Id])
+ {
continue;
+ }
var enabledMessageMetadata = _enabledMessagesByNumber[messageMetadata.Number];
if (enabledMessageMetadata != null && enabledMessageMetadata != messageMetadata)
{
throw CreateMessageTypeAlreadyEnabledForOtherMessageException(messageMetadata.Number,
- messageMetadata.Name,
- enabledMessageMetadata.Name);
+ messageMetadata.Name,
+ enabledMessageMetadata.Name);
}
+
_enabledMessagesByNumber[messageMetadata.Number] = messageMetadata;
}
}
public void EnableAndActivateMessage(string messageName)
{
- if (messageName == null)
- throw new ArgumentNullException("messageName");
-
- lock (this)
+ if (messageName is null)
{
- MessageMetadata messageMetadata;
+ throw new ArgumentNullException(nameof(messageName));
+ }
- if (!MessagesByName.TryGetValue(messageName, out messageMetadata))
+ lock (_lock)
+ {
+ if (!MessagesByName.TryGetValue(messageName, out var messageMetadata))
{
throw CreateMessageNotSupportedException(messageName);
}
@@ -185,14 +181,14 @@ public void EnableAndActivateMessage(string messageName)
public void DisableAndDeactivateMessage(string messageName)
{
- if (messageName == null)
- throw new ArgumentNullException("messageName");
-
- lock (this)
+ if (messageName is null)
{
- MessageMetadata messageMetadata;
+ throw new ArgumentNullException(nameof(messageName));
+ }
- if (!MessagesByName.TryGetValue(messageName, out messageMetadata))
+ lock (_lock)
+ {
+ if (!MessagesByName.TryGetValue(messageName, out var messageMetadata))
{
throw CreateMessageNotSupportedException(messageName);
}
@@ -201,8 +197,8 @@ public void DisableAndDeactivateMessage(string messageName)
if (enabledMessageMetadata != null && enabledMessageMetadata != messageMetadata)
{
throw CreateMessageTypeAlreadyEnabledForOtherMessageException(messageMetadata.Number,
- messageMetadata.Name,
- enabledMessageMetadata.Name);
+ messageMetadata.Name,
+ enabledMessageMetadata.Name);
}
_activatedMessagesById[messageMetadata.Id] = false;
@@ -210,6 +206,19 @@ public void DisableAndDeactivateMessage(string messageName)
}
}
+ private static Dictionary CreateMessagesByNameMapping()
+ {
+ var messagesByName = new Dictionary(AllMessages.Length);
+
+ for (var i = 0; i < AllMessages.Length; i++)
+ {
+ var messageMetadata = AllMessages[i];
+ messagesByName.Add(messageMetadata.Name, messageMetadata);
+ }
+
+ return messagesByName;
+ }
+
private static SshException CreateMessageTypeNotSupportedException(byte messageNumber)
{
throw new SshException(string.Format(CultureInfo.InvariantCulture, "Message type {0} is not supported.", messageNumber));
@@ -223,11 +232,13 @@ private static SshException CreateMessageNotSupportedException(string messageNam
private static SshException CreateMessageTypeAlreadyEnabledForOtherMessageException(byte messageNumber, string messageName, string currentEnabledForMessageName)
{
throw new SshException(string.Format(CultureInfo.InvariantCulture,
- "Cannot enable message '{0}'. Message type {1} is already enabled for '{2}'.",
- messageName, messageNumber, currentEnabledForMessageName));
+ "Cannot enable message '{0}'. Message type {1} is already enabled for '{2}'.",
+ messageName,
+ messageNumber,
+ currentEnabledForMessageName));
}
- internal abstract class MessageMetadata
+ private abstract class MessageMetadata
{
protected MessageMetadata(byte id, string name, byte number)
{
@@ -236,16 +247,17 @@ protected MessageMetadata(byte id, string name, byte number)
Number = number;
}
- public readonly byte Id;
+ public byte Id { get; }
- public readonly string Name;
+ public string Name { get; }
- public readonly byte Number;
+ public byte Number { get; }
public abstract Message Create();
}
- internal class MessageMetadata : MessageMetadata where T : Message, new()
+ private sealed class MessageMetadata : MessageMetadata
+ where T : Message, new()
{
public MessageMetadata(byte id, string name, byte number)
: base(id, name, number)
diff --git a/src/Renci.SshNet/SubsystemSession.cs b/src/Renci.SshNet/SubsystemSession.cs
index 943a2db9e..70385d903 100644
--- a/src/Renci.SshNet/SubsystemSession.cs
+++ b/src/Renci.SshNet/SubsystemSession.cs
@@ -1,6 +1,8 @@
using System;
using System.Globalization;
+using System.Runtime.ExceptionServices;
using System.Threading;
+
using Renci.SshNet.Abstractions;
using Renci.SshNet.Channels;
using Renci.SshNet.Common;
@@ -8,7 +10,7 @@
namespace Renci.SshNet
{
///
- /// Base class for SSH subsystem implementations
+ /// Base class for SSH subsystem implementations.
///
internal abstract class SubsystemSession : ISubsystemSession
{
@@ -18,13 +20,14 @@ internal abstract class SubsystemSession : ISubsystemSession
///
private const int SystemWaitHandleCount = 3;
- private ISession _session;
private readonly string _subsystemName;
+ private ISession _session;
private IChannelSession _channel;
private Exception _exception;
- private EventWaitHandle _errorOccuredWaitHandle = new ManualResetEvent(false);
- private EventWaitHandle _sessionDisconnectedWaitHandle = new ManualResetEvent(false);
- private EventWaitHandle _channelClosedWaitHandle = new ManualResetEvent(false);
+ private EventWaitHandle _errorOccuredWaitHandle = new ManualResetEvent(initialState: false);
+ private EventWaitHandle _sessionDisconnectedWaitHandle = new ManualResetEvent(initialState: false);
+ private EventWaitHandle _channelClosedWaitHandle = new ManualResetEvent(initialState: false);
+ private bool _isDisposed;
///
/// Gets or set the number of seconds to wait for an operation to complete.
@@ -64,26 +67,31 @@ internal IChannelSession Channel
/// Gets a value indicating whether this session is open.
///
///
- /// true if this session is open; otherwise, false.
+ /// if this session is open; otherwise, .
///
public bool IsOpen
{
- get { return _channel != null && _channel.IsOpen; }
+ get { return _channel is not null && _channel.IsOpen; }
}
///
- /// Initializes a new instance of the SubsystemSession class.
+ /// Initializes a new instance of the class.
///
/// The session.
/// Name of the subsystem.
/// The number of milliseconds to wait for a given operation to complete, or -1 to wait indefinitely.
- /// or is null.
+ /// or is .
protected SubsystemSession(ISession session, string subsystemName, int operationTimeout)
{
- if (session == null)
- throw new ArgumentNullException("session");
- if (subsystemName == null)
- throw new ArgumentNullException("subsystemName");
+ if (session is null)
+ {
+ throw new ArgumentNullException(nameof(session));
+ }
+
+ if (subsystemName is null)
+ {
+ throw new ArgumentNullException(nameof(subsystemName));
+ }
_session = session;
_subsystemName = subsystemName;
@@ -101,13 +109,15 @@ public void Connect()
EnsureNotDisposed();
if (IsOpen)
+ {
throw new InvalidOperationException("The session is already connected.");
+ }
// reset waithandles in case we're reconnecting
- _errorOccuredWaitHandle.Reset();
- _sessionDisconnectedWaitHandle.Reset();
- _sessionDisconnectedWaitHandle.Reset();
- _channelClosedWaitHandle.Reset();
+ _ = _errorOccuredWaitHandle.Reset();
+ _ = _sessionDisconnectedWaitHandle.Reset();
+ _ = _sessionDisconnectedWaitHandle.Reset();
+ _ = _channelClosedWaitHandle.Reset();
_session.ErrorOccured += Session_ErrorOccured;
_session.Disconnected += Session_Disconnected;
@@ -122,6 +132,7 @@ public void Connect()
{
// close channel session
Disconnect();
+
// signal subsystem failure
throw new SshException(string.Format(CultureInfo.InvariantCulture,
"Subsystem '{0}' could not be executed.",
@@ -139,7 +150,7 @@ public void Disconnect()
UnsubscribeFromSessionEvents(_session);
var channel = _channel;
- if (channel != null)
+ if (channel is not null)
{
_channel = null;
channel.DataReceived -= Channel_DataReceived;
@@ -182,9 +193,7 @@ protected void RaiseError(Exception error)
DiagnosticAbstraction.Log("Raised exception: " + error);
- var errorOccuredWaitHandle = _errorOccuredWaitHandle;
- if (errorOccuredWaitHandle != null)
- errorOccuredWaitHandle.Set();
+ _ = _errorOccuredWaitHandle?.Set();
SignalErrorOccurred(error);
}
@@ -208,9 +217,7 @@ private void Channel_Exception(object sender, ExceptionEventArgs e)
private void Channel_Closed(object sender, ChannelEventArgs e)
{
- var channelClosedWaitHandle = _channelClosedWaitHandle;
- if (channelClosedWaitHandle != null)
- channelClosedWaitHandle.Set();
+ _ = _channelClosedWaitHandle?.Set();
}
///
@@ -235,7 +242,8 @@ public void WaitOnHandle(WaitHandle waitHandle, int millisecondsTimeout)
switch (result)
{
case 0:
- throw _exception;
+ ExceptionDispatchInfo.Capture(_exception).Throw();
+ break;
case 1:
throw new SshException("Connection was closed by the server.");
case 2:
@@ -256,8 +264,8 @@ public void WaitOnHandle(WaitHandle waitHandle, int millisecondsTimeout)
/// The handle to wait for.
/// To number of milliseconds to wait for to get signaled, or -1 to wait indefinitely.
///
- /// true if received a signal within the specified timeout;
- /// otherwise, false.
+ /// if received a signal within the specified timeout;
+ /// otherwise, .
///
/// The connection was closed by the server.
/// The channel was closed.
@@ -280,7 +288,8 @@ public bool WaitOne(WaitHandle waitHandle, int millisecondsTimeout)
switch (result)
{
case 0:
- throw _exception;
+ ExceptionDispatchInfo.Capture(_exception).Throw();
+ return false; // unreached
case 1:
throw new SshException("Connection was closed by the server.");
case 2:
@@ -298,12 +307,12 @@ public bool WaitOne(WaitHandle waitHandle, int millisecondsTimeout)
/// Blocks the current thread until the specified gets signaled, using a
/// 32-bit signed integer to specify the time interval in milliseconds.
///
- /// The first handle to wait for.
- /// The second handle to wait for.
+ /// The first handle to wait for.
+ /// The second handle to wait for.
/// To number of milliseconds to wait for a to get signaled, or -1 to wait indefinitely.
///
- /// 0 if received a signal within the specified timeout, and 1
- /// if received a signal within the specified timeout.
+ /// 0 if received a signal within the specified timeout, and 1
+ /// if received a signal within the specified timeout.
///
/// The connection was closed by the server.
/// The channel was closed.
@@ -315,26 +324,27 @@ public bool WaitOne(WaitHandle waitHandle, int millisecondsTimeout)
/// or session event.
///
///
- /// When both and are signaled during the call,
+ /// When both and are signaled during the call,
/// then 0 is returned.
///
///
- public int WaitAny(WaitHandle waitHandle1, WaitHandle waitHandle2, int millisecondsTimeout)
+ public int WaitAny(WaitHandle waitHandleA, WaitHandle waitHandleB, int millisecondsTimeout)
{
var waitHandles = new[]
{
_errorOccuredWaitHandle,
_sessionDisconnectedWaitHandle,
_channelClosedWaitHandle,
- waitHandle1,
- waitHandle2
+ waitHandleA,
+ waitHandleB
};
var result = WaitHandle.WaitAny(waitHandles, millisecondsTimeout);
switch (result)
{
case 0:
- throw _exception;
+ ExceptionDispatchInfo.Capture(_exception).Throw();
+ return -1; // unreached
case 1:
throw new SshException("Connection was closed by the server.");
case 2:
@@ -371,7 +381,8 @@ public int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout)
switch (result)
{
case 0:
- throw _exception;
+ ExceptionDispatchInfo.Capture(_exception).Throw();
+ return -1; // unreached
case 1:
throw new SshException("Connection was closed by the server.");
case 2:
@@ -429,9 +440,7 @@ public WaitHandle[] CreateWaitHandleArray(params WaitHandle[] waitHandles)
private void Session_Disconnected(object sender, EventArgs e)
{
- var sessionDisconnectedWaitHandle = _sessionDisconnectedWaitHandle;
- if (sessionDisconnectedWaitHandle != null)
- sessionDisconnectedWaitHandle.Set();
+ _ = _sessionDisconnectedWaitHandle?.Set();
SignalDisconnected();
}
@@ -443,26 +452,20 @@ private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
private void SignalErrorOccurred(Exception error)
{
- var errorOccurred = ErrorOccurred;
- if (errorOccurred != null)
- {
- errorOccurred(this, new ExceptionEventArgs(error));
- }
+ ErrorOccurred?.Invoke(this, new ExceptionEventArgs(error));
}
private void SignalDisconnected()
{
- var disconnected = Disconnected;
- if (disconnected != null)
- {
- disconnected(this, new EventArgs());
- }
+ Disconnected?.Invoke(this, EventArgs.Empty);
}
private void EnsureSessionIsOpen()
{
if (!IsOpen)
+ {
throw new InvalidOperationException("The session is not open.");
+ }
}
///
@@ -470,38 +473,38 @@ private void EnsureSessionIsOpen()
///
/// The session.
///
- /// Does nothing when is null.
+ /// Does nothing when is .
///
private void UnsubscribeFromSessionEvents(ISession session)
{
- if (session == null)
+ if (session is null)
+ {
return;
+ }
session.Disconnected -= Session_Disconnected;
session.ErrorOccured -= Session_ErrorOccured;
}
- #region IDisposable Members
-
- private bool _isDisposed;
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
- Dispose(true);
+ Dispose(disposing: true);
GC.SuppressFinalize(this);
}
///
- /// Releases unmanaged and - optionally - managed resources
+ /// Releases unmanaged and - optionally - managed resources.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
+ /// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
+ {
return;
+ }
if (disposing)
{
@@ -539,15 +542,19 @@ protected virtual void Dispose(bool disposing)
///
~SubsystemSession()
{
- Dispose(false);
+ Dispose(disposing: false);
}
private void EnsureNotDisposed()
{
+#if NET7_0_OR_GREATER
+ ObjectDisposedException.ThrowIf(_isDisposed, this);
+#else
if (_isDisposed)
+ {
throw new ObjectDisposedException(GetType().FullName);
+ }
+#endif // NET7_0_OR_GREATER
}
-
- #endregion
}
}
diff --git a/stylecop.json b/stylecop.json
new file mode 100644
index 000000000..ff7c9dbfb
--- /dev/null
+++ b/stylecop.json
@@ -0,0 +1,25 @@
+{
+ "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
+ "settings": {
+ "documentationRules": {
+ "xmlHeader": false,
+ "documentInternalElements": false
+ },
+ "layoutRules": {
+ "newlineAtEndOfFile": "require"
+ },
+ "indentation": {
+ "indentationSize": 4,
+ "tabSize": 4,
+ "useTabs": false
+ },
+ "namingRules": {
+ "allowCommonHungarianPrefixes": false
+ },
+ "orderingRules": {
+ "systemUsingDirectivesFirst": true,
+ "usingDirectivesPlacement": "outsideNamespace",
+ "blankLinesBetweenUsingGroups": "require"
+ }
+ }
+}
diff --git a/test/.editorconfig b/test/.editorconfig
new file mode 100644
index 000000000..d04fb3f83
--- /dev/null
+++ b/test/.editorconfig
@@ -0,0 +1,146 @@
+[*.cs]
+
+#### Sonar rules ####
+
+# S1215: ""GC.Collect" should not be called
+# https://rules.sonarsource.com/csharp/RSPEC-1215
+dotnet_diagnostic.S1215.severity = none
+
+# S1854: Unused assignments should be removed
+# https://rules.sonarsource.com/csharp/RSPEC-1854
+#
+# We sometimes increment the value of a variable on each use to make the code future-proof.
+#
+# For example:
+# int idSequence = 0;
+# var train1 = new Train { Id = ++idSequence };
+# var train2 = new Train { Id = ++idSequence };
+#
+# The increment of 'idSequence' in the last line will cause this diagnostic to be reported. We prefer to keep the increment to make
+# sure the value of the variable will remain correct when we introduce a 'train3'.
+#
+# For unit tests, we do not care about this diagnostic.
+dotnet_diagnostic.S1854.severity = none
+
+#### Meziantou.Analyzer rules ####
+
+# MA0089: Optimize string method usage
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0089.md
+dotnet_diagnostic.MA0089.severity = suggestion
+
+#MA0136 - Raw String contains an implicit end of line character
+dotnet_diagnostic.MA0136.severity = none
+
+#### StyleCop rules ####
+
+# SA1202: Elements must be ordered by access
+dotnet_diagnostic.SA1202.severity = none
+
+# SA1600: Elements must be documented
+#
+# For unit test projects, we do not care about documentation.
+dotnet_diagnostic.SA1600.severity = none
+
+# SA1601: Partial elements should be documented
+#
+# For unit test projects, we do not care about documentation.
+dotnet_diagnostic.SA1601.severity = none
+
+# SA1602: Enumeration items must be documented
+#
+# For unit test projects, we do not care about documentation.
+dotnet_diagnostic.SA1602.severity = none
+
+# SA1604: Element documentation should have summary
+#
+# TODO: Remove this when code has been updated!
+dotnet_diagnostic.SA1604.severity = none
+
+# SA1606: Element documentation should have summary text
+#
+# TODO: Remove this when code has been updated!
+dotnet_diagnostic.SA1606.severity = none
+
+# SA1607: Partial element documentation should have summary text
+#
+# For unit test projects, we do not care about documentation.
+dotnet_diagnostic.SA1607.severity = none
+
+# SA1611: Element parameters must be documented
+#
+# For unit test projects, we do not care about documentation.
+dotnet_diagnostic.SA1611.severity = none
+
+# SA1614: Element parameter documentation must have text
+#
+# TODO: Remove this when code has been updated!
+dotnet_diagnostic.SA1614.severity = none
+
+# SA1615: Element return value must be documented
+#
+# For unit test projects, we do not care about documentation.
+dotnet_diagnostic.SA1615.severity = none
+
+# SA1616: Element return value documentation should have text
+#
+# TODO: Remove this when code has been updated!
+dotnet_diagnostic.SA1616.severity = none
+
+# SA1623: Property summary documentation must match accessors
+#
+# TODO: Remove this when code has been updated!
+dotnet_diagnostic.SA1623.severity = none
+
+# SA1629: Documentation text must end with a period
+#
+# For unit test projects, we do not care about documentation.
+dotnet_diagnostic.SA1629.severity = none
+
+#### .NET Compiler Platform analysers rules ####
+
+# CA1001: Types that own disposable fields should be disposable
+#
+# We do not care about this for unit tests.
+dotnet_diagnostic.CA1001.severity = none
+
+# CA1707: Identifiers should not contain underscores
+#
+# We frequently use underscores in test classes and test methods.
+dotnet_diagnostic.CA1707.severity = none
+
+# CA1824: Mark assemblies with NeutralResourcesLanguageAttribute
+# https://learn.microsoft.com/en-US/dotnet/fundamentals/code-analysis/quality-rules/ca1824
+#
+# We do not care (much) about performance for tests.
+dotnet_diagnostic.CA1824.severity = none
+
+# CA1835: Prefer the memory-based overloads of ReadAsync/WriteAsync methods in stream-based classes
+# https://learn.microsoft.com/en-US/dotnet/fundamentals/code-analysis/quality-rules/ca1835
+#
+# We do not care about this for unit tests.
+dotnet_diagnostic.CA1835.severity = none
+
+# CA1711: Identifiers should not have incorrect suffix
+#
+# We frequently define test classes and test method with a suffix that refers to a type.
+dotnet_diagnostic.CA1711.severity = none
+
+# CA1720: Identifiers should not contain type names
+#
+# We do not care about this for unit tests.
+dotnet_diagnostic.CA1720.severity = none
+
+# CA1861: Avoid constant arrays as arguments
+#
+# We do not care about this for unit tests.
+dotnet_diagnostic.CA1861.severity = none
+
+# CA5351: Do not use broken cryptographic algorithms
+#
+# We do not care about this for unit tests.
+dotnet_diagnostic.CA5351.severity = none
+
+# CA5394: Do not use insecure randomness
+#
+# We do not care about this for unit tests.
+dotnet_diagnostic.CA5394.severity = none
diff --git a/test/Data/Key.DSA.pub b/test/Data/Key.DSA.pub
new file mode 100644
index 000000000..f32c6fae0
--- /dev/null
+++ b/test/Data/Key.DSA.pub
@@ -0,0 +1 @@
+ssh-dss AAAAB3NzaC1kc3MAAACBALVl3fae2O4qwsAK95SUShX0KMUNP+yl/uT3lGH9T/ZptnHSlrTxnTWXCl0g91KEeCaEnDDhLxm4aCv1Ag4B/yvcM4u34qkmaNLy2LiAxiqdobZcNG61Pqwqd5IDkp38LBsn8tmb12xu9NalpUfOiSEB1cyCr4zFZMrm0wtdyJQVAAAAFQCu+iNkqf/YOAYjYrHSCHFmWAfEYQAAAIAOVJ434UAR3Hn6lA5nWNfFOuUVH3W7nJaP0FQJiIPx7GUbdxO9qtDNTbWkWL3c9qx5+B7Ole4xM7cvyXPrNQUYDHCFlS+Ue2x3IeJrkdfZkH9ePP25y5A0J4/c+8XXvQaj4zA5nfw13oy5Ptyd7d3Kq5tEDM8KiVdIhwkXjUA3PQAAAIEAm8IGZQatS7M6AfNITNWG4TI7Z2aRQjLb9/MWJIID7c/VQ4zdTZdG3kpk0Gj9n4xreopK5NmYAdj8rtFfPBgmXltsLqt+bBcXkpxW//7WC29WOXW3t90ySTh+cWuWfr9fV7mf4Ql/6u/ZIgpQNvnNYezazt3fK8EXjI1dAXEuQxE=
diff --git a/test/Data/Key.DSA.txt b/test/Data/Key.DSA.txt
new file mode 100644
index 000000000..6c84e0c65
--- /dev/null
+++ b/test/Data/Key.DSA.txt
@@ -0,0 +1,12 @@
+-----BEGIN DSA PRIVATE KEY-----
+MIIBuwIBAAKBgQC1Zd32ntjuKsLACveUlEoV9CjFDT/spf7k95Rh/U/2abZx0pa0
+8Z01lwpdIPdShHgmhJww4S8ZuGgr9QIOAf8r3DOLt+KpJmjS8ti4gMYqnaG2XDRu
+tT6sKneSA5Kd/CwbJ/LZm9dsbvTWpaVHzokhAdXMgq+MxWTK5tMLXciUFQIVAK76
+I2Sp/9g4BiNisdIIcWZYB8RhAoGADlSeN+FAEdx5+pQOZ1jXxTrlFR91u5yWj9BU
+CYiD8exlG3cTvarQzU21pFi93PasefgezpXuMTO3L8lz6zUFGAxwhZUvlHtsdyHi
+a5HX2ZB/Xjz9ucuQNCeP3PvF170Go+MwOZ38Nd6MuT7cne3dyqubRAzPColXSIcJ
+F41ANz0CgYEAm8IGZQatS7M6AfNITNWG4TI7Z2aRQjLb9/MWJIID7c/VQ4zdTZdG
+3kpk0Gj9n4xreopK5NmYAdj8rtFfPBgmXltsLqt+bBcXkpxW//7WC29WOXW3t90y
+STh+cWuWfr9fV7mf4Ql/6u/ZIgpQNvnNYezazt3fK8EXjI1dAXEuQxECFBhGOzk+
+Aimeob964E8+HsQNlyde
+-----END DSA PRIVATE KEY-----
diff --git a/test/Data/Key.ECDSA.Encrypted.pub b/test/Data/Key.ECDSA.Encrypted.pub
new file mode 100644
index 000000000..17df3f932
--- /dev/null
+++ b/test/Data/Key.ECDSA.Encrypted.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOwUDIZhrxd1VJ7ByUuB25kdZlU0iCl/vru8VZcwmd0ROMLe0FruHkhG54JWTKcOxOOA1ITzEVXVTMpgN9ruRLs= imported-openssh-key
diff --git a/src/Renci.SshNet.Tests/Data/Key.ECDSA.Encrypted.txt b/test/Data/Key.ECDSA.Encrypted.txt
similarity index 89%
rename from src/Renci.SshNet.Tests/Data/Key.ECDSA.Encrypted.txt
rename to test/Data/Key.ECDSA.Encrypted.txt
index f0af5ba7d..405b4105c 100644
--- a/src/Renci.SshNet.Tests/Data/Key.ECDSA.Encrypted.txt
+++ b/test/Data/Key.ECDSA.Encrypted.txt
@@ -1,4 +1,4 @@
------BEGIN EC PRIVATE KEY-----
+-----BEGIN EC PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,54D46F498C989115AAE14FEA21E3AF11
diff --git a/test/Data/Key.ECDSA.pub b/test/Data/Key.ECDSA.pub
new file mode 100644
index 000000000..61919aa53
--- /dev/null
+++ b/test/Data/Key.ECDSA.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEA+TDv5/cqkg07M8M1aQKS8eUkBXnBOWXw5IMalXR0HnJtQQD6M2eHihjYSp+9oU+/Zi5afR11/qDRHLlU/Nx8= imported-openssh-key
diff --git a/src/Renci.SshNet.Tests/Data/Key.ECDSA.txt b/test/Data/Key.ECDSA.txt
similarity index 85%
rename from src/Renci.SshNet.Tests/Data/Key.ECDSA.txt
rename to test/Data/Key.ECDSA.txt
index 13ac9fb49..3c1c9ed81 100644
--- a/src/Renci.SshNet.Tests/Data/Key.ECDSA.txt
+++ b/test/Data/Key.ECDSA.txt
@@ -1,4 +1,4 @@
------BEGIN EC PRIVATE KEY-----
+-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIEdqaFKgJBIibVjyUh1v7Y35LwIQJrocdTaYFLwl7iB0oAoGCCqGSM49
AwEHoUQDQgAEQD5MO/n9yqSDTszwzVpApLx5SQFecE5ZfDkgxqVdHQecm1BAPozZ
4eKGNhKn72hT79mLlp9HXX+oNEcuVT83Hw==
diff --git a/test/Data/Key.ECDSA384.Encrypted.pub b/test/Data/Key.ECDSA384.Encrypted.pub
new file mode 100644
index 000000000..5131ee4c8
--- /dev/null
+++ b/test/Data/Key.ECDSA384.Encrypted.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBAKCegTbmw9KKkPpn6qMsTmPMp9yCr+xOyrRgQOFaToNzFq57mT1jxfIXRL0wyAgINVGNTyHpS2sMalvOYD2lKQkD/i3SlgQXXiGx9yopulY07Q1n2pNk1g8ay4k4Yt24Q== imported-openssh-key
diff --git a/src/Renci.SshNet.Tests/Data/Key.ECDSA384.Encrypted.txt b/test/Data/Key.ECDSA384.Encrypted.txt
similarity index 91%
rename from src/Renci.SshNet.Tests/Data/Key.ECDSA384.Encrypted.txt
rename to test/Data/Key.ECDSA384.Encrypted.txt
index 00072ce24..c0e1a360a 100644
--- a/src/Renci.SshNet.Tests/Data/Key.ECDSA384.Encrypted.txt
+++ b/test/Data/Key.ECDSA384.Encrypted.txt
@@ -1,4 +1,4 @@
------BEGIN EC PRIVATE KEY-----
+-----BEGIN EC PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,1D64653C5E18C2AACB0B17E3FE43C219
diff --git a/test/Data/Key.ECDSA384.pub b/test/Data/Key.ECDSA384.pub
new file mode 100644
index 000000000..1253fba19
--- /dev/null
+++ b/test/Data/Key.ECDSA384.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBBSTitW+g48jWFDNak3HT1Sjqob6ysZxu8GrXl4UrQacr9PRQErF1tnb7/8oBgjpJ4Mcz23c5EXVpfkSmNMQEjh3tlj+VX2Nfoycnhe4a14mx6UzaIybL6n1ljDzcFgHVg== imported-openssh-key
diff --git a/src/Renci.SshNet.Tests/Data/Key.ECDSA384.txt b/test/Data/Key.ECDSA384.txt
similarity index 88%
rename from src/Renci.SshNet.Tests/Data/Key.ECDSA384.txt
rename to test/Data/Key.ECDSA384.txt
index f2d658ea4..43edbf09c 100644
--- a/src/Renci.SshNet.Tests/Data/Key.ECDSA384.txt
+++ b/test/Data/Key.ECDSA384.txt
@@ -1,4 +1,4 @@
------BEGIN EC PRIVATE KEY-----
+-----BEGIN EC PRIVATE KEY-----
MIGkAgEBBDCQawHdHLR7NvKa2vPV0sVkbzOE8c0enp95iEysGcGV66RXE1EH//nh
gu5UzeTR4KigBwYFK4EEACKhZANiAAQUk4rVvoOPI1hQzWpNx09Uo6qG+srGcbvB
q15eFK0GnK/T0UBKxdbZ2+//KAYI6SeDHM9t3ORF1aX5EpjTEBI4d7ZY/lV9jX6M
diff --git a/test/Data/Key.ECDSA521.Encrypted.pub b/test/Data/Key.ECDSA521.Encrypted.pub
new file mode 100644
index 000000000..6e85066c4
--- /dev/null
+++ b/test/Data/Key.ECDSA521.Encrypted.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBACwzN70vaXBOSasttYWPYsPTwe4aQWx86wSig5xddvJXwX0Wzg0KYRkF5f2wJbk59JufZVaLcQpOQ/kN/2EOHVzhgA1V1BcBFbmoKSnMMwx/pQUVOu54tPC3CTAIN1CeG9UaBWcz44YXmSRQM5vz4OzZnzVFusFvY6+fnldTeNgQYqz9g== imported-openssh-key
diff --git a/src/Renci.SshNet.Tests/Data/Key.ECDSA521.Encrypted.txt b/test/Data/Key.ECDSA521.Encrypted.txt
similarity index 92%
rename from src/Renci.SshNet.Tests/Data/Key.ECDSA521.Encrypted.txt
rename to test/Data/Key.ECDSA521.Encrypted.txt
index 381b30be8..79b339079 100644
--- a/src/Renci.SshNet.Tests/Data/Key.ECDSA521.Encrypted.txt
+++ b/test/Data/Key.ECDSA521.Encrypted.txt
@@ -1,4 +1,4 @@
------BEGIN EC PRIVATE KEY-----
+-----BEGIN EC PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,F995028237EBD79C928530CC6C3E957F
diff --git a/test/Data/Key.ECDSA521.pub b/test/Data/Key.ECDSA521.pub
new file mode 100644
index 000000000..5d1ba5185
--- /dev/null
+++ b/test/Data/Key.ECDSA521.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBABrpVjsANqcvqMUo1wo0I1uVCXQ6xrauy4iU86FiOwFmkYRrle4w3oYdRJwniC3TwGMuBuMPMIoCTXr0UtUzn1vkQESNR/J/jAxVseLlVe+KDfZHKvsvk2+O4XaSa1qMfLwN3spwlj08+ylKjlO6V3g0hbz4ZaSVwuiRS7Xsv8W2MV6rg== imported-openssh-key
diff --git a/src/Renci.SshNet.Tests/Data/Key.ECDSA521.txt b/test/Data/Key.ECDSA521.txt
similarity index 90%
rename from src/Renci.SshNet.Tests/Data/Key.ECDSA521.txt
rename to test/Data/Key.ECDSA521.txt
index 31abe917a..27a74ff9a 100644
--- a/src/Renci.SshNet.Tests/Data/Key.ECDSA521.txt
+++ b/test/Data/Key.ECDSA521.txt
@@ -1,4 +1,4 @@
------BEGIN EC PRIVATE KEY-----
+-----BEGIN EC PRIVATE KEY-----
MIHcAgEBBEIBn2DAme7AU8sCA+/sd6s3c2FNW26IiPvulGd3FC8k5q+fjBZ5LUWR
iJMGrsf2rJLO8hXMGJYoF9tjZEGaabQ8KVagBwYFK4EEACOhgYkDgYYABABrpVjs
ANqcvqMUo1wo0I1uVCXQ6xrauy4iU86FiOwFmkYRrle4w3oYdRJwniC3TwGMuBuM
diff --git a/test/Data/Key.OPENSSH.ECDSA.Encrypted.pub b/test/Data/Key.OPENSSH.ECDSA.Encrypted.pub
new file mode 100644
index 000000000..30e33d96b
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA.Encrypted.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBK6YY2NwwLDSMnJTD+a4OfitCDuG/MnY/AstPgh54xMrZF6Qr0U1H6kRMKY6JJsj31CI97qDYrnTA00Sx5Jy6yw= Key.OPENSSH.ECDSA.Encrypted
diff --git a/test/Data/Key.OPENSSH.ECDSA.Encrypted.txt b/test/Data/Key.OPENSSH.ECDSA.Encrypted.txt
new file mode 100644
index 000000000..d2f158941
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA.Encrypted.txt
@@ -0,0 +1,10 @@
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABCY
+dyRpKP91m/llh14yqcTgAAAAEAAAAAEAAABoAAAAE2VjZHNhLXNoYTItbmlzdHAy
+NTYAAAAIbmlzdHAyNTYAAABBBK6YY2NwwLDSMnJTD+a4OfitCDuG/MnY/AstPgh5
+4xMrZF6Qr0U1H6kRMKY6JJsj31CI97qDYrnTA00Sx5Jy6ywAAADAE2+HapLgUUft
+e6Nl4XWsAEQdjicejaI1F1+ByHcpmd0Sudqd+P33KliXt48HKcygeqi86QVv3YOj
+IpyXj5ndP6Luy7U5kMIJDyfWi1eRKouFfmektEp3KIktpSHO62NykMK6D1U5rzDo
+7QRdKWUXaVU7P/OGPsaWL7T+/xDn7J/EZVhNrIuV71gyQifID1gbM8mGDdyAa8qd
+peeYuVaKQt3qltAZsRN0q8WC0EHbxeh40hrvwWTAY+wKfGMxS5cf
+-----END OPENSSH PRIVATE KEY-----
diff --git a/test/Data/Key.OPENSSH.ECDSA.pub b/test/Data/Key.OPENSSH.ECDSA.pub
new file mode 100644
index 000000000..f0398673c
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI/dlNvfssW9KYrB67TcDmz9zBzDf7eMvUupAroP3b3FjUnYnpL3Utc4GkF/PiX7w2DuxaG70/+EX/CYHZBHKCs= Key.OPENSSH.ECDSA
diff --git a/test/Data/Key.OPENSSH.ECDSA.txt b/test/Data/Key.OPENSSH.ECDSA.txt
new file mode 100644
index 000000000..d61dfead9
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA.txt
@@ -0,0 +1,9 @@
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNl
+Y2RzYS1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQSP3ZTb37LFvSmKweu0
+3A5s/cwcw3+3jL1LqQK6D929xY1J2J6S91LXOBpBfz4l+8Ng7sWhu9P/hF/wmB2Q
+RygrAAAAsC+6dPMvunTzAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAy
+NTYAAABBBI/dlNvfssW9KYrB67TcDmz9zBzDf7eMvUupAroP3b3FjUnYnpL3Utc4
+GkF/PiX7w2DuxaG70/+EX/CYHZBHKCsAAAAhALVqID3K/N7IazKNbhrg09r7rLLt
+jy81RLV+VDxloQnxAAAAEUtleS5PUEVOU1NILkVDRFNBAQIDBAUG
+-----END OPENSSH PRIVATE KEY-----
diff --git a/test/Data/Key.OPENSSH.ECDSA384.Encrypted.pub b/test/Data/Key.OPENSSH.ECDSA384.Encrypted.pub
new file mode 100644
index 000000000..2ca7e4d3f
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA384.Encrypted.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBFL5NEL9uRhgkF2q+8m58EvtZq4mDGgcVEzafPRuNIn1018m9KuqNpOQ6d+435n+MRYThe4MUdijSIDuopX2i14Z35oKZ9x2LsV+RxQczjmbnoWZdvgcvdOo6jiJdY7XJw== Key.OPENSSH.ECDSA384.Encrypted
diff --git a/test/Data/Key.OPENSSH.ECDSA384.Encrypted.txt b/test/Data/Key.OPENSSH.ECDSA384.Encrypted.txt
new file mode 100644
index 000000000..5083342db
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA384.Encrypted.txt
@@ -0,0 +1,12 @@
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAi
+RxrKRE4zQH82w0Rd0v/ZAAAAEAAAAAEAAACIAAAAE2VjZHNhLXNoYTItbmlzdHAz
+ODQAAAAIbmlzdHAzODQAAABhBFL5NEL9uRhgkF2q+8m58EvtZq4mDGgcVEzafPRu
+NIn1018m9KuqNpOQ6d+435n+MRYThe4MUdijSIDuopX2i14Z35oKZ9x2LsV+RxQc
+zjmbnoWZdvgcvdOo6jiJdY7XJwAAAPADDlLFKHgORBmNlg6LYOSdYyZFCVjmRbwm
+j1X1qDSxgr48+OEJYr/nEfd6jMBKyS1mAHuvStxe1rA0PQMCrjyk/pmjbFQ6uEC4
+u31RHE9N0ZgKCgYLeT7s30ODh5TChmubbjdzHDXNYm3oKTGoaGYRBI6Yp+9+DFId
+qEXVZzZV+w7dnPWh4L6YjBIoqnwlxW9XOSqizXOcjUbZrrZIA13rbYKVlCmVXlMW
+SgWjbdg4+L/ijwZdO2O5XrcLmpU3rTa2wjlREE1fqH7Wm/qKMF28YF1Ytuus+XSr
+BoU/lLWDW4BL1lyROGByxz3zYUpVgfo=
+-----END OPENSSH PRIVATE KEY-----
diff --git a/test/Data/Key.OPENSSH.ECDSA384.pub b/test/Data/Key.OPENSSH.ECDSA384.pub
new file mode 100644
index 000000000..33a0bcab6
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA384.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBFM/UMxegeBb5Ff5L83FQQSWi7VyYsPoISJH7OnNoYbqbOXouFRj5nd/Yze7i7u1wzxOAH+OIducj1Np43lArgdfUP0NeQflGF+ct+ubeQJM2gIUp3RZr9AC8quU0qJGLw== Key.OPENSSH.ECDSA384
diff --git a/test/Data/Key.OPENSSH.ECDSA384.txt b/test/Data/Key.OPENSSH.ECDSA384.txt
new file mode 100644
index 000000000..620bd7ee3
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA384.txt
@@ -0,0 +1,11 @@
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAiAAAABNl
+Y2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRTP1DMXoHgW+RX+S/N
+xUEElou1cmLD6CEiR+zpzaGG6mzl6LhUY+Z3f2M3u4u7tcM8TgB/jiHbnI9TaeN5
+QK4HX1D9DXkH5RhfnLfrm3kCTNoCFKd0Wa/QAvKrlNKiRi8AAADgj+zzrY/s860A
+AAATZWNkc2Etc2hhMi1uaXN0cDM4NAAAAAhuaXN0cDM4NAAAAGEEUz9QzF6B4Fvk
+V/kvzcVBBJaLtXJiw+ghIkfs6c2hhups5ei4VGPmd39jN7uLu7XDPE4Af44h25yP
+U2njeUCuB19Q/Q15B+UYX5y365t5AkzaAhSndFmv0ALyq5TSokYvAAAAMAXLUgK3
+2yWzUrpeLzpdFB2/eiNnkxQlu5OneTPukKcZYclfgojv0YHK5LCvAtF8lwAAABRL
+ZXkuT1BFTlNTSC5FQ0RTQTM4NAECAwQ=
+-----END OPENSSH PRIVATE KEY-----
diff --git a/test/Data/Key.OPENSSH.ECDSA521.Encrypted.pub b/test/Data/Key.OPENSSH.ECDSA521.Encrypted.pub
new file mode 100644
index 000000000..1dcc63771
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA521.Encrypted.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBAH9BVM6bRhbELtgdMGsin5lM42R2EWoT+6Akakl5rQy2tHHLIYGLEfaqI+0iUo2V6MxEf9w0hVz6SEsF+yDgyrYPQCIieaB1oBvIl+PZmL1XsuAXs2uMRsNJb4myGU/DiekxqzIPa0LMrBZ4xmErcn5Gazkw1EA0B3HoaW5wj+geI/efQ== Key.OPENSSH.ECDSA521.Encrypted
diff --git a/test/Data/Key.OPENSSH.ECDSA521.Encrypted.txt b/test/Data/Key.OPENSSH.ECDSA521.Encrypted.txt
new file mode 100644
index 000000000..e87218820
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA521.Encrypted.txt
@@ -0,0 +1,14 @@
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABCr
+ps+rr4kkPvUVZfJpoR4GAAAAEAAAAAEAAACsAAAAE2VjZHNhLXNoYTItbmlzdHA1
+MjEAAAAIbmlzdHA1MjEAAACFBAH9BVM6bRhbELtgdMGsin5lM42R2EWoT+6Akakl
+5rQy2tHHLIYGLEfaqI+0iUo2V6MxEf9w0hVz6SEsF+yDgyrYPQCIieaB1oBvIl+P
+ZmL1XsuAXs2uMRsNJb4myGU/DiekxqzIPa0LMrBZ4xmErcn5Gazkw1EA0B3HoaW5
+wj+geI/efQAAASD6gdu6JHpiY92v0ED6YQ9FjYvjaRrIDUAbFv3jnuQ+sWsyaxTk
+lSHI+4A/jxxIT/MMtNNLZiArZXD889BNA+mXrZIQ7i2DiYoLJWRHvmmPSxcGlHUF
+PfwPwwPlK/nkR6NKuT7zP0daGMQYf8Njq727qpltkPmGQGDknN8tbX4RUOUGBPNh
+UuRHRwqK3tHF5vDpUrJ09bsnClqGP6ufq3Zf+yb1r1tQK3uXadoE0wl8P8WZJRXo
+JX8ngVVy6JMOiyAWZkTukKzVBAE1CMW8FOgX6ErqghqBD6s7YCxITXcyvwkWyQuc
+oEr+BCLpwvXZ44CsOH96R+QevFz5ZI/dJx67Ccvdj2+8v5rECN4U8zpK7t5BYjla
+hOkBkliF7QD8OmI=
+-----END OPENSSH PRIVATE KEY-----
diff --git a/test/Data/Key.OPENSSH.ECDSA521.pub b/test/Data/Key.OPENSSH.ECDSA521.pub
new file mode 100644
index 000000000..8db24c3ba
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA521.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBABrunhZWBr7Tyq7XrQGt3MrJE0kxAJ4aEWW412rvf+5pbeqWqgSJo21zm4HscfKMJZBOZ/OtJEtFntgHBRqdzDKHgCrqAGAaxdXPA29jeTFEOUatJ8yaweVfPjV2DD3CbV8Fx/3ueJ7FFD/EaWGTJ/shiVD+zkGlcXaVL2XQfmEGKmlGA== Key.OPENSSH.ECDSA521
diff --git a/test/Data/Key.OPENSSH.ECDSA521.txt b/test/Data/Key.OPENSSH.ECDSA521.txt
new file mode 100644
index 000000000..85e3b07e5
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ECDSA521.txt
@@ -0,0 +1,13 @@
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAArAAAABNl
+Y2RzYS1zaGEyLW5pc3RwNTIxAAAACG5pc3RwNTIxAAAAhQQAa7p4WVga+08qu160
+BrdzKyRNJMQCeGhFluNdq73/uaW3qlqoEiaNtc5uB7HHyjCWQTmfzrSRLRZ7YBwU
+ancwyh4Aq6gBgGsXVzwNvY3kxRDlGrSfMmsHlXz41dgw9wm1fBcf97niexRQ/xGl
+hkyf7IYlQ/s5BpXF2lS9l0H5hBippRgAAAEgzPWTIsz1kyIAAAATZWNkc2Etc2hh
+Mi1uaXN0cDUyMQAAAAhuaXN0cDUyMQAAAIUEAGu6eFlYGvtPKrtetAa3cyskTSTE
+AnhoRZbjXau9/7mlt6paqBImjbXObgexx8owlkE5n860kS0We2AcFGp3MMoeAKuo
+AYBrF1c8Db2N5MUQ5Rq0nzJrB5V8+NXYMPcJtXwXH/e54nsUUP8RpYZMn+yGJUP7
+OQaVxdpUvZdB+YQYqaUYAAAAQXwQnI20tNxwLKHPMDmumblDb0sBqW5Y9248L//x
+4sWFrkjk6k1LcZno9KLqz8+tIFMJ5sji+axRoUZCXb3cIPzPAAAAFEtleS5PUEVO
+U1NILkVDRFNBNTIxAQIDBAUGBwgJCgsMDQ4P
+-----END OPENSSH PRIVATE KEY-----
diff --git a/test/Data/Key.OPENSSH.ED25519.Encrypted.pub b/test/Data/Key.OPENSSH.ED25519.Encrypted.pub
new file mode 100644
index 000000000..62327be27
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ED25519.Encrypted.pub
@@ -0,0 +1 @@
+ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGFdyflleGqSPOhgSYZf7ZQFlG0zEL9VDGC69UbtaaBy Key.OPENSSH.ED25519.Encrypted
diff --git a/test/Data/Key.OPENSSH.ED25519.Encrypted.txt b/test/Data/Key.OPENSSH.ED25519.Encrypted.txt
new file mode 100644
index 000000000..b0f4e4d78
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ED25519.Encrypted.txt
@@ -0,0 +1,9 @@
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAb
+LdF3aDTKufq+4lmfYt9wAAAAEAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIGFd
+yflleGqSPOhgSYZf7ZQFlG0zEL9VDGC69UbtaaByAAAAsPooI5L5r84607ib9qOp
+QLZYY2fVriZcZZ5TTnCj8rb3SkiZ+vS7Or+HjsAszKkvEO3We8OslmYoAUjuFJsc
+D4IImAKZAO345IGBMELO71tUtpn9OGII5uyeINsnCiPz83My7mxNt1nJHluFTja5
+aoAqW30nnvwpJ2Dt82BITEmGsAmOkP9BqJNWL+p7jEEI0CXjKbzv/Sg7l7IraKJL
+A1XoNHcjTXd5LGr1gYSD5LCe
+-----END OPENSSH PRIVATE KEY-----
diff --git a/test/Data/Key.OPENSSH.ED25519.pub b/test/Data/Key.OPENSSH.ED25519.pub
new file mode 100644
index 000000000..a4c452e63
--- /dev/null
+++ b/test/Data/Key.OPENSSH.ED25519.pub
@@ -0,0 +1 @@
+ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIA0JZnDQrxQZcNALfZYG7LPAW1MYEGvVW5nje7OlMGMi Key.OPENSSH.ED25519
diff --git a/src/Renci.SshNet.Tests/Data/Key.OPENSSH.ED25519.txt b/test/Data/Key.OPENSSH.ED25519.txt
similarity index 54%
rename from src/Renci.SshNet.Tests/Data/Key.OPENSSH.ED25519.txt
rename to test/Data/Key.OPENSSH.ED25519.txt
index 84811f653..34cab676a 100644
--- a/src/Renci.SshNet.Tests/Data/Key.OPENSSH.ED25519.txt
+++ b/test/Data/Key.OPENSSH.ED25519.txt
@@ -1,8 +1,8 @@
------BEGIN OPENSSH PRIVATE KEY-----
+-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtz
c2gtZWQyNTUxOQAAACANCWZw0K8UGXDQC32WBuyzwFtTGBBr1VuZ43uzpTBjIgAA
-AKBATgCiQE4AogAAAAtzc2gtZWQyNTUxOQAAACANCWZw0K8UGXDQC32WBuyzwFtT
+AKCgIja8oCI2vAAAAAtzc2gtZWQyNTUxOQAAACANCWZw0K8UGXDQC32WBuyzwFtT
GBBr1VuZ43uzpTBjIgAAAEAAzBF1MPUxrs+ycpJh28zzo/F3m6WcKO+orsSbR5Lw
-KQ0JZnDQrxQZcNALfZYG7LPAW1MYEGvVW5nje7OlMGMiAAAAFGVkMjU1MTkta2V5
-LTIwMTgxMTI3AQIDBAUGBwgJ
+KQ0JZnDQrxQZcNALfZYG7LPAW1MYEGvVW5nje7OlMGMiAAAAE0tleS5PUEVOU1NI
+LkVEMjU1MTkBAgMEBQYHCAkK
-----END OPENSSH PRIVATE KEY-----
diff --git a/test/Data/Key.OPENSSH.RSA.Encrypted.pub b/test/Data/Key.OPENSSH.RSA.Encrypted.pub
new file mode 100644
index 000000000..a4479683d
--- /dev/null
+++ b/test/Data/Key.OPENSSH.RSA.Encrypted.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCxOfnmxC1gmmX18LCBG/X73BoCXQEBEAJz3V9w0FMTgUBebK3fkfOMLNzWn5aMR608wQHOEPYhHffCJfdJR6lUWLHZz5+EZRfM9oHpysMtToYQoGtb9xM7D5J3lnWZgSea2R7xSeqpClN5nQUMGu8y2d2S3g9o1vrTdeu71u09QFOx2AXBPUmCjpCuBlNyYEEQMfRMtQ6PDbPdvLM1uylbQqB+/6jMsCyEFvlLit9GcZ7ItKQN+jsZNmP+f7ytVXLsZTjPLd5mWWrf6T1T1Xt9DBoLXnMrmDiCf/EXiTYonIO6B0FHvNUCrDzZ7rxIebqePLes1Q2yoUqmC8g+cww3 Key.OPENSSH.RSA.Encrypted
diff --git a/test/Data/Key.OPENSSH.RSA.Encrypted.txt b/test/Data/Key.OPENSSH.RSA.Encrypted.txt
new file mode 100644
index 000000000..62586de3e
--- /dev/null
+++ b/test/Data/Key.OPENSSH.RSA.Encrypted.txt
@@ -0,0 +1,30 @@
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABBG
+IAWU/wNbg8olz6BhAdPiAAAAEAAAAAEAAAEXAAAAB3NzaC1yc2EAAAADAQABAAAB
+AQCxOfnmxC1gmmX18LCBG/X73BoCXQEBEAJz3V9w0FMTgUBebK3fkfOMLNzWn5aM
+R608wQHOEPYhHffCJfdJR6lUWLHZz5+EZRfM9oHpysMtToYQoGtb9xM7D5J3lnWZ
+gSea2R7xSeqpClN5nQUMGu8y2d2S3g9o1vrTdeu71u09QFOx2AXBPUmCjpCuBlNy
+YEEQMfRMtQ6PDbPdvLM1uylbQqB+/6jMsCyEFvlLit9GcZ7ItKQN+jsZNmP+f7yt
+VXLsZTjPLd5mWWrf6T1T1Xt9DBoLXnMrmDiCf/EXiTYonIO6B0FHvNUCrDzZ7rxI
+ebqePLes1Q2yoUqmC8g+cww3AAAD0FJlZT8ZlW/a4ZLCYzZw1XpWsoHxrrFkmO4C
+bLYeMnpHge24Cx7vV5DT9L3GIPrKvHwDMn0a0fW3GNPRWWV6dCTNiN+YZYUFCJQT
+TIFRQMqLqXOiAneDYOpGK739jp/v8joEPGirpnQ6kNW3dMgjgWsrYe8mMwqQ4Q/W
+yFyYfEcZHK0/rKBs3pYKT5dH4EemCOnbxIGxf1FBp6++F9J4cIOFF7kDEsdaBZff
+PHsxFheIEP7yeZM6IMchJQ4EbfXb61f62IHjRMfXkENzTDnMklxM3wgNLIgV9sXt
+XDhYq/mVYrbts7sLKyFQvhM79GcDmxI+ZU7qPQ2cjuOtw734GAWsOmXyA/NUii9l
+AjIZp2N/xDAUTypBNcsp7T0ijmTvJVlsVyKIPX4bzl2wPgJth4+IqgFftOUHDsVX
+D6/+pu64rYG5g2YQOeL5Cs2kngqtFEVs2Kgz8i8C7Rse7Fkckfwg3bDXOjU/3GRR
+XYfAgOCsOQ8sFbfnyuRqC55sW7Nc0BGEJ5aEliByF0gNnlAxrX6BJwO8EVQlP5GQ
+dtN91F6TvdKgSJvshINKrr8D39JoK9MtjyeZ/t1mPZiRfwtjtd52T+BwKq+oM7HB
+D/pgDlsdvHnTE2b7sGIq6MP8vMAXpuTcaTgvFj/lzhJ8193ufTwU1U6WJ5egSEkk
+k8HXbaLo0g5vaBmpM6ImLJD7REgOEV3TWxKWDRscdZhcNTiDZMY6/1K0SoFjJQ1t
+a3rzqS4lGaexsT2RlBdSAl7f0A6VHMRM9CNUJFogpjw6BzxTWXhJbRzgLPPxlity
+sRMmdBVzV+O4l+Xht3eVrC2pk/qGytlmlWku2Wto+mHA/FUj7NdEBElevgHeXjhL
+fKHsumP7Wr1P5KYFOFBnZqNvHU1CmQ4vm3/YEyClhJNzvMFou80i1ll4rBTnLozV
+jDbIy5An8qFmB566CdHg/iGbdq85iL4ae8PrFb9Qc5mCJf8OCmNeeYu4f3yCeXZu
+TjCVJHwx7wVEegS2MZbLWDL1Jds0d7kx0h24zn8QI0EdZrugQc3gZxpbLmmua5Kd
+XWJw4zqaFFP9QU+OLVDBAn+RFF/rj6aHa18v6Udyulj5mGaSDANv3JcAHxy7QVZ2
+Kc3qlD49SKL8H6zj1ozeh0M2J5GRHEPS1DUmauW+Qkl8admEsctunjbbNMjCRc5J
+M1U8tI5NyPAihovpIRMnz8yhuFgcL9jLREokw/eNNRpayWSwKfLKdn2/DC2ZLx2n
+CgP5dGDweT48SE9BveF0SfO2/6c/9QxkYEvA8YFWRB4Bd/NtiL0=
+-----END OPENSSH PRIVATE KEY-----
diff --git a/test/Data/Key.OPENSSH.RSA.pub b/test/Data/Key.OPENSSH.RSA.pub
new file mode 100644
index 000000000..3e77649c4
--- /dev/null
+++ b/test/Data/Key.OPENSSH.RSA.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDtbs6KCLsePWaxraXweKYs/NqBWYT8Kx4woJHE8xO1ZO+hl0y3uF+S2FYDuHbRruhJJ4fa3sWp46lU0YVi9FXcFVawpkkxFx0mJMJkCMffytiT3Re9neYqso3/d9xCyHg6I+dapPodKqDXiiJXxQ+1TCcTrmyRZLG/G34QuVWkKobm8TY78Y0MpATsXNi3q9CKEwVIAEGqO9q7SaNfTTYpiIIyvq+CXxdiQMDifn4nJBJDHOed+sv3dmhqq6NE/ZtPlSFeBvOvwcXC6pAa9REQJlNMjwGK//q04if3HaERo3q/EMu1dz30TZ3o1bpx2uLBoYUniOBVYMTmZTTTpd09 Key.OPENSSH.RSA
diff --git a/test/Data/Key.OPENSSH.RSA.txt b/test/Data/Key.OPENSSH.RSA.txt
new file mode 100644
index 000000000..ac60a2ff0
--- /dev/null
+++ b/test/Data/Key.OPENSSH.RSA.txt
@@ -0,0 +1,30 @@
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdz
+c2gtcnNhAAAAAwEAAQAAAQEA7W7Oigi7Hj1msa2l8HimLPzagVmE/CseMKCRxPMT
+tWTvoZdMt7hfkthWA7h20a7oSSeH2t7FqeOpVNGFYvRV3BVWsKZJMRcdJiTCZAjH
+38rYk90XvZ3mKrKN/3fcQsh4OiPnWqT6HSqg14oiV8UPtUwnE65skWSxvxt+ELlV
+pCqG5vE2O/GNDKQE7FzYt6vQihMFSABBqjvau0mjX002KYiCMr6vgl8XYkDA4n5+
+JyQSQxznnfrL93ZoaqujRP2bT5UhXgbzr8HFwuqQGvURECZTTI8Biv/6tOIn9x2h
+EaN6vxDLtXc99E2d6NW6cdriwaGFJ4jgVWDE5mU006XdPQAAA9DGPmJsxj5ibAAA
+AAdzc2gtcnNhAAABAQDtbs6KCLsePWaxraXweKYs/NqBWYT8Kx4woJHE8xO1ZO+h
+l0y3uF+S2FYDuHbRruhJJ4fa3sWp46lU0YVi9FXcFVawpkkxFx0mJMJkCMffytiT
+3Re9neYqso3/d9xCyHg6I+dapPodKqDXiiJXxQ+1TCcTrmyRZLG/G34QuVWkKobm
+8TY78Y0MpATsXNi3q9CKEwVIAEGqO9q7SaNfTTYpiIIyvq+CXxdiQMDifn4nJBJD
+HOed+sv3dmhqq6NE/ZtPlSFeBvOvwcXC6pAa9REQJlNMjwGK//q04if3HaERo3q/
+EMu1dz30TZ3o1bpx2uLBoYUniOBVYMTmZTTTpd09AAAAAwEAAQAAAQEA6Xgq+gpp
+zOt9nrtsz5Ajf1tHlSesn7XaYuCRVgPb3mOZSuEW3BUdTa0Sr2fk1nzSBpUrfqnN
+3idyK2g3bD1sbBRDgUKR+AaNcCN3TpxfxgyVeJhQLvEkEdovzQRUfwrXRfxmE3jk
+RGfVbvxylrG8p35xcmXydel46r2i8dj8gIY3tKp0RMvZ4ZlNbhWHPd5OxyHWL9e3
+gbOSyIyjQgTKZezhzErS/X/KJ/XYqzyBAqNqZ2Rg1kKiHRlHS6KEI2tyFwYfh+Rb
+6L9xch1SqOtQhTWirmxS25dpGD2jgalXeyiw8PmuqTiWCqUmUMx6MdF3tFsirr54
+K4QA9kqMeaRLtQAAAIEAsUQT0Uhq7l0ugTd4Y989bH6eW0fol21/m7B5zkJQepNa
+dUPTs188uvv4inW8n2O3RCanXWHZfCJ1AsR/MEEW2C6QDtvqKXHbzfWQlCYSVxB1
+7CjURKa8fNaIAk98zgmNNwO53NBleyrUhPgvm3xt7ACgpzXY5RwNJL8/a0WOmgwA
+AACBAP508Op6wWPAwn1JfBZuqQtjcfnJeN4NkYQBdybn0vVu5UdyqSQLa8hlAzRO
+hA+qJvrlsZgM9h8CyLTyuim8likZHocwO13zBTdVaQ8c2lJvf2uXTIXNZHseS7IT
+kfBiO1hSB4z8RDkOr35mGfdbyJIFAwFZF4Xs8WnQF+vHEadrAAAAgQDu329eCwVF
+f9g0zNHfZu31p0WtErcsRv57fq+UoPtov8nxUF71oOWe5KSGnGtMICI31kBtPhUb
+vfOmuqNrgJBjgjbPQmi0xSAE5L3QuEKRNjlaE3/WadKBwzhJDtauuYk1ifkrdAVp
+67XyQ5puyuGgVaQBNPbrxA9g1IbyeL4/9wAAAA9LZXkuT1BFTlNTSC5SU0EBAgME
+BQYHCAkK
+-----END OPENSSH PRIVATE KEY-----
diff --git a/test/Data/Key.RSA.Encrypted.Aes.128.CBC.12345.pub b/test/Data/Key.RSA.Encrypted.Aes.128.CBC.12345.pub
new file mode 100644
index 000000000..2147fb08a
--- /dev/null
+++ b/test/Data/Key.RSA.Encrypted.Aes.128.CBC.12345.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCha/vKqT3Nf07l0b/7A5BtSdTy+WnCt9z8QVMq85RjgYc4n3cCh0tEmyE3EjR9Bmc9bBIR2wWUHnLc2gmDXe4Y1YGKQyWCPTVnPPpBN+eama+BYPbfQDn8wRNsEghtc2TgXH2Oj28yGnGf7JM46rSCsyJwx9doEvrFptQGiAdXCk6aLnRzFhC4reVe9iBi1y1A4T5mVkljjwdVRpIMZYshHEi8mc/mvV+f7t9aXG33WZ+r6rGUT4cs6hpcxyg8AStnlpwYuLApeX6I/1rqGLktJCPGFeFAJS+Oy/I1sK7IgvKqSMSikKRT5hKoBra4EHRspe4giqRQFf402jfr4EKr imported-openssh-key
diff --git a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Aes.128.CBC.12345.txt b/test/Data/Key.RSA.Encrypted.Aes.128.CBC.12345.txt
similarity index 98%
rename from src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Aes.128.CBC.12345.txt
rename to test/Data/Key.RSA.Encrypted.Aes.128.CBC.12345.txt
index cc017a909..c86a05726 100644
--- a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Aes.128.CBC.12345.txt
+++ b/test/Data/Key.RSA.Encrypted.Aes.128.CBC.12345.txt
@@ -1,4 +1,4 @@
------BEGIN RSA PRIVATE KEY-----
+-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,AD7A2024C208E41F91C191B89AB9515A
diff --git a/test/Data/Key.RSA.Encrypted.Aes.192.CBC.12345.pub b/test/Data/Key.RSA.Encrypted.Aes.192.CBC.12345.pub
new file mode 100644
index 000000000..4fc4b25c0
--- /dev/null
+++ b/test/Data/Key.RSA.Encrypted.Aes.192.CBC.12345.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC4nJsl4i410AyFpLbh7AWSq+X+q6lbRSUW8XqhSb6b2AClQ7pBkwPm2/VL1Jk3+d1itzChHAQgQWjt0E9uh/BL/Rz0fHXqzrbOn1Yuwq0N9ZMsIss8ue6q2Txi8tn2qBIhhB37MZcOZYH2Vp4+kLf5SmqOr/0/Iyz4H77NnJz9H8VWNnmIC/lVmFnpdrzCkn5RzKrlfZElrQPfYXMwM6ivKoB3j5S5EThn0RAyLpGJsD2nB+/0bLbPyvIa+EEzzfsIBvO9Q9ULWPEBGJdSLsz++NvNGay40uVT7PDsUB59n/vsT1/gZ+kbl6gneM+qnhTxZUFzxtDqJXx9dXwymZqz
diff --git a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Aes.192.CBC.12345.txt b/test/Data/Key.RSA.Encrypted.Aes.192.CBC.12345.txt
similarity index 98%
rename from src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Aes.192.CBC.12345.txt
rename to test/Data/Key.RSA.Encrypted.Aes.192.CBC.12345.txt
index 51e902101..41945ff22 100644
--- a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Aes.192.CBC.12345.txt
+++ b/test/Data/Key.RSA.Encrypted.Aes.192.CBC.12345.txt
@@ -1,4 +1,4 @@
------BEGIN RSA PRIVATE KEY-----
+-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-192-CBC,0E34605476FC4C57886CE6350CD6F61E
diff --git a/test/Data/Key.RSA.Encrypted.Aes.256.CBC.12345.pub b/test/Data/Key.RSA.Encrypted.Aes.256.CBC.12345.pub
new file mode 100644
index 000000000..8b041597f
--- /dev/null
+++ b/test/Data/Key.RSA.Encrypted.Aes.256.CBC.12345.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC6KpJwRX4HfoFimrRTxqHsyAoPgMD+dm2/6NjIZiy2CPuNGfci+EKjSmdQHhqM8jlhBKhSiAnsEuW46WGlCzpQm2uSA1hFCz/pdExNw9onfY2hdJwOrFlDO9rOcedeZhSQ5gDW/c/MreQQDgEST8tBBM8Yuuk9h6763+Cbd7TAvOskfmx9RXRMeFaqYOe8uVvNQDAYKlcfhjRESfkDtUvJSUyjZYkKR0wnm9fFGL6K/jQrbDYG75wEyB6+bSPHl3ZLakjHJiNOXVlOgJVk9Gw147hLPd+zxyE4eJV5J7rQv96QUWouYPFcMD4EfginfkIbNg02A5onkjTTVUBnIK31
diff --git a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Aes.256.CBC.12345.txt b/test/Data/Key.RSA.Encrypted.Aes.256.CBC.12345.txt
similarity index 98%
rename from src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Aes.256.CBC.12345.txt
rename to test/Data/Key.RSA.Encrypted.Aes.256.CBC.12345.txt
index cb31e913c..a26bdef3d 100644
--- a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Aes.256.CBC.12345.txt
+++ b/test/Data/Key.RSA.Encrypted.Aes.256.CBC.12345.txt
@@ -1,4 +1,4 @@
------BEGIN RSA PRIVATE KEY-----
+-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,063DE67AE11456C89BCE9D4A21BE3DFB
diff --git a/test/Data/Key.RSA.Encrypted.Des.CBC.12345.pub b/test/Data/Key.RSA.Encrypted.Des.CBC.12345.pub
new file mode 100644
index 000000000..0c98bc9f0
--- /dev/null
+++ b/test/Data/Key.RSA.Encrypted.Des.CBC.12345.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCs7PAiYUZLgiAKPJpJ62JFBrE1d4lfG0w5vbTkMuwJvYmvWyBPU+Hc7jXxgK1iqsz/s0wDZutENyE9VBilTHAYDBOauXjSfQwlo7zHmK1HZ7h87jcIhltpY0NzBGmd/lQ+yDeXiSFGGoFyjwW6VpOfs0AR+oLA2Hpy4b9lI/QWzGPnSz53LVpALI9ssx15OgwjCNxUW+gjMMNrDN4Gz8EryvY28fwGVgPt6uZeT7bU02aSdcsTvWneGwoNeKIGWuwfIXghiTzIosijMbftWnWVNylM5hQOYlQloxVtCCKe5vnz5PeYfwE38yElu7XV6LqEibFNjor9Mcsc+Rr7d/rN
diff --git a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Des.CBC.12345.txt b/test/Data/Key.RSA.Encrypted.Des.CBC.12345.txt
similarity index 97%
rename from src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Des.CBC.12345.txt
rename to test/Data/Key.RSA.Encrypted.Des.CBC.12345.txt
index 32734a07a..9ce0163d3 100644
--- a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Des.CBC.12345.txt
+++ b/test/Data/Key.RSA.Encrypted.Des.CBC.12345.txt
@@ -1,4 +1,4 @@
------BEGIN RSA PRIVATE KEY-----
+-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-CBC,BD35E157CDD07CAD
diff --git a/test/Data/Key.RSA.Encrypted.Des.Ede3.CBC.12345.pub b/test/Data/Key.RSA.Encrypted.Des.Ede3.CBC.12345.pub
new file mode 100644
index 000000000..d5265ace0
--- /dev/null
+++ b/test/Data/Key.RSA.Encrypted.Des.Ede3.CBC.12345.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCY3ezaIynwdqwNBagUkBVhXETR16+KFGBy9bKcocgAmfvJR1HZc1xiyYPFMh32bN8ZNM6n9PVoBWwtSEmUyUbULa2/EOjOR+Vg9KzFC2Sw1yvu5DyRZngFWpZXZ4rYHVXZCF2cNeQ2uC5zilgdxmSmdDGokHBDuVv89n2DzqwymuCPFOkw+FXCdyaELro2tUmF1VBKHPj5It5U9HauPfcVmWX4ZD1wsEEVmKZS/03h+MDGCjUQE59DGIwZrWsIkOY9/QIU0040XYVOWsHdXlL58fjveOoSDz78dVaVbTE7HRJv0iO71o7xwyc/6js1SoHjRFlQNP4b6q5Z8NYqiL6T imported-openssh-key
diff --git a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Des.Ede3.CBC.12345.txt b/test/Data/Key.RSA.Encrypted.Des.Ede3.CBC.12345.txt
similarity index 97%
rename from src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Des.Ede3.CBC.12345.txt
rename to test/Data/Key.RSA.Encrypted.Des.Ede3.CBC.12345.txt
index aa9250a6d..a0f4b0e75 100644
--- a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Des.Ede3.CBC.12345.txt
+++ b/test/Data/Key.RSA.Encrypted.Des.Ede3.CBC.12345.txt
@@ -1,4 +1,4 @@
------BEGIN RSA PRIVATE KEY-----
+-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,AF373EFF708479DF
diff --git a/test/Data/Key.RSA.Encrypted.Des.Ede3.CFB.1234567890.pub b/test/Data/Key.RSA.Encrypted.Des.Ede3.CFB.1234567890.pub
new file mode 100644
index 000000000..9bd8adc51
--- /dev/null
+++ b/test/Data/Key.RSA.Encrypted.Des.Ede3.CFB.1234567890.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAs8tm1pWW8JOQTpuvsGlf/x7su38XuKo7zOLiY/6gB+ZBWs6UC3TnP1UnG13qyS9euWmIWqVz/3d6OM/O9ysjwgzBjRGQIyekxbXxDb+IpYrZR8T5QHXFjPp/yXGcknurUYF8G4ubxqJAULe5lCzg/b4aN9Vxv1tMTRdaArLPldc=
diff --git a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Des.Ede3.CFB.1234567890.txt b/test/Data/Key.RSA.Encrypted.Des.Ede3.CFB.1234567890.txt
similarity index 96%
rename from src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Des.Ede3.CFB.1234567890.txt
rename to test/Data/Key.RSA.Encrypted.Des.Ede3.CFB.1234567890.txt
index 066d39fb3..8021cda6d 100644
--- a/src/Renci.SshNet.Tests/Data/Key.RSA.Encrypted.Des.Ede3.CFB.1234567890.txt
+++ b/test/Data/Key.RSA.Encrypted.Des.Ede3.CFB.1234567890.txt
@@ -1,4 +1,4 @@
------BEGIN RSA PRIVATE KEY-----
+-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CFB,81C75CC63A21DFFB
diff --git a/test/Data/Key.RSA.pub b/test/Data/Key.RSA.pub
new file mode 100644
index 000000000..071cafa1b
--- /dev/null
+++ b/test/Data/Key.RSA.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAuTtXn+BatX1oJuvhqfJZw5jc/pcIxJUPmuoFCH3+bXfKBJ/94ixNETzZBasyvT/ozboAbCG3qcJOYxf2BEeTAIXe1jLAoTd1GKCwMvZOyjnsPN95/lChwfdnBbMzpZYTGfoUylXme/mzjjLu/J0qXgR5lyk9HFT+x5YEtRl8VSHiDkLKTZ37dwhsqgcs+PkfvYMUK+C8evnfE0tgWgKZk0Eatl87nLWyVXB4LzhSDtGKLCPAOgrX7fYfplDwJ2WK1N6nG0FnxW1HhDeSK7e2TbAa2vZQgvFXMWnO4O/NZKp4COpOReyliWhdtKAjr/+cD4yDfPjhjjKOYfxbvdRG4Q== imported-openssh-key
diff --git a/src/Renci.SshNet.Tests/Data/Key.RSA.txt b/test/Data/Key.RSA.txt
similarity index 97%
rename from src/Renci.SshNet.Tests/Data/Key.RSA.txt
rename to test/Data/Key.RSA.txt
index cf2cc9795..76971dfe2 100644
--- a/src/Renci.SshNet.Tests/Data/Key.RSA.txt
+++ b/test/Data/Key.RSA.txt
@@ -1,4 +1,4 @@
------BEGIN RSA PRIVATE KEY-----
+-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQEAuTtXn+BatX1oJuvhqfJZw5jc/pcIxJUPmuoFCH3+bXfKBJ/9
4ixNETzZBasyvT/ozboAbCG3qcJOYxf2BEeTAIXe1jLAoTd1GKCwMvZOyjnsPN95
/lChwfdnBbMzpZYTGfoUylXme/mzjjLu/J0qXgR5lyk9HFT+x5YEtRl8VSHiDkLK
diff --git a/test/Data/Key.SSH2.DSA.Encrypted.Des.CBC.12345.pub b/test/Data/Key.SSH2.DSA.Encrypted.Des.CBC.12345.pub
new file mode 100644
index 000000000..3b07844b3
--- /dev/null
+++ b/test/Data/Key.SSH2.DSA.Encrypted.Des.CBC.12345.pub
@@ -0,0 +1 @@
+ssh-dss AAAAB3NzaC1kc3MAAACBAI8gyHFchkVhkPiwkhkjFDqN6w2nFWTqVy9sLjFs38oEWLMpAw9+c132erUptAhNQ6JZUAVZGllv/3V5hksSDyChe9WY5IfsOlh6X0dcZCwBKysEzQlPyMFqAtbc9uv7oUWNzBfvEbtV6WN/VmcmXf7dyo3EBVXbBFdPl1NKC7W9AAAAFQDY1+bTt7s2iNmYoBE4C9hdWRCyeQAAAIAEtj09ugx/Tdl6bo7X6mX17hcgVgIxcYj5VNONg2k6IHmRFriLviYaS68mIB4SG3jmvvxbXAGqR1bWBUrv90n0wpxxcuuNoCFylJQyuqUkzSsUHb0WMcncZ/tBQt+NJnRB1Zp9sw8n20ocpg3WVPdaXTtc4pk83NYB6ywG6UFPvgAAAIAX+De5dwo33LMl9W8IvA4dY8Q1wshdycAGJzhy+qYF9dCcwD1Pg+4EbPjYPmzJopsVrK97v9QhxyYcXMr/iHhngGwd9nYNzzSKx665vkSjzyeJWpeQ+fvNV3CLItP01ypbUreM+s+Vz1wor5joLKcDS4X0oQ0RIVZNEHnekuLuFg==
diff --git a/src/Renci.SshNet.Tests/Data/Key.SSH2.DSA.Encrypted.Des.CBC.12345.txt b/test/Data/Key.SSH2.DSA.Encrypted.Des.CBC.12345.txt
similarity index 100%
rename from src/Renci.SshNet.Tests/Data/Key.SSH2.DSA.Encrypted.Des.CBC.12345.txt
rename to test/Data/Key.SSH2.DSA.Encrypted.Des.CBC.12345.txt
diff --git a/test/Data/Key.SSH2.DSA.pub b/test/Data/Key.SSH2.DSA.pub
new file mode 100644
index 000000000..3b07844b3
--- /dev/null
+++ b/test/Data/Key.SSH2.DSA.pub
@@ -0,0 +1 @@
+ssh-dss AAAAB3NzaC1kc3MAAACBAI8gyHFchkVhkPiwkhkjFDqN6w2nFWTqVy9sLjFs38oEWLMpAw9+c132erUptAhNQ6JZUAVZGllv/3V5hksSDyChe9WY5IfsOlh6X0dcZCwBKysEzQlPyMFqAtbc9uv7oUWNzBfvEbtV6WN/VmcmXf7dyo3EBVXbBFdPl1NKC7W9AAAAFQDY1+bTt7s2iNmYoBE4C9hdWRCyeQAAAIAEtj09ugx/Tdl6bo7X6mX17hcgVgIxcYj5VNONg2k6IHmRFriLviYaS68mIB4SG3jmvvxbXAGqR1bWBUrv90n0wpxxcuuNoCFylJQyuqUkzSsUHb0WMcncZ/tBQt+NJnRB1Zp9sw8n20ocpg3WVPdaXTtc4pk83NYB6ywG6UFPvgAAAIAX+De5dwo33LMl9W8IvA4dY8Q1wshdycAGJzhy+qYF9dCcwD1Pg+4EbPjYPmzJopsVrK97v9QhxyYcXMr/iHhngGwd9nYNzzSKx665vkSjzyeJWpeQ+fvNV3CLItP01ypbUreM+s+Vz1wor5joLKcDS4X0oQ0RIVZNEHnekuLuFg==
diff --git a/src/Renci.SshNet.Tests/Data/Key.SSH2.DSA.txt b/test/Data/Key.SSH2.DSA.txt
similarity index 100%
rename from src/Renci.SshNet.Tests/Data/Key.SSH2.DSA.txt
rename to test/Data/Key.SSH2.DSA.txt
diff --git a/test/Data/Key.SSH2.RSA.Encrypted.Des.CBC.12345.pub b/test/Data/Key.SSH2.RSA.Encrypted.Des.CBC.12345.pub
new file mode 100644
index 000000000..128dbc936
--- /dev/null
+++ b/test/Data/Key.SSH2.RSA.Encrypted.Des.CBC.12345.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDVwZxtc4I5nngC8qAu7uJsl9yEqccA5MbUHEyTHL/SkKhM9IMBeIfI3GM3iqOTyeqDV1+w92NcJGlb54GxAyElnU+oiHhYHt+Qrv5abi3CGpCEtDu4/COc1+U1ipGLN5gnnBSh+4rYjfQOCI1CPDaFXpOizyKS9UDsYJ52OdJxFhtRq5XyutcLr5efLqYPYXcEYT8JB1hNlc2zuYoiQKlv3OIlcwzuO4J8FI6pBLBnLtd4Qq4yrM/12IcIHKqoJyKmkdzRFlMs40JNZrud2ioB2FmmST+kOqYVMRYQm5Q83yNYKq6RLhHPFcQTeVvNlsidiayV2Vch5uhCgUkz7hZf imported-openssh-key
diff --git a/src/Renci.SshNet.Tests/Data/Key.SSH2.RSA.Encrypted.Des.CBC.12345.txt b/test/Data/Key.SSH2.RSA.Encrypted.Des.CBC.12345.txt
similarity index 96%
rename from src/Renci.SshNet.Tests/Data/Key.SSH2.RSA.Encrypted.Des.CBC.12345.txt
rename to test/Data/Key.SSH2.RSA.Encrypted.Des.CBC.12345.txt
index 2a81a23d5..952b012f9 100644
--- a/src/Renci.SshNet.Tests/Data/Key.SSH2.RSA.Encrypted.Des.CBC.12345.txt
+++ b/test/Data/Key.SSH2.RSA.Encrypted.Des.CBC.12345.txt
@@ -1,4 +1,4 @@
----- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----
+---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----
Comment: "imported-openssh-key"
P2/56wAAA/MAAAA3aWYtbW9kbntzaWdue3JzYS1wa2NzMS1zaGExfSxlbmNyeXB0e3JzYS
1wa2NzMXYyLW9hZXB9fQAAAAgzZGVzLWNiYwAAA6A6Wt6IR5cz0PCsSJDOjcs3MdQscfdN
diff --git a/test/Data/Key.SSH2.RSA.pub b/test/Data/Key.SSH2.RSA.pub
new file mode 100644
index 000000000..128dbc936
--- /dev/null
+++ b/test/Data/Key.SSH2.RSA.pub
@@ -0,0 +1 @@
+ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDVwZxtc4I5nngC8qAu7uJsl9yEqccA5MbUHEyTHL/SkKhM9IMBeIfI3GM3iqOTyeqDV1+w92NcJGlb54GxAyElnU+oiHhYHt+Qrv5abi3CGpCEtDu4/COc1+U1ipGLN5gnnBSh+4rYjfQOCI1CPDaFXpOizyKS9UDsYJ52OdJxFhtRq5XyutcLr5efLqYPYXcEYT8JB1hNlc2zuYoiQKlv3OIlcwzuO4J8FI6pBLBnLtd4Qq4yrM/12IcIHKqoJyKmkdzRFlMs40JNZrud2ioB2FmmST+kOqYVMRYQm5Q83yNYKq6RLhHPFcQTeVvNlsidiayV2Vch5uhCgUkz7hZf imported-openssh-key
diff --git a/src/Renci.SshNet.Tests/Data/Key.SSH2.RSA.txt b/test/Data/Key.SSH2.RSA.txt
similarity index 96%
rename from src/Renci.SshNet.Tests/Data/Key.SSH2.RSA.txt
rename to test/Data/Key.SSH2.RSA.txt
index 04f9a3ce7..2de7f0f80 100644
--- a/src/Renci.SshNet.Tests/Data/Key.SSH2.RSA.txt
+++ b/test/Data/Key.SSH2.RSA.txt
@@ -1,4 +1,4 @@
----- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----
+---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----
Comment: "imported-openssh-key"
P2/56wAAA+4AAAA3aWYtbW9kbntzaWdue3JzYS1wa2NzMS1zaGExfSxlbmNyeXB0e3JzYS
1wa2NzMXYyLW9hZXB9fQAAAARub25lAAADnwAAA5sAAAARAQABAAAIAJoF62h2fdR02ncN
diff --git a/test/Directory.Build.props b/test/Directory.Build.props
new file mode 100644
index 000000000..1e96f3c4d
--- /dev/null
+++ b/test/Directory.Build.props
@@ -0,0 +1,16 @@
+
+
+
+
+
+ $(NoWarn);CS1591
+
+
diff --git a/test/Renci.SshNet.Benchmarks/.editorconfig b/test/Renci.SshNet.Benchmarks/.editorconfig
new file mode 100644
index 000000000..e903a76d8
--- /dev/null
+++ b/test/Renci.SshNet.Benchmarks/.editorconfig
@@ -0,0 +1,72 @@
+[*.cs]
+
+#### Sonar rules ####
+
+# S125: Sections of code should not be commented out
+https://rules.sonarsource.com/csharp/RSPEC-125/
+dotnet_diagnostic.S125.severity = suggestion
+
+# S1118: Utility classes should not have public constructors
+# https://rules.sonarsource.com/csharp/RSPEC-1118/
+dotnet_diagnostic.S1118.severity = suggestion
+
+# S1450: Private fields only used as local variables in methods should become local variables
+# https://rules.sonarsource.com/csharp/RSPEC-1450/
+dotnet_diagnostic.S1450.severity = suggestion
+
+# S4144: Methods should not have identical implementations
+# https://rules.sonarsource.com/csharp/RSPEC-4144/
+dotnet_diagnostic.S4144.severity = suggestion
+
+#### SYSLIB diagnostics ####
+
+
+#### StyleCop Analyzers rules ####
+
+# SA1028: Code must not contain trailing whitespace
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1028.md
+dotnet_diagnostic.SA1028.severity = suggestion
+
+# SA1414: Tuple types in signatures should have element names
+https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1414.md
+dotnet_diagnostic.SA1414.severity = suggestion
+
+# SA1400: Access modifier must be declared
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1400.md
+dotnet_diagnostic.SA1400.severity = suggestion
+
+# SA1401: Fields must be private
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1401.md
+dotnet_diagnostic.SA1401.severity = suggestion
+
+# SA1411: Attribute constructor must not use unnecessary parenthesis
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1411.md
+dotnet_diagnostic.SA1411.severity = suggestion
+
+# SA1505: Opening braces must not be followed by blank line
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md
+dotnet_diagnostic.SA1505.severity = suggestion
+
+# SA1512: Single line comments must not be followed by blank line
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1512.md
+dotnet_diagnostic.SA1512.severity = suggestion
+
+# SA1513: Closing brace must be followed by blank line
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1513.md
+dotnet_diagnostic.SA1513.severity = suggestion
+
+#### Meziantou.Analyzer rules ####
+
+# MA0003: Add parameter name to improve readability
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0003.md
+dotnet_diagnostic.MA0003.severity = suggestion
+
+# MA0053: Make class sealed
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0053.md
+dotnet_diagnostic.MA0053.severity = suggestion
+
+#### .NET Compiler Platform analysers rules ####
+
+# CA2000: Dispose objects before losing scope
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2000
+dotnet_diagnostic.CA2000.severity = suggestion
diff --git a/test/Renci.SshNet.Benchmarks/Common/ExtensionsBenchmarks.cs b/test/Renci.SshNet.Benchmarks/Common/ExtensionsBenchmarks.cs
new file mode 100644
index 000000000..547c20d6a
--- /dev/null
+++ b/test/Renci.SshNet.Benchmarks/Common/ExtensionsBenchmarks.cs
@@ -0,0 +1,27 @@
+using BenchmarkDotNet.Attributes;
+
+using Renci.SshNet.Common;
+
+namespace Renci.SshNet.Benchmarks.Common
+{
+ public class ExtensionsBenchmarks
+ {
+ private byte[]? _data;
+
+ [Params(1000, 10000)]
+ public int N;
+
+ [GlobalSetup]
+ public void Setup()
+ {
+ _data = new byte[N];
+ new Random(42).NextBytes(_data);
+ }
+
+ [Benchmark]
+ public byte[] Reverse()
+ {
+ return _data.Reverse();
+ }
+ }
+}
diff --git a/test/Renci.SshNet.Benchmarks/Common/HostKeyEventArgsBenchmarks.cs b/test/Renci.SshNet.Benchmarks/Common/HostKeyEventArgsBenchmarks.cs
new file mode 100644
index 000000000..c3b070884
--- /dev/null
+++ b/test/Renci.SshNet.Benchmarks/Common/HostKeyEventArgsBenchmarks.cs
@@ -0,0 +1,65 @@
+using BenchmarkDotNet.Attributes;
+
+using Renci.SshNet.Common;
+using Renci.SshNet.Security;
+
+namespace Renci.SshNet.Benchmarks.Common
+{
+ [MemoryDiagnoser]
+ [ShortRunJob]
+ public class HostKeyEventArgsBenchmarks
+ {
+ private readonly KeyHostAlgorithm _keyHostAlgorithm;
+
+ public HostKeyEventArgsBenchmarks()
+ {
+ _keyHostAlgorithm = GetKeyHostAlgorithm();
+ }
+ private static KeyHostAlgorithm GetKeyHostAlgorithm()
+ {
+ using (var s = typeof(HostKeyEventArgsBenchmarks).Assembly.GetManifestResourceStream("Renci.SshNet.Benchmarks.Data.Key.RSA.txt"))
+ {
+ var privateKey = new PrivateKeyFile(s);
+ return (KeyHostAlgorithm) privateKey.HostKeyAlgorithms.First();
+ }
+ }
+
+ [Benchmark()]
+ public HostKeyEventArgs Constructor()
+ {
+ return new HostKeyEventArgs(_keyHostAlgorithm);
+ }
+
+ [Benchmark()]
+ public (string, string) CalculateFingerPrintSHA256AndMD5()
+ {
+ var test = new HostKeyEventArgs(_keyHostAlgorithm);
+
+ return (test.FingerPrintSHA256, test.FingerPrintMD5);
+ }
+
+ [Benchmark()]
+ public string CalculateFingerPrintSHA256()
+ {
+ var test = new HostKeyEventArgs(_keyHostAlgorithm);
+
+ return test.FingerPrintSHA256;
+ }
+
+ [Benchmark()]
+ public byte[] CalculateFingerPrint()
+ {
+ var test = new HostKeyEventArgs(_keyHostAlgorithm);
+
+ return test.FingerPrint;
+ }
+
+ [Benchmark()]
+ public string CalculateFingerPrintMD5()
+ {
+ var test = new HostKeyEventArgs(_keyHostAlgorithm);
+
+ return test.FingerPrintSHA256;
+ }
+ }
+}
diff --git a/test/Renci.SshNet.Benchmarks/Messages/MessageBenchmarks.cs b/test/Renci.SshNet.Benchmarks/Messages/MessageBenchmarks.cs
new file mode 100644
index 000000000..5a15773e4
--- /dev/null
+++ b/test/Renci.SshNet.Benchmarks/Messages/MessageBenchmarks.cs
@@ -0,0 +1,35 @@
+using BenchmarkDotNet.Attributes;
+
+using Renci.SshNet.Common;
+using Renci.SshNet.Messages;
+using Renci.SshNet.Messages.Transport;
+
+namespace Renci.SshNet.Benchmarks.Messages
+{
+ [MemoryDiagnoser]
+ public class MessageBenchmarks
+ {
+ [Benchmark]
+ public Message WriteBytes()
+ {
+ using var sshDataStream = new SshDataStream(SshData.DefaultCapacity);
+ var bannerMessage = new WritableDisconnectMessage(DisconnectReason.ServiceNotAvailable, "Goodbye");
+ bannerMessage.WritePrivateBytes(sshDataStream);
+
+ return bannerMessage; // Avoid JIT elimination
+ }
+
+ private sealed class WritableDisconnectMessage : DisconnectMessage
+ {
+ public WritableDisconnectMessage(DisconnectReason reasonCode, string message)
+ : base(reasonCode, message)
+ {
+ }
+
+ public void WritePrivateBytes(SshDataStream sshDataStream)
+ {
+ WriteBytes(sshDataStream);
+ }
+ }
+ }
+}
diff --git a/test/Renci.SshNet.Benchmarks/Program.cs b/test/Renci.SshNet.Benchmarks/Program.cs
new file mode 100644
index 000000000..3249baa99
--- /dev/null
+++ b/test/Renci.SshNet.Benchmarks/Program.cs
@@ -0,0 +1,27 @@
+using BenchmarkDotNet.Running;
+
+namespace Renci.SshNet.Benchmarks
+{
+ class Program
+ {
+ static void Main(string[] args)
+ {
+ // Usage examples:
+ // 1. Run all benchmarks:
+ // dotnet run -c Release -- --filter *
+ // 2. List all benchmarks:
+ // dotnet run -c Release -- --list flat
+ // 3. Run a subset of benchmarks based on a filter (of a benchmark method's fully-qualified name,
+ // e.g. "Renci.SshNet.Benchmarks.Security.Cryptography.Ciphers.AesCipherBenchmarks.Encrypt_CBC"):
+ // dotnet run -c Release -- --filter *Ciphers*
+ // 4. Run benchmarks and include memory usage statistics in the output:
+ // dotnet run -c Release -- filter *Rsa* --memory
+ // 3. Print help:
+ // dotnet run -c Release -- --help
+
+ // See also https://benchmarkdotnet.org/articles/guides/console-args.html
+
+ _ = BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);
+ }
+ }
+}
diff --git a/test/Renci.SshNet.Benchmarks/Renci.SshNet.Benchmarks.csproj b/test/Renci.SshNet.Benchmarks/Renci.SshNet.Benchmarks.csproj
new file mode 100644
index 000000000..e9e964377
--- /dev/null
+++ b/test/Renci.SshNet.Benchmarks/Renci.SshNet.Benchmarks.csproj
@@ -0,0 +1,20 @@
+
+
+ Exe
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/Renci.SshNet.Benchmarks/Security/Cryptography/Ciphers/AesCipherBenchmarks.cs b/test/Renci.SshNet.Benchmarks/Security/Cryptography/Ciphers/AesCipherBenchmarks.cs
new file mode 100644
index 000000000..f24559c5b
--- /dev/null
+++ b/test/Renci.SshNet.Benchmarks/Security/Cryptography/Ciphers/AesCipherBenchmarks.cs
@@ -0,0 +1,73 @@
+using BenchmarkDotNet.Attributes;
+using Renci.SshNet.Security.Cryptography.Ciphers;
+
+namespace Renci.SshNet.Benchmarks.Security.Cryptography.Ciphers
+{
+ [MemoryDiagnoser]
+ public class AesCipherBenchmarks
+ {
+ private readonly byte[] _key;
+ private readonly byte[] _iv;
+ private readonly byte[] _data;
+
+ public AesCipherBenchmarks()
+ {
+ _key = new byte[32];
+ _iv = new byte[16];
+ _data = new byte[32 * 1024];
+
+ Random random = new(Seed: 12345);
+ random.NextBytes(_key);
+ random.NextBytes(_iv);
+ random.NextBytes(_data);
+ }
+
+ [Benchmark]
+ public byte[] Encrypt_CBC()
+ {
+ return new AesCipher(_key, _iv, AesCipherMode.CBC, false).Encrypt(_data);
+ }
+
+ [Benchmark]
+ public byte[] Decrypt_CBC()
+ {
+ return new AesCipher(_key, _iv, AesCipherMode.CBC, false).Decrypt(_data);
+ }
+
+ [Benchmark]
+ public byte[] Encrypt_CFB()
+ {
+ return new AesCipher(_key, _iv, AesCipherMode.CFB, false).Encrypt(_data);
+ }
+
+ [Benchmark]
+ public byte[] Decrypt_CFB()
+ {
+ return new AesCipher(_key, _iv, AesCipherMode.CFB, false).Decrypt(_data);
+ }
+
+ [Benchmark]
+ public byte[] Encrypt_CTR()
+ {
+ return new AesCipher(_key, _iv, AesCipherMode.CTR, false).Encrypt(_data);
+ }
+
+ [Benchmark]
+ public byte[] Decrypt_CTR()
+ {
+ return new AesCipher(_key, _iv, AesCipherMode.CTR, false).Decrypt(_data);
+ }
+
+ [Benchmark]
+ public byte[] Encrypt_ECB()
+ {
+ return new AesCipher(_key, null, AesCipherMode.ECB, false).Encrypt(_data);
+ }
+
+ [Benchmark]
+ public byte[] Decrypt_ECB()
+ {
+ return new AesCipher(_key, null, AesCipherMode.ECB, false).Decrypt(_data);
+ }
+ }
+}
diff --git a/test/Renci.SshNet.Benchmarks/Security/Cryptography/ED25519DigitalSignatureBenchmarks.cs b/test/Renci.SshNet.Benchmarks/Security/Cryptography/ED25519DigitalSignatureBenchmarks.cs
new file mode 100644
index 000000000..44b2da8a6
--- /dev/null
+++ b/test/Renci.SshNet.Benchmarks/Security/Cryptography/ED25519DigitalSignatureBenchmarks.cs
@@ -0,0 +1,41 @@
+using BenchmarkDotNet.Attributes;
+
+using Renci.SshNet.Security;
+using Renci.SshNet.Security.Cryptography;
+
+namespace Renci.SshNet.Benchmarks.Security.Cryptography
+{
+ [MemoryDiagnoser]
+ public class ED25519DigitalSignatureBenchmarks
+ {
+ private readonly ED25519Key _key;
+ private readonly byte[] _data;
+ private readonly byte[] _signature;
+
+ public ED25519DigitalSignatureBenchmarks()
+ {
+ _data = new byte[128];
+
+ Random random = new(Seed: 12345);
+ random.NextBytes(_data);
+
+ using (var s = typeof(ED25519DigitalSignatureBenchmarks).Assembly.GetManifestResourceStream("Renci.SshNet.Benchmarks.Data.Key.OPENSSH.ED25519.txt"))
+ {
+ _key = (ED25519Key) new PrivateKeyFile(s).Key;
+ }
+ _signature = new ED25519DigitalSignature(_key).Sign(_data);
+ }
+
+ [Benchmark]
+ public byte[] Sign()
+ {
+ return new ED25519DigitalSignature(_key).Sign(_data);
+ }
+
+ [Benchmark]
+ public bool Verify()
+ {
+ return new ED25519DigitalSignature(_key).Verify(_data, _signature);
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/.editorconfig b/test/Renci.SshNet.IntegrationTests/.editorconfig
new file mode 100644
index 000000000..dfeca510a
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/.editorconfig
@@ -0,0 +1,344 @@
+[*.cs]
+
+#### Sonar rules ####
+
+# S108: Nested blocks of code should not be left empty
+# https://rules.sonarsource.com/csharp/RSPEC-108/
+dotnet_diagnostic.S108.severity = none
+
+# S125: Sections of code should not be commented out
+# https://rules.sonarsource.com/csharp/RSPEC-125/
+dotnet_diagnostic.S125.severity = none
+
+# S1118: Utility classes should not have public constructors
+# https://rules.sonarsource.com/csharp/RSPEC-1118/
+dotnet_diagnostic.S1118.severity = none
+
+# S1155: "Any()" should be used to test for emptiness
+# https://rules.sonarsource.com/csharp/RSPEC-1155/
+dotnet_diagnostic.S1155.severity = none
+
+# S1607: Tests should not be ignored
+# https://rules.sonarsource.com/csharp/RSPEC-1607/
+dotnet_diagnostic.S1607.severity = none
+
+# S2925: "Thread.Sleep" should not be used in tests
+# https://rules.sonarsource.com/csharp/RSPEC-2925/
+dotnet_diagnostic.S2925.severity = none
+
+# 53241: Methods should not return values that are never used
+# https://rules.sonarsource.com/csharp/RSPEC-3241/
+dotnet_diagnostic.S3241.severity = none
+
+# S3415: Assertion arguments should be passed in the correct order
+# https://rules.sonarsource.com/csharp/RSPEC-3415/
+dotnet_diagnostic.S3415.severity = none
+
+# S3881: "IDisposable" should be implemented correctly
+# https://rules.sonarsource.com/csharp/RSPEC-3881/
+dotnet_diagnostic.S3881.severity = none
+
+# S3966: Objects should not be disposed more than once
+# https://rules.sonarsource.com/csharp/RSPEC-3966/
+dotnet_diagnostic.S3966.severity = none
+
+# S4144: Methods should not have identical implementations
+# https://rules.sonarsource.com/csharp/RSPEC-4144/
+dotnet_diagnostic.S4144.severity = none
+
+# S6602: "Find" method should be used instead of the "FirstOrDefault" extension
+# https://rules.sonarsource.com/csharp/RSPEC-6602/
+dotnet_diagnostic.S6602.severity = none
+
+# S6610: "StartsWith" and "EndsWith" overloads that take a "char" should be used instead of the ones that take a "string"
+# https://rules.sonarsource.com/csharp/RSPEC-6610/
+dotnet_diagnostic.S6610.severity = none
+
+#### SYSLIB diagnostics ####
+
+# SYSLIB1045: Use 'GeneratedRegexAttribute' to generate the regular expression implementation at compile-time
+#
+# TODO: Remove this when https://github.com/sshnet/SSH.NET/issues/1131 is implemented.
+dotnet_diagnostic.SYSLIB1045.severity = none
+
+### StyleCop Analyzers rules ###
+
+# SA1000: Keywords must be spaced correctly
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1000.md
+dotnet_diagnostic.SA1000.severity = suggestion
+
+# SA1004: Documentation lines must begin with single space
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1004.md
+dotnet_diagnostic.SA1004.severity = suggestion
+
+# SA1005: Single line comments must begin with single space
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1005.md
+dotnet_diagnostic.SA1005.severity = suggestion
+
+# SA1012: Opening braces must be spaced correctly
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1012.md
+dotnet_diagnostic.SA1012.severity = suggestion
+
+# SA1025: Code must not contain multiple whitespace in a row
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1025.md
+dotnet_diagnostic.SA1025.severity = suggestion
+
+# SA1028: Code must not contain trailing whitespace
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1028.md
+dotnet_diagnostic.SA1028.severity = suggestion
+
+# SA1111: Closing parenthesis must be on line of last parameter
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1111.md
+dotnet_diagnostic.SA1111.severity = suggestion
+
+# SA1117: Parameters must be on same line or separate lines
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1117.md
+dotnet_diagnostic.SA1117.severity = suggestion
+
+# SA1119: Statement must not use unnecessary parenthesis
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1119.md
+dotnet_diagnostic.SA1119.severity = suggestion
+
+# SA1122: Use String.Empty for empty strings
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1122.md
+dotnet_diagnostic.SA1122.severity = suggestion
+
+# SA1123:Do not place regions within elements
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1123.md
+dotnet_diagnostic.SA1123.severity = suggestion
+
+# SA1130: Use lambda syntax
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1130.md
+dotnet_diagnostic.SA1130.severity = suggestion
+
+# SA1133: Do not combine attributes
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1133.md
+dotnet_diagnostic.SA1133.severity = suggestion
+
+# SA1203: Constants must appear before fields
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1203.md
+dotnet_diagnostic.SA1203.severity = suggestion
+
+# SA1204: Static elements must appear before instance elements
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1204.md
+dotnet_diagnostic.SA1204.severity = suggestion
+
+# SA1400: Access modifier must be declared
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1400.md
+dotnet_diagnostic.SA1400.severity = suggestion
+
+# SA1401: Fields must be private
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1401.md
+dotnet_diagnostic.SA1401.severity = suggestion
+
+# SA1411: Attribute constructor must not use unnecessary parenthesis
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1411.md
+dotnet_diagnostic.SA1411.severity = suggestion
+
+# SA1505: Opening braces must not be followed by blank line
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md
+dotnet_diagnostic.SA1505.severity = suggestion
+
+# SA1507: Code must not contain multiple blank lines in a row
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1507.md
+dotnet_diagnostic.SA1507.severity = suggestion
+
+# SA1508: Closing braces must not be preceded by blank line
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1508.md
+dotnet_diagnostic.SA1508.severity = suggestion
+
+# SA1510: Chained statement blocks must not be preceded by blank line
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1510.md
+dotnet_diagnostic.SA1510.severity = suggestion
+
+# SA1512: Single line comments must not be followed by blank line
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1512.md
+dotnet_diagnostic.SA1512.severity = suggestion
+
+# SA1513: Closing brace must be followed by blank line
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1513.md
+dotnet_diagnostic.SA1513.severity = suggestion
+
+# SA1514: Element documentation header must be preceded by blank line
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1514.md
+dotnet_diagnostic.SA1514.severity = suggestion
+
+# SA1515: Single line comment must be preceded by blank line
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1515.md
+dotnet_diagnostic.SA1515.severity = suggestion
+
+# SA1517: Code must not contain blank lines at start of file
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1517.md
+dotnet_diagnostic.SA1517.severity = suggestion
+
+# SA1518: Use line endings correctly at end of file
+https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1518.md
+dotnet_diagnostic.SA1518.severity = suggestion
+
+# SA1626: Single line comments must not use documentation style slashes
+https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1626.md
+dotnet_diagnostic.SA1626.severity = suggestion
+
+#### Meziantou.Analyzer rules ####
+
+# MA0001: StringComparison is missing
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0001.md
+dotnet_diagnostic.MA0001.severity = suggestion
+
+# MA0003: Add parameter name to improve readability
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0003.md
+dotnet_diagnostic.MA0003.severity = suggestion
+
+# MA0004: Use Task.ConfigureAwait(false)
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0004.md
+dotnet_diagnostic.MA0004.severity = suggestion
+
+# MA0011: IFormatProvider is missing
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0011.md
+dotnet_diagnostic.MA0011.severity = suggestion
+
+# MA0042: Do not use blocking calls in an async method
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0042.md
+dotnet_diagnostic.MA0042.severity = suggestion
+
+# MA0043: Use nameof operator in ArgumentException
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0043.md
+dotnet_diagnostic.MA0043.severity = suggestion
+
+# MA0046: Use EventHandler to declare events
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0046.md
+dotnet_diagnostic.MA0046.severity = suggestion
+
+# MA0053: Make class sealed
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0053.md
+dotnet_diagnostic.MA0053.severity = suggestion
+
+# MA0060: The value returned by Stream.Read/Stream.ReadAsync is not used
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0060.md
+dotnet_diagnostic.MA0060.severity = suggestion
+
+# MA0074: Avoid implicit culture-sensitive methods
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0074.md
+dotnet_diagnostic.MA0074.severity = suggestion
+
+# MA0075: Do not use implicit culture-sensitive ToString
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0075.md
+dotnet_diagnostic.MA0075.severity = suggestion
+
+# MA0076: Do not use implicit culture-sensitive ToString in interpolated strings
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0076.md
+dotnet_diagnostic.MA0076.severity = suggestion
+
+# MA0099 - Use Explicit enum value instead of 0
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0099.md
+dotnet_diagnostic.MA0099.severity = suggestion
+
+# MA0101: String contains an implicit end of line character
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0101.md
+dotnet_diagnostic.MA0101.severity = suggestion
+
+# MA0110: Use the Regex source generator
+# https://github.com/meziantou/Meziantou.Analyzer/blob/main/docs/Rules/MA0110.md
+dotnet_diagnostic.MA0110.severity = suggestion
+
+#### .NET Compiler Platform analysers rules ####
+
+# CA1031: Do not catch general exception types
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1031
+dotnet_diagnostic.CA1031.severity = suggestion
+
+# CA1052: Static holder types should be Static or NotInheritable
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1052
+dotnet_diagnostic.CA1052.severity = suggestion
+
+# CA1062: Validate arguments of public methods
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1062
+dotnet_diagnostic.CA1062.severity = suggestion
+
+# CA1063: Implement IDisposable correctly
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1063
+dotnet_diagnostic.CA1063.severity = suggestion
+
+# CA1307: Specify StringComparison for clarity
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1307
+dotnet_diagnostic.CA1307.severity = suggestion
+
+# CA1310: Specify StringComparison for correctness
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1310
+dotnet_diagnostic.CA1310.severity = suggestion
+
+# CA1507: Use nameof in place of string
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1507
+dotnet_diagnostic.CA1507.severity = suggestion
+
+# CA1827: Do not use Count()/LongCount() when Any() can be used
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1827
+dotnet_diagnostic.CA1827.severity = suggestion
+
+# CA1812: Avoid uninstantiated internal classes
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1812
+dotnet_diagnostic.CA1812.severity = suggestion
+
+# CA1816: Call GC.SuppressFinalize correctly
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1816
+dotnet_diagnostic.CA1816.severity = suggestion
+
+# CA1822: Mark members as static
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1822
+dotnet_diagnostic.CA1822.severity = suggestion
+
+# CA1840: Use Environment.CurrentManagedThreadId instead of Thread.CurrentThread.ManagedThreadId
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1840
+dotnet_diagnostic.CA1840.severity = suggestion
+
+# CA1851: Possible multiple enumerations of IEnumerable collection
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1851
+dotnet_diagnostic.CA1851.severity = suggestion
+
+# CA1859: Use concrete types when possible for improved performance
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1859
+dotnet_diagnostic.CA1859.severity = suggestion
+
+# CA2000: Dispose objects before losing scope
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2000
+dotnet_diagnostic.CA2000.severity = suggestion
+
+# CA2007: Do not directly await a Task
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2007
+dotnet_diagnostic.CA2007.severity = suggestion
+
+# CA2008: Do not create tasks without passing a TaskScheduler
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2008
+dotnet_diagnostic.CA2008.severity = suggestion
+
+# CA2201: Do not raise reserved exception types
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2201
+dotnet_diagnostic.CA2201.severity = suggestion
+
+# CA2213: Disposable fields should be disposed
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2213
+dotnet_diagnostic.CA2213.severity = suggestion
+
+# CA2234: Pass System.Uri objects instead of strings
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2234
+dotnet_diagnostic.CA2234.severity = suggestion
+
+# IDE0007: Use var instead of explicit type
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0007
+dotnet_diagnostic.IDE0007.severity = suggestion
+
+# IDE0028: Use collection initializers
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0028
+dotnet_diagnostic.IDE0028.severity = suggestion
+
+# IDE0058: Remove unnecessary expression value
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0058
+dotnet_diagnostic.IDE0058.severity = suggestion
+
+# IDE0059: Remove unnecessary value assignment
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0059
+dotnet_diagnostic.IDE0059.severity = suggestion
+
+# IDE0230: Use UTF-8 string literal
+# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0230
+dotnet_diagnostic.IDE0230.severity = suggestion
diff --git a/test/Renci.SshNet.IntegrationTests/.gitignore b/test/Renci.SshNet.IntegrationTests/.gitignore
new file mode 100644
index 000000000..0819dad73
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/.gitignore
@@ -0,0 +1 @@
+TestResults/
\ No newline at end of file
diff --git a/test/Renci.SshNet.IntegrationTests/App.config b/test/Renci.SshNet.IntegrationTests/App.config
new file mode 100644
index 000000000..c9794e84d
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/App.config
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/Renci.SshNet.IntegrationTests/AuthenticationMethodFactory.cs b/test/Renci.SshNet.IntegrationTests/AuthenticationMethodFactory.cs
new file mode 100644
index 000000000..edb3e74d1
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/AuthenticationMethodFactory.cs
@@ -0,0 +1,103 @@
+namespace Renci.SshNet.IntegrationTests
+{
+ public class AuthenticationMethodFactory
+ {
+ public PasswordAuthenticationMethod CreatePowerUserPasswordAuthenticationMethod()
+ {
+ var user = Users.Admin;
+ return new PasswordAuthenticationMethod(user.UserName, user.Password);
+ }
+
+ public PrivateKeyAuthenticationMethod CreateRegularUserPrivateKeyAuthenticationMethod()
+ {
+ var privateKeyFile = GetPrivateKey("Data.Key.RSA.txt");
+ return new PrivateKeyAuthenticationMethod(Users.Regular.UserName, privateKeyFile);
+ }
+
+ public PrivateKeyAuthenticationMethod CreateRegularUserMultiplePrivateKeyAuthenticationMethod()
+ {
+ var privateKeyFile1 = GetPrivateKey("Data.Key.RSA.txt");
+ var privateKeyFile2 = GetPrivateKey("Data.Key.RSA.txt");
+ return new PrivateKeyAuthenticationMethod(Users.Regular.UserName, privateKeyFile1, privateKeyFile2);
+ }
+
+ public PrivateKeyAuthenticationMethod CreateRegularUserPrivateKeyWithPassPhraseAuthenticationMethod()
+ {
+ var privateKeyFile = GetPrivateKey("Data.Key.RSA.Encrypted.Aes.256.CBC.12345.txt", "12345");
+ return new PrivateKeyAuthenticationMethod(Users.Regular.UserName, privateKeyFile);
+ }
+
+ public PrivateKeyAuthenticationMethod CreateRegularUserPrivateKeyWithEmptyPassPhraseAuthenticationMethod()
+ {
+ var privateKeyFile = GetPrivateKey("Data.Key.RSA.Encrypted.Aes.256.CBC.12345.txt", null);
+ return new PrivateKeyAuthenticationMethod(Users.Regular.UserName, privateKeyFile);
+ }
+
+ public PrivateKeyAuthenticationMethod CreateRegularUserPrivateKeyAuthenticationMethodWithBadKey()
+ {
+ string unauthorizedKey = """
+ -----BEGIN RSA PRIVATE KEY-----
+ MIIEpAIBAAKCAQEAuK3OhcrEnQbbE1+WaE57tUCcTz1yqdE2AwvMfs3of1nyfGcS
+ Rz9vzAFYU+3uEEApk0QOsIeWCyB2DIlPnlQHyjVWRYPqiTtQ7GmdzbF0ISa7dr23
+ EHJKgtJxSm3O/sb5F9JyqlxFMhKpz5NVgnN7NFcej93opHZN6h9LaP8cHgJIepWV
+ IkZqhcv8v6SpAgei0muoPHB+ZA6Rycnv+2//WUBzu+3AJu0PiHUkTTVC8M5svMRV
+ Ah8CnLsCkAAx7ld4AH7McRlFjymmkwxTSewFJYkloI/OqDOjsmuW03Gmx+eytPWa
+ HEPGeRhcz1kZ6eOmqrPMlTaLPV1MbFn86nauAQIDAQABAoIBAGEiWauZOMx2nKeV
+ 8SAvl3V/5DbxVOvotAXqIMbZOl4xSw8Pj1eWEBE26+RJEpvNg5CHjUpgJhT4H978
+ Ibpe7DH418V8WtGPN0MBUhSsLy54lsUfh7fIxVQFp7zEAMmUkdNrxw+/tE1f75zU
+ G3efkb+3ysVUrFZEOzrW9uzksT8+gm2Ll/IKuDy2r5k9mJr2cX5OYKxXjtNo5duO
+ UK+M3jW9Sk1k23Jzpq2GwuJGTTjgtI41ND6CDkrY7COdRQdIx3eQ0uQSXosKNREe
+ lv0VTlboVyh8JXt+G1tkfA6+Al77/mzycaZVX26C8Io7Y/S7JVG7TT1p1RsFGZM8
+ kcqvpBkCgYEA7vD3S+6T+8Ql8U877nDi/Ttf16NEUUQllgjWgCP+DiWcqQGWaiaB
+ JTYyM4Ydb4jy2jAcAdf3HfImE4QO3+u/wyuQrdlvWByHo2NqOxYMdyqKqwGh7qhU
+ zZFbGfHRD/gV4hWXfzj65wA8uMBVc5J3/ug7nmkTWywiDH/SsPdbxmcCgYEAxd0c
+ EbJ3dlIyK5Ul1Gw5dASyE91Nx/NHAvB+5QHH5rIe/IqbtxbXmEMKcxwEPN8hvpzs
+ g487TQFkNPze6X8vZkiuaNLUq9vwRlQwr/LIdjLLKOA69wKfFDSkei8LEMgEz7Wg
+ ZEm8ifJP75hGozx31bW4dYX2o2X75SbXneMVF1cCgYEAo4h8WJXC5o9KwKtQA1Nz
+ p4lZgUaW3V/csaD+3djEan5HiEwz3BbaUNOU7DqgLtP2EmrW4FQlJ3Oxp628WHkL
+ V9KbRMEKOa3dD3BdJm9ivLR7D6sgXy0KTV9skIc2ZM2QfJn2g/ZFkpBQ/sl0MpNO
+ WUIse7DCtKWx8AgT9VZ2k4UCgYB1G8JSQyPrtwiUvQkP6iIzJdhUY4Z20ulztu4U
+ EvLC+yfV5x/0xKNELmHP8YQclyA81loyH6NEl488wXIaFznxuxDnX+mZ8moK5ieO
+ 7A5zzuppvhWIP1fyOJok6xUMkKYwXdqZoP7jUrS3JZShZteyeIS9olVxLpphbZTu
+ kQnZrwKBgQDhO2+iGXwNLS+OFKwEiyUgvi6jb5OrIsdwWgqaqQarm6h0QWtxrCs6
+ CMFFEusswZEGRo83J6lQxtcXvhWzTkVPu69J8YvTQqcKlvUSA9TEG2iX9bwXSWzy
+ LeGb5NjBZ3szfzp9l5Utnj5GuAGoDDDKpf7M6S95Lg6F58Mhd/tCFA==
+ -----END RSA PRIVATE KEY-----
+ """;
+
+ using MemoryStream memoryStream = new(Encoding.UTF8.GetBytes(unauthorizedKey));
+ return new PrivateKeyAuthenticationMethod(Users.Regular.UserName, new PrivateKeyFile(memoryStream));
+ }
+
+ public PasswordAuthenticationMethod CreateRegularUserPasswordAuthenticationMethod()
+ {
+ return new PasswordAuthenticationMethod(Users.Regular.UserName, Users.Regular.Password);
+ }
+
+ public PasswordAuthenticationMethod CreateRegularUserPasswordAuthenticationMethodWithBadPassword()
+ {
+ return new PasswordAuthenticationMethod(Users.Regular.UserName, "xxx");
+ }
+
+ public KeyboardInteractiveAuthenticationMethod CreateRegularUserKeyboardInteractiveAuthenticationMethod()
+ {
+ var keyboardInteractive = new KeyboardInteractiveAuthenticationMethod(Users.Regular.UserName);
+ keyboardInteractive.AuthenticationPrompt += (sender, args) =>
+ {
+ foreach (var authenticationPrompt in args.Prompts)
+ {
+ authenticationPrompt.Response = Users.Regular.Password;
+ }
+ };
+ return keyboardInteractive;
+ }
+
+ private PrivateKeyFile GetPrivateKey(string resourceName, string passPhrase = null)
+ {
+ using (var stream = TestBase.GetData(resourceName))
+ {
+ return new PrivateKeyFile(stream, passPhrase);
+ }
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/AuthenticationTests.cs b/test/Renci.SshNet.IntegrationTests/AuthenticationTests.cs
new file mode 100644
index 000000000..dd0a4f3d9
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/AuthenticationTests.cs
@@ -0,0 +1,457 @@
+using Renci.SshNet.Common;
+using Renci.SshNet.IntegrationTests.Common;
+
+namespace Renci.SshNet.IntegrationTests
+{
+ [TestClass]
+ public class AuthenticationTests : IntegrationTestBase
+ {
+ private AuthenticationMethodFactory _authenticationMethodFactory;
+ private IConnectionInfoFactory _connectionInfoFactory;
+ private IConnectionInfoFactory _adminConnectionInfoFactory;
+ private RemoteSshdConfig _remoteSshdConfig;
+
+ [TestInitialize]
+ public void SetUp()
+ {
+ _authenticationMethodFactory = new AuthenticationMethodFactory();
+ _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort, _authenticationMethodFactory);
+ _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
+ _remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
+ }
+
+ [TestCleanup]
+ public void TearDown()
+ {
+ _remoteSshdConfig?.Reset();
+
+ using (var client = new SshClient(_adminConnectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ // Reset the password back to the "regular" password.
+ using (var cmd = client.RunCommand($"echo \"{Users.Regular.Password}\n{Users.Regular.Password}\" | sudo passwd " + Users.Regular.UserName))
+ {
+ Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
+ }
+
+ // Remove password expiration
+ using (var cmd = client.RunCommand($"sudo chage --expiredate -1 " + Users.Regular.UserName))
+ {
+ Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
+ }
+ }
+ }
+
+ [TestMethod]
+ public void Multifactor_PublicKey()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "publickey")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Authentication")]
+ public void Multifactor_PublicKey_Connect_Then_Reconnect()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "publickey")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ client.Disconnect();
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ public void Multifactor_PublicKeyWithPassPhrase()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "publickey")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPrivateKeyWithPassPhraseAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+ }
+
+ [TestMethod]
+ [ExpectedException(typeof(SshPassPhraseNullOrEmptyException))]
+ public void Multifactor_PublicKeyWithEmptyPassPhrase()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "publickey")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPrivateKeyWithEmptyPassPhraseAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+ }
+
+ [TestMethod]
+ public void Multifactor_PublicKey_MultiplePrivateKey()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "publickey")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserMultiplePrivateKeyAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+ }
+
+ [TestMethod]
+ public void Multifactor_PublicKey_MultipleAuthenticationMethod()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "publickey")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethod(),
+ _authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+ }
+
+ [TestMethod]
+ public void Multifactor_KeyboardInteractiveAndPublicKey()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "keyboard-interactive,publickey")
+ .WithChallengeResponseAuthentication(true)
+ .WithKeyboardInteractiveAuthentication(true)
+ .WithUsePAM(true)
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPasswordAuthenticationMethodWithBadPassword(),
+ _authenticationMethodFactory.CreateRegularUserKeyboardInteractiveAuthenticationMethod(),
+ _authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+ }
+
+ [TestMethod]
+ public void Multifactor_Password_ExceedsPartialSuccessLimit()
+ {
+ // configure server to require more successfull authentications from a given method than our partial
+ // success limit (5) allows
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "password,password,password,password,password,password")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPasswordAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ try
+ {
+ client.Connect();
+ Assert.Fail();
+ }
+ catch (SshAuthenticationException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual("Reached authentication attempt limit for method (password).", ex.Message);
+ }
+ }
+ }
+
+ [TestMethod]
+ public void Multifactor_Password_MatchPartialSuccessLimit()
+ {
+ // configure server to require a number of successfull authentications from a given method that exactly
+ // matches our partial success limit (5)
+
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "password,password,password,password,password")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPasswordAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+ }
+
+ [TestMethod]
+ public void Multifactor_Password_Or_PublicKeyAndKeyboardInteractive()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "password publickey,keyboard-interactive")
+ .WithChallengeResponseAuthentication(true)
+ .WithKeyboardInteractiveAuthentication(true)
+ .WithUsePAM(true)
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethod(),
+ _authenticationMethodFactory.CreateRegularUserPasswordAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+ }
+
+ [TestMethod]
+ public void Multifactor_Password_Or_PublicKeyAndPassword_BadPassword()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "password publickey,password")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPasswordAuthenticationMethodWithBadPassword(),
+ _authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ try
+ {
+ client.Connect();
+ Assert.Fail();
+ }
+ catch (SshAuthenticationException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual("Permission denied (password).", ex.Message);
+ }
+ }
+ }
+
+ [TestMethod]
+ public void Multifactor_PasswordAndPublicKey_Or_PasswordAndPassword()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "password,publickey password,password")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPasswordAuthenticationMethod(),
+ _authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethodWithBadKey());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+
+ connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPasswordAuthenticationMethodWithBadPassword(),
+ _authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ try
+ {
+ client.Connect();
+ Assert.Fail();
+ }
+ catch (SshAuthenticationException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual("Permission denied (password).", ex.Message);
+ }
+ }
+
+ }
+
+ [TestMethod]
+ public void Multifactor_PasswordAndPassword_Or_PublicKey()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "password,password publickey")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPasswordAuthenticationMethod(),
+ _authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethodWithBadKey());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+
+ connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPasswordAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+
+ }
+
+ [TestMethod]
+ public void Multifactor_Password_Or_Password()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "password password")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPasswordAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+
+ connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserPasswordAuthenticationMethod(),
+ _authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethodWithBadKey());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ }
+ }
+
+ [TestMethod]
+ public void KeyboardInteractive_PasswordExpired()
+ {
+ var temporaryPassword = new Random().Next().ToString();
+
+ using (var client = new SshClient(_adminConnectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ // Temporarity modify password so that when we expire this password, we change reset the password back to
+ // the "regular" password.
+ using (var cmd = client.RunCommand($"echo \"{temporaryPassword}\n{temporaryPassword}\" | sudo passwd " + Users.Regular.UserName))
+ {
+ Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
+ }
+
+ // Force the password to expire immediately
+ using (var cmd = client.RunCommand($"sudo chage -d 0 " + Users.Regular.UserName))
+ {
+ Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
+ }
+ }
+
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "keyboard-interactive")
+ .WithChallengeResponseAuthentication(true)
+ .WithKeyboardInteractiveAuthentication(true)
+ .WithUsePAM(true)
+ .Update()
+ .Restart();
+
+ var keyboardInteractive = new KeyboardInteractiveAuthenticationMethod(Users.Regular.UserName);
+ int authenticationPromptCount = 0;
+ keyboardInteractive.AuthenticationPrompt += (sender, args) =>
+ {
+ Console.WriteLine(args.Instruction);
+ foreach (var authenticationPrompt in args.Prompts)
+ {
+ Console.WriteLine(authenticationPrompt.Request);
+ switch (authenticationPromptCount)
+ {
+ case 0:
+ // Regular password prompt
+ authenticationPrompt.Response = temporaryPassword;
+ break;
+ case 1:
+ // Password expired, provide current password
+ authenticationPrompt.Response = temporaryPassword;
+ break;
+ case 2:
+ // Password expired, provide new password
+ authenticationPrompt.Response = Users.Regular.Password;
+ break;
+ case 3:
+ // Password expired, retype new password
+ authenticationPrompt.Response = Users.Regular.Password;
+ break;
+ }
+
+ authenticationPromptCount++;
+ }
+ };
+
+ var connectionInfo = _connectionInfoFactory.Create(keyboardInteractive);
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+ Assert.AreEqual(4, authenticationPromptCount);
+ }
+ }
+
+ [TestMethod]
+ public void KeyboardInteractiveConnectionInfo()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "keyboard-interactive")
+ .WithChallengeResponseAuthentication(true)
+ .WithKeyboardInteractiveAuthentication(true)
+ .WithUsePAM(true)
+ .Update()
+ .Restart();
+
+ var host = SshServerHostName;
+ var port = SshServerPort;
+ var username = User.UserName;
+ var password = User.Password;
+
+ #region Example KeyboardInteractiveConnectionInfo AuthenticationPrompt
+
+ var connectionInfo = new KeyboardInteractiveConnectionInfo(host, port, username);
+ connectionInfo.AuthenticationPrompt += delegate (object sender, AuthenticationPromptEventArgs e)
+ {
+ Console.WriteLine(e.Instruction);
+
+ foreach (var prompt in e.Prompts)
+ {
+ Console.WriteLine(prompt.Request);
+ prompt.Response = password;
+ }
+ };
+
+ using (var client = new SftpClient(connectionInfo))
+ {
+ client.Connect();
+
+ // Do something here
+ client.Disconnect();
+ }
+
+ #endregion
+
+ Assert.AreEqual(connectionInfo.Host, SshServerHostName);
+ Assert.AreEqual(connectionInfo.Username, User.UserName);
+ }
+
+ [TestMethod]
+ public void KeyboardInteractive_NoResponseSet_ThrowsSshAuthenticationException()
+ {
+ // ...instead of a cryptic ArgumentNullException
+ // https://github.com/sshnet/SSH.NET/issues/382
+
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "keyboard-interactive")
+ .WithChallengeResponseAuthentication(true)
+ .WithKeyboardInteractiveAuthentication(true)
+ .WithUsePAM(true)
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(new KeyboardInteractiveAuthenticationMethod(Users.Regular.UserName));
+
+ using (var client = new SftpClient(connectionInfo))
+ {
+ try
+ {
+ client.Connect();
+ Assert.Fail();
+ }
+ catch (SshAuthenticationException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.IsTrue(ex.Message.StartsWith("AuthenticationPrompt.Response is null for prompt \"Password: \""), $"Message was \"{ex.Message}\"");
+ }
+ }
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/CipherTests.cs b/test/Renci.SshNet.IntegrationTests/CipherTests.cs
new file mode 100644
index 000000000..1a11f9814
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/CipherTests.cs
@@ -0,0 +1,81 @@
+using Renci.SshNet.IntegrationTests.Common;
+using Renci.SshNet.TestTools.OpenSSH;
+
+namespace Renci.SshNet.IntegrationTests
+{
+ [TestClass]
+ public class CipherTests : IntegrationTestBase
+ {
+ private IConnectionInfoFactory _connectionInfoFactory;
+ private RemoteSshdConfig _remoteSshdConfig;
+
+ [TestInitialize]
+ public void SetUp()
+ {
+ _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
+ _remoteSshdConfig = new RemoteSshd(new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort)).OpenConfig();
+ }
+
+ [TestCleanup]
+ public void TearDown()
+ {
+ _remoteSshdConfig?.Reset();
+ }
+
+ [TestMethod]
+ public void TripledesCbc()
+ {
+ DoTest(Cipher.TripledesCbc);
+ }
+
+ [TestMethod]
+ public void Aes128Cbc()
+ {
+ DoTest(Cipher.Aes128Cbc);
+ }
+
+ [TestMethod]
+ public void Aes192Cbc()
+ {
+ DoTest(Cipher.Aes192Cbc);
+ }
+
+ [TestMethod]
+ public void Aes256Cbc()
+ {
+ DoTest(Cipher.Aes256Cbc);
+ }
+
+ [TestMethod]
+ public void Aes128Ctr()
+ {
+ DoTest(Cipher.Aes128Ctr);
+ }
+
+ [TestMethod]
+ public void Aes192Ctr()
+ {
+ DoTest(Cipher.Aes192Ctr);
+ }
+
+ [TestMethod]
+ public void Aes256Ctr()
+ {
+ DoTest(Cipher.Aes256Ctr);
+ }
+
+ private void DoTest(Cipher cipher)
+ {
+ _remoteSshdConfig.ClearCiphers()
+ .AddCipher(cipher)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/Common/ArrayBuilder.cs b/test/Renci.SshNet.IntegrationTests/Common/ArrayBuilder.cs
new file mode 100644
index 000000000..1720c19c9
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/Common/ArrayBuilder.cs
@@ -0,0 +1,32 @@
+namespace Renci.SshNet.IntegrationTests.Common
+{
+ public class ArrayBuilder
+ {
+ private readonly List _buffer;
+
+ public ArrayBuilder()
+ {
+ _buffer = new List();
+ }
+
+ public ArrayBuilder Add(T[] array)
+ {
+ return Add(array, 0, array.Length);
+ }
+
+ public ArrayBuilder Add(T[] array, int index, int length)
+ {
+ for (var i = 0; i < length; i++)
+ {
+ _buffer.Add(array[index + i]);
+ }
+
+ return this;
+ }
+
+ public T[] Build()
+ {
+ return _buffer.ToArray();
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/Common/AsyncSocketListener.cs b/test/Renci.SshNet.IntegrationTests/Common/AsyncSocketListener.cs
new file mode 100644
index 000000000..753385582
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/Common/AsyncSocketListener.cs
@@ -0,0 +1,393 @@
+using System.Net;
+using System.Net.Sockets;
+
+namespace Renci.SshNet.IntegrationTests.Common
+{
+ public class AsyncSocketListener : IDisposable
+ {
+ private readonly IPEndPoint _endPoint;
+ private readonly ManualResetEvent _acceptCallbackDone;
+ private readonly List _connectedClients;
+ private readonly object _syncLock;
+ private Socket _listener;
+ private Thread _receiveThread;
+ private bool _started;
+ private string _stackTrace;
+
+ public delegate void BytesReceivedHandler(byte[] bytesReceived, Socket socket);
+ public delegate void ConnectedHandler(Socket socket);
+
+ public event BytesReceivedHandler BytesReceived;
+ public event ConnectedHandler Connected;
+ public event ConnectedHandler Disconnected;
+
+ public AsyncSocketListener(IPEndPoint endPoint)
+ {
+ _endPoint = endPoint;
+ _acceptCallbackDone = new ManualResetEvent(false);
+ _connectedClients = new List();
+ _syncLock = new object();
+ ShutdownRemoteCommunicationSocket = true;
+ }
+
+ ///
+ /// Gets a value indicating whether the is invoked on the
+ /// that is used to handle the communication with the remote host, when the remote host has closed the connection.
+ ///
+ ///
+ /// to invoke on the that is used
+ /// to handle the communication with the remote host, when the remote host has closed the connection; otherwise,
+ /// . The default is .
+ ///
+ public bool ShutdownRemoteCommunicationSocket { get; set; }
+
+ public void Start()
+ {
+ _listener = new Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
+ _listener.Bind(_endPoint);
+ _listener.Listen(1);
+
+ _started = true;
+
+ _receiveThread = new Thread(StartListener);
+ _receiveThread.Start(_listener);
+
+ _stackTrace = Environment.StackTrace;
+ }
+
+ public void Stop()
+ {
+ _started = false;
+
+ lock (_syncLock)
+ {
+ foreach (var connectedClient in _connectedClients)
+ {
+ try
+ {
+ connectedClient.Shutdown(SocketShutdown.Send);
+ }
+ catch (Exception ex)
+ {
+ Console.Error.WriteLine("[{0}] Failure shutting down socket: {1}",
+ typeof(AsyncSocketListener).FullName,
+ ex);
+ }
+
+ DrainSocket(connectedClient);
+ connectedClient.Dispose();
+ }
+
+ _connectedClients.Clear();
+ }
+
+ _listener?.Dispose();
+
+ if (_receiveThread != null)
+ {
+ _receiveThread.Join();
+ _receiveThread = null;
+ }
+ }
+
+ public void Dispose()
+ {
+ Stop();
+ GC.SuppressFinalize(this);
+ }
+
+ private void StartListener(object state)
+ {
+ try
+ {
+ var listener = (Socket) state;
+ while (_started)
+ {
+ _ = _acceptCallbackDone.Reset();
+ _ = listener.BeginAccept(AcceptCallback, listener);
+ _ = _acceptCallbackDone.WaitOne();
+ }
+ }
+ catch (Exception ex)
+ {
+ // On .NET framework when Thread throws an exception then unit tests
+ // were executed without any problem.
+ // On new .NET exceptions from Thread breaks unit tests session.
+ Console.Error.WriteLine("[{0}] Failure in StartListener: {1}",
+ typeof(AsyncSocketListener).FullName,
+ ex);
+ }
+ }
+
+ private void AcceptCallback(IAsyncResult ar)
+ {
+ // Signal the main thread to continue
+ _ = _acceptCallbackDone.Set();
+
+ // Get the socket that listens for inbound connections
+ var listener = (Socket) ar.AsyncState;
+
+ // Get the socket that handles the client request
+ Socket handler;
+
+ try
+ {
+ handler = listener.EndAccept(ar);
+ }
+ catch (SocketException ex)
+ {
+ // The listener is stopped through a Dispose() call, which in turn causes
+ // Socket.EndAccept(...) to throw a SocketException or
+ // ObjectDisposedException
+ //
+ // Since we consider such an exception normal when the listener is being
+ // stopped, we only write a message to stderr if the listener is considered
+ // to be up and running
+ if (_started)
+ {
+ Console.Error.WriteLine("[{0}] Failure accepting new connection: {1}",
+ typeof(AsyncSocketListener).FullName,
+ ex);
+ }
+ return;
+ }
+ catch (ObjectDisposedException ex)
+ {
+ // The listener is stopped through a Dispose() call, which in turn causes
+ // Socket.EndAccept(IAsyncResult) to throw a SocketException or
+ // ObjectDisposedException
+ //
+ // Since we consider such an exception normal when the listener is being
+ // stopped, we only write a message to stderr if the listener is considered
+ // to be up and running
+ if (_started)
+ {
+ Console.Error.WriteLine("[{0}] Failure accepting new connection: {1}",
+ typeof(AsyncSocketListener).FullName,
+ ex);
+ }
+ return;
+ }
+
+ // Signal new connection
+ SignalConnected(handler);
+
+ lock (_syncLock)
+ {
+ // Register client socket
+ _connectedClients.Add(handler);
+ }
+
+ var state = new SocketStateObject(handler);
+
+ try
+ {
+ _ = handler.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, ReadCallback, state);
+ }
+ catch (SocketException ex)
+ {
+ // The listener is stopped through a Dispose() call, which in turn causes
+ // Socket.BeginReceive(...) to throw a SocketException or
+ // ObjectDisposedException
+ //
+ // Since we consider such an exception normal when the listener is being
+ // stopped, we only write a message to stderr if the listener is considered
+ // to be up and running
+ if (_started)
+ {
+ Console.Error.WriteLine("[{0}] Failure receiving new data: {1}",
+ typeof(AsyncSocketListener).FullName,
+ ex);
+ }
+ }
+ catch (ObjectDisposedException ex)
+ {
+ // The listener is stopped through a Dispose() call, which in turn causes
+ // Socket.BeginReceive(...) to throw a SocketException or
+ // ObjectDisposedException
+ //
+ // Since we consider such an exception normal when the listener is being
+ // stopped, we only write a message to stderr if the listener is considered
+ // to be up and running
+ if (_started)
+ {
+ Console.Error.WriteLine("[{0}] Failure receiving new data: {1}",
+ typeof(AsyncSocketListener).FullName,
+ ex);
+ }
+ }
+ }
+
+ private void ReadCallback(IAsyncResult ar)
+ {
+ // Retrieve the state object and the handler socket
+ // from the asynchronous state object
+ var state = (SocketStateObject) ar.AsyncState;
+ var handler = state.Socket;
+
+ int bytesRead;
+ try
+ {
+ // Read data from the client socket.
+ bytesRead = handler.EndReceive(ar, out var errorCode);
+ if (errorCode != SocketError.Success)
+ {
+ bytesRead = 0;
+ }
+ }
+ catch (SocketException ex)
+ {
+ // The listener is stopped through a Dispose() call, which in turn causes
+ // Socket.EndReceive(...) to throw a SocketException or
+ // ObjectDisposedException
+ //
+ // Since we consider such an exception normal when the listener is being
+ // stopped, we only write a message to stderr if the listener is considered
+ // to be up and running
+ if (_started)
+ {
+ Console.Error.WriteLine("[{0}] Failure receiving new data: {1}",
+ typeof(AsyncSocketListener).FullName,
+ ex);
+ }
+ return;
+ }
+ catch (ObjectDisposedException ex)
+ {
+ // The listener is stopped through a Dispose() call, which in turn causes
+ // Socket.EndReceive(...) to throw a SocketException or
+ // ObjectDisposedException
+ //
+ // Since we consider such an exception normal when the listener is being
+ // stopped, we only write a message to stderr if the listener is considered
+ // to be up and running
+ if (_started)
+ {
+ Console.Error.WriteLine("[{0}] Failure receiving new data: {1}",
+ typeof(AsyncSocketListener).FullName,
+ ex);
+ }
+ return;
+ }
+
+ void ConnectionDisconnected()
+ {
+ SignalDisconnected(handler);
+
+ if (ShutdownRemoteCommunicationSocket)
+ {
+ lock (_syncLock)
+ {
+ if (!_started)
+ {
+ return;
+ }
+
+ try
+ {
+ handler.Shutdown(SocketShutdown.Send);
+ handler.Close();
+ }
+ catch (SocketException ex) when (ex.SocketErrorCode == SocketError.ConnectionReset)
+ {
+ // On .NET 7 we got Socker Exception with ConnectionReset from Shutdown method
+ // when the socket is disposed
+ }
+ catch (SocketException ex)
+ {
+ throw new Exception("Exception in ReadCallback: " + ex.SocketErrorCode + " " + _stackTrace, ex);
+ }
+ catch (Exception ex)
+ {
+ throw new Exception("Exception in ReadCallback: " + _stackTrace, ex);
+ }
+
+ _ = _connectedClients.Remove(handler);
+ }
+ }
+ }
+
+ if (bytesRead > 0)
+ {
+ var bytesReceived = new byte[bytesRead];
+ Array.Copy(state.Buffer, bytesReceived, bytesRead);
+ SignalBytesReceived(bytesReceived, handler);
+
+ try
+ {
+ _ = handler.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, ReadCallback, state);
+ }
+ catch (ObjectDisposedException)
+ {
+ // TODO On .NET 7, sometimes we get ObjectDisposedException when _started but only on appveyor, locally it works
+ ConnectionDisconnected();
+ }
+ catch (SocketException ex)
+ {
+ if (!_started)
+ {
+ throw new Exception("BeginReceive while stopping!", ex);
+ }
+
+ throw new Exception("BeginReceive while started!: " + ex.SocketErrorCode + " " + _stackTrace, ex);
+ }
+
+ }
+ else
+ {
+ ConnectionDisconnected();
+ }
+ }
+
+ private void SignalBytesReceived(byte[] bytesReceived, Socket client)
+ {
+ BytesReceived?.Invoke(bytesReceived, client);
+ }
+
+ private void SignalConnected(Socket client)
+ {
+ Connected?.Invoke(client);
+ }
+
+ private void SignalDisconnected(Socket client)
+ {
+ Disconnected?.Invoke(client);
+ }
+
+ private static void DrainSocket(Socket socket)
+ {
+ var buffer = new byte[128];
+
+ try
+ {
+ while (true && socket.Connected)
+ {
+ var bytesRead = socket.Receive(buffer);
+ if (bytesRead == 0)
+ {
+ break;
+ }
+ }
+ }
+ catch (SocketException ex)
+ {
+ Console.Error.WriteLine("[{0}] Failure draining socket ({1}): {2}",
+ typeof(AsyncSocketListener).FullName,
+ ex.SocketErrorCode.ToString("G"),
+ ex);
+ }
+ }
+
+ private class SocketStateObject
+ {
+ public Socket Socket { get; private set; }
+
+ public readonly byte[] Buffer = new byte[1024];
+
+ public SocketStateObject(Socket handler)
+ {
+ Socket = handler;
+ }
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/Common/DateTimeAssert.cs b/test/Renci.SshNet.IntegrationTests/Common/DateTimeAssert.cs
new file mode 100644
index 000000000..036a122d5
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/Common/DateTimeAssert.cs
@@ -0,0 +1,11 @@
+namespace Renci.SshNet.IntegrationTests.Common
+{
+ public static class DateTimeAssert
+ {
+ public static void AreEqual(DateTime expected, DateTime actual)
+ {
+ Assert.AreEqual(expected, actual, $"Expected {expected:o}, but was {actual:o}.");
+ Assert.AreEqual(expected.Kind, actual.Kind);
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/Common/DateTimeExtensions.cs b/test/Renci.SshNet.IntegrationTests/Common/DateTimeExtensions.cs
new file mode 100644
index 000000000..d9f0d22e7
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/Common/DateTimeExtensions.cs
@@ -0,0 +1,12 @@
+namespace Renci.SshNet.IntegrationTests.Common
+{
+ public static class DateTimeExtensions
+ {
+ public static DateTime TruncateToWholeSeconds(this DateTime dateTime)
+ {
+ return dateTime.AddMilliseconds(-dateTime.Millisecond)
+ .AddMicroseconds(-dateTime.Microsecond)
+ .AddTicks(-(dateTime.Nanosecond / 100));
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/Common/RemoteSshdConfigExtensions.cs b/test/Renci.SshNet.IntegrationTests/Common/RemoteSshdConfigExtensions.cs
new file mode 100644
index 000000000..865154bfb
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/Common/RemoteSshdConfigExtensions.cs
@@ -0,0 +1,30 @@
+using Renci.SshNet.TestTools.OpenSSH;
+
+namespace Renci.SshNet.IntegrationTests.Common
+{
+ internal static class RemoteSshdConfigExtensions
+ {
+ private const string DefaultAuthenticationMethods = "password publickey";
+
+ public static void Reset(this RemoteSshdConfig remoteSshdConfig)
+ {
+ remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, DefaultAuthenticationMethods)
+ .WithChallengeResponseAuthentication(false)
+ .WithKeyboardInteractiveAuthentication(false)
+ .PrintMotd()
+ .WithLogLevel(LogLevel.Debug3)
+ .ClearHostKeyFiles()
+ .AddHostKeyFile(HostKeyFile.Rsa.FilePath)
+ .ClearSubsystems()
+ .AddSubsystem(new Subsystem("sftp", "/usr/lib/ssh/sftp-server"))
+ .ClearCiphers()
+ .ClearKeyExchangeAlgorithms()
+ .ClearHostKeyAlgorithms()
+ .ClearPublicKeyAcceptedAlgorithms()
+ .ClearMessageAuthenticationCodeAlgorithms()
+ .WithUsePAM(true)
+ .Update()
+ .Restart();
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/Common/Socks5Handler.cs b/test/Renci.SshNet.IntegrationTests/Common/Socks5Handler.cs
new file mode 100644
index 000000000..e50858c33
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/Common/Socks5Handler.cs
@@ -0,0 +1,255 @@
+using System.Net;
+using System.Net.Sockets;
+
+using Renci.SshNet.Abstractions;
+using Renci.SshNet.Common;
+using Renci.SshNet.Messages.Transport;
+
+namespace Renci.SshNet.IntegrationTests.Common
+{
+ class Socks5Handler
+ {
+ private readonly IPEndPoint _proxyEndPoint;
+ private readonly string _userName;
+ private readonly string _password;
+
+ public Socks5Handler(IPEndPoint proxyEndPoint, string userName, string password)
+ {
+ _proxyEndPoint = proxyEndPoint;
+ _userName = userName;
+ _password = password;
+ }
+
+ public Socket Connect(IPEndPoint endPoint)
+ {
+ if (endPoint == null)
+ {
+ throw new ArgumentNullException("endPoint");
+ }
+
+ var addressBytes = GetAddressBytes(endPoint);
+ return Connect(addressBytes, endPoint.Port);
+ }
+
+ public Socket Connect(string host, int port)
+ {
+ if (host == null)
+ {
+ throw new ArgumentNullException(nameof(host));
+ }
+
+ if (host.Length > byte.MaxValue)
+ {
+ throw new ArgumentException($@"Cannot be more than {byte.MaxValue} characters.", nameof(host));
+ }
+
+ var addressBytes = new byte[host.Length + 2];
+ addressBytes[0] = 0x03;
+ addressBytes[1] = (byte) host.Length;
+ Encoding.ASCII.GetBytes(host, 0, host.Length, addressBytes, 2);
+ return Connect(addressBytes, port);
+ }
+
+ private Socket Connect(byte[] addressBytes, int port)
+ {
+ var socket = SocketAbstraction.Connect(_proxyEndPoint, TimeSpan.FromSeconds(5));
+
+ // Send socks version number
+ SocketWriteByte(socket, 0x05);
+
+ // Send number of supported authentication methods
+ SocketWriteByte(socket, 0x02);
+
+ // Send supported authentication methods
+ SocketWriteByte(socket, 0x00); // No authentication
+ SocketWriteByte(socket, 0x02); // Username/Password
+
+ var socksVersion = SocketReadByte(socket);
+ if (socksVersion != 0x05)
+ {
+ throw new ProxyException(string.Format("SOCKS Version '{0}' is not supported.", socksVersion));
+ }
+
+ var authenticationMethod = SocketReadByte(socket);
+ switch (authenticationMethod)
+ {
+ case 0x00:
+ break;
+ case 0x02:
+
+ // Send version
+ SocketWriteByte(socket, 0x01);
+
+ var username = Encoding.ASCII.GetBytes(_userName);
+ if (username.Length > byte.MaxValue)
+ {
+ throw new ProxyException("Proxy username is too long.");
+ }
+
+ // Send username length
+ SocketWriteByte(socket, (byte) username.Length);
+
+ // Send username
+ SocketAbstraction.Send(socket, username);
+
+ var password = Encoding.ASCII.GetBytes(_password);
+
+ if (password.Length > byte.MaxValue)
+ {
+ throw new ProxyException("Proxy password is too long.");
+ }
+
+ // Send username length
+ SocketWriteByte(socket, (byte) password.Length);
+
+ // Send username
+ SocketAbstraction.Send(socket, password);
+
+ var serverVersion = SocketReadByte(socket);
+
+ if (serverVersion != 1)
+ {
+ throw new ProxyException("SOCKS5: Server authentication version is not valid.");
+ }
+
+ var statusCode = SocketReadByte(socket);
+ if (statusCode != 0)
+ {
+ throw new ProxyException("SOCKS5: Username/Password authentication failed.");
+ }
+
+ break;
+ case 0xFF:
+ throw new ProxyException("SOCKS5: No acceptable authentication methods were offered.");
+ default:
+ throw new ProxyException("SOCKS5: No acceptable authentication methods were offered.");
+ }
+
+ // Send socks version number
+ SocketWriteByte(socket, 0x05);
+
+ // Send command code
+ SocketWriteByte(socket, 0x01); // establish a TCP/IP stream connection
+
+ // Send reserved, must be 0x00
+ SocketWriteByte(socket, 0x00);
+
+ // Send address type and address
+ SocketAbstraction.Send(socket, addressBytes);
+
+ // Send port
+ SocketWriteByte(socket, (byte)(port / 0xFF));
+ SocketWriteByte(socket, (byte)(port % 0xFF));
+
+ // Read Server SOCKS5 version
+ if (SocketReadByte(socket) != 5)
+ {
+ throw new ProxyException("SOCKS5: Version 5 is expected.");
+ }
+
+ // Read response code
+ var status = SocketReadByte(socket);
+
+ switch (status)
+ {
+ case 0x00:
+ break;
+ case 0x01:
+ throw new ProxyException("SOCKS5: General failure.");
+ case 0x02:
+ throw new ProxyException("SOCKS5: Connection not allowed by ruleset.");
+ case 0x03:
+ throw new ProxyException("SOCKS5: Network unreachable.");
+ case 0x04:
+ throw new ProxyException("SOCKS5: Host unreachable.");
+ case 0x05:
+ throw new ProxyException("SOCKS5: Connection refused by destination host.");
+ case 0x06:
+ throw new ProxyException("SOCKS5: TTL expired.");
+ case 0x07:
+ throw new ProxyException("SOCKS5: Command not supported or protocol error.");
+ case 0x08:
+ throw new ProxyException("SOCKS5: Address type not supported.");
+ default:
+ throw new ProxyException("SOCKS4: Not valid response.");
+ }
+
+ // Read 0
+ if (SocketReadByte(socket) != 0)
+ {
+ throw new ProxyException("SOCKS5: 0 byte is expected.");
+ }
+
+ var addressType = SocketReadByte(socket);
+ var responseIp = new byte[16];
+
+ switch (addressType)
+ {
+ case 0x01:
+ SocketRead(socket, responseIp, 0, 4);
+ break;
+ case 0x04:
+ SocketRead(socket, responseIp, 0, 16);
+ break;
+ default:
+ throw new ProxyException(string.Format("Address type '{0}' is not supported.", addressType));
+ }
+
+ var portBytes = new byte[2];
+
+ // Read 2 bytes to be ignored
+ SocketRead(socket, portBytes, 0, 2);
+
+ return socket;
+ }
+
+ private static byte[] GetAddressBytes(IPEndPoint endPoint)
+ {
+ if (endPoint.AddressFamily == AddressFamily.InterNetwork)
+ {
+ var addressBytes = new byte[4 + 1];
+ addressBytes[0] = 0x01;
+ var address = endPoint.Address.GetAddressBytes();
+ Buffer.BlockCopy(address, 0, addressBytes, 1, address.Length);
+ return addressBytes;
+ }
+
+ if (endPoint.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ var addressBytes = new byte[16 + 1];
+ addressBytes[0] = 0x04;
+ var address = endPoint.Address.GetAddressBytes();
+ Buffer.BlockCopy(address, 0, addressBytes, 1, address.Length);
+ return addressBytes;
+ }
+
+ throw new ProxyException(string.Format("SOCKS5: IP address '{0}' is not supported.", endPoint.Address));
+ }
+
+ private static void SocketWriteByte(Socket socket, byte data)
+ {
+ SocketAbstraction.Send(socket, new[] { data });
+ }
+
+ private static byte SocketReadByte(Socket socket)
+ {
+ var buffer = new byte[1];
+ SocketRead(socket, buffer, 0, 1);
+ return buffer[0];
+ }
+
+ private static int SocketRead(Socket socket, byte[] buffer, int offset, int length)
+ {
+ var bytesRead = SocketAbstraction.Read(socket, buffer, offset, length, TimeSpan.FromMilliseconds(-1));
+ if (bytesRead == 0)
+ {
+ // when we're in the disconnecting state (either triggered by client or server), then the
+ // SshConnectionException will interrupt the message listener loop (if not already interrupted)
+ // and the exception itself will be ignored (in RaiseError)
+ throw new SshConnectionException("An established connection was aborted by the server.",
+ DisconnectReason.ConnectionLost);
+ }
+ return bytesRead;
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/ConnectivityTests.cs b/test/Renci.SshNet.IntegrationTests/ConnectivityTests.cs
new file mode 100644
index 000000000..2f94ba7ff
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/ConnectivityTests.cs
@@ -0,0 +1,462 @@
+using Renci.SshNet.Common;
+using Renci.SshNet.IntegrationTests.Common;
+using Renci.SshNet.Messages.Transport;
+
+namespace Renci.SshNet.IntegrationTests
+{
+ [TestClass]
+ public class ConnectivityTests : IntegrationTestBase
+ {
+ private AuthenticationMethodFactory _authenticationMethodFactory;
+ private IConnectionInfoFactory _connectionInfoFactory;
+ private IConnectionInfoFactory _adminConnectionInfoFactory;
+ private RemoteSshdConfig _remoteSshdConfig;
+ private SshConnectionDisruptor _sshConnectionDisruptor;
+
+ [TestInitialize]
+ public void SetUp()
+ {
+ _authenticationMethodFactory = new AuthenticationMethodFactory();
+ _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort, _authenticationMethodFactory);
+ _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
+ _remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
+ _sshConnectionDisruptor = new SshConnectionDisruptor(_adminConnectionInfoFactory);
+ }
+
+ [TestCleanup]
+ public void TearDown()
+ {
+ _remoteSshdConfig?.Reset();
+ }
+
+ [TestMethod]
+ public void Common_CreateMoreChannelsThanMaxSessions()
+ {
+ var connectionInfo = _connectionInfoFactory.Create();
+ connectionInfo.MaxSessions = 2;
+
+ using (var client = new SshClient(connectionInfo))
+ {
+ client.Connect();
+
+ // create one more channel than the maximum number of sessions
+ // as that would block indefinitely when creating the last channel
+ // if the channel would not be properly closed
+ for (var i = 0; i < connectionInfo.MaxSessions + 1; i++)
+ {
+ using (var stream = client.CreateShellStream("vt220", 20, 20, 20, 20, 0))
+ {
+ stream.WriteLine("echo test");
+ stream.ReadLine();
+ }
+ }
+ }
+ }
+
+ [TestMethod]
+ public void Common_DisposeAfterLossOfNetworkConnectivity()
+ {
+ var hostNetworkConnectionDisabled = false;
+ SshConnectionRestorer disruptor = null;
+ try
+ {
+ Exception errorOccurred = null;
+ int count = 0;
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.ErrorOccurred += (sender, args) =>
+ {
+ Console.WriteLine("Exception " + count++);
+ Console.WriteLine(args.Exception);
+ errorOccurred = args.Exception;
+ };
+ client.Connect();
+
+ disruptor = _sshConnectionDisruptor.BreakConnections();
+ hostNetworkConnectionDisabled = true;
+ WaitForConnectionInterruption(client);
+ }
+
+ Assert.IsNotNull(errorOccurred);
+ Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
+
+ var connectionException = (SshConnectionException) errorOccurred;
+ Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
+ Assert.IsNull(connectionException.InnerException);
+ Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
+ }
+ finally
+ {
+ if (hostNetworkConnectionDisabled)
+ {
+ disruptor?.RestoreConnections();
+ disruptor?.Dispose();
+ }
+ }
+ }
+
+ [TestMethod]
+ public void Common_DetectLossOfNetworkConnectivityThroughKeepAlive()
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ Exception errorOccurred = null;
+ int count = 0;
+ client.ErrorOccurred += (sender, args) =>
+ {
+ Console.WriteLine("Exception "+ count++);
+ Console.WriteLine(args.Exception);
+ errorOccurred = args.Exception;
+ };
+ client.KeepAliveInterval = new TimeSpan(0, 0, 0, 0, 50);
+ client.Connect();
+
+ var disruptor = _sshConnectionDisruptor.BreakConnections();
+
+ try
+ {
+ WaitForConnectionInterruption(client);
+
+ Assert.IsFalse(client.IsConnected);
+
+ Assert.IsNotNull(errorOccurred);
+ Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
+
+ var connectionException = (SshConnectionException) errorOccurred;
+ Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
+ Assert.IsNull(connectionException.InnerException);
+ Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
+ }
+ finally
+ {
+ disruptor?.RestoreConnections();
+ disruptor?.Dispose();
+ }
+ }
+ }
+
+ private static void WaitForConnectionInterruption(SftpClient client)
+ {
+ for (var i = 0; i < 500; i++)
+ {
+ if (!client.IsConnected)
+ {
+ break;
+ }
+
+ Thread.Sleep(100);
+ }
+
+ // After interruption, you have to wait for the events to propagate.
+ Thread.Sleep(100);
+ }
+
+ [TestMethod]
+ public void Common_DetectConnectionResetThroughSftpInvocation()
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.KeepAliveInterval = TimeSpan.FromSeconds(1);
+ client.OperationTimeout = TimeSpan.FromSeconds(60);
+ ManualResetEvent errorOccurredSignaled = new ManualResetEvent(false);
+ Exception errorOccurred = null;
+ client.ErrorOccurred += (sender, args) =>
+ {
+ errorOccurred = args.Exception;
+ errorOccurredSignaled.Set();
+ };
+ client.Connect();
+
+ var disruptor = _sshConnectionDisruptor.BreakConnections();
+
+ try
+ {
+ client.ListDirectory("/");
+ Assert.Fail();
+ }
+ catch (SshConnectionException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual("Client not connected.", ex.Message);
+
+ Assert.IsNotNull(errorOccurred);
+ Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
+
+ var connectionException = (SshConnectionException) errorOccurred;
+ Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
+ Assert.IsNull(connectionException.InnerException);
+ Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
+ }
+ finally
+ {
+ disruptor.RestoreConnections();
+ disruptor.Dispose();
+ }
+ }
+ }
+
+ [TestMethod]
+ public void Common_LossOfNetworkConnectivityDisconnectAndConnect()
+ {
+ bool vmNetworkConnectionDisabled = false;
+ SshConnectionRestorer disruptor = null;
+ try
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ Exception errorOccurred = null;
+ client.ErrorOccurred += (sender, args) => errorOccurred = args.Exception;
+
+ client.Connect();
+
+ disruptor = _sshConnectionDisruptor.BreakConnections();
+ vmNetworkConnectionDisabled = true;
+
+ WaitForConnectionInterruption(client);
+ // disconnect while network connectivity is lost
+ client.Disconnect();
+
+ Assert.IsFalse(client.IsConnected);
+
+ disruptor.RestoreConnections();
+ vmNetworkConnectionDisabled = false;
+
+ // connect when network connectivity is restored
+ client.Connect();
+ client.ChangeDirectory(client.WorkingDirectory);
+ client.Dispose();
+
+ Assert.IsNotNull(errorOccurred);
+ Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
+
+ var connectionException = (SshConnectionException) errorOccurred;
+ Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
+ Assert.IsNull(connectionException.InnerException);
+ Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
+ }
+ }
+ finally
+ {
+ if (vmNetworkConnectionDisabled)
+ {
+ disruptor.RestoreConnections();
+ }
+ disruptor?.Dispose();
+ }
+ }
+
+ [TestMethod]
+ public void Common_DetectLossOfNetworkConnectivityThroughSftpInvocation()
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ ManualResetEvent errorOccurredSignaled = new ManualResetEvent(false);
+ Exception errorOccurred = null;
+ client.ErrorOccurred += (sender, args) =>
+ {
+ errorOccurred = args.Exception;
+ errorOccurredSignaled.Set();
+ };
+ client.Connect();
+
+ var disruptor = _sshConnectionDisruptor.BreakConnections();
+ Thread.Sleep(100);
+ try
+ {
+ client.ListDirectory("/");
+ Assert.Fail();
+ }
+ catch (SshConnectionException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual("Client not connected.", ex.Message);
+
+ Assert.IsNotNull(errorOccurred);
+ Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
+
+ var connectionException = (SshConnectionException) errorOccurred;
+ Assert.AreEqual(DisconnectReason.ConnectionLost, connectionException.DisconnectReason);
+ Assert.IsNull(connectionException.InnerException);
+ Assert.AreEqual("An established connection was aborted by the server.", connectionException.Message);
+ }
+ finally
+ {
+ disruptor.RestoreConnections();
+ disruptor.Dispose();
+ }
+ }
+ }
+
+ [TestMethod]
+ public void Common_DetectSessionKilledOnServer()
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ ManualResetEvent errorOccurredSignaled = new ManualResetEvent(false);
+ Exception errorOccurred = null;
+ client.ErrorOccurred += (sender, args) =>
+ {
+ errorOccurred = args.Exception;
+ errorOccurredSignaled.Set();
+ };
+ client.Connect();
+
+ // Kill the server session
+ using (var adminClient = new SshClient(_adminConnectionInfoFactory.Create()))
+ {
+ adminClient.Connect();
+
+ var command = $"sudo ps --no-headers -u {client.ConnectionInfo.Username} -f | grep \"{client.ConnectionInfo.Username}@notty\" | awk '{{print $2}}' | xargs sudo kill -9";
+ var sshCommand = adminClient.CreateCommand(command);
+ var result = sshCommand.Execute();
+ Assert.AreEqual(0, sshCommand.ExitStatus, sshCommand.Error);
+ }
+
+ Assert.IsTrue(errorOccurredSignaled.WaitOne(200));
+ Assert.IsNotNull(errorOccurred);
+ Assert.AreEqual(typeof(SshConnectionException), errorOccurred.GetType());
+ Assert.IsNull(errorOccurred.InnerException);
+ Assert.AreEqual("An established connection was aborted by the server.", errorOccurred.Message);
+ Assert.IsFalse(client.IsConnected);
+ }
+ }
+
+ [TestMethod]
+ public void Common_HostKeyValidation_Failure()
+ {
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.HostKeyReceived += (sender, e) => { e.CanTrust = false; };
+
+ try
+ {
+ client.Connect();
+ Assert.Fail();
+ }
+ catch (SshConnectionException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual("Key exchange negotiation failed.", ex.Message);
+ }
+ }
+ }
+
+ [TestMethod]
+ public void Common_HostKeyValidation_Success()
+ {
+ byte[] host_rsa_key_openssh_fingerprint =
+ {
+ 0x3d, 0x90, 0xd8, 0x0d, 0xd5, 0xe0, 0xb6, 0x13,
+ 0x42, 0x7c, 0x78, 0x1e, 0x19, 0xa3, 0x99, 0x2b
+ };
+
+ var hostValidationSuccessful = false;
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.HostKeyReceived += (sender, e) =>
+ {
+ if (host_rsa_key_openssh_fingerprint.Length == e.FingerPrint.Length)
+ {
+ for (var i = 0; i < host_rsa_key_openssh_fingerprint.Length; i++)
+ {
+ if (host_rsa_key_openssh_fingerprint[i] != e.FingerPrint[i])
+ {
+ e.CanTrust = false;
+ break;
+ }
+ }
+
+ hostValidationSuccessful = e.CanTrust;
+ }
+ else
+ {
+ e.CanTrust = false;
+ }
+ };
+ client.Connect();
+ }
+
+ Assert.IsTrue(hostValidationSuccessful);
+ }
+
+ [TestMethod]
+ public void Common_HostKeyValidationSHA256_Success()
+ {
+ var hostValidationSuccessful = false;
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.HostKeyReceived += (sender, e) =>
+ {
+ if (e.FingerPrintSHA256 == "9fa6vbz64gimzsGZ/xZi3aaYE1o7E96iU2NjcfQNGwI")
+ {
+ hostValidationSuccessful = e.CanTrust;
+ }
+ else
+ {
+ e.CanTrust = false;
+ }
+ };
+ client.Connect();
+ }
+
+ Assert.IsTrue(hostValidationSuccessful);
+ }
+
+ [TestMethod]
+ public void Common_HostKeyValidationMD5_Success()
+ {
+ var hostValidationSuccessful = false;
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.HostKeyReceived += (sender, e) =>
+ {
+ if (e.FingerPrintMD5 == "3d:90:d8:0d:d5:e0:b6:13:42:7c:78:1e:19:a3:99:2b")
+ {
+ hostValidationSuccessful = e.CanTrust;
+ }
+ else
+ {
+ e.CanTrust = false;
+ }
+ };
+ client.Connect();
+ }
+
+ Assert.IsTrue(hostValidationSuccessful);
+ }
+ ///
+ /// Verifies whether we handle a disconnect initiated by the SSH server (through a SSH_MSG_DISCONNECT message).
+ ///
+ ///
+ /// We force this by only configuring keyboard-interactive as authentication method, while ChallengeResponseAuthentication
+ /// is not enabled. This causes OpenSSH to terminate the connection because there are no authentication methods left.
+ ///
+ [TestMethod]
+ public void Common_ServerRejectsConnection()
+ {
+ _remoteSshdConfig.WithAuthenticationMethods(Users.Regular.UserName, "keyboard-interactive")
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(_authenticationMethodFactory.CreateRegularUserKeyboardInteractiveAuthenticationMethod());
+ using (var client = new SftpClient(connectionInfo))
+ {
+ try
+ {
+ client.Connect();
+ Assert.Fail();
+ }
+ catch (SshConnectionException ex)
+ {
+ Assert.AreEqual(DisconnectReason.ProtocolError, ex.DisconnectReason);
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual("The connection was closed by the server: no authentication methods enabled (ProtocolError).", ex.Message);
+ }
+ }
+ }
+
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/Credential.cs b/test/Renci.SshNet.IntegrationTests/Credential.cs
new file mode 100644
index 000000000..ee62d0f7b
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/Credential.cs
@@ -0,0 +1,14 @@
+namespace Renci.SshNet.IntegrationTests
+{
+ internal class Credential
+ {
+ public Credential(string userName, string password)
+ {
+ UserName = userName;
+ Password = password;
+ }
+
+ public string UserName { get; }
+ public string Password { get; }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/Dockerfile.TestServer b/test/Renci.SshNet.IntegrationTests/Dockerfile.TestServer
new file mode 100644
index 000000000..19ef6e19e
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/Dockerfile.TestServer
@@ -0,0 +1,50 @@
+FROM alpine:latest
+
+COPY --chown=root:root server/ssh /etc/ssh/
+COPY --chown=root:root server/script /opt/sshnet
+COPY user/sshnet /home/sshnet/.ssh
+
+RUN apk update && apk upgrade --no-cache && \
+ apk add --no-cache syslog-ng && \
+ # install and configure sshd
+ apk add --no-cache openssh && \
+ # install openssh-server-pam to allow for keyboard-interactive authentication
+ apk add --no-cache openssh-server-pam && \
+ dos2unix /etc/ssh/* && \
+ chmod 400 /etc/ssh/ssh*key && \
+ sed -i 's/#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config && \
+ sed -i 's/#LogLevel\s*INFO/LogLevel DEBUG3/' /etc/ssh/sshd_config && \
+ # Set the default RSA key
+ echo 'HostKey /etc/ssh/ssh_host_rsa_key' >> /etc/ssh/sshd_config && \
+ chmod 646 /etc/ssh/sshd_config && \
+ # install and configure sudo
+ apk add --no-cache sudo && \
+ addgroup sudo && \
+ # allow root to run any command
+ echo 'root ALL=(ALL) ALL' > /etc/sudoers && \
+ # allow everyone in the 'sudo' group to run any command without a password
+ echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers && \
+ # add user to run most of the integration tests
+ adduser -D sshnet && \
+ passwd -u sshnet && \
+ echo 'sshnet:ssh4ever' | chpasswd && \
+ dos2unix /home/sshnet/.ssh/* && \
+ chown -R sshnet:sshnet /home/sshnet && \
+ chmod -R 700 /home/sshnet/.ssh && \
+ chmod -R 644 /home/sshnet/.ssh/authorized_keys && \
+ # add user to administer container (update configs, restart sshd)
+ adduser -D sshnetadm && \
+ passwd -u sshnetadm && \
+ echo 'sshnetadm:ssh4ever' | chpasswd && \
+ addgroup sshnetadm sudo && \
+ dos2unix /opt/sshnet/* && \
+ # install shadow package; we use chage command in this package to expire/unexpire password of the sshnet user
+ apk add --no-cache shadow && \
+ # allow us to use telnet command; we use this in the remote port forwarding tests
+ apk --no-cache add busybox-extras && \
+ # install full-fledged ps command
+ apk add --no-cache procps
+
+EXPOSE 22 22
+
+ENTRYPOINT ["/opt/sshnet/start.sh"]
diff --git a/test/Renci.SshNet.IntegrationTests/HmacTests.cs b/test/Renci.SshNet.IntegrationTests/HmacTests.cs
new file mode 100644
index 000000000..993e5ec98
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/HmacTests.cs
@@ -0,0 +1,75 @@
+using Renci.SshNet.IntegrationTests.Common;
+using Renci.SshNet.TestTools.OpenSSH;
+
+namespace Renci.SshNet.IntegrationTests
+{
+ [TestClass]
+ public class HmacTests : IntegrationTestBase
+ {
+ private IConnectionInfoFactory _connectionInfoFactory;
+ private RemoteSshdConfig _remoteSshdConfig;
+
+ [TestInitialize]
+ public void SetUp()
+ {
+ _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
+ _remoteSshdConfig = new RemoteSshd(new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort)).OpenConfig();
+ }
+
+ [TestCleanup]
+ public void TearDown()
+ {
+ _remoteSshdConfig?.Reset();
+ }
+
+ [TestMethod]
+ public void HmacMd5()
+ {
+ DoTest(MessageAuthenticationCodeAlgorithm.HmacMd5);
+ }
+
+ [TestMethod]
+ public void HmacMd5_96()
+ {
+ DoTest(MessageAuthenticationCodeAlgorithm.HmacMd5_96);
+ }
+
+ [TestMethod]
+ public void HmacSha1()
+ {
+ DoTest(MessageAuthenticationCodeAlgorithm.HmacSha1);
+ }
+
+ [TestMethod]
+ public void HmacSha1_96()
+ {
+ DoTest(MessageAuthenticationCodeAlgorithm.HmacSha1_96);
+ }
+
+ [TestMethod]
+ public void HmacSha2_256()
+ {
+ DoTest(MessageAuthenticationCodeAlgorithm.HmacSha2_256);
+ }
+
+ [TestMethod]
+ public void HmacSha2_512()
+ {
+ DoTest(MessageAuthenticationCodeAlgorithm.HmacSha2_512);
+ }
+
+ private void DoTest(MessageAuthenticationCodeAlgorithm macAlgorithm)
+ {
+ _remoteSshdConfig.ClearMessageAuthenticationCodeAlgorithms()
+ .AddMessageAuthenticationCodeAlgorithm(macAlgorithm)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/HostConfig.cs b/test/Renci.SshNet.IntegrationTests/HostConfig.cs
new file mode 100644
index 000000000..c328a729c
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/HostConfig.cs
@@ -0,0 +1,101 @@
+using System.Net;
+using System.Text.RegularExpressions;
+
+namespace Renci.SshNet.IntegrationTests
+{
+ class HostConfig
+ {
+ private static readonly Regex HostsEntryRegEx = new Regex(@"^(?[\S]+)\s+(?[a-zA-Z]+[a-zA-Z\-\.]*[a-zA-Z]+)\s*(?.+)*$", RegexOptions.Singleline);
+
+ public List Entries { get; }
+
+ private HostConfig()
+ {
+ Entries = new List();
+ }
+
+ public static HostConfig Read(ScpClient scpClient, string path)
+ {
+ HostConfig hostConfig = new HostConfig();
+
+ using (var ms = new MemoryStream())
+ {
+ scpClient.Download(path, ms);
+ ms.Position = 0;
+
+ using (var sr = new StreamReader(ms, Encoding.ASCII))
+ {
+ string line;
+ while ((line = sr.ReadLine()) != null)
+ {
+ // skip comments
+ if (line.StartsWith('#'))
+ {
+ continue;
+ }
+
+ var hostEntryMatch = HostsEntryRegEx.Match(line);
+ if (!hostEntryMatch.Success)
+ {
+ continue;
+ }
+
+ var entryIPAddress = hostEntryMatch.Groups["IPAddress"].Value;
+ var entryAliasesGroup = hostEntryMatch.Groups["Aliases"];
+
+ var entry = new HostEntry(IPAddress.Parse(entryIPAddress), hostEntryMatch.Groups["HostName"].Value);
+
+ if (entryAliasesGroup.Success)
+ {
+ var aliases = entryAliasesGroup.Value.Split(' ');
+ foreach (var alias in aliases)
+ {
+ entry.Aliases.Add(alias);
+ }
+ }
+
+ hostConfig.Entries.Add(entry);
+ }
+ }
+ }
+
+ return hostConfig;
+ }
+
+ public void Write(ScpClient scpClient, string path)
+ {
+ using (var ms = new MemoryStream())
+ using (var sw = new StreamWriter(ms, Encoding.ASCII))
+ {
+ // Use linux line ending
+ sw.NewLine = "\n";
+
+ foreach (var hostEntry in Entries)
+ {
+ sw.Write(hostEntry.IPAddress);
+ sw.Write(" ");
+ sw.Write(hostEntry.HostName);
+
+ if (hostEntry.Aliases.Count > 0)
+ {
+ sw.Write(" ");
+ for (var i = 0; i < hostEntry.Aliases.Count; i++)
+ {
+ if (i > 0)
+ {
+ sw.Write(' ');
+ }
+ sw.Write(hostEntry.Aliases[i]);
+ }
+ }
+ sw.WriteLine();
+ }
+
+ sw.Flush();
+ ms.Position = 0;
+
+ scpClient.Upload(ms, path);
+ }
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/HostEntry.cs b/test/Renci.SshNet.IntegrationTests/HostEntry.cs
new file mode 100644
index 000000000..9127e820a
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/HostEntry.cs
@@ -0,0 +1,18 @@
+using System.Net;
+
+namespace Renci.SshNet.IntegrationTests
+{
+ public sealed class HostEntry
+ {
+ public HostEntry(IPAddress ipAddress, string hostName)
+ {
+ IPAddress = ipAddress;
+ HostName = hostName;
+ Aliases = new List();
+ }
+
+ public IPAddress IPAddress { get; private set; }
+ public string HostName { get; set; }
+ public List Aliases { get; }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/HostKeyAlgorithmTests.cs b/test/Renci.SshNet.IntegrationTests/HostKeyAlgorithmTests.cs
new file mode 100644
index 000000000..d827fb47c
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/HostKeyAlgorithmTests.cs
@@ -0,0 +1,80 @@
+using Renci.SshNet.Common;
+using Renci.SshNet.IntegrationTests.Common;
+using Renci.SshNet.TestTools.OpenSSH;
+
+namespace Renci.SshNet.IntegrationTests
+{
+ [TestClass]
+ public class HostKeyAlgorithmTests : IntegrationTestBase
+ {
+ private IConnectionInfoFactory _connectionInfoFactory;
+ private RemoteSshdConfig _remoteSshdConfig;
+
+ [TestInitialize]
+ public void SetUp()
+ {
+ _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
+ _remoteSshdConfig = new RemoteSshd(new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort)).OpenConfig();
+ }
+
+ [TestCleanup]
+ public void TearDown()
+ {
+ _remoteSshdConfig?.Reset();
+ }
+
+ [TestMethod]
+ public void SshDss()
+ {
+ DoTest(HostKeyAlgorithm.SshDss, HostKeyFile.Dsa, 2048);
+ }
+
+ [TestMethod]
+ public void SshRsa()
+ {
+ DoTest(HostKeyAlgorithm.SshRsa, HostKeyFile.Rsa, 3072);
+ }
+
+ [TestMethod]
+ public void SshRsaSha256()
+ {
+ DoTest(HostKeyAlgorithm.RsaSha2256, HostKeyFile.Rsa, 3072);
+ }
+
+ [TestMethod]
+ public void SshRsaSha512()
+ {
+ DoTest(HostKeyAlgorithm.RsaSha2512, HostKeyFile.Rsa, 3072);
+ }
+
+ [TestMethod]
+ public void SshEd25519()
+ {
+ DoTest(HostKeyAlgorithm.SshEd25519, HostKeyFile.Ed25519, 256);
+ }
+
+ private void DoTest(HostKeyAlgorithm hostKeyAlgorithm, HostKeyFile hostKeyFile, int keyLength)
+ {
+ _remoteSshdConfig.ClearHostKeyAlgorithms()
+ .AddHostKeyAlgorithm(hostKeyAlgorithm)
+ .ClearHostKeyFiles()
+ .AddHostKeyFile(hostKeyFile.FilePath)
+ .Update()
+ .Restart();
+
+ HostKeyEventArgs hostKeyEventsArgs = null;
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.HostKeyReceived += (sender, e) => hostKeyEventsArgs = e;
+ client.Connect();
+ client.Disconnect();
+ }
+
+ Assert.IsNotNull(hostKeyEventsArgs);
+ Assert.AreEqual(hostKeyAlgorithm.Name, hostKeyEventsArgs.HostKeyName);
+ Assert.AreEqual(keyLength, hostKeyEventsArgs.KeyLength);
+ CollectionAssert.AreEqual(hostKeyFile.FingerPrint, hostKeyEventsArgs.FingerPrint);
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/HostKeyFile.cs b/test/Renci.SshNet.IntegrationTests/HostKeyFile.cs
new file mode 100644
index 000000000..66d09fd29
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/HostKeyFile.cs
@@ -0,0 +1,23 @@
+namespace Renci.SshNet.IntegrationTests
+{
+ public sealed class HostKeyFile
+ {
+ public static readonly HostKeyFile Rsa = new HostKeyFile("ssh-rsa", "/etc/ssh/ssh_host_rsa_key", new byte[] { 0x3d, 0x90, 0xd8, 0x0d, 0xd5, 0xe0, 0xb6, 0x13, 0x42, 0x7c, 0x78, 0x1e, 0x19, 0xa3, 0x99, 0x2b });
+ public static readonly HostKeyFile Dsa = new HostKeyFile("ssh-dsa", "/etc/ssh/ssh_host_dsa_key", new byte[] { 0x50, 0xe0, 0xd5, 0x11, 0xf7, 0xed, 0x54, 0x75, 0x0d, 0x03, 0xc6, 0x52, 0x9b, 0x3b, 0x3c, 0x9f });
+ public static readonly HostKeyFile Ed25519 = new HostKeyFile("ssh-ed25519", "/etc/ssh/ssh_host_ed25519_key", new byte[] { 0xb3, 0xb9, 0xd0, 0x1b, 0x73, 0xc4, 0x60, 0xb4, 0xce, 0xed, 0x06, 0xf8, 0x58, 0x49, 0xa3, 0xda });
+ public const string Ecdsa = "/etc/ssh/ssh_host_ecdsa_key";
+
+ private HostKeyFile(string keyName, string filePath, byte[] fingerPrint)
+ {
+ KeyName = keyName;
+ FilePath = filePath;
+ FingerPrint = fingerPrint;
+ }
+
+ public string KeyName {get; }
+ public string FilePath { get; }
+ public byte[] FingerPrint { get; }
+ }
+
+
+}
diff --git a/test/Renci.SshNet.IntegrationTests/IConnectionInfoFactory.cs b/test/Renci.SshNet.IntegrationTests/IConnectionInfoFactory.cs
new file mode 100644
index 000000000..858dd0872
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/IConnectionInfoFactory.cs
@@ -0,0 +1,10 @@
+namespace Renci.SshNet.IntegrationTests
+{
+ public interface IConnectionInfoFactory
+ {
+ ConnectionInfo Create();
+ ConnectionInfo Create(params AuthenticationMethod[] authenticationMethods);
+ ConnectionInfo CreateWithProxy();
+ ConnectionInfo CreateWithProxy(params AuthenticationMethod[] authenticationMethods);
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/KeyExchangeAlgorithmTests.cs b/test/Renci.SshNet.IntegrationTests/KeyExchangeAlgorithmTests.cs
new file mode 100644
index 000000000..dfd6b6394
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/KeyExchangeAlgorithmTests.cs
@@ -0,0 +1,206 @@
+using Renci.SshNet.IntegrationTests.Common;
+using Renci.SshNet.TestTools.OpenSSH;
+
+namespace Renci.SshNet.IntegrationTests
+{
+ [TestClass]
+ public class KeyExchangeAlgorithmTests : IntegrationTestBase
+ {
+ private IConnectionInfoFactory _connectionInfoFactory;
+ private RemoteSshdConfig _remoteSshdConfig;
+
+ [TestInitialize]
+ public void SetUp()
+ {
+ _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
+ _remoteSshdConfig = new RemoteSshd(new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort)).OpenConfig();
+ }
+
+ [TestCleanup]
+ public void TearDown()
+ {
+ _remoteSshdConfig?.Reset();
+ }
+
+ [TestMethod]
+ public void Curve25519Sha256()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.Curve25519Sha256)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ public void Curve25519Sha256Libssh()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.Curve25519Sha256Libssh)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ public void DiffieHellmanGroup1Sha1()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.DiffieHellmanGroup1Sha1)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ public void DiffieHellmanGroup14Sha1()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.DiffieHellmanGroup14Sha1)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ public void DiffieHellmanGroup14Sha256()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.DiffieHellmanGroup14Sha256)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ public void DiffieHellmanGroup16Sha512()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.DiffieHellmanGroup16Sha512)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ [Ignore]
+ public void DiffieHellmanGroup18Sha512()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.DiffieHellmanGroup18Sha512)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ public void DiffieHellmanGroupExchangeSha1()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.DiffieHellmanGroupExchangeSha1)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ public void DiffieHellmanGroupExchangeSha256()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.DiffieHellmanGroupExchangeSha256)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ public void EcdhSha2Nistp256()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.EcdhSha2Nistp256)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ public void EcdhSha2Nistp384()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.EcdhSha2Nistp384)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ public void EcdhSha2Nistp521()
+ {
+ _remoteSshdConfig.ClearKeyExchangeAlgorithms()
+ .AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.EcdhSha2Nistp521)
+ .Update()
+ .Restart();
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.Disconnect();
+ }
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/LinuxAdminConnectionFactory.cs b/test/Renci.SshNet.IntegrationTests/LinuxAdminConnectionFactory.cs
new file mode 100644
index 000000000..dfb5c1369
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/LinuxAdminConnectionFactory.cs
@@ -0,0 +1,36 @@
+namespace Renci.SshNet.IntegrationTests
+{
+ public class LinuxAdminConnectionFactory : IConnectionInfoFactory
+ {
+ private readonly string _host;
+ private readonly int _port;
+
+ public LinuxAdminConnectionFactory(string sshServerHostName, ushort sshServerPort)
+ {
+ _host = sshServerHostName;
+ _port = sshServerPort;
+ }
+
+ public ConnectionInfo Create()
+ {
+ var user = Users.Admin;
+ return new ConnectionInfo(_host, _port, user.UserName, new PasswordAuthenticationMethod(user.UserName, user.Password));
+ }
+
+ public ConnectionInfo Create(params AuthenticationMethod[] authenticationMethods)
+ {
+ throw new NotImplementedException();
+ }
+
+ public ConnectionInfo CreateWithProxy()
+ {
+ throw new NotImplementedException();
+ }
+
+ public ConnectionInfo CreateWithProxy(params AuthenticationMethod[] authenticationMethods)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
+
diff --git a/test/Renci.SshNet.IntegrationTests/LinuxVMConnectionFactory.cs b/test/Renci.SshNet.IntegrationTests/LinuxVMConnectionFactory.cs
new file mode 100644
index 000000000..f2f04dbfc
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/LinuxVMConnectionFactory.cs
@@ -0,0 +1,62 @@
+namespace Renci.SshNet.IntegrationTests
+{
+ public class LinuxVMConnectionFactory : IConnectionInfoFactory
+ {
+
+
+ private const string ProxyHost = "127.0.0.1";
+ private const int ProxyPort = 1234;
+ private const string ProxyUserName = "test";
+ private const string ProxyPassword = "123";
+ private readonly string _host;
+ private readonly int _port;
+ private readonly AuthenticationMethodFactory _authenticationMethodFactory;
+
+
+ public LinuxVMConnectionFactory(string sshServerHostName, ushort sshServerPort)
+ {
+ _host = sshServerHostName;
+ _port = sshServerPort;
+
+ _authenticationMethodFactory = new AuthenticationMethodFactory();
+ }
+
+ public LinuxVMConnectionFactory(string sshServerHostName, ushort sshServerPort, AuthenticationMethodFactory authenticationMethodFactory)
+ {
+ _host = sshServerHostName;
+ _port = sshServerPort;
+
+ _authenticationMethodFactory = authenticationMethodFactory;
+ }
+
+ public ConnectionInfo Create()
+ {
+ return Create(_authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethod());
+ }
+
+ public ConnectionInfo Create(params AuthenticationMethod[] authenticationMethods)
+ {
+ return new ConnectionInfo(_host, _port, Users.Regular.UserName, authenticationMethods);
+ }
+
+ public ConnectionInfo CreateWithProxy()
+ {
+ return CreateWithProxy(_authenticationMethodFactory.CreateRegularUserPrivateKeyAuthenticationMethod());
+ }
+
+ public ConnectionInfo CreateWithProxy(params AuthenticationMethod[] authenticationMethods)
+ {
+ return new ConnectionInfo(
+ _host,
+ _port,
+ Users.Regular.UserName,
+ ProxyTypes.Socks4,
+ ProxyHost,
+ ProxyPort,
+ ProxyUserName,
+ ProxyPassword,
+ authenticationMethods);
+ }
+ }
+}
+
diff --git a/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/ForwardedPortLocalTest.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/ForwardedPortLocalTest.cs
new file mode 100644
index 000000000..ec28a738e
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/ForwardedPortLocalTest.cs
@@ -0,0 +1,158 @@
+using System.Diagnostics;
+
+using Renci.SshNet.Common;
+
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
+{
+ ///
+ /// Provides functionality for local port forwarding
+ ///
+ [TestClass]
+ public class ForwardedPortLocalTest : IntegrationTestBase
+ {
+ [TestMethod]
+ [WorkItem(713)]
+ [Owner("Kenneth_aa")]
+ [TestCategory("PortForwarding")]
+ [Description("Test if calling Stop on ForwardedPortLocal instance causes wait.")]
+ public void Test_PortForwarding_Local_Stop_Hangs_On_Wait()
+ {
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ client.Connect();
+
+ using var port1 = new ForwardedPortLocal("localhost", 8085, "www.google.com", 80);
+ client.AddForwardedPort(port1);
+ port1.Exception += delegate (object sender, ExceptionEventArgs e)
+ {
+ Assert.Fail(e.Exception.ToString());
+ };
+
+ port1.Start();
+
+ var hasTestedTunnel = false;
+
+ _ = ThreadPool.QueueUserWorkItem(delegate (object state)
+ {
+ try
+ {
+ var url = "http://www.google.com/";
+ Debug.WriteLine("Starting web request to \"" + url + "\"");
+
+#if NET6_0_OR_GREATER
+ var httpClient = new HttpClient();
+ var response = httpClient.GetAsync(url)
+ .ConfigureAwait(false)
+ .GetAwaiter()
+ .GetResult();
+#else
+ var request = (HttpWebRequest) WebRequest.Create(url);
+ var response = (HttpWebResponse) request.GetResponse();
+#endif // NET6_0_OR_GREATER
+
+ Assert.IsNotNull(response);
+
+ Debug.WriteLine("Http Response status code: " + response.StatusCode.ToString());
+
+ response.Dispose();
+
+ hasTestedTunnel = true;
+ }
+ catch (Exception ex)
+ {
+ Assert.Fail(ex.ToString());
+ }
+ });
+
+ // Wait for the web request to complete.
+ while (!hasTestedTunnel)
+ {
+ Thread.Sleep(1000);
+ }
+
+ try
+ {
+ // Try stop the port forwarding, wait 3 seconds and fail if it is still started.
+ _ = ThreadPool.QueueUserWorkItem(delegate (object state)
+ {
+ Debug.WriteLine("Trying to stop port forward.");
+ port1.Stop();
+ Debug.WriteLine("Port forwarding stopped.");
+ });
+
+ Thread.Sleep(3000);
+ if (port1.IsStarted)
+ {
+ Assert.Fail("Port forwarding not stopped.");
+ }
+ }
+ catch (Exception ex)
+ {
+ Assert.Fail(ex.ToString());
+ }
+ client.RemoveForwardedPort(port1);
+ client.Disconnect();
+ Debug.WriteLine("Success.");
+ }
+ }
+
+ [TestMethod]
+ [ExpectedException(typeof(SshConnectionException))]
+ public void Test_PortForwarding_Local_Without_Connecting()
+ {
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ using var port1 = new ForwardedPortLocal("localhost", 8084, "www.renci.org", 80);
+ client.AddForwardedPort(port1);
+ port1.Exception += delegate (object sender, ExceptionEventArgs e)
+ {
+ Assert.Fail(e.Exception.ToString());
+ };
+ port1.Start();
+
+ var test = Parallel.For(0,
+ 100,
+ counter =>
+ {
+ var start = DateTime.Now;
+
+#if NET6_0_OR_GREATER
+ var httpClient = new HttpClient();
+ using (var response = httpClient.GetAsync("http://localhost:8084").GetAwaiter().GetResult())
+ {
+ var data = ReadStream(response.Content.ReadAsStream());
+#else
+ var request = (HttpWebRequest) WebRequest.Create("http://localhost:8084");
+ using (var response = (HttpWebResponse) request.GetResponse())
+ {
+ var data = ReadStream(response.GetResponseStream());
+#endif // NET6_0_OR_GREATER
+ var end = DateTime.Now;
+
+ Debug.WriteLine(string.Format("Request# {2}: Lenght: {0} Time: {1}", data.Length, end - start, counter));
+ }
+ });
+ }
+ }
+
+ private static byte[] ReadStream(Stream stream)
+ {
+ var buffer = new byte[1024];
+ using (var ms = new MemoryStream())
+ {
+ while (true)
+ {
+ var read = stream.Read(buffer, 0, buffer.Length);
+ if (read > 0)
+ {
+ ms.Write(buffer, 0, read);
+ }
+ else
+ {
+ return ms.ToArray();
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/ScpClientTest.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/ScpClientTest.cs
new file mode 100644
index 000000000..e9015a3c6
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/ScpClientTest.cs
@@ -0,0 +1,336 @@
+using System.Security.Cryptography;
+
+using Renci.SshNet.Common;
+
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
+{
+ ///
+ /// Provides SCP client functionality.
+ ///
+ [TestClass]
+ public partial class ScpClientTest : IntegrationTestBase
+ {
+ [TestMethod]
+ [TestCategory("Scp")]
+ public void Test_Scp_File_Upload_Download()
+ {
+ RemoveAllFiles();
+
+ using (var scp = new ScpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ scp.Connect();
+
+ var uploadedFileName = Path.GetTempFileName();
+ var downloadedFileName = Path.GetTempFileName();
+
+ CreateTestFile(uploadedFileName, 1);
+
+ scp.Upload(new FileInfo(uploadedFileName), Path.GetFileName(uploadedFileName));
+
+ scp.Download(Path.GetFileName(uploadedFileName), new FileInfo(downloadedFileName));
+
+ // Calculate MD5 value
+ var uploadedHash = CalculateMD5(uploadedFileName);
+ var downloadedHash = CalculateMD5(downloadedFileName);
+
+ File.Delete(uploadedFileName);
+ File.Delete(downloadedFileName);
+
+ scp.Disconnect();
+
+ Assert.AreEqual(uploadedHash, downloadedHash);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Scp")]
+ public void Test_Scp_Stream_Upload_Download()
+ {
+ RemoveAllFiles();
+
+ using (var scp = new ScpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ scp.Connect();
+
+ var uploadedFileName = Path.GetTempFileName();
+ var downloadedFileName = Path.GetTempFileName();
+
+ CreateTestFile(uploadedFileName, 1);
+
+ // Calculate has value
+ using (var stream = File.OpenRead(uploadedFileName))
+ {
+ scp.Upload(stream, Path.GetFileName(uploadedFileName));
+ }
+
+ using (var stream = File.OpenWrite(downloadedFileName))
+ {
+ scp.Download(Path.GetFileName(uploadedFileName), stream);
+ }
+
+ // Calculate MD5 value
+ var uploadedHash = CalculateMD5(uploadedFileName);
+ var downloadedHash = CalculateMD5(downloadedFileName);
+
+ File.Delete(uploadedFileName);
+ File.Delete(downloadedFileName);
+
+ scp.Disconnect();
+
+ Assert.AreEqual(uploadedHash, downloadedHash);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Scp")]
+ public void Test_Scp_10MB_File_Upload_Download()
+ {
+ RemoveAllFiles();
+
+ using (var scp = new ScpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ scp.Connect();
+
+ var uploadedFileName = Path.GetTempFileName();
+ var downloadedFileName = Path.GetTempFileName();
+
+ CreateTestFile(uploadedFileName, 10);
+
+ scp.Upload(new FileInfo(uploadedFileName), Path.GetFileName(uploadedFileName));
+
+ scp.Download(Path.GetFileName(uploadedFileName), new FileInfo(downloadedFileName));
+
+ // Calculate MD5 value
+ var uploadedHash = CalculateMD5(uploadedFileName);
+ var downloadedHash = CalculateMD5(downloadedFileName);
+
+ File.Delete(uploadedFileName);
+ File.Delete(downloadedFileName);
+
+ scp.Disconnect();
+
+ Assert.AreEqual(uploadedHash, downloadedHash);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Scp")]
+ public void Test_Scp_10MB_Stream_Upload_Download()
+ {
+ RemoveAllFiles();
+
+ using (var scp = new ScpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ scp.Connect();
+
+ var uploadedFileName = Path.GetTempFileName();
+ var downloadedFileName = Path.GetTempFileName();
+
+ CreateTestFile(uploadedFileName, 10);
+
+ // Calculate has value
+ using (var stream = File.OpenRead(uploadedFileName))
+ {
+ scp.Upload(stream, Path.GetFileName(uploadedFileName));
+ }
+
+ using (var stream = File.OpenWrite(downloadedFileName))
+ {
+ scp.Download(Path.GetFileName(uploadedFileName), stream);
+ }
+
+ // Calculate MD5 value
+ var uploadedHash = CalculateMD5(uploadedFileName);
+ var downloadedHash = CalculateMD5(downloadedFileName);
+
+ File.Delete(uploadedFileName);
+ File.Delete(downloadedFileName);
+
+ scp.Disconnect();
+
+ Assert.AreEqual(uploadedHash, downloadedHash);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Scp")]
+ public void Test_Scp_Directory_Upload_Download()
+ {
+ RemoveAllFiles();
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ sftp.Connect();
+ sftp.CreateDirectory("uploaded_dir");
+ }
+
+ using (var scp = new ScpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ scp.Connect();
+
+ var uploadDirectory =
+ Directory.CreateDirectory(string.Format("{0}\\{1}", Path.GetTempPath(), Path.GetRandomFileName()));
+ for (var i = 0; i < 3; i++)
+ {
+ var subfolder = Directory.CreateDirectory(string.Format(@"{0}\folder_{1}", uploadDirectory.FullName, i));
+
+ for (var j = 0; j < 5; j++)
+ {
+ CreateTestFile(string.Format(@"{0}\file_{1}", subfolder.FullName, j), 1);
+ }
+
+ CreateTestFile(string.Format(@"{0}\file_{1}", uploadDirectory.FullName, i), 1);
+ }
+
+ scp.Upload(uploadDirectory, "uploaded_dir");
+
+ var downloadDirectory =
+ Directory.CreateDirectory(string.Format("{0}\\{1}", Path.GetTempPath(), Path.GetRandomFileName()));
+
+ scp.Download("uploaded_dir", downloadDirectory);
+
+ var uploadedFiles = uploadDirectory.GetFiles("*.*", SearchOption.AllDirectories);
+ var downloadFiles = downloadDirectory.GetFiles("*.*", SearchOption.AllDirectories);
+
+ var result = from f1 in uploadedFiles
+ from f2 in downloadFiles
+ where
+ f1.FullName.Substring(uploadDirectory.FullName.Length) ==
+ f2.FullName.Substring(downloadDirectory.FullName.Length)
+ && CalculateMD5(f1.FullName) == CalculateMD5(f2.FullName)
+ select f1;
+
+ var counter = result.Count();
+
+ scp.Disconnect();
+
+ Assert.IsTrue(counter == uploadedFiles.Length && uploadedFiles.Length == downloadFiles.Length);
+ }
+ RemoveAllFiles();
+ }
+
+ [TestMethod]
+ [TestCategory("Scp")]
+ public void Test_Scp_File_20_Parallel_Upload_Download()
+ {
+ using (var scp = new ScpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ scp.Connect();
+
+ var uploadFilenames = new string[20];
+ for (var i = 0; i < uploadFilenames.Length; i++)
+ {
+ uploadFilenames[i] = Path.GetTempFileName();
+ CreateTestFile(uploadFilenames[i], 1);
+ }
+
+ _ = Parallel.ForEach(uploadFilenames,
+ filename =>
+ {
+ scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
+ });
+ _ = Parallel.ForEach(uploadFilenames,
+ filename =>
+ {
+ scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename)));
+ });
+
+ var result = from file in uploadFilenames
+ where CalculateMD5(file) == CalculateMD5(string.Format("{0}.down", file))
+ select file;
+
+ scp.Disconnect();
+
+ Assert.IsTrue(result.Count() == uploadFilenames.Length);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Scp")]
+ public void Test_Scp_File_Upload_Download_Events()
+ {
+ using (var scp = new ScpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ scp.Connect();
+
+ var uploadFilenames = new string[10];
+
+ for (var i = 0; i < uploadFilenames.Length; i++)
+ {
+ uploadFilenames[i] = Path.GetTempFileName();
+ CreateTestFile(uploadFilenames[i], 1);
+ }
+
+ var uploadedFiles = uploadFilenames.ToDictionary(Path.GetFileName, (filename) => 0L);
+ var downloadedFiles = uploadFilenames.ToDictionary((filename) => string.Format("{0}.down", Path.GetFileName(filename)), (filename) => 0L);
+
+ scp.Uploading += delegate (object sender, ScpUploadEventArgs e)
+ {
+ uploadedFiles[e.Filename] = e.Uploaded;
+ };
+
+ scp.Downloading += delegate (object sender, ScpDownloadEventArgs e)
+ {
+ downloadedFiles[string.Format("{0}.down", e.Filename)] = e.Downloaded;
+ };
+
+ _ = Parallel.ForEach(uploadFilenames,
+ filename =>
+ {
+ scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
+ });
+ _ = Parallel.ForEach(uploadFilenames,
+ filename =>
+ {
+ scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename)));
+ });
+
+ var result = from uf in uploadedFiles
+ from df in downloadedFiles
+ where string.Format("{0}.down", uf.Key) == df.Key && uf.Value == df.Value
+ select uf;
+
+ scp.Disconnect();
+
+ Assert.IsTrue(result.Count() == uploadFilenames.Length && uploadFilenames.Length == uploadedFiles.Count && uploadedFiles.Count == downloadedFiles.Count);
+ }
+ }
+
+ protected static string CalculateMD5(string fileName)
+ {
+ using (var file = new FileStream(fileName, FileMode.Open))
+ {
+#if NET7_0_OR_GREATER
+ var hash = MD5.HashData(file);
+#else
+#if NET6_0
+ var md5 = MD5.Create();
+#else
+ MD5 md5 = new MD5CryptoServiceProvider();
+#endif // NET6_0
+ var hash = md5.ComputeHash(file);
+#endif // NET7_0_OR_GREATER
+
+ file.Close();
+
+ var sb = new StringBuilder();
+
+ for (var i = 0; i < hash.Length; i++)
+ {
+ _ = sb.Append(i.ToString("x2"));
+ }
+
+ return sb.ToString();
+ }
+ }
+
+ private void RemoveAllFiles()
+ {
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ client.Connect();
+ _ = client.RunCommand("rm -rf *");
+ client.Disconnect();
+ }
+ }
+ }
+}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.ChangeDirectory.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.ChangeDirectory.cs
similarity index 66%
rename from src/Renci.SshNet.Tests/Classes/SftpClientTest.ChangeDirectory.cs
rename to test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.ChangeDirectory.cs
index 5c58e1fa1..6fb518506 100644
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.ChangeDirectory.cs
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.ChangeDirectory.cs
@@ -1,21 +1,18 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Properties;
+using Renci.SshNet.Common;
-namespace Renci.SshNet.Tests.Classes
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
{
///
/// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
///
- public partial class SftpClientTest
+ public partial class SftpClientTest : IntegrationTestBase
{
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(SftpPathNotFoundException))]
public void Test_Sftp_ChangeDirectory_Root_Dont_Exists()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
sftp.ChangeDirectory("/asdasd");
@@ -24,11 +21,10 @@ public void Test_Sftp_ChangeDirectory_Root_Dont_Exists()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(SftpPathNotFoundException))]
public void Test_Sftp_ChangeDirectory_Root_With_Slash_Dont_Exists()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
sftp.ChangeDirectory("/asdasd/");
@@ -37,11 +33,10 @@ public void Test_Sftp_ChangeDirectory_Root_With_Slash_Dont_Exists()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(SftpPathNotFoundException))]
public void Test_Sftp_ChangeDirectory_Subfolder_Dont_Exists()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
sftp.ChangeDirectory("/asdasd/sssddds");
@@ -50,11 +45,10 @@ public void Test_Sftp_ChangeDirectory_Subfolder_Dont_Exists()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(SftpPathNotFoundException))]
public void Test_Sftp_ChangeDirectory_Subfolder_With_Slash_Dont_Exists()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
sftp.ChangeDirectory("/asdasd/sssddds/");
@@ -63,10 +57,9 @@ public void Test_Sftp_ChangeDirectory_Subfolder_With_Slash_Dont_Exists()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_ChangeDirectory_Which_Exists()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
sftp.ChangeDirectory("/usr");
@@ -76,10 +69,9 @@ public void Test_Sftp_ChangeDirectory_Which_Exists()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_ChangeDirectory_Which_Exists_With_Slash()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
sftp.ChangeDirectory("/usr/");
@@ -87,4 +79,4 @@ public void Test_Sftp_ChangeDirectory_Which_Exists_With_Slash()
}
}
}
-}
\ No newline at end of file
+}
diff --git a/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.CreateDirectory.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.CreateDirectory.cs
new file mode 100644
index 000000000..43b176697
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.CreateDirectory.cs
@@ -0,0 +1,72 @@
+
+using Renci.SshNet.Common;
+
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
+{
+ ///
+ /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
+ ///
+ public partial class SftpClientTest : IntegrationTestBase
+ {
+ [TestMethod]
+ [TestCategory("Sftp")]
+ public void Test_Sftp_CreateDirectory_In_Current_Location()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ sftp.Connect();
+
+ sftp.CreateDirectory("test-in-current");
+
+ sftp.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Sftp")]
+ [ExpectedException(typeof(SftpPermissionDeniedException))]
+ public void Test_Sftp_CreateDirectory_In_Forbidden_Directory()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, AdminUser.UserName, AdminUser.Password))
+ {
+ sftp.Connect();
+
+ sftp.CreateDirectory("/sbin/test");
+
+ sftp.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Sftp")]
+ [ExpectedException(typeof(SftpPathNotFoundException))]
+ public void Test_Sftp_CreateDirectory_Invalid_Path()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ sftp.Connect();
+
+ sftp.CreateDirectory("/abcdefg/abcefg");
+
+ sftp.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Sftp")]
+ [ExpectedException(typeof(SshException))]
+ public void Test_Sftp_CreateDirectory_Already_Exists()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ sftp.Connect();
+
+ sftp.CreateDirectory("test");
+
+ sftp.CreateDirectory("test");
+
+ sftp.Disconnect();
+ }
+ }
+ }
+}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.DeleteDirectory.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.DeleteDirectory.cs
similarity index 54%
rename from src/Renci.SshNet.Tests/Classes/SftpClientTest.DeleteDirectory.cs
rename to test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.DeleteDirectory.cs
index 5e981afc0..30697ddce 100644
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.DeleteDirectory.cs
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.DeleteDirectory.cs
@@ -1,33 +1,18 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
+using Renci.SshNet.Common;
-namespace Renci.SshNet.Tests.Classes
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
{
///
/// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
///
- public partial class SftpClientTest
+ public partial class SftpClientTest : IntegrationTestBase
{
[TestMethod]
[TestCategory("Sftp")]
- [ExpectedException(typeof(SshConnectionException))]
- public void Test_Sftp_DeleteDirectory_Without_Connecting()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- sftp.DeleteDirectory("test");
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(SftpPathNotFoundException))]
public void Test_Sftp_DeleteDirectory_Which_Doesnt_Exists()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -39,14 +24,10 @@ public void Test_Sftp_DeleteDirectory_Which_Doesnt_Exists()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(SftpPermissionDeniedException))]
public void Test_Sftp_DeleteDirectory_Which_No_Permissions()
{
- if (Resources.USERNAME == "root")
- Assert.Fail("Must not run this test as root!");
-
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, AdminUser.UserName, AdminUser.Password))
{
sftp.Connect();
@@ -58,10 +39,9 @@ public void Test_Sftp_DeleteDirectory_Which_No_Permissions()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_DeleteDirectory()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -74,12 +54,11 @@ public void Test_Sftp_DeleteDirectory()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test passing null to DeleteDirectory.")]
[ExpectedException(typeof(ArgumentException))]
public void Test_Sftp_DeleteDirectory_Null()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -89,4 +68,4 @@ public void Test_Sftp_DeleteDirectory_Null()
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.Download.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.Download.cs
similarity index 70%
rename from src/Renci.SshNet.Tests/Classes/SftpClientTest.Download.cs
rename to test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.Download.cs
index 85a2d7ecd..318834e4c 100644
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.Download.cs
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.Download.cs
@@ -1,26 +1,18 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.IO;
+using Renci.SshNet.Common;
-namespace Renci.SshNet.Tests.Classes
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
{
///
/// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
///
- public partial class SftpClientTest
+ public partial class SftpClientTest : IntegrationTestBase
{
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(SftpPermissionDeniedException))]
public void Test_Sftp_Download_Forbidden()
{
- if (Resources.USERNAME == "root")
- Assert.Fail("Must not run this test as root!");
-
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, AdminUser.UserName, AdminUser.Password))
{
sftp.Connect();
@@ -37,11 +29,10 @@ public void Test_Sftp_Download_Forbidden()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(SftpPathNotFoundException))]
public void Test_Sftp_Download_File_Not_Exists()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -57,12 +48,11 @@ public void Test_Sftp_Download_File_Not_Exists()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test passing null to BeginDownloadFile")]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Sftp_BeginDownloadFile_StreamIsNull()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
sftp.BeginDownloadFile("aaaa", null, null, null);
@@ -72,12 +62,11 @@ public void Test_Sftp_BeginDownloadFile_StreamIsNull()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test passing null to BeginDownloadFile")]
[ExpectedException(typeof(ArgumentException))]
public void Test_Sftp_BeginDownloadFile_FileNameIsWhiteSpace()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
sftp.BeginDownloadFile(" ", new MemoryStream(), null, null);
@@ -87,12 +76,11 @@ public void Test_Sftp_BeginDownloadFile_FileNameIsWhiteSpace()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test passing null to BeginDownloadFile")]
[ExpectedException(typeof(ArgumentException))]
public void Test_Sftp_BeginDownloadFile_FileNameIsNull()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
sftp.BeginDownloadFile(null, new MemoryStream(), null, null);
@@ -102,15 +90,14 @@ public void Test_Sftp_BeginDownloadFile_FileNameIsNull()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(ArgumentException))]
public void Test_Sftp_EndDownloadFile_Invalid_Async_Handle()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
var filename = Path.GetTempFileName();
- this.CreateTestFile(filename, 1);
+ CreateTestFile(filename, 1);
sftp.UploadFile(File.OpenRead(filename), "test123");
var async1 = sftp.BeginListDirectory("/", null, null);
var async2 = sftp.BeginDownloadFile("test123", new MemoryStream(), null, null);
@@ -118,4 +105,4 @@ public void Test_Sftp_EndDownloadFile_Invalid_Async_Handle()
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.ListDirectory.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.ListDirectory.cs
similarity index 67%
rename from src/Renci.SshNet.Tests/Classes/SftpClientTest.ListDirectory.cs
rename to test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.ListDirectory.cs
index 69f90aefe..e37e937f9 100644
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.ListDirectory.cs
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.ListDirectory.cs
@@ -1,39 +1,20 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Diagnostics;
+
using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.Diagnostics;
-using System.Linq;
-namespace Renci.SshNet.Tests.Classes
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
{
///
/// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
///
- public partial class SftpClientTest
+ public partial class SftpClientTest : IntegrationTestBase
{
[TestMethod]
[TestCategory("Sftp")]
- [ExpectedException(typeof(SshConnectionException))]
- public void Test_Sftp_ListDirectory_Without_Connecting()
- {
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- var files = sftp.ListDirectory(".");
- foreach (var file in files)
- {
- Debug.WriteLine(file.FullName);
- }
- }
- }
-
- [TestMethod]
- [TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(SftpPermissionDeniedException))]
public void Test_Sftp_ListDirectory_Permission_Denied()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -49,11 +30,10 @@ public void Test_Sftp_ListDirectory_Permission_Denied()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(SftpPathNotFoundException))]
public void Test_Sftp_ListDirectory_Not_Exists()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -69,10 +49,9 @@ public void Test_Sftp_ListDirectory_Not_Exists()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_ListDirectory_Current()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -89,12 +68,34 @@ public void Test_Sftp_ListDirectory_Current()
}
}
+#if NET6_0_OR_GREATER
+ [TestMethod]
+ [TestCategory("Sftp")]
+ public async Task Test_Sftp_ListDirectoryAsync_Current()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ sftp.Connect();
+ var cts = new CancellationTokenSource();
+ cts.CancelAfter(TimeSpan.FromMinutes(1));
+ var count = 0;
+ await foreach(var file in sftp.ListDirectoryAsync(".", cts.Token))
+ {
+ count++;
+ Debug.WriteLine(file.FullName);
+ }
+
+ Assert.IsTrue(count > 0);
+
+ sftp.Disconnect();
+ }
+ }
+#endif
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_ListDirectory_Empty()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -113,12 +114,11 @@ public void Test_Sftp_ListDirectory_Empty()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test passing null to ListDirectory.")]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Sftp_ListDirectory_Null()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -137,10 +137,9 @@ public void Test_Sftp_ListDirectory_Null()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_ListDirectory_HugeDirectory()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -148,7 +147,6 @@ public void Test_Sftp_ListDirectory_HugeDirectory()
for (int i = 0; i < 10000; i++)
{
sftp.CreateDirectory(string.Format("test_{0}", i));
- Debug.WriteLine("Created " + i);
}
var files = sftp.ListDirectory(".");
@@ -164,20 +162,19 @@ public void Test_Sftp_ListDirectory_HugeDirectory()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_Change_Directory()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
- Assert.AreEqual(sftp.WorkingDirectory, "/home/tester");
+ Assert.AreEqual(sftp.WorkingDirectory, "/home/sshnet");
sftp.CreateDirectory("test1");
sftp.ChangeDirectory("test1");
- Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1");
+ Assert.AreEqual(sftp.WorkingDirectory, "/home/sshnet/test1");
sftp.CreateDirectory("test1_1");
sftp.CreateDirectory("test1_2");
@@ -189,19 +186,19 @@ public void Test_Sftp_Change_Directory()
sftp.ChangeDirectory("test1_1");
- Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");
+ Assert.AreEqual(sftp.WorkingDirectory, "/home/sshnet/test1/test1_1");
sftp.ChangeDirectory("../test1_2");
- Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2");
+ Assert.AreEqual(sftp.WorkingDirectory, "/home/sshnet/test1/test1_2");
sftp.ChangeDirectory("..");
- Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1");
+ Assert.AreEqual(sftp.WorkingDirectory, "/home/sshnet/test1");
sftp.ChangeDirectory("..");
- Assert.AreEqual(sftp.WorkingDirectory, "/home/tester");
+ Assert.AreEqual(sftp.WorkingDirectory, "/home/sshnet");
files = sftp.ListDirectory("test1/test1_1");
@@ -209,15 +206,15 @@ public void Test_Sftp_Change_Directory()
sftp.ChangeDirectory("test1/test1_1");
- Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");
+ Assert.AreEqual(sftp.WorkingDirectory, "/home/sshnet/test1/test1_1");
- sftp.ChangeDirectory("/home/tester/test1/test1_1");
+ sftp.ChangeDirectory("/home/sshnet/test1/test1_1");
- Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");
+ Assert.AreEqual(sftp.WorkingDirectory, "/home/sshnet/test1/test1_1");
- sftp.ChangeDirectory("/home/tester/test1/test1_1/../test1_2");
+ sftp.ChangeDirectory("/home/sshnet/test1/test1_1/../test1_2");
- Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2");
+ Assert.AreEqual(sftp.WorkingDirectory, "/home/sshnet/test1/test1_2");
sftp.ChangeDirectory("../../");
@@ -234,12 +231,11 @@ public void Test_Sftp_Change_Directory()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test passing null to ChangeDirectory.")]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Sftp_ChangeDirectory_Null()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -251,12 +247,11 @@ public void Test_Sftp_ChangeDirectory_Null()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test calling EndListDirectory method more then once.")]
[ExpectedException(typeof(ArgumentException))]
public void Test_Sftp_Call_EndListDirectory_Twice()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
var ar = sftp.BeginListDirectory("/", null, null);
@@ -265,4 +260,4 @@ public void Test_Sftp_Call_EndListDirectory_Twice()
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.RenameFile.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.RenameFile.cs
similarity index 69%
rename from src/Renci.SshNet.Tests/Classes/SftpClientTest.RenameFile.cs
rename to test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.RenameFile.cs
index e1685d099..e74a8e7ed 100644
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.RenameFile.cs
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.RenameFile.cs
@@ -1,21 +1,15 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.IO;
-
-namespace Renci.SshNet.Tests.Classes
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
{
///
/// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
///
- public partial class SftpClientTest
+ public partial class SftpClientTest : IntegrationTestBase
{
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_Rename_File()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -23,7 +17,7 @@ public void Test_Sftp_Rename_File()
string remoteFileName1 = Path.GetRandomFileName();
string remoteFileName2 = Path.GetRandomFileName();
- this.CreateTestFile(uploadedFileName, 1);
+ CreateTestFile(uploadedFileName, 1);
using (var file = File.OpenRead(uploadedFileName))
{
@@ -42,12 +36,11 @@ public void Test_Sftp_Rename_File()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test passing null to RenameFile.")]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Sftp_RenameFile_Null()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
@@ -57,4 +50,4 @@ public void Test_Sftp_RenameFile_Null()
}
}
}
-}
\ No newline at end of file
+}
diff --git a/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.RenameFileAsync.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.RenameFileAsync.cs
new file mode 100644
index 000000000..ade91099c
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.RenameFileAsync.cs
@@ -0,0 +1,56 @@
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
+{
+ ///
+ /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
+ ///
+ public partial class SftpClientTest : IntegrationTestBase
+ {
+ [TestMethod]
+ [TestCategory("Sftp")]
+ public async Task Test_Sftp_RenameFileAsync()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ await sftp.ConnectAsync(default);
+
+ string uploadedFileName = Path.GetTempFileName();
+ string remoteFileName1 = Path.GetRandomFileName();
+ string remoteFileName2 = Path.GetRandomFileName();
+
+ CreateTestFile(uploadedFileName, 1);
+
+ using (var file = File.OpenRead(uploadedFileName))
+ {
+ using (Stream remoteStream = await sftp.OpenAsync(remoteFileName1, FileMode.CreateNew, FileAccess.Write, default))
+ {
+ await file.CopyToAsync(remoteStream, 81920, default);
+ }
+ }
+
+ await sftp.RenameFileAsync(remoteFileName1, remoteFileName2, default);
+
+ File.Delete(uploadedFileName);
+
+ sftp.Disconnect();
+ }
+
+ RemoveAllFiles();
+ }
+
+ [TestMethod]
+ [TestCategory("Sftp")]
+ [Description("Test passing null to RenameFile.")]
+ [ExpectedException(typeof(ArgumentNullException))]
+ public async Task Test_Sftp_RenameFileAsync_Null()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ await sftp.ConnectAsync(default);
+
+ await sftp.RenameFileAsync(null, null, default);
+
+ sftp.Disconnect();
+ }
+ }
+ }
+}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.SynchronizeDirectories.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.SynchronizeDirectories.cs
similarity index 78%
rename from src/Renci.SshNet.Tests/Classes/SftpClientTest.SynchronizeDirectories.cs
rename to test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.SynchronizeDirectories.cs
index 2c9ddb3e0..4964715ef 100644
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.SynchronizeDirectories.cs
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.SynchronizeDirectories.cs
@@ -1,31 +1,26 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Tests.Properties;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
+using System.Diagnostics;
-namespace Renci.SshNet.Tests.Classes
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
{
///
/// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
///
- public partial class SftpClientTest
+ public partial class SftpClientTest : IntegrationTestBase
{
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_SynchronizeDirectories()
{
RemoveAllFiles();
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
string uploadedFileName = Path.GetTempFileName();
string sourceDir = Path.GetDirectoryName(uploadedFileName);
- string destDir = "/";
+ string destDir = "/home/sshnet/";
string searchPattern = Path.GetFileName(uploadedFileName);
var upLoadedFiles = sftp.SynchronizeDirectories(sourceDir, destDir, searchPattern);
@@ -42,19 +37,18 @@ public void Test_Sftp_SynchronizeDirectories()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_BeginSynchronizeDirectories()
{
RemoveAllFiles();
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
string uploadedFileName = Path.GetTempFileName();
string sourceDir = Path.GetDirectoryName(uploadedFileName);
- string destDir = "/";
+ string destDir = "/home/sshnet/";
string searchPattern = Path.GetFileName(uploadedFileName);
var asyncResult = sftp.BeginSynchronizeDirectories(sourceDir,
@@ -83,4 +77,4 @@ public void Test_Sftp_BeginSynchronizeDirectories()
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.Upload.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.Upload.cs
similarity index 69%
rename from src/Renci.SshNet.Tests/Classes/SftpClientTest.Upload.cs
rename to test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.Upload.cs
index aa70e232d..91c248bd3 100644
--- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.Upload.cs
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.Upload.cs
@@ -1,34 +1,27 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Renci.SshNet.Common;
+using Renci.SshNet.Common;
using Renci.SshNet.Sftp;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading;
-namespace Renci.SshNet.Tests.Classes
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
{
///
/// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
///
- public partial class SftpClientTest
+ public partial class SftpClientTest : IntegrationTestBase
{
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_Upload_And_Download_1MB_File()
{
RemoveAllFiles();
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
- string uploadedFileName = Path.GetTempFileName();
- string remoteFileName = Path.GetRandomFileName();
+ var uploadedFileName = Path.GetTempFileName();
+ var remoteFileName = Path.GetRandomFileName();
- this.CreateTestFile(uploadedFileName, 1);
+ CreateTestFile(uploadedFileName, 1);
// Calculate has value
var uploadedHash = CalculateMD5(uploadedFileName);
@@ -38,7 +31,7 @@ public void Test_Sftp_Upload_And_Download_1MB_File()
sftp.UploadFile(file, remoteFileName);
}
- string downloadedFileName = Path.GetTempFileName();
+ var downloadedFileName = Path.GetTempFileName();
using (var file = File.OpenWrite(downloadedFileName))
{
@@ -60,18 +53,17 @@ public void Test_Sftp_Upload_And_Download_1MB_File()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(SftpPermissionDeniedException))]
public void Test_Sftp_Upload_Forbidden()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
- string uploadedFileName = Path.GetTempFileName();
- string remoteFileName = "/root/1";
+ var uploadedFileName = Path.GetTempFileName();
+ var remoteFileName = "/root/1";
- this.CreateTestFile(uploadedFileName, 1);
+ CreateTestFile(uploadedFileName, 1);
using (var file = File.OpenRead(uploadedFileName))
{
@@ -84,7 +76,6 @@ public void Test_Sftp_Upload_Forbidden()
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each()
{
var maxFiles = 10;
@@ -92,20 +83,23 @@ public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each()
RemoveAllFiles();
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
+ sftp.OperationTimeout = TimeSpan.FromMinutes(1);
sftp.Connect();
var testInfoList = new Dictionary();
- for (int i = 0; i < maxFiles; i++)
+ for (var i = 0; i < maxFiles; i++)
{
- var testInfo = new TestInfo();
- testInfo.UploadedFileName = Path.GetTempFileName();
- testInfo.DownloadedFileName = Path.GetTempFileName();
- testInfo.RemoteFileName = Path.GetRandomFileName();
+ var testInfo = new TestInfo
+ {
+ UploadedFileName = Path.GetTempFileName(),
+ DownloadedFileName = Path.GetTempFileName(),
+ RemoteFileName = Path.GetRandomFileName()
+ };
- this.CreateTestFile(testInfo.UploadedFileName, maxSize);
+ CreateTestFile(testInfo.UploadedFileName, maxSize);
// Calculate hash value
testInfo.UploadedHash = CalculateMD5(testInfo.UploadedFileName);
@@ -130,7 +124,7 @@ public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each()
}
// Wait for upload to finish
- bool uploadCompleted = false;
+ var uploadCompleted = false;
while (!uploadCompleted)
{
// Assume upload completed
@@ -174,7 +168,7 @@ public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each()
}
// Wait for download to finish
- bool downloadCompleted = false;
+ var downloadCompleted = false;
while (!downloadCompleted)
{
// Assume download completed
@@ -206,6 +200,11 @@ public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each()
testInfo.DownloadedHash = CalculateMD5(testInfo.DownloadedFileName);
+ Console.WriteLine(remoteFile);
+ Console.WriteLine("UploadedBytes: "+ testInfo.UploadResult.UploadedBytes);
+ Console.WriteLine("DownloadedBytes: " + testInfo.DownloadResult.DownloadedBytes);
+ Console.WriteLine("UploadedHash: " + testInfo.UploadedHash);
+ Console.WriteLine("DownloadedHash: " + testInfo.DownloadedHash);
if (!(testInfo.UploadResult.UploadedBytes > 0 && testInfo.DownloadResult.DownloadedBytes > 0 && testInfo.DownloadResult.DownloadedBytes == testInfo.UploadResult.UploadedBytes))
{
uploadDownloadSizeOk = false;
@@ -238,21 +237,20 @@ public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each()
// TODO: Split this test into multiple tests
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test that delegates passed to BeginUploadFile, BeginDownloadFile and BeginListDirectory are actually called.")]
public void Test_Sftp_Ensure_Async_Delegates_Called_For_BeginFileUpload_BeginFileDownload_BeginListDirectory()
{
RemoveAllFiles();
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
- string remoteFileName = Path.GetRandomFileName();
- string localFileName = Path.GetRandomFileName();
- bool uploadDelegateCalled = false;
- bool downloadDelegateCalled = false;
- bool listDirectoryDelegateCalled = false;
+ var remoteFileName = Path.GetRandomFileName();
+ var localFileName = Path.GetRandomFileName();
+ var uploadDelegateCalled = false;
+ var downloadDelegateCalled = false;
+ var listDirectoryDelegateCalled = false;
IAsyncResult asyncResult;
// Test for BeginUploadFile.
@@ -261,11 +259,14 @@ public void Test_Sftp_Ensure_Async_Delegates_Called_For_BeginFileUpload_BeginFil
using (var fileStream = File.OpenRead(localFileName))
{
- asyncResult = sftp.BeginUploadFile(fileStream, remoteFileName, delegate(IAsyncResult ar)
- {
- sftp.EndUploadFile(ar);
- uploadDelegateCalled = true;
- }, null);
+ asyncResult = sftp.BeginUploadFile(fileStream,
+ remoteFileName,
+ delegate(IAsyncResult ar)
+ {
+ sftp.EndUploadFile(ar);
+ uploadDelegateCalled = true;
+ },
+ null);
while (!asyncResult.IsCompleted)
{
@@ -282,11 +283,14 @@ public void Test_Sftp_Ensure_Async_Delegates_Called_For_BeginFileUpload_BeginFil
asyncResult = null;
using (var fileStream = File.OpenWrite(localFileName))
{
- asyncResult = sftp.BeginDownloadFile(remoteFileName, fileStream, delegate(IAsyncResult ar)
- {
- sftp.EndDownloadFile(ar);
- downloadDelegateCalled = true;
- }, null);
+ asyncResult = sftp.BeginDownloadFile(remoteFileName,
+ fileStream,
+ delegate(IAsyncResult ar)
+ {
+ sftp.EndDownloadFile(ar);
+ downloadDelegateCalled = true;
+ },
+ null);
while (!asyncResult.IsCompleted)
{
@@ -301,11 +305,13 @@ public void Test_Sftp_Ensure_Async_Delegates_Called_For_BeginFileUpload_BeginFil
// Test for BeginListDirectory.
asyncResult = null;
- asyncResult = sftp.BeginListDirectory(sftp.WorkingDirectory, delegate(IAsyncResult ar)
- {
- sftp.EndListDirectory(ar);
- listDirectoryDelegateCalled = true;
- }, null);
+ asyncResult = sftp.BeginListDirectory(sftp.WorkingDirectory,
+ delegate(IAsyncResult ar)
+ {
+ _ = sftp.EndListDirectory(ar);
+ listDirectoryDelegateCalled = true;
+ },
+ null);
while (!asyncResult.IsCompleted)
{
@@ -318,64 +324,60 @@ public void Test_Sftp_Ensure_Async_Delegates_Called_For_BeginFileUpload_BeginFil
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test passing null to BeginUploadFile")]
[ExpectedException(typeof(ArgumentNullException))]
public void Test_Sftp_BeginUploadFile_StreamIsNull()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
- sftp.BeginUploadFile(null, "aaaaa", null, null);
+ _ = sftp.BeginUploadFile(null, "aaaaa", null, null);
sftp.Disconnect();
}
}
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test passing null to BeginUploadFile")]
[ExpectedException(typeof(ArgumentException))]
public void Test_Sftp_BeginUploadFile_FileNameIsWhiteSpace()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
- sftp.BeginUploadFile(new MemoryStream(), " ", null, null);
+ _ = sftp.BeginUploadFile(new MemoryStream(), " ", null, null);
sftp.Disconnect();
}
}
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[Description("Test passing null to BeginUploadFile")]
[ExpectedException(typeof(ArgumentException))]
public void Test_Sftp_BeginUploadFile_FileNameIsNull()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
- sftp.BeginUploadFile(new MemoryStream(), null, null, null);
+ _ = sftp.BeginUploadFile(new MemoryStream(), null, null, null);
sftp.Disconnect();
}
}
[TestMethod]
[TestCategory("Sftp")]
- [TestCategory("integration")]
[ExpectedException(typeof(ArgumentException))]
public void Test_Sftp_EndUploadFile_Invalid_Async_Handle()
{
- using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
sftp.Connect();
var async1 = sftp.BeginListDirectory("/", null, null);
var filename = Path.GetTempFileName();
- this.CreateTestFile(filename, 100);
+ CreateTestFile(filename, 100);
var async2 = sftp.BeginUploadFile(File.OpenRead(filename), "test", null, null);
sftp.EndUploadFile(async1);
}
}
}
-}
\ No newline at end of file
+}
diff --git a/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.cs
new file mode 100644
index 000000000..1c7def55b
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpClientTest.cs
@@ -0,0 +1,68 @@
+using System.Security.Cryptography;
+
+using Renci.SshNet.Sftp;
+
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
+{
+ ///
+ /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
+ ///
+ [TestClass]
+ public partial class SftpClientTest
+ {
+ protected static string CalculateMD5(string fileName)
+ {
+ using (FileStream file = new FileStream(fileName, FileMode.Open))
+ {
+ var hash = MD5.HashData(file);
+
+ file.Close();
+
+ StringBuilder sb = new StringBuilder();
+ for (var i = 0; i < hash.Length; i++)
+ {
+ sb.Append(hash[i].ToString("x2"));
+ }
+ return sb.ToString();
+ }
+ }
+
+ private void RemoveAllFiles()
+ {
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ client.Connect();
+ client.RunCommand("rm -rf *");
+ client.Disconnect();
+ }
+ }
+
+ ///
+ /// Helper class to help with upload and download testing
+ ///
+ private class TestInfo
+ {
+ public string RemoteFileName { get; set; }
+
+ public string UploadedFileName { get; set; }
+
+ public string DownloadedFileName { get; set; }
+
+ //public ulong UploadedBytes { get; set; }
+
+ //public ulong DownloadedBytes { get; set; }
+
+ public FileStream UploadedFile { get; set; }
+
+ public FileStream DownloadedFile { get; set; }
+
+ public string UploadedHash { get; set; }
+
+ public string DownloadedHash { get; set; }
+
+ public SftpUploadAsyncResult UploadResult { get; set; }
+
+ public SftpDownloadAsyncResult DownloadResult { get; set; }
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpFileTest.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpFileTest.cs
new file mode 100644
index 000000000..058442511
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SftpFileTest.cs
@@ -0,0 +1,120 @@
+using Renci.SshNet.Common;
+
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
+{
+ ///
+ /// Represents SFTP file information
+ ///
+ [TestClass]
+ public class SftpFileTest : IntegrationTestBase
+ {
+ [TestMethod]
+ [TestCategory("Sftp")]
+ public void Test_Get_Root_Directory()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ sftp.Connect();
+ var directory = sftp.Get("/");
+
+ Assert.AreEqual("/", directory.FullName);
+ Assert.IsTrue(directory.IsDirectory);
+ Assert.IsFalse(directory.IsRegularFile);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Sftp")]
+ [ExpectedException(typeof(SftpPathNotFoundException))]
+ public void Test_Get_Invalid_Directory()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ sftp.Connect();
+
+ sftp.Get("/xyz");
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Sftp")]
+ public void Test_Get_File()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ sftp.Connect();
+
+ sftp.UploadFile(new MemoryStream(), "abc.txt");
+
+ var file = sftp.Get("abc.txt");
+
+ Assert.AreEqual("/home/sshnet/abc.txt", file.FullName);
+ Assert.IsTrue(file.IsRegularFile);
+ Assert.IsFalse(file.IsDirectory);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Sftp")]
+ [Description("Test passing null to Get.")]
+ [ExpectedException(typeof(ArgumentNullException))]
+ public void Test_Get_File_Null()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ sftp.Connect();
+
+ var file = sftp.Get(null);
+
+ sftp.Disconnect();
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Sftp")]
+ public void Test_Get_International_File()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ sftp.Connect();
+
+ sftp.UploadFile(new MemoryStream(), "test-üöä-");
+
+ var file = sftp.Get("test-üöä-");
+
+ Assert.AreEqual("/home/sshnet/test-üöä-", file.FullName);
+ Assert.IsTrue(file.IsRegularFile);
+ Assert.IsFalse(file.IsDirectory);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory("Sftp")]
+ public void Test_Sftp_SftpFile_MoveTo()
+ {
+ using (var sftp = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
+ {
+ sftp.Connect();
+
+ string uploadedFileName = Path.GetTempFileName();
+ string remoteFileName = Path.GetRandomFileName();
+ string newFileName = Path.GetRandomFileName();
+
+ CreateTestFile(uploadedFileName, 1);
+
+ using (var file = File.OpenRead(uploadedFileName))
+ {
+ sftp.UploadFile(file, remoteFileName);
+ }
+
+ var sftpFile = sftp.Get(remoteFileName);
+
+ sftpFile.MoveTo(newFileName);
+
+ Assert.AreEqual(newFileName, sftpFile.Name);
+
+ sftp.Disconnect();
+ }
+ }
+ }
+}
diff --git a/src/Renci.SshNet.Tests/Classes/SshCommandTest.cs b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SshCommandTest.cs
similarity index 56%
rename from src/Renci.SshNet.Tests/Classes/SshCommandTest.cs
rename to test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SshCommandTest.cs
index cfd68b078..e5e78a762 100644
--- a/src/Renci.SshNet.Tests/Classes/SshCommandTest.cs
+++ b/test/Renci.SshNet.IntegrationTests/OldIntegrationTests/SshCommandTest.cs
@@ -1,45 +1,19 @@
-using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Diagnostics;
+
using Renci.SshNet.Common;
-using Renci.SshNet.Tests.Common;
-using Renci.SshNet.Tests.Properties;
-using System;
-using System.IO;
-using System.Text;
-using System.Threading;
-#if FEATURE_TPL
-using System.Diagnostics;
-using System.Threading.Tasks;
-#endif // FEATURE_TPL
-
-namespace Renci.SshNet.Tests.Classes
+
+namespace Renci.SshNet.IntegrationTests.OldIntegrationTests
{
///
/// Represents SSH command that can be executed.
///
[TestClass]
- public partial class SshCommandTest : TestBase
+ public class SshCommandTest : IntegrationTestBase
{
[TestMethod]
- [ExpectedException(typeof(SshConnectionException))]
- public void Test_Execute_SingleCommand_Without_Connecting()
- {
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
- {
- var result = ExecuteTestCommand(client);
-
- Assert.IsTrue(result);
- }
- }
-
- [TestMethod]
- [TestCategory("integration")]
public void Test_Run_SingleCommand()
{
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
-
- using (var client = new SshClient(host, username, password))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
#region Example SshCommand RunCommand Result
client.Connect();
@@ -57,14 +31,9 @@ public void Test_Run_SingleCommand()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_SingleCommand()
{
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
-
- using (var client = new SshClient(host, username, password))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
#region Example SshCommand CreateCommand Execute
client.Connect();
@@ -83,14 +52,9 @@ public void Test_Execute_SingleCommand()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_OutputStream()
{
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
-
- using (var client = new SshClient(host, username, password))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
#region Example SshCommand CreateCommand Execute OutputStream
client.Connect();
@@ -104,10 +68,14 @@ public void Test_Execute_OutputStream()
{
var result = reader.ReadToEnd();
if (string.IsNullOrEmpty(result))
+ {
continue;
+ }
+
Console.Write(result);
}
- cmd.EndExecute(asynch);
+
+ _ = cmd.EndExecute(asynch);
client.Disconnect();
#endregion
@@ -117,14 +85,9 @@ public void Test_Execute_OutputStream()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_ExtendedOutputStream()
{
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
-
- using (var client = new SshClient(host, username, password))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
#region Example SshCommand CreateCommand Execute ExtendedOutputStream
@@ -147,11 +110,10 @@ public void Test_Execute_ExtendedOutputStream()
}
[TestMethod]
- [TestCategory("integration")]
[ExpectedException(typeof(SshOperationTimeoutException))]
public void Test_Execute_Timeout()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
#region Example SshCommand CreateCommand Execute CommandTimeout
client.Connect();
@@ -164,10 +126,9 @@ public void Test_Execute_Timeout()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_Infinite_Timeout()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
var cmd = client.CreateCommand("sleep 10s");
@@ -177,10 +138,9 @@ public void Test_Execute_Infinite_Timeout()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_InvalidCommand()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
@@ -197,10 +157,9 @@ public void Test_Execute_InvalidCommand()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_InvalidCommand_Then_Execute_ValidCommand()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
var cmd = client.CreateCommand(";");
@@ -220,10 +179,9 @@ public void Test_Execute_InvalidCommand_Then_Execute_ValidCommand()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_Command_with_ExtendedOutput()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
var cmd = client.CreateCommand("echo 12345; echo 654321 >&2");
@@ -239,10 +197,9 @@ public void Test_Execute_Command_with_ExtendedOutput()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_Command_Reconnect_Execute_Command()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
var result = ExecuteTestCommand(client);
@@ -257,10 +214,9 @@ public void Test_Execute_Command_Reconnect_Execute_Command()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_Command_ExitStatus()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
#region Example SshCommand RunCommand ExitStatus
client.Connect();
@@ -277,10 +233,9 @@ public void Test_Execute_Command_ExitStatus()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_Command_Asynchronously()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
@@ -300,10 +255,9 @@ public void Test_Execute_Command_Asynchronously()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_Command_Asynchronously_With_Error()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
@@ -323,10 +277,9 @@ public void Test_Execute_Command_Asynchronously_With_Error()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_Command_Asynchronously_With_Callback()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
@@ -337,13 +290,11 @@ public void Test_Execute_Command_Asynchronously_With_Callback()
{
callbackCalled = true;
}), null);
- while (!asyncResult.IsCompleted)
- {
- Thread.Sleep(100);
- }
cmd.EndExecute(asyncResult);
+ Thread.Sleep(100);
+
Assert.IsTrue(callbackCalled);
client.Disconnect();
@@ -351,10 +302,9 @@ public void Test_Execute_Command_Asynchronously_With_Callback()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_Command_Asynchronously_With_Callback_On_Different_Thread()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
@@ -366,13 +316,11 @@ public void Test_Execute_Command_Asynchronously_With_Callback_On_Different_Threa
{
callbackThreadId = Thread.CurrentThread.ManagedThreadId;
}), null);
- while (!asyncResult.IsCompleted)
- {
- Thread.Sleep(100);
- }
cmd.EndExecute(asyncResult);
+ Thread.Sleep(100);
+
Assert.AreNotEqual(currentThreadId, callbackThreadId);
client.Disconnect();
@@ -383,10 +331,9 @@ public void Test_Execute_Command_Asynchronously_With_Callback_On_Different_Threa
/// Tests for Issue 563.
///
[WorkItem(563), TestMethod]
- [TestCategory("integration")]
public void Test_Execute_Command_Same_Object_Different_Commands()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
var cmd = client.CreateCommand("echo 12345");
@@ -399,10 +346,9 @@ public void Test_Execute_Command_Same_Object_Different_Commands()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Get_Result_Without_Execution()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
var cmd = client.CreateCommand("ls -l");
@@ -413,10 +359,9 @@ public void Test_Get_Result_Without_Execution()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Get_Error_Without_Execution()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
var cmd = client.CreateCommand("ls -l");
@@ -427,11 +372,10 @@ public void Test_Get_Error_Without_Execution()
}
[WorkItem(703), TestMethod]
- [ExpectedException(typeof(ArgumentException))]
- [TestCategory("integration")]
+ [ExpectedException(typeof(ArgumentNullException))]
public void Test_EndExecute_Before_BeginExecute()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
var cmd = client.CreateCommand("ls -l");
@@ -444,13 +388,12 @@ public void Test_EndExecute_Before_BeginExecute()
///A test for BeginExecute
///
[TestMethod()]
- [TestCategory("integration")]
public void BeginExecuteTest()
{
string expected = "123\n";
string result;
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
#region Example SshCommand CreateCommand BeginExecute IsCompleted EndExecute
@@ -476,10 +419,9 @@ public void BeginExecuteTest()
}
[TestMethod]
- [TestCategory("integration")]
public void Test_Execute_Invalid_Command()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
#region Example SshCommand CreateCommand Error
@@ -500,148 +442,16 @@ public void Test_Execute_Invalid_Command()
}
}
-
- ///
- ///A test for BeginExecute
- ///
[TestMethod]
- [Ignore] // placeholder for actual test
- public void BeginExecuteTest1()
- {
- Session session = null; // TODO: Initialize to an appropriate value
- string commandText = string.Empty; // TODO: Initialize to an appropriate value
- var encoding = Encoding.UTF8;
- SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
- string commandText1 = string.Empty; // TODO: Initialize to an appropriate value
- AsyncCallback callback = null; // TODO: Initialize to an appropriate value
- object state = null; // TODO: Initialize to an appropriate value
- IAsyncResult expected = null; // TODO: Initialize to an appropriate value
- IAsyncResult actual;
- actual = target.BeginExecute(commandText1, callback, state);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CancelAsync
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CancelAsyncTest()
- {
- Session session = null; // TODO: Initialize to an appropriate value
- string commandText = string.Empty; // TODO: Initialize to an appropriate value
- var encoding = Encoding.UTF8;
- SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
- target.CancelAsync();
- Assert.Inconclusive("A method that does not return a value cannot be verified.");
- }
-
-
- ///
- ///A test for Execute
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ExecuteTest()
- {
- Session session = null; // TODO: Initialize to an appropriate value
- string commandText = string.Empty; // TODO: Initialize to an appropriate value
- var encoding = Encoding.UTF8;
- SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
- string expected = string.Empty; // TODO: Initialize to an appropriate value
- string actual;
- actual = target.Execute();
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Execute
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ExecuteTest1()
- {
- Session session = null; // TODO: Initialize to an appropriate value
- string commandText = string.Empty; // TODO: Initialize to an appropriate value
- var encoding = Encoding.UTF8;
- SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
- string commandText1 = string.Empty; // TODO: Initialize to an appropriate value
- string expected = string.Empty; // TODO: Initialize to an appropriate value
- string actual;
- actual = target.Execute(commandText1);
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for CommandTimeout
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void CommandTimeoutTest()
- {
- Session session = null; // TODO: Initialize to an appropriate value
- string commandText = string.Empty; // TODO: Initialize to an appropriate value
- var encoding = Encoding.UTF8;
- SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
- TimeSpan expected = new TimeSpan(); // TODO: Initialize to an appropriate value
- TimeSpan actual;
- target.CommandTimeout = expected;
- actual = target.CommandTimeout;
- Assert.AreEqual(expected, actual);
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Error
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ErrorTest()
- {
- Session session = null; // TODO: Initialize to an appropriate value
- string commandText = string.Empty; // TODO: Initialize to an appropriate value
- var encoding = Encoding.UTF8;
- SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.Error;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
- ///
- ///A test for Result
- ///
- [TestMethod]
- [Ignore] // placeholder for actual test
- public void ResultTest()
- {
- Session session = null; // TODO: Initialize to an appropriate value
- string commandText = string.Empty; // TODO: Initialize to an appropriate value
- var encoding = Encoding.UTF8;
- SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
- string actual;
- actual = target.Result;
- Assert.Inconclusive("Verify the correctness of this test method.");
- }
-
-#if FEATURE_TPL
- [TestMethod]
- [TestCategory("integration")]
public void Test_MultipleThread_Example_MultipleConnections()
{
- var host = Resources.HOST;
- var username = Resources.USERNAME;
- var password = Resources.PASSWORD;
-
try
{
#region Example SshCommand RunCommand Parallel
- System.Threading.Tasks.Parallel.For(0, 10000,
+ Parallel.For(0, 100,
() =>
{
- var client = new SshClient(host, username, password);
+ var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password);
client.Connect();
return client;
},
@@ -667,15 +477,15 @@ public void Test_MultipleThread_Example_MultipleConnections()
}
[TestMethod]
- [TestCategory("integration")]
- public void Test_MultipleThread_10000_MultipleConnections()
+
+ public void Test_MultipleThread_100_MultipleConnections()
{
try
{
- System.Threading.Tasks.Parallel.For(0, 10000,
+ Parallel.For(0, 100,
() =>
{
- var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD);
+ var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password);
client.Connect();
return client;
},
@@ -700,13 +510,12 @@ public void Test_MultipleThread_10000_MultipleConnections()
}
[TestMethod]
- [TestCategory("integration")]
- public void Test_MultipleThread_10000_MultipleSessions()
+ public void Test_MultipleThread_100_MultipleSessions()
{
- using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
+ using (var client = new SshClient(SshServerHostName, SshServerPort, User.UserName, User.Password))
{
client.Connect();
- System.Threading.Tasks.Parallel.For(0, 10000,
+ Parallel.For(0, 100,
(counter) =>
{
var result = ExecuteTestCommand(client);
@@ -718,7 +527,6 @@ public void Test_MultipleThread_10000_MultipleSessions()
client.Disconnect();
}
}
-#endif // FEATURE_TPL
private static bool ExecuteTestCommand(SshClient s)
{
@@ -730,4 +538,4 @@ private static bool ExecuteTestCommand(SshClient s)
return result.Equals(testValue);
}
}
-}
\ No newline at end of file
+}
diff --git a/test/Renci.SshNet.IntegrationTests/PrivateKeyAuthenticationTests.cs b/test/Renci.SshNet.IntegrationTests/PrivateKeyAuthenticationTests.cs
new file mode 100644
index 000000000..19414999e
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/PrivateKeyAuthenticationTests.cs
@@ -0,0 +1,96 @@
+using Renci.SshNet.IntegrationTests.Common;
+using Renci.SshNet.TestTools.OpenSSH;
+
+namespace Renci.SshNet.IntegrationTests
+{
+ [TestClass]
+ public class PrivateKeyAuthenticationTests : TestBase
+ {
+ private IConnectionInfoFactory _connectionInfoFactory;
+ private RemoteSshdConfig _remoteSshdConfig;
+
+ [TestInitialize]
+ public void SetUp()
+ {
+ _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
+ _remoteSshdConfig = new RemoteSshd(new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort)).OpenConfig();
+ }
+
+ [TestCleanup]
+ public void TearDown()
+ {
+ _remoteSshdConfig?.Reset();
+ }
+
+ [TestMethod]
+ public void SshDss()
+ {
+ DoTest(PublicKeyAlgorithm.SshDss, "Data.Key.SSH2.DSA.Encrypted.Des.CBC.12345.txt", "12345");
+ }
+
+ [TestMethod]
+ public void SshRsa()
+ {
+ DoTest(PublicKeyAlgorithm.SshRsa, "Data.Key.RSA.txt");
+ }
+
+ [TestMethod]
+ public void SshRsaSha256()
+ {
+ DoTest(PublicKeyAlgorithm.RsaSha2256, "Data.Key.RSA.txt");
+ }
+
+ [TestMethod]
+ public void SshRsaSha512()
+ {
+ DoTest(PublicKeyAlgorithm.RsaSha2512, "Data.Key.RSA.txt");
+ }
+
+ [TestMethod]
+ public void Ecdsa256()
+ {
+ DoTest(PublicKeyAlgorithm.EcdsaSha2Nistp256, "Data.Key.ECDSA.Encrypted.txt", "12345");
+ }
+
+ [TestMethod]
+ public void Ecdsa384()
+ {
+ DoTest(PublicKeyAlgorithm.EcdsaSha2Nistp384, "Data.Key.OPENSSH.ECDSA384.Encrypted.txt", "12345");
+ }
+
+ [TestMethod]
+ public void Ecdsa521()
+ {
+ DoTest(PublicKeyAlgorithm.EcdsaSha2Nistp521, "Data.Key.OPENSSH.ECDSA521.Encrypted.txt", "12345");
+ }
+
+ [TestMethod]
+ public void Ed25519()
+ {
+ DoTest(PublicKeyAlgorithm.SshEd25519, "Data.Key.OPENSSH.ED25519.Encrypted.txt", "12345");
+ }
+
+ private void DoTest(PublicKeyAlgorithm publicKeyAlgorithm, string keyResource, string passPhrase = null)
+ {
+ _remoteSshdConfig.ClearPublicKeyAcceptedAlgorithms()
+ .AddPublicKeyAcceptedAlgorithm(publicKeyAlgorithm)
+ .Update()
+ .Restart();
+
+ var connectionInfo = _connectionInfoFactory.Create(CreatePrivateKeyAuthenticationMethod(keyResource, passPhrase));
+
+ using (var client = new SshClient(connectionInfo))
+ {
+ client.Connect();
+ }
+ }
+
+ private static PrivateKeyAuthenticationMethod CreatePrivateKeyAuthenticationMethod(string keyResource, string passPhrase)
+ {
+ using (var stream = GetData(keyResource))
+ {
+ return new PrivateKeyAuthenticationMethod(Users.Regular.UserName, new PrivateKeyFile(stream, passPhrase));
+ }
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/Program.cs b/test/Renci.SshNet.IntegrationTests/Program.cs
new file mode 100644
index 000000000..af2b60d51
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/Program.cs
@@ -0,0 +1,11 @@
+namespace Renci.SshNet.IntegrationTests
+{
+ class Program
+ {
+#if NETFRAMEWORK
+ private static void Main()
+ {
+ }
+#endif
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/Properties/AssemblyInfo.cs b/test/Renci.SshNet.IntegrationTests/Properties/AssemblyInfo.cs
new file mode 100644
index 000000000..a3ec2d895
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/Properties/AssemblyInfo.cs
@@ -0,0 +1,5 @@
+#if NET6_0_OR_GREATER
+using System.Diagnostics.CodeAnalysis;
+
+[assembly: ExcludeFromCodeCoverage]
+#endif // NET6_0_OR_GREATER
diff --git a/test/Renci.SshNet.IntegrationTests/RemoteSshd.cs b/test/Renci.SshNet.IntegrationTests/RemoteSshd.cs
new file mode 100644
index 000000000..476671f1a
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/RemoteSshd.cs
@@ -0,0 +1,51 @@
+namespace Renci.SshNet.IntegrationTests
+{
+ internal class RemoteSshd
+ {
+ private readonly IConnectionInfoFactory _connectionInfoFactory;
+
+ public RemoteSshd(IConnectionInfoFactory connectionInfoFactory)
+ {
+ _connectionInfoFactory = connectionInfoFactory;
+ }
+
+ public RemoteSshdConfig OpenConfig()
+ {
+ return new RemoteSshdConfig(this, _connectionInfoFactory);
+ }
+
+ public RemoteSshd Restart()
+ {
+ // Restart SSH daemon
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ // Kill all processes that start with 'sshd' and that run as root
+ var stopCommand = client.CreateCommand("sudo pkill -9 -U 0 sshd.pam");
+ var stopOutput = stopCommand.Execute();
+ if (stopCommand.ExitStatus != 0)
+ {
+ throw new ApplicationException($"Stopping ssh service failed with exit code {stopCommand.ExitStatus}.\r\n{stopOutput}\r\n{stopCommand.Error}");
+ }
+
+ var resetFailedCommand = client.CreateCommand("sudo /usr/sbin/sshd.pam");
+ var resetFailedOutput = resetFailedCommand.Execute();
+ if (resetFailedCommand.ExitStatus != 0)
+ {
+ throw new ApplicationException($"Reset failures for ssh service failed with exit code {resetFailedCommand.ExitStatus}.\r\n{resetFailedOutput}\r\n{resetFailedCommand.Error}");
+ }
+ }
+
+ // Socket fails on Linux, reporting inability early. This is the Linux behavior by design.
+ // https://github.com/dotnet/runtime/issues/47484#issuecomment-769239699
+ // At this point we have to wait until the ssh server in the container is available after reconfiguration.
+ if (Environment.OSVersion.Platform == PlatformID.Unix)
+ {
+ Thread.Sleep(300);
+ }
+
+ return this;
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/RemoteSshdConfig.cs b/test/Renci.SshNet.IntegrationTests/RemoteSshdConfig.cs
new file mode 100644
index 000000000..391449973
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/RemoteSshdConfig.cs
@@ -0,0 +1,217 @@
+using Renci.SshNet.TestTools.OpenSSH;
+
+namespace Renci.SshNet.IntegrationTests
+{
+ internal sealed class RemoteSshdConfig
+ {
+ private const string SshdConfigFilePath = "/etc/ssh/sshd_config";
+ private static readonly Encoding Utf8NoBom = new UTF8Encoding(false, true);
+
+ private readonly RemoteSshd _remoteSshd;
+ private readonly IConnectionInfoFactory _connectionInfoFactory;
+ private readonly SshdConfig _config;
+
+ public RemoteSshdConfig(RemoteSshd remoteSshd, IConnectionInfoFactory connectionInfoFactory)
+ {
+ _remoteSshd = remoteSshd;
+ _connectionInfoFactory = connectionInfoFactory;
+
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ using (var memoryStream = new MemoryStream())
+ {
+ client.Download(SshdConfigFilePath, memoryStream);
+
+ memoryStream.Position = 0;
+ _config = SshdConfig.LoadFrom(memoryStream, Encoding.UTF8);
+ }
+ }
+ }
+
+ ///
+ /// Specifies whether challenge-response authentication is allowed.
+ ///
+ /// to allow challenge-response authentication.
+ ///
+ /// The current instance.
+ ///
+ public RemoteSshdConfig WithChallengeResponseAuthentication(bool? value)
+ {
+ _config.ChallengeResponseAuthentication = value;
+ return this;
+ }
+
+ ///
+ /// Specifies whether to allow keyboard-interactive authentication.
+ ///
+ /// to allow keyboard-interactive authentication.
+ ///
+ /// The current instance.
+ ///
+ public RemoteSshdConfig WithKeyboardInteractiveAuthentication(bool value)
+ {
+ _config.KeyboardInteractiveAuthentication = value;
+ return this;
+ }
+
+ ///
+ /// Specifies whether sshd should print /etc/motd when a user logs in interactively.
+ ///
+ /// if sshd should print /etc/motd when a user logs in interactively.
+ ///
+ /// The current instance.
+ ///
+ public RemoteSshdConfig PrintMotd(bool? value = true)
+ {
+ _config.PrintMotd = value;
+ return this;
+ }
+
+ ///
+ /// Specifies whether TCP forwarding is permitted.
+ ///
+ /// to allow TCP forwarding.
+ ///
+ /// The current instance.
+ ///
+ public RemoteSshdConfig AllowTcpForwarding(bool? value = true)
+ {
+ _config.AllowTcpForwarding = value;
+ return this;
+ }
+
+ public RemoteSshdConfig WithAuthenticationMethods(string user, string authenticationMethods)
+ {
+ var sshNetMatch = _config.Matches.Find(m => m.Users.Contains(user));
+ if (sshNetMatch is null)
+ {
+ sshNetMatch = new Match(new[] { user }, Array.Empty());
+ _config.Matches.Add(sshNetMatch);
+ }
+
+ sshNetMatch.AuthenticationMethods = authenticationMethods;
+
+ return this;
+ }
+
+ public RemoteSshdConfig ClearCiphers()
+ {
+ _config.Ciphers.Clear();
+ return this;
+ }
+
+ public RemoteSshdConfig AddCipher(Cipher cipher)
+ {
+ _config.Ciphers.Add(cipher);
+ return this;
+ }
+
+ public RemoteSshdConfig ClearKeyExchangeAlgorithms()
+ {
+ _config.KeyExchangeAlgorithms.Clear();
+ return this;
+ }
+
+ public RemoteSshdConfig AddKeyExchangeAlgorithm(KeyExchangeAlgorithm keyExchangeAlgorithm)
+ {
+ _config.KeyExchangeAlgorithms.Add(keyExchangeAlgorithm);
+ return this;
+ }
+
+ public RemoteSshdConfig ClearPublicKeyAcceptedAlgorithms()
+ {
+ _config.PublicKeyAcceptedAlgorithms.Clear();
+ return this;
+ }
+
+ public RemoteSshdConfig AddPublicKeyAcceptedAlgorithm(PublicKeyAlgorithm publicKeyAlgorithm)
+ {
+ _config.PublicKeyAcceptedAlgorithms.Add(publicKeyAlgorithm);
+ return this;
+ }
+
+ public RemoteSshdConfig ClearMessageAuthenticationCodeAlgorithms()
+ {
+ _config.MessageAuthenticationCodeAlgorithms.Clear();
+ return this;
+ }
+
+ public RemoteSshdConfig AddMessageAuthenticationCodeAlgorithm(MessageAuthenticationCodeAlgorithm messageAuthenticationCodeAlgorithm)
+ {
+ _config.MessageAuthenticationCodeAlgorithms.Add(messageAuthenticationCodeAlgorithm);
+ return this;
+ }
+
+ public RemoteSshdConfig ClearHostKeyAlgorithms()
+ {
+ _config.HostKeyAlgorithms.Clear();
+ return this;
+ }
+
+ public RemoteSshdConfig AddHostKeyAlgorithm(HostKeyAlgorithm hostKeyAlgorithm)
+ {
+ _config.HostKeyAlgorithms.Add(hostKeyAlgorithm);
+ return this;
+ }
+
+ public RemoteSshdConfig ClearSubsystems()
+ {
+ _config.Subsystems.Clear();
+ return this;
+ }
+
+ public RemoteSshdConfig AddSubsystem(Subsystem subsystem)
+ {
+ _config.Subsystems.Add(subsystem);
+ return this;
+ }
+
+ public RemoteSshdConfig WithLogLevel(LogLevel logLevel)
+ {
+ _config.LogLevel = logLevel;
+ return this;
+ }
+
+ public RemoteSshdConfig WithUsePAM(bool usePAM)
+ {
+ _config.UsePAM = usePAM;
+ return this;
+ }
+
+ public RemoteSshdConfig ClearHostKeyFiles()
+ {
+ _config.HostKeyFiles.Clear();
+ return this;
+ }
+
+ public RemoteSshdConfig AddHostKeyFile(string hostKeyFile)
+ {
+ _config.HostKeyFiles.Add(hostKeyFile);
+ return this;
+ }
+
+ public RemoteSshd Update()
+ {
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ using (var memoryStream = new MemoryStream())
+ using (var sw = new StreamWriter(memoryStream, Utf8NoBom))
+ {
+ sw.NewLine = "\n";
+ _config.SaveTo(sw);
+ sw.Flush();
+
+ memoryStream.Position = 0;
+
+ client.Upload(memoryStream, SshdConfigFilePath);
+ }
+ }
+
+ return _remoteSshd;
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/Renci.SshNet.IntegrationTests.csproj b/test/Renci.SshNet.IntegrationTests/Renci.SshNet.IntegrationTests.csproj
new file mode 100644
index 000000000..f55b67440
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/Renci.SshNet.IntegrationTests.csproj
@@ -0,0 +1,48 @@
+
+
+
+ net8.0
+ enable
+ false
+ true
+ $(NoWarn);SYSLIB0021;SYSLIB1045;SYSLIB0014;IDE0220;IDE0010
+
+
+
+
+
+
+
+
+
+
+
+
+
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+ all
+
+
+ build; native; contentfiles; analyzers; buildtransitive
+ all
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/Renci.SshNet.IntegrationTests/ScpClientTests.cs b/test/Renci.SshNet.IntegrationTests/ScpClientTests.cs
new file mode 100644
index 000000000..fc90554a5
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/ScpClientTests.cs
@@ -0,0 +1,41 @@
+namespace Renci.SshNet.IntegrationTests
+{
+ ///
+ /// The SCP client integration tests
+ ///
+ [TestClass]
+ public class ScpClientTests : IntegrationTestBase, IDisposable
+ {
+ private readonly ScpClient _scpClient;
+
+ public ScpClientTests()
+ {
+ _scpClient = new ScpClient(SshServerHostName, SshServerPort, User.UserName, User.Password);
+ _scpClient.Connect();
+ }
+
+ [TestMethod]
+
+ public void Upload_And_Download_FileStream()
+ {
+ var file = $"/tmp/{Guid.NewGuid()}.txt";
+ var fileContent = "File content !@#$%^&*()_+{}:,./<>[];'\\|";
+
+ using var uploadStream = new MemoryStream(Encoding.UTF8.GetBytes(fileContent));
+ _scpClient.Upload(uploadStream, file);
+
+ using var downloadStream = new MemoryStream();
+ _scpClient.Download(file, downloadStream);
+
+ var result = Encoding.UTF8.GetString(downloadStream.ToArray());
+
+ Assert.AreEqual(fileContent, result);
+ }
+
+ public void Dispose()
+ {
+ _scpClient.Disconnect();
+ _scpClient.Dispose();
+ }
+ }
+}
diff --git a/test/Renci.SshNet.IntegrationTests/ScpTests.cs b/test/Renci.SshNet.IntegrationTests/ScpTests.cs
new file mode 100644
index 000000000..c244b86a8
--- /dev/null
+++ b/test/Renci.SshNet.IntegrationTests/ScpTests.cs
@@ -0,0 +1,2101 @@
+using Renci.SshNet.Common;
+
+namespace Renci.SshNet.IntegrationTests
+{
+ // TODO SCP: UPLOAD / DOWNLOAD ZERO LENGTH FILES
+ // TODO SCP: UPLOAD / DOWNLOAD EMPTY DIRECTORY
+ // TODO SCP: UPLOAD DIRECTORY THAT ALREADY EXISTS ON REMOTE HOST
+
+ [TestClass]
+ public class ScpTests : TestBase
+ {
+ private IConnectionInfoFactory _connectionInfoFactory;
+ private IRemotePathTransformation _remotePathTransformation;
+
+ [TestInitialize]
+ public void SetUp()
+ {
+ _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
+ _remotePathTransformation = RemotePathTransformation.ShellQuote;
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpDownloadStreamDirectoryDoesNotExistData), DynamicDataSourceType.Method)]
+ public void Scp_Download_Stream_DirectoryDoesNotExist(IRemotePathTransformation remotePathTransformation,
+ string remotePath,
+ string remoteFile)
+ {
+ var completeRemotePath = CombinePaths(remotePath, remoteFile);
+
+ // remove complete directory if it's not the home directory of the user
+ // or else remove the remote file
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+
+ try
+ {
+ using (var downloaded = new MemoryStream())
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Download(completeRemotePath, downloaded);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {completeRemotePath}: No such file or directory", ex.Message);
+ }
+ }
+ }
+ finally
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpDownloadStreamFileDoesNotExistData), DynamicDataSourceType.Method)]
+ public void Scp_Download_Stream_FileDoesNotExist(IRemotePathTransformation remotePathTransformation,
+ string remotePath,
+ string remoteFile)
+ {
+ var completeRemotePath = CombinePaths(remotePath, remoteFile);
+
+ // remove complete directory if it's not the home directory of the user
+ // or else remove the remote file
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+
+ client.CreateDirectory(remotePath);
+ }
+ }
+
+ try
+ {
+ using (var downloaded = new MemoryStream())
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Download(completeRemotePath, downloaded);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {completeRemotePath}: No such file or directory", ex.Message);
+ }
+ }
+ }
+ finally
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpDownloadDirectoryInfoDirectoryDoesNotExistData), DynamicDataSourceType.Method)]
+ public void Scp_Download_DirectoryInfo_DirectoryDoesNotExist(IRemotePathTransformation remotePathTransformation,
+ string remotePath)
+ {
+ var localDirectory = Path.GetTempFileName();
+ File.Delete(localDirectory);
+ Directory.CreateDirectory(localDirectory);
+
+ try
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Download(remotePath, new DirectoryInfo(localDirectory));
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {remotePath}: No such file or directory", ex.Message);
+ }
+ }
+ }
+ finally
+ {
+ Directory.Delete(localDirectory, true);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpDownloadDirectoryInfoExistingFileData), DynamicDataSourceType.Method)]
+ public void Scp_Download_DirectoryInfo_ExistingFile(IRemotePathTransformation remotePathTransformation,
+ string remotePath)
+ {
+ var content = CreateMemoryStream(100);
+ content.Position = 0;
+
+ var localDirectory = Path.GetTempFileName();
+ File.Delete(localDirectory);
+ Directory.CreateDirectory(localDirectory);
+
+ var localFile = Path.Combine(localDirectory, PosixPath.GetFileName(remotePath));
+
+ try
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.UploadFile(content, remotePath);
+ }
+
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+ client.Download(remotePath, new DirectoryInfo(localDirectory));
+ }
+
+ Assert.IsTrue(File.Exists(localFile));
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ using (var downloaded = new MemoryStream())
+ {
+ client.DownloadFile(remotePath, downloaded);
+ downloaded.Position = 0;
+ Assert.AreEqual(CreateFileHash(localFile), CreateHash(downloaded));
+ }
+ }
+ }
+ finally
+ {
+ Directory.Delete(localDirectory, true);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remotePath))
+ {
+ client.DeleteFile(remotePath);
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpDownloadDirectoryInfoExistingDirectoryData), DynamicDataSourceType.Method)]
+ public void Scp_Download_DirectoryInfo_ExistingDirectory(IRemotePathTransformation remotePathTransformation,
+ string remotePath)
+ {
+ var localDirectory = Path.GetTempFileName();
+ File.Delete(localDirectory);
+ Directory.CreateDirectory(localDirectory);
+
+ var localPathFile1 = Path.Combine(localDirectory, "file1 23");
+ var remotePathFile1 = CombinePaths(remotePath, "file1 23");
+ var contentFile1 = CreateMemoryStream(1024);
+ contentFile1.Position = 0;
+
+ var localPathFile2 = Path.Combine(localDirectory, "file2 #$%");
+ var remotePathFile2 = CombinePaths(remotePath, "file2 #$%");
+ var contentFile2 = CreateMemoryStream(2048);
+ contentFile2.Position = 0;
+
+ var localPathSubDirectory = Path.Combine(localDirectory, "subdir $1%#");
+ var remotePathSubDirectory = CombinePaths(remotePath, "subdir $1%#");
+
+ var localPathFile3 = Path.Combine(localPathSubDirectory, "file3 %$#");
+ var remotePathFile3 = CombinePaths(remotePathSubDirectory, "file3 %$#");
+ var contentFile3 = CreateMemoryStream(256);
+ contentFile3.Position = 0;
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remotePathFile1))
+ {
+ client.DeleteFile(remotePathFile1);
+ }
+
+ if (client.Exists(remotePathFile2))
+ {
+ client.DeleteFile(remotePathFile2);
+ }
+
+ if (client.Exists(remotePathFile3))
+ {
+ client.DeleteFile(remotePathFile3);
+ }
+
+ if (client.Exists(remotePathSubDirectory))
+ {
+ client.DeleteDirectory(remotePathSubDirectory);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+
+ try
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (!client.Exists(remotePath))
+ {
+ client.CreateDirectory(remotePath);
+ }
+
+ client.UploadFile(contentFile1, remotePathFile1);
+ client.UploadFile(contentFile1, remotePathFile2);
+
+ client.CreateDirectory(remotePathSubDirectory);
+ client.UploadFile(contentFile3, remotePathFile3);
+ }
+
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+ client.Download(remotePath, new DirectoryInfo(localDirectory));
+ }
+
+ var localFiles = Directory.GetFiles(localDirectory);
+ Assert.AreEqual(2, localFiles.Length);
+ Assert.IsTrue(localFiles.Contains(localPathFile1));
+ Assert.IsTrue(localFiles.Contains(localPathFile2));
+
+ var localSubDirecties = Directory.GetDirectories(localDirectory);
+ Assert.AreEqual(1, localSubDirecties.Length);
+ Assert.AreEqual(localPathSubDirectory, localSubDirecties[0]);
+
+ var localFilesSubDirectory = Directory.GetFiles(localPathSubDirectory);
+ Assert.AreEqual(1, localFilesSubDirectory.Length);
+ Assert.AreEqual(localPathFile3, localFilesSubDirectory[0]);
+
+ Assert.AreEqual(0, Directory.GetDirectories(localPathSubDirectory).Length);
+ }
+ finally
+ {
+ Directory.Delete(localDirectory, true);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remotePathFile1))
+ {
+ client.DeleteFile(remotePathFile1);
+ }
+
+ if (client.Exists(remotePathFile2))
+ {
+ client.DeleteFile(remotePathFile2);
+ }
+
+ if (client.Exists(remotePathFile3))
+ {
+ client.DeleteFile(remotePathFile3);
+ }
+
+ if (client.Exists(remotePathSubDirectory))
+ {
+ client.DeleteDirectory(remotePathSubDirectory);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpDownloadFileInfoDirectoryDoesNotExistData), DynamicDataSourceType.Method)]
+ public void Scp_Download_FileInfo_DirectoryDoesNotExist(IRemotePathTransformation remotePathTransformation,
+ string remotePath,
+ string remoteFile)
+ {
+ var completeRemotePath = CombinePaths(remotePath, remoteFile);
+
+ // remove complete directory if it's not the home directory of the user
+ // or else remove the remote file
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+
+ var fileInfo = new FileInfo(Path.GetTempFileName());
+
+ try
+ {
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Download(completeRemotePath, fileInfo);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {completeRemotePath}: No such file or directory", ex.Message);
+ }
+ }
+ }
+ finally
+ {
+ fileInfo.Delete();
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpDownloadFileInfoFileDoesNotExistData), DynamicDataSourceType.Method)]
+ public void Scp_Download_FileInfo_FileDoesNotExist(IRemotePathTransformation remotePathTransformation,
+ string remotePath,
+ string remoteFile)
+ {
+ var completeRemotePath = CombinePaths(remotePath, remoteFile);
+
+ // remove complete directory if it's not the home directory of the user
+ // or else remove the remote file
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+
+ client.CreateDirectory(remotePath);
+ }
+ }
+
+ var fileInfo = new FileInfo(Path.GetTempFileName());
+
+ try
+ {
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Download(completeRemotePath, fileInfo);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {completeRemotePath}: No such file or directory", ex.Message);
+ }
+ }
+ }
+ finally
+ {
+ fileInfo.Delete();
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpDownloadFileInfoExistingDirectoryData), DynamicDataSourceType.Method)]
+ public void Scp_Download_FileInfo_ExistingDirectory(IRemotePathTransformation remotePathTransformation,
+ string remotePath)
+ {
+ // remove complete directory if it's not the home directory of the user
+ // or else remove the remote file
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+
+ client.CreateDirectory(remotePath);
+ }
+ }
+
+ var fileInfo = new FileInfo(Path.GetTempFileName());
+ fileInfo.Delete();
+
+ try
+ {
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Download(remotePath, fileInfo);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {remotePath}: not a regular file", ex.Message);
+ }
+
+ Assert.IsFalse(fileInfo.Exists);
+ }
+ }
+ finally
+ {
+ fileInfo.Delete();
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpDownloadFileInfoExistingFileData), DynamicDataSourceType.Method)]
+ public void Scp_Download_FileInfo_ExistingFile(IRemotePathTransformation remotePathTransformation,
+ string remotePath,
+ string remoteFile,
+ int size)
+ {
+ var completeRemotePath = CombinePaths(remotePath, remoteFile);
+
+ // remove complete directory if it's not the home directory of the user
+ // or else remove the remote file
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+
+ client.CreateDirectory(remotePath);
+ }
+ }
+
+ var fileInfo = new FileInfo(Path.GetTempFileName());
+
+ try
+ {
+ var content = CreateMemoryStream(size);
+ content.Position = 0;
+
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+ client.Upload(content, completeRemotePath);
+ }
+
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+ client.Download(completeRemotePath, fileInfo);
+ }
+
+ using (var fs = fileInfo.OpenRead())
+ {
+ var downloadedBytes = new byte[fs.Length];
+ Assert.AreEqual(downloadedBytes.Length, fs.Read(downloadedBytes, 0, downloadedBytes.Length));
+ content.Position = 0;
+ Assert.AreEqual(CreateHash(content), CreateHash(downloadedBytes));
+ }
+ }
+ finally
+ {
+ fileInfo.Delete();
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpDownloadStreamExistingDirectoryData), DynamicDataSourceType.Method)]
+ public void Scp_Download_Stream_ExistingDirectory(IRemotePathTransformation remotePathTransformation,
+ string remotePath)
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+
+ client.CreateDirectory(remotePath);
+ }
+ }
+
+ var file = Path.GetTempFileName();
+ File.Delete(file);
+
+ try
+ {
+ using (var fs = File.OpenWrite(file))
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Download(remotePath, fs);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {remotePath}: not a regular file", ex.Message);
+ }
+
+ Assert.AreEqual(0, fs.Length);
+ }
+ }
+ finally
+ {
+ File.Delete(file);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpDownloadStreamExistingFileData), DynamicDataSourceType.Method)]
+ public void Scp_Download_Stream_ExistingFile(IRemotePathTransformation remotePathTransformation,
+ string remotePath,
+ string remoteFile,
+ int size)
+ {
+ var completeRemotePath = CombinePaths(remotePath, remoteFile);
+
+ // remove complete directory if it's not the home directory of the user
+ // or else remove the remote file
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+
+ client.CreateDirectory(remotePath);
+ }
+ }
+
+ var file = CreateTempFile(size);
+
+ try
+ {
+ using (var fs = File.OpenRead(file))
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+ client.Upload(fs, completeRemotePath);
+ }
+
+ using (var fs = File.OpenRead(file))
+ using (var downloaded = new MemoryStream(size))
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ client.Download(completeRemotePath, downloaded);
+ downloaded.Position = 0;
+ Assert.AreEqual(CreateHash(fs), CreateHash(downloaded));
+ }
+ }
+ finally
+ {
+ File.Delete(file);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpUploadFileStreamDirectoryDoesNotExistData), DynamicDataSourceType.Method)]
+ public void Scp_Upload_FileStream_DirectoryDoesNotExist(IRemotePathTransformation remotePathTransformation,
+ string remotePath,
+ string remoteFile)
+ {
+ var completeRemotePath = CombinePaths(remotePath, remoteFile);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+
+ var file = CreateTempFile(1000);
+
+ try
+ {
+ using (var fs = File.OpenRead(file))
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Upload(fs, completeRemotePath);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {remotePath}: No such file or directory", ex.Message);
+ }
+ }
+ }
+ finally
+ {
+ File.Delete(file);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpUploadFileStreamExistingDirectoryData), DynamicDataSourceType.Method)]
+ public void Scp_Upload_FileStream_ExistingDirectory(IRemotePathTransformation remotePathTransformation,
+ string remoteFile)
+ {
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteFile)))
+ {
+ command.Execute();
+ }
+ }
+
+ var file = CreateTempFile(1000);
+
+ try
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.CreateDirectory(remoteFile);
+ }
+
+ using (var fs = File.OpenRead(file))
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Upload(fs, remoteFile);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {remoteFile}: Is a directory", ex.Message);
+ }
+ }
+ }
+ finally
+ {
+ File.Delete(file);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remoteFile))
+ {
+ client.DeleteDirectory(remoteFile);
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(ScpUploadFileStreamExistingFileData), DynamicDataSourceType.Method)]
+ public void Scp_Upload_FileStream_ExistingFile(IRemotePathTransformation remotePathTransformation,
+ string remoteFile)
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remoteFile))
+ {
+ client.DeleteFile(remoteFile);
+ }
+ }
+
+ // original content is bigger than new content to ensure file is fully overwritten
+ var originalContent = CreateMemoryStream(2000);
+ var file = CreateTempFile(1000);
+
+ try
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ originalContent.Position = 0;
+ client.UploadFile(originalContent, remoteFile);
+ }
+
+ using (var fs = File.OpenRead(file))
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+ client.Upload(fs, remoteFile);
+ }
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ using (var downloaded = new MemoryStream(1000))
+ {
+ client.DownloadFile(remoteFile, downloaded);
+ downloaded.Position = 0;
+ Assert.AreEqual(CreateFileHash(file), CreateHash(downloaded));
+ }
+ }
+ }
+ finally
+ {
+ File.Delete(file);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remoteFile))
+ {
+ client.DeleteFile(remoteFile);
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpUploadFileStreamFileDoesNotExistData), DynamicDataSourceType.Method)]
+ public void Scp_Upload_FileStream_FileDoesNotExist(IRemotePathTransformation remotePathTransformation,
+ string remotePath,
+ string remoteFile,
+ int size)
+ {
+ var completeRemotePath = CombinePaths(remotePath, remoteFile);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ // remove complete directory if it's not the home directory of the user
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+
+ var file = CreateTempFile(size);
+
+ try
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ // create directory if it's not the home directory of the user
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (!client.Exists((remotePath)))
+ {
+ client.CreateDirectory(remotePath);
+ }
+ }
+ }
+
+ using (var fs = File.OpenRead(file))
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+ client.Upload(fs, completeRemotePath);
+ }
+
+ using (var fs = File.OpenRead(file))
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ var sftpFile = client.Get(completeRemotePath);
+ Assert.AreEqual(GetAbsoluteRemotePath(client, remotePath, remoteFile), sftpFile.FullName);
+ Assert.AreEqual(size, sftpFile.Length);
+
+ var downloaded = client.ReadAllBytes(completeRemotePath);
+ Assert.AreEqual(CreateHash(fs), CreateHash(downloaded));
+ }
+ }
+ finally
+ {
+ File.Delete(file);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ // remove complete directory if it's not the home directory of the user
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+ }
+
+ ///
+ /// https://github.com/sshnet/SSH.NET/issues/289
+ ///
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpUploadFileInfoDirectoryDoesNotExistData), DynamicDataSourceType.Method)]
+ public void Scp_Upload_FileInfo_DirectoryDoesNotExist(IRemotePathTransformation remotePathTransformation,
+ string remotePath,
+ string remoteFile)
+ {
+ var completeRemotePath = CombinePaths(remotePath, remoteFile);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+
+ var file = CreateTempFile(1000);
+
+ try
+ {
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Upload(new FileInfo(file), completeRemotePath);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {remotePath}: No such file or directory", ex.Message);
+ }
+ }
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ Assert.IsFalse(client.Exists(completeRemotePath));
+ Assert.IsFalse(client.Exists(remotePath));
+ }
+ }
+ finally
+ {
+ File.Delete(file);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+
+ ///
+ /// https://github.com/sshnet/SSH.NET/issues/286
+ ///
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpUploadFileInfoExistingDirectoryData), DynamicDataSourceType.Method)]
+ public void Scp_Upload_FileInfo_ExistingDirectory(IRemotePathTransformation remotePathTransformation,
+ string remoteFile)
+ {
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteFile)))
+ {
+ command.Execute();
+ }
+ }
+
+ var file = CreateTempFile(1000);
+
+ try
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+ client.CreateDirectory(remoteFile);
+ }
+
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Upload(new FileInfo(file), remoteFile);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {remoteFile}: Is a directory", ex.Message);
+ }
+ }
+ }
+ finally
+ {
+ File.Delete(file);
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteFile)))
+ {
+ command.Execute();
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpUploadFileInfoExistingFileData), DynamicDataSourceType.Method)]
+ public void Scp_Upload_FileInfo_ExistingFile(IRemotePathTransformation remotePathTransformation,
+ string remoteFile)
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remoteFile))
+ {
+ client.DeleteFile(remoteFile);
+ }
+ }
+
+ // original content is bigger than new content to ensure file is fully overwritten
+ var originalContent = CreateMemoryStream(2000);
+ var file = CreateTempFile(1000);
+
+ try
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ originalContent.Position = 0;
+ client.UploadFile(originalContent, remoteFile);
+ }
+
+ var fileInfo = new FileInfo(file)
+ {
+ LastAccessTimeUtc = new DateTime(1973, 8, 13, 20, 15, 33, DateTimeKind.Utc),
+ LastWriteTimeUtc = new DateTime(1974, 1, 24, 3, 55, 12, DateTimeKind.Utc)
+ };
+
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+ client.Upload(fileInfo, remoteFile);
+ }
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ var uploadedFile = client.Get(remoteFile);
+ Assert.AreEqual(fileInfo.LastAccessTimeUtc, uploadedFile.LastAccessTimeUtc);
+ Assert.AreEqual(fileInfo.LastWriteTimeUtc, uploadedFile.LastWriteTimeUtc);
+
+ using (var downloaded = new MemoryStream(1000))
+ {
+ client.DownloadFile(remoteFile, downloaded);
+ downloaded.Position = 0;
+ Assert.AreEqual(CreateFileHash(file), CreateHash(downloaded));
+ }
+ }
+ }
+ finally
+ {
+ File.Delete(file);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remoteFile))
+ {
+ client.DeleteFile(remoteFile);
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpUploadFileInfoFileDoesNotExistData), DynamicDataSourceType.Method)]
+ public void Scp_Upload_FileInfo_FileDoesNotExist(IRemotePathTransformation remotePathTransformation,
+ string remotePath,
+ string remoteFile,
+ int size)
+ {
+ var completeRemotePath = CombinePaths(remotePath, remoteFile);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.DeleteFile(completeRemotePath);
+ }
+
+ // remove complete directory if it's not the home directory of the user
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+
+ var file = CreateTempFile(size);
+
+ try
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ // create directory if it's not the home directory of the user
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (!client.Exists(remotePath))
+ {
+ client.CreateDirectory(remotePath);
+ }
+ }
+ }
+
+ var fileInfo = new FileInfo(file)
+ {
+ LastAccessTimeUtc = new DateTime(1973, 8, 13, 20, 15, 33, DateTimeKind.Utc),
+ LastWriteTimeUtc = new DateTime(1974, 1, 24, 3, 55, 12, DateTimeKind.Utc)
+ };
+
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+ client.Upload(fileInfo, completeRemotePath);
+ }
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ var uploadedFile = client.Get(completeRemotePath);
+ Assert.AreEqual(fileInfo.LastAccessTimeUtc, uploadedFile.LastAccessTimeUtc);
+ Assert.AreEqual(fileInfo.LastWriteTimeUtc, uploadedFile.LastWriteTimeUtc);
+ Assert.AreEqual(size, uploadedFile.Length);
+
+ using (var downloaded = new MemoryStream(size))
+ {
+ client.DownloadFile(completeRemotePath, downloaded);
+ downloaded.Position = 0;
+ Assert.AreEqual(CreateFileHash(file), CreateHash(downloaded));
+ }
+ }
+ }
+ finally
+ {
+ File.Delete(file);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(completeRemotePath))
+ {
+ client.Delete(completeRemotePath);
+ }
+
+ // remove complete directory if it's not the home directory of the user
+ if (remotePath.Length > 0 && remotePath != client.WorkingDirectory)
+ {
+ if (client.Exists(remotePath))
+ {
+ client.DeleteDirectory(remotePath);
+ }
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpUploadDirectoryInfoDirectoryDoesNotExistData), DynamicDataSourceType.Method)]
+ public void Scp_Upload_DirectoryInfo_DirectoryDoesNotExist(IRemotePathTransformation remotePathTransformation,
+ string remoteDirectory)
+ {
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists((remoteDirectory)))
+ {
+ client.DeleteDirectory(remoteDirectory);
+ }
+ }
+
+ var localDirectory = Path.GetTempFileName();
+ File.Delete(localDirectory);
+ Directory.CreateDirectory(localDirectory);
+
+ try
+ {
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ try
+ {
+ client.Upload(new DirectoryInfo(localDirectory), remoteDirectory);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {remoteDirectory}: No such file or directory", ex.Message);
+ }
+ }
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ Assert.IsFalse(client.Exists(remoteDirectory));
+ }
+ }
+ finally
+ {
+ Directory.Delete(localDirectory, true);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists((remoteDirectory)))
+ {
+ client.DeleteDirectory(remoteDirectory);
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpUploadDirectoryInfoExistingDirectoryData), DynamicDataSourceType.Method)]
+ public void Scp_Upload_DirectoryInfo_ExistingDirectory(IRemotePathTransformation remotePathTransformation,
+ string remoteDirectory)
+ {
+ string absoluteRemoteDirectory = GetAbsoluteRemotePath(_connectionInfoFactory, remoteDirectory);
+
+ var remotePathFile1 = CombinePaths(remoteDirectory, "file1");
+ var remotePathFile2 = CombinePaths(remoteDirectory, "file2");
+
+ var absoluteremoteSubDirectory1 = CombinePaths(absoluteRemoteDirectory, "sub1");
+ var remoteSubDirectory1 = CombinePaths(remoteDirectory, "sub1");
+ var remotePathSubFile1 = CombinePaths(remoteSubDirectory1, "file1");
+ var remotePathSubFile2 = CombinePaths(remoteSubDirectory1, "file2");
+ var absoluteremoteSubDirectory2 = CombinePaths(absoluteRemoteDirectory, "sub2");
+ var remoteSubDirectory2 = CombinePaths(remoteDirectory, "sub2");
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remotePathSubFile1))
+ {
+ client.DeleteFile(remotePathSubFile1);
+ }
+ if (client.Exists(remotePathSubFile2))
+ {
+ client.DeleteFile(remotePathSubFile2);
+ }
+ if (client.Exists(remoteSubDirectory1))
+ {
+ client.DeleteDirectory(remoteSubDirectory1);
+ }
+ if (client.Exists(remoteSubDirectory2))
+ {
+ client.DeleteDirectory(remoteSubDirectory2);
+ }
+ if (client.Exists(remotePathFile1))
+ {
+ client.DeleteFile(remotePathFile1);
+ }
+ if (client.Exists(remotePathFile2))
+ {
+ client.DeleteFile(remotePathFile2);
+ }
+
+ if (remoteDirectory.Length > 0 && remoteDirectory != "." && remoteDirectory != client.WorkingDirectory)
+ {
+ if (client.Exists(remoteDirectory))
+ {
+ client.DeleteDirectory(remoteDirectory);
+ }
+
+ client.CreateDirectory(remoteDirectory);
+ }
+ }
+
+ var localDirectory = Path.GetTempFileName();
+ File.Delete(localDirectory);
+ Directory.CreateDirectory(localDirectory);
+
+ var localPathFile1 = Path.Combine(localDirectory, "file1");
+ var localPathFile2 = Path.Combine(localDirectory, "file2");
+
+ var localSubDirectory1 = Path.Combine(localDirectory, "sub1");
+ var localPathSubFile1 = Path.Combine(localSubDirectory1, "file1");
+ var localPathSubFile2 = Path.Combine(localSubDirectory1, "file2");
+ var localSubDirectory2 = Path.Combine(localDirectory, "sub2");
+
+ try
+ {
+ CreateFile(localPathFile1, 2000);
+ File.SetLastWriteTimeUtc(localPathFile1, new DateTime(2015, 8, 24, 5, 32, 16, DateTimeKind.Utc));
+
+ CreateFile(localPathFile2, 1000);
+ File.SetLastWriteTimeUtc(localPathFile2, new DateTime(2012, 3, 27, 23, 2, 54, DateTimeKind.Utc));
+
+ // create subdirectory with two files
+ Directory.CreateDirectory(localSubDirectory1);
+ CreateFile(localPathSubFile1, 1000);
+ File.SetLastWriteTimeUtc(localPathSubFile1, new DateTime(2013, 4, 12, 16, 54, 22, DateTimeKind.Utc));
+ CreateFile(localPathSubFile2, 2000);
+ File.SetLastWriteTimeUtc(localPathSubFile2, new DateTime(2015, 8, 4, 12, 43, 12, DateTimeKind.Utc));
+ Directory.SetLastWriteTimeUtc(localSubDirectory1,
+ new DateTime(2014, 6, 12, 13, 2, 44, DateTimeKind.Utc));
+
+ // create empty subdirectory
+ Directory.CreateDirectory(localSubDirectory2);
+ Directory.SetLastWriteTimeUtc(localSubDirectory2,
+ new DateTime(2011, 5, 14, 1, 5, 12, DateTimeKind.Utc));
+
+ Directory.SetLastWriteTimeUtc(localDirectory, new DateTime(2015, 10, 14, 22, 45, 11, DateTimeKind.Utc));
+
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+ client.Upload(new DirectoryInfo(localDirectory), remoteDirectory);
+ }
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ Assert.IsTrue(client.Exists(remoteDirectory));
+
+ var remoteSftpDirectory = client.Get(remoteDirectory);
+ Assert.IsNotNull(remoteSftpDirectory);
+ Assert.AreEqual(absoluteRemoteDirectory, remoteSftpDirectory.FullName);
+ Assert.IsTrue(remoteSftpDirectory.IsDirectory);
+ Assert.IsFalse(remoteSftpDirectory.IsRegularFile);
+
+ // Due to CVE-2018-20685, we can no longer set the times or modes on a file or directory
+ // that refers to the current directory ('.'), the parent directory ('..') or a directory
+ // containing a forward slash ('/').
+ Assert.AreNotEqual(Directory.GetLastWriteTimeUtc(localDirectory), remoteSftpDirectory.LastWriteTimeUtc);
+
+ Assert.IsTrue(client.Exists(remotePathFile1));
+ Assert.AreEqual(CreateFileHash(localPathFile1), CreateRemoteFileHash(client, remotePathFile1));
+ var remoteSftpFile = client.Get(remotePathFile1);
+ Assert.IsNotNull(remoteSftpFile);
+ Assert.IsFalse(remoteSftpFile.IsDirectory);
+ Assert.IsTrue(remoteSftpFile.IsRegularFile);
+ Assert.AreEqual(File.GetLastWriteTimeUtc(localPathFile1), remoteSftpFile.LastWriteTimeUtc);
+
+ Assert.IsTrue(client.Exists(remotePathFile2));
+ Assert.AreEqual(CreateFileHash(localPathFile2), CreateRemoteFileHash(client, remotePathFile2));
+ remoteSftpFile = client.Get(remotePathFile2);
+ Assert.IsNotNull(remoteSftpFile);
+ Assert.IsFalse(remoteSftpFile.IsDirectory);
+ Assert.IsTrue(remoteSftpFile.IsRegularFile);
+ Assert.AreEqual(File.GetLastWriteTimeUtc(localPathFile2), remoteSftpFile.LastWriteTimeUtc);
+
+ Assert.IsTrue(client.Exists(remoteSubDirectory1));
+ remoteSftpDirectory = client.Get(remoteSubDirectory1);
+ Assert.IsNotNull(remoteSftpDirectory);
+ Assert.AreEqual(absoluteremoteSubDirectory1, remoteSftpDirectory.FullName);
+ Assert.IsTrue(remoteSftpDirectory.IsDirectory);
+ Assert.IsFalse(remoteSftpDirectory.IsRegularFile);
+ Assert.AreEqual(Directory.GetLastWriteTimeUtc(localSubDirectory1), remoteSftpDirectory.LastWriteTimeUtc);
+
+ Assert.IsTrue(client.Exists(remotePathSubFile1));
+ Assert.AreEqual(CreateFileHash(localPathSubFile1), CreateRemoteFileHash(client, remotePathSubFile1));
+
+ Assert.IsTrue(client.Exists(remotePathSubFile2));
+ Assert.AreEqual(CreateFileHash(localPathSubFile2), CreateRemoteFileHash(client, remotePathSubFile2));
+
+ Assert.IsTrue(client.Exists(remoteSubDirectory2));
+ remoteSftpDirectory = client.Get(remoteSubDirectory2);
+ Assert.IsNotNull(remoteSftpDirectory);
+ Assert.AreEqual(absoluteremoteSubDirectory2, remoteSftpDirectory.FullName);
+ Assert.IsTrue(remoteSftpDirectory.IsDirectory);
+ Assert.IsFalse(remoteSftpDirectory.IsRegularFile);
+ Assert.AreEqual(Directory.GetLastWriteTimeUtc(localSubDirectory2), remoteSftpDirectory.LastWriteTimeUtc);
+ }
+ }
+ finally
+ {
+ Directory.Delete(localDirectory, true);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remotePathSubFile1))
+ {
+ client.DeleteFile(remotePathSubFile1);
+ }
+ if (client.Exists(remotePathSubFile2))
+ {
+ client.DeleteFile(remotePathSubFile2);
+ }
+ if (client.Exists(remoteSubDirectory1))
+ {
+ client.DeleteDirectory(remoteSubDirectory1);
+ }
+ if (client.Exists(remoteSubDirectory2))
+ {
+ client.DeleteDirectory(remoteSubDirectory2);
+ }
+ if (client.Exists(remotePathFile1))
+ {
+ client.DeleteFile(remotePathFile1);
+ }
+ if (client.Exists(remotePathFile2))
+ {
+ client.DeleteFile(remotePathFile2);
+ }
+
+ if (remoteDirectory.Length > 0 && remoteDirectory != "." && remoteDirectory != client.WorkingDirectory)
+ {
+ if (client.Exists(remoteDirectory))
+ {
+ client.DeleteDirectory(remoteDirectory);
+ }
+ }
+ }
+ }
+ }
+
+ [DataTestMethod]
+ [DynamicData(nameof(GetScpUploadDirectoryInfoExistingFileData), DynamicDataSourceType.Method)]
+ public void Scp_Upload_DirectoryInfo_ExistingFile(IRemotePathTransformation remotePathTransformation,
+ string remoteDirectory)
+ {
+ var remotePathFile1 = CombinePaths(remoteDirectory, "file1");
+ var remotePathFile2 = CombinePaths(remoteDirectory, "file2");
+
+ using (var client = new SshClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ Console.WriteLine(client.ConnectionInfo.CurrentKeyExchangeAlgorithm);
+
+ using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
+ {
+ command.Execute();
+ }
+ }
+
+ var localDirectory = Path.GetTempFileName();
+ File.Delete(localDirectory);
+ Directory.CreateDirectory(localDirectory);
+
+ var localPathFile1 = Path.Combine(localDirectory, "file1");
+ var localPathFile2 = Path.Combine(localDirectory, "file2");
+
+ try
+ {
+ CreateFile(localPathFile1, 50);
+ CreateFile(localPathFile2, 50);
+
+ using (var client = new ScpClient(_connectionInfoFactory.Create()))
+ {
+ if (remotePathTransformation != null)
+ {
+ client.RemotePathTransformation = remotePathTransformation;
+ }
+
+ client.Connect();
+
+ CreateRemoteFile(client, remoteDirectory, 10);
+
+ try
+ {
+ client.Upload(new DirectoryInfo(localDirectory), remoteDirectory);
+ Assert.Fail();
+ }
+ catch (ScpException ex)
+ {
+ Assert.IsNull(ex.InnerException);
+ Assert.AreEqual($"scp: {remoteDirectory}: Not a directory", ex.Message);
+ }
+ }
+ }
+ finally
+ {
+ Directory.Delete(localDirectory, true);
+
+ using (var client = new SftpClient(_connectionInfoFactory.Create()))
+ {
+ client.Connect();
+
+ if (client.Exists(remotePathFile1))
+ {
+ client.DeleteFile(remotePathFile1);
+ }
+ if (client.Exists(remotePathFile2))
+ {
+ client.DeleteFile(remotePathFile2);
+ }
+ if (client.Exists((remoteDirectory)))
+ {
+ client.DeleteFile(remoteDirectory);
+ }
+ }
+ }
+ }
+
+ private static IEnumerable