From 0f08b8502a71c92597fa20da6319fb14e91c4468 Mon Sep 17 00:00:00 2001 From: Gert Driesen Date: Sun, 15 Oct 2017 11:46:10 +0200 Subject: [PATCH 01/15] Prepare for 2016.1.0 RTW. --- build/nuget/SSH.NET.nuspec | 4 ++-- src/Renci.SshNet/Properties/CommonAssemblyInfo.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/build/nuget/SSH.NET.nuspec b/build/nuget/SSH.NET.nuspec index 039a9e116..12bffe81e 100644 --- a/build/nuget/SSH.NET.nuspec +++ b/build/nuget/SSH.NET.nuspec @@ -2,7 +2,7 @@ SSH.NET - 2016.1.0-beta4 + 2016.1.0 SSH.NET Renci olegkap,drieseng @@ -10,7 +10,7 @@ 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. - https://github.com/sshnet/SSH.NET/releases/tag/2016.1.0-beta4 + https://github.com/sshnet/SSH.NET/releases/tag/2016.1.0 A Secure Shell (SSH) library for .NET, optimized for parallelism. 2012-2017, RENCI en-US diff --git a/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs b/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs index 8497d5fb0..2c41da970 100644 --- a/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs +++ b/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs @@ -11,7 +11,7 @@ [assembly: AssemblyVersion("2016.1.0")] [assembly: AssemblyFileVersion("2016.1.0")] -[assembly: AssemblyInformationalVersion("2016.1.0-beta4")] +[assembly: AssemblyInformationalVersion("2016.1.0")] [assembly: CLSCompliant(false)] // Setting ComVisible to false makes the types in this assembly not visible From 4583da528f93294f37f66d176cc23bfcb0d71e01 Mon Sep 17 00:00:00 2001 From: drieseng Date: Sun, 3 May 2020 17:46:40 +0200 Subject: [PATCH 02/15] Remove CWLs. --- src/Renci.SshNet/Session.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/Renci.SshNet/Session.cs b/src/Renci.SshNet/Session.cs index 058e589ab..897796850 100644 --- a/src/Renci.SshNet/Session.cs +++ b/src/Renci.SshNet/Session.cs @@ -1992,8 +1992,6 @@ private void MessageListener() // * a call to Disconnect() // * a call to Dispose() // * a SSH_MSG_DISCONNECT received from server - - Console.WriteLine("B"); break; } @@ -2002,7 +2000,6 @@ private void MessageListener() { // connection with SSH server was closed; // break out of the message loop - Console.WriteLine("C"); break; } @@ -2010,8 +2007,6 @@ private void MessageListener() message.Process(this); } - Console.WriteLine("D"); - // connection with SSH server was closed or socket was disposed RaiseError(CreateConnectionAbortedByServerException()); } From 66e24e7462e263069166d67f16c26a627262e375 Mon Sep 17 00:00:00 2001 From: Gert Driesen Date: Sun, 7 Jun 2020 10:52:12 +0200 Subject: [PATCH 03/15] Sponsoring (#691) * Create FUNDING.yml * Add sponsor info. --- .github/FUNDING.yml | 3 +++ README.md | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 .github/FUNDING.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..81a8e9b30 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: sshnet diff --git a/README.md b/README.md index 0790a2bba..ebf9118f7 100644 --- a/README.md +++ b/README.md @@ -188,4 +188,6 @@ Visual Studio 2015 Update 3 | x | x | | Visual Studio 2017 | x | x | x | x | | | | | Visual Studio 2019 | x | x | x | x | | | | | -[![NDepend](http://download-codeplex.sec.s-msft.com/Download?ProjectName=sshnet&DownloadId=629750)](http://ndepend.com) +## Supporting SSH.NET + +Do you or your company rely on **SSH.NET** in your projects? If you 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. From 66cf838d264b1a03c05bedbdbbf72fe6654f4308 Mon Sep 17 00:00:00 2001 From: drieseng Date: Mon, 1 Jun 2020 10:03:51 +0200 Subject: [PATCH 04/15] Prepare for 2020.0.0-beta1 --- src/Renci.SshNet/Properties/CommonAssemblyInfo.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs b/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs index 2c41da970..cba256303 100644 --- a/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs +++ b/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs @@ -5,13 +5,13 @@ [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-2017")] +[assembly: AssemblyCopyright("Copyright © Renci 2010-2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("2016.1.0")] -[assembly: AssemblyFileVersion("2016.1.0")] -[assembly: AssemblyInformationalVersion("2016.1.0")] +[assembly: AssemblyVersion("2020.0.0")] +[assembly: AssemblyFileVersion("2020.0.0")] +[assembly: AssemblyInformationalVersion("2020.0.0-beta1")] [assembly: CLSCompliant(false)] // Setting ComVisible to false makes the types in this assembly not visible From d8fbae3c51bc489d8735e534df5143243a428fcc Mon Sep 17 00:00:00 2001 From: drieseng Date: Sun, 7 Jun 2020 13:23:50 +0200 Subject: [PATCH 05/15] Update name of Sandcastle Help File Builder environment variable. --- build/sandcastle/SSH.NET.shfbproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build/sandcastle/SSH.NET.shfbproj b/build/sandcastle/SSH.NET.shfbproj index 50141f16e..539865294 100644 --- a/build/sandcastle/SSH.NET.shfbproj +++ b/build/sandcastle/SSH.NET.shfbproj @@ -36,7 +36,7 @@ {@HelpFormatOutputPaths} - + @@ -72,5 +72,5 @@ - + \ No newline at end of file From 32f26157957a99516f98f98eb2905b15f0fcf447 Mon Sep 17 00:00:00 2001 From: drieseng Date: Sun, 7 Jun 2020 15:31:29 +0200 Subject: [PATCH 06/15] Fix path to source file. --- src/Renci.SshNet/SshClient.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Renci.SshNet/SshClient.cs b/src/Renci.SshNet/SshClient.cs index b6b7cbb02..49c9ff84b 100644 --- a/src/Renci.SshNet/SshClient.cs +++ b/src/Renci.SshNet/SshClient.cs @@ -261,7 +261,7 @@ public SshCommand CreateCommand(string commandText, Encoding encoding) /// This method internally uses asynchronous calls. /// /// - /// + /// /// /// CommandText property is empty. /// Invalid Operation - An existing channel was used to execute this command. From bf651cac1eeb8f4f1594c74e9b90793d2f2602e9 Mon Sep 17 00:00:00 2001 From: drieseng Date: Sun, 7 Jun 2020 15:39:54 +0200 Subject: [PATCH 07/15] Remove local-use file. --- runtest.cmd | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 runtest.cmd diff --git a/runtest.cmd b/runtest.cmd deleted file mode 100644 index ad4c0f5ae..000000000 --- a/runtest.cmd +++ /dev/null @@ -1,3 +0,0 @@ -rem vstest.console src\Renci.SshNet.Tests\bin\Debug\net40\Renci.SshNet.Tests.dll "/TestCaseFilter:TestCategory=Gert - -vstest.console src\Renci.SshNet.Tests\bin\Debug\net40\Renci.SshNet.Tests.dll /TestCaseFilter:"TestCategory!=integration&TestCategory!=LongRunning" \ No newline at end of file From 853ec99609fbdb69ccd705fdefc3fa580237ce6a Mon Sep 17 00:00:00 2001 From: drieseng Date: Thu, 31 Dec 2020 13:06:47 +0100 Subject: [PATCH 08/15] Prepare for 2020.0.0 release. --- src/Renci.SshNet/Properties/CommonAssemblyInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs b/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs index cba256303..4941731e9 100644 --- a/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs +++ b/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs @@ -11,7 +11,7 @@ [assembly: AssemblyVersion("2020.0.0")] [assembly: AssemblyFileVersion("2020.0.0")] -[assembly: AssemblyInformationalVersion("2020.0.0-beta1")] +[assembly: AssemblyInformationalVersion("2020.0.0")] [assembly: CLSCompliant(false)] // Setting ComVisible to false makes the types in this assembly not visible From acda1431d23a9196377464e6f48056dfd42cc867 Mon Sep 17 00:00:00 2001 From: drieseng Date: Sun, 24 Jan 2021 14:40:24 +0100 Subject: [PATCH 09/15] Prepare for 2020.0.1 release --- src/Renci.SshNet/Properties/CommonAssemblyInfo.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs b/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs index 4941731e9..0883060cc 100644 --- a/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs +++ b/src/Renci.SshNet/Properties/CommonAssemblyInfo.cs @@ -5,13 +5,13 @@ [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-2020")] +[assembly: AssemblyCopyright("Copyright © Renci 2010-2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("2020.0.0")] -[assembly: AssemblyFileVersion("2020.0.0")] -[assembly: AssemblyInformationalVersion("2020.0.0")] +[assembly: AssemblyVersion("2020.0.1")] +[assembly: AssemblyFileVersion("2020.0.1")] +[assembly: AssemblyInformationalVersion("2020.0.1")] [assembly: CLSCompliant(false)] // Setting ComVisible to false makes the types in this assembly not visible From 4cdedf65247a0e720f0723bcd9edb773b3f2223f Mon Sep 17 00:00:00 2001 From: drieseng Date: Sun, 29 May 2022 16:59:38 +0200 Subject: [PATCH 10/15] Use cryptographically secure random number generator. Fixes CVE-2022-29245. --- src/Renci.SshNet/Security/KeyExchangeECCurve25519.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/Renci.SshNet/Security/KeyExchangeECCurve25519.cs b/src/Renci.SshNet/Security/KeyExchangeECCurve25519.cs index 9de7af8fb..b7a318bb9 100644 --- a/src/Renci.SshNet/Security/KeyExchangeECCurve25519.cs +++ b/src/Renci.SshNet/Security/KeyExchangeECCurve25519.cs @@ -1,5 +1,4 @@ -using System; -using Renci.SshNet.Abstractions; +using Renci.SshNet.Abstractions; using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; using Renci.SshNet.Security.Chaos.NaCl; @@ -46,9 +45,7 @@ public override void Start(Session session, KeyExchangeInitMessage message) var basepoint = new byte[MontgomeryCurve25519.PublicKeySizeInBytes]; basepoint[0] = 9; - var rnd = new Random(); - _privateKey = new byte[MontgomeryCurve25519.PrivateKeySizeInBytes]; - rnd.NextBytes(_privateKey); + _privateKey = CryptoAbstraction.GenerateRandom(MontgomeryCurve25519.PrivateKeySizeInBytes); _clientExchangeValue = new byte[MontgomeryCurve25519.PublicKeySizeInBytes]; MontgomeryOperations.scalarmult(_clientExchangeValue, 0, _privateKey, 0, basepoint, 0); From 49c7729f85700a110528e1cec1638f4dcceda143 Mon Sep 17 00:00:00 2001 From: Toni Spets Date: Fri, 6 Jan 2017 19:44:53 +0200 Subject: [PATCH 11/15] New pipe implementation for SshCommand --- src/Renci.SshNet/Common/LinkedListQueue.cs | 134 ++++++++++++++++++++ src/Renci.SshNet/Common/Pipe.cs | 47 +++++++ src/Renci.SshNet/Common/PipeInputStream.cs | 112 ++++++++++++++++ src/Renci.SshNet/Common/PipeOutputStream.cs | 111 ++++++++++++++++ src/Renci.SshNet/SshCommand.cs | 72 +++++------ 5 files changed, 439 insertions(+), 37 deletions(-) create mode 100644 src/Renci.SshNet/Common/LinkedListQueue.cs create mode 100644 src/Renci.SshNet/Common/Pipe.cs create mode 100644 src/Renci.SshNet/Common/PipeInputStream.cs create mode 100644 src/Renci.SshNet/Common/PipeOutputStream.cs diff --git a/src/Renci.SshNet/Common/LinkedListQueue.cs b/src/Renci.SshNet/Common/LinkedListQueue.cs new file mode 100644 index 000000000..d8f164a71 --- /dev/null +++ b/src/Renci.SshNet/Common/LinkedListQueue.cs @@ -0,0 +1,134 @@ +namespace Renci.SshNet.Common +{ + using System; + using System.Threading; + + /// + /// Fast concurrent generic linked list queue. + /// + public class LinkedListQueue : IDisposable + { + sealed class Entry + { + public E Item; + public Entry Next; + } + + private readonly object _lock = new object(); + + private Entry _first; + private Entry _last; + + private bool _isAddingCompleted; + + /// + /// Gets whether this has been marked as complete for adding and is empty. + /// + /// Whether this queue has been marked as complete for adding and is empty. + public bool IsCompleted + { + get { return _isAddingCompleted && _first == null && _last == null; } + } + + /// + /// Gets whether this has been marked as complete for adding. + /// + /// Whether this queue has been marked as complete for adding. + public bool IsAddingCompleted + { + get { return _isAddingCompleted; } + set + { + lock (_lock) + { + _isAddingCompleted = value; + } + } + } + + /// + /// Adds the item to . + /// + /// The item to be added to the queue. The value can be a null reference. + public void Add(T item) + { + lock (_lock) + { + if (_isAddingCompleted) + return; + + var entry = new Entry(); + entry.Item = item; + + if (_last != null) + { + _last.Next = entry; + } + + _last = entry; + + if (_first == null) + { + _first = entry; + } + + Monitor.PulseAll(_lock); + } + } + + /// + /// Marks the instances as not accepting any more additions. + /// + public void CompleteAdding() + { + lock (_lock) + { + IsAddingCompleted = true; + Monitor.PulseAll(_lock); + } + } + + /// + /// Tries to remove an item from the . + /// + /// true, if an item could be removed; otherwise false. + /// The item to be removed from the queue. + public bool TryTake(out T item) + { + lock (_lock) + { + while (_first == null && !_isAddingCompleted) + Monitor.Wait(_lock); + + if (_first == null && _isAddingCompleted) + { + item = default(T); + return false; + } + + item = _first.Item; + _first = _first.Next; + return true; + } + } + + /// + /// Releases all resource used by the object. + /// + /// Call when you are finished using the + /// . The method leaves the + /// in an unusable state. After calling + /// , you must release all references to the + /// so the garbage collector can reclaim the memory that + /// the was occupying. + public void Dispose() + { + lock (_lock) + { + _first = null; + _last = null; + _isAddingCompleted = true; + } + } + } +} diff --git a/src/Renci.SshNet/Common/Pipe.cs b/src/Renci.SshNet/Common/Pipe.cs new file mode 100644 index 000000000..2ef08d49b --- /dev/null +++ b/src/Renci.SshNet/Common/Pipe.cs @@ -0,0 +1,47 @@ +namespace Renci.SshNet.Common +{ + using System; + using System.IO; + + /// + /// A generic pipe to pass through data. + /// + internal class Pipe : IDisposable + { + private readonly LinkedListQueue _queue; + + /// + /// Gets the input stream. + /// + /// The input stream. + public Stream InputStream { get; private set; } + + /// + /// Gets the output stream. + /// + /// The output stream. + public Stream OutputStream { get; private set; } + + public Pipe() + { + _queue = new LinkedListQueue(); + InputStream = new PipeInputStream(_queue); + OutputStream = new PipeOutputStream(_queue); + } + + /// + /// Releases all resource used by the object. + /// + /// Call when you are finished using the . The + /// method leaves the in an unusable state. After + /// calling , you must release all references to the + /// so the garbage collector can reclaim the memory that the + /// was occupying. + public void Dispose() + { + OutputStream.Dispose(); + InputStream.Dispose(); + _queue.Dispose(); + } + } +} diff --git a/src/Renci.SshNet/Common/PipeInputStream.cs b/src/Renci.SshNet/Common/PipeInputStream.cs new file mode 100644 index 000000000..d18192655 --- /dev/null +++ b/src/Renci.SshNet/Common/PipeInputStream.cs @@ -0,0 +1,112 @@ +namespace Renci.SshNet.Common +{ + using System; + using System.IO; + + internal class PipeInputStream : Stream + { + private LinkedListQueue _queue; + private byte[] _current; + private int _currentPosition; + private bool _isDisposed; + + public PipeInputStream(LinkedListQueue queue) + { + _queue = queue; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + if (buffer == null) + throw new ArgumentNullException("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 (_isDisposed) + throw CreateObjectDisposedException(); + + if (_current == null || _currentPosition == _current.Length) + { + if (_queue.IsCompleted || !_queue.TryTake(out _current)) + return 0; + + _currentPosition = 0; + } + + var avail = _current.Length - _currentPosition; + if (count > avail) + count = avail; + + Buffer.BlockCopy(_current, _currentPosition, buffer, offset, count); + + _currentPosition += count; + return count; + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + + public override bool CanRead + { + get { return true; } + } + + public override bool CanSeek + { + get { return false; } + } + + public override bool CanWrite + { + get { return false; } + } + + public override long Length + { + get + { + throw new NotSupportedException(); + } + } + + public override long Position + { + get + { + throw new NotSupportedException(); + } + set + { + throw new NotSupportedException(); + } + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + _isDisposed = true; + } + + private ObjectDisposedException CreateObjectDisposedException() + { + return new ObjectDisposedException(GetType().FullName); + } + } +} diff --git a/src/Renci.SshNet/Common/PipeOutputStream.cs b/src/Renci.SshNet/Common/PipeOutputStream.cs new file mode 100644 index 000000000..8cfd1d98c --- /dev/null +++ b/src/Renci.SshNet/Common/PipeOutputStream.cs @@ -0,0 +1,111 @@ +namespace Renci.SshNet.Common +{ + using System; + using System.IO; + + internal class PipeOutputStream : Stream + { + private LinkedListQueue _queue; + private bool _isDisposed; + + public PipeOutputStream(LinkedListQueue queue) + { + _queue = queue; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + if (buffer == null) + throw new ArgumentNullException("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 (_isDisposed) + throw CreateObjectDisposedException(); + if (_queue.IsAddingCompleted) + return; + + byte[] tmp = new byte[count]; + Buffer.BlockCopy(buffer, offset, tmp, 0, count); + _queue.Add(tmp); + } + + public override bool CanRead + { + get { return false; } + } + + public override bool CanSeek + { + get { return false; } + } + + public override bool CanWrite + { + get { return true; } + } + + public override long Length + { + get + { + throw new NotSupportedException(); + } + } + + public override long Position + { + get + { + throw new NotSupportedException(); + } + set + { + throw new NotSupportedException(); + } + } + + public override void Close() + { + if (!_queue.IsAddingCompleted) + _queue.CompleteAdding(); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + if (!_isDisposed) + { + if (!_queue.IsAddingCompleted) + _queue.CompleteAdding(); + _isDisposed = true; + } + } + + private ObjectDisposedException CreateObjectDisposedException() + { + return new ObjectDisposedException(GetType().FullName); + } + } +} diff --git a/src/Renci.SshNet/SshCommand.cs b/src/Renci.SshNet/SshCommand.cs index 37e91da08..4a2a9bb27 100644 --- a/src/Renci.SshNet/SshCommand.cs +++ b/src/Renci.SshNet/SshCommand.cs @@ -25,6 +25,8 @@ public class SshCommand : IDisposable private Exception _exception; private bool _hasError; private readonly object _endExecuteLock = new object(); + private Pipe _stdoutPipe; + private Pipe _stderrPipe; /// /// Gets the command text. @@ -56,7 +58,10 @@ public class SshCommand : IDisposable /// /// /// - public Stream OutputStream { get; private set; } + public Stream OutputStream + { + get { return _stdoutPipe.InputStream; } + } /// /// Gets the extended output stream. @@ -64,7 +69,10 @@ public class SshCommand : IDisposable /// /// /// - public Stream ExtendedOutputStream { get; private set; } + public Stream ExtendedOutputStream + { + get { return _stderrPipe.InputStream; } + } private StringBuilder _result; /// @@ -82,10 +90,10 @@ public string Result _result = new StringBuilder(); } - if (OutputStream != null && OutputStream.Length > 0) + if (_stdoutPipe != null) { // do not dispose the StreamReader, as it would also dispose the stream - var sr = new StreamReader(OutputStream, _encoding); + var sr = new StreamReader(_stdoutPipe.InputStream, _encoding); _result.Append(sr.ReadToEnd()); } @@ -111,10 +119,10 @@ public string Error _error = new StringBuilder(); } - if (ExtendedOutputStream != null && ExtendedOutputStream.Length > 0) + if (_stderrPipe != null) { // do not dispose the StreamReader, as it would also dispose the stream - var sr = new StreamReader(ExtendedOutputStream, _encoding); + var sr = new StreamReader(_stderrPipe.InputStream, _encoding); _error.Append(sr.ReadToEnd()); } @@ -230,23 +238,19 @@ public IAsyncResult BeginExecute(AsyncCallback callback, object state) if (string.IsNullOrEmpty(CommandText)) throw new ArgumentException("CommandText property is empty."); - var outputStream = OutputStream; - if (outputStream != null) + if (_stdoutPipe != null) { - outputStream.Dispose(); - OutputStream = null; + _stdoutPipe.Dispose(); } - var extendedOutputStream = ExtendedOutputStream; - if (extendedOutputStream != null) + if (_stderrPipe != null) { - extendedOutputStream.Dispose(); - ExtendedOutputStream = null; + _stderrPipe.Dispose(); } - // Initialize output streams - OutputStream = new PipeStream(); - ExtendedOutputStream = new PipeStream(); + // Initialize pipes + _stdoutPipe = new Pipe(); + _stderrPipe = new Pipe(); _result = null; _error = null; @@ -395,16 +399,14 @@ private void Session_ErrorOccured(object sender, ExceptionEventArgs e) private void Channel_Closed(object sender, ChannelEventArgs e) { - var outputStream = OutputStream; - if (outputStream != null) + if (_stdoutPipe != null) { - outputStream.Flush(); + _stdoutPipe.OutputStream.Close(); } - var extendedOutputStream = ExtendedOutputStream; - if (extendedOutputStream != null) + if (_stderrPipe != null) { - extendedOutputStream.Flush(); + _stderrPipe.OutputStream.Close(); } _asyncResult.IsCompleted = true; @@ -442,10 +444,9 @@ private void Channel_RequestReceived(object sender, ChannelRequestEventArgs e) private void Channel_ExtendedDataReceived(object sender, ChannelExtendedDataEventArgs e) { - if (ExtendedOutputStream != null) + if (_stderrPipe != null) { - ExtendedOutputStream.Write(e.Data, 0, e.Data.Length); - ExtendedOutputStream.Flush(); + _stderrPipe.OutputStream.Write(e.Data, 0, e.Data.Length); } if (e.DataTypeCode == 1) @@ -456,10 +457,9 @@ private void Channel_ExtendedDataReceived(object sender, ChannelExtendedDataEven private void Channel_DataReceived(object sender, ChannelDataEventArgs e) { - if (OutputStream != null) + if (_stdoutPipe != null) { - OutputStream.Write(e.Data, 0, e.Data.Length); - OutputStream.Flush(); + _stdoutPipe.OutputStream.Write(e.Data, 0, e.Data.Length); } if (_asyncResult != null) @@ -557,18 +557,16 @@ protected virtual void Dispose(bool disposing) _channel = null; } - var outputStream = OutputStream; - if (outputStream != null) + if (_stdoutPipe != null) { - outputStream.Dispose(); - OutputStream = null; + _stdoutPipe.Dispose(); + _stdoutPipe = null; } - var extendedOutputStream = ExtendedOutputStream; - if (extendedOutputStream != null) + if (_stderrPipe != null) { - extendedOutputStream.Dispose(); - ExtendedOutputStream = null; + _stderrPipe.Dispose(); + _stderrPipe = null; } var sessionErrorOccuredWaitHandle = _sessionErrorOccuredWaitHandle; From 796d7b0d7b00c3ec487b1ea0e6675a8fde8929fe Mon Sep 17 00:00:00 2001 From: Toni Spets Date: Sat, 7 Jan 2017 06:53:03 +0200 Subject: [PATCH 12/15] Small fixes --- src/Renci.SshNet/Common/LinkedListQueue.cs | 2 +- src/Renci.SshNet/Common/PipeInputStream.cs | 2 +- src/Renci.SshNet/Common/PipeOutputStream.cs | 6 ++---- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/Renci.SshNet/Common/LinkedListQueue.cs b/src/Renci.SshNet/Common/LinkedListQueue.cs index d8f164a71..b07f64846 100644 --- a/src/Renci.SshNet/Common/LinkedListQueue.cs +++ b/src/Renci.SshNet/Common/LinkedListQueue.cs @@ -6,7 +6,7 @@ /// /// Fast concurrent generic linked list queue. /// - public class LinkedListQueue : IDisposable + internal class LinkedListQueue : IDisposable { sealed class Entry { diff --git a/src/Renci.SshNet/Common/PipeInputStream.cs b/src/Renci.SshNet/Common/PipeInputStream.cs index d18192655..bc37d52fb 100644 --- a/src/Renci.SshNet/Common/PipeInputStream.cs +++ b/src/Renci.SshNet/Common/PipeInputStream.cs @@ -65,7 +65,7 @@ public override void Write(byte[] buffer, int offset, int count) public override bool CanRead { - get { return true; } + get { return !_isDisposed; } } public override bool CanSeek diff --git a/src/Renci.SshNet/Common/PipeOutputStream.cs b/src/Renci.SshNet/Common/PipeOutputStream.cs index 8cfd1d98c..42905608f 100644 --- a/src/Renci.SshNet/Common/PipeOutputStream.cs +++ b/src/Renci.SshNet/Common/PipeOutputStream.cs @@ -40,10 +40,8 @@ public override void Write(byte[] buffer, int offset, int count) 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 (_isDisposed) + if (_isDisposed || _queue.IsAddingCompleted) throw CreateObjectDisposedException(); - if (_queue.IsAddingCompleted) - return; byte[] tmp = new byte[count]; Buffer.BlockCopy(buffer, offset, tmp, 0, count); @@ -62,7 +60,7 @@ public override bool CanSeek public override bool CanWrite { - get { return true; } + get { return !_isDisposed; } } public override long Length From b430a8324f1f56c5ffbd49cc5b02e04ec01b65d2 Mon Sep 17 00:00:00 2001 From: Toni Spets Date: Sat, 7 Jan 2017 16:09:16 +0200 Subject: [PATCH 13/15] PipeInputStream will read as much as it can without blocking --- src/Renci.SshNet/Common/LinkedListQueue.cs | 9 +++++- src/Renci.SshNet/Common/PipeInputStream.cs | 32 ++++++++++++++-------- 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/src/Renci.SshNet/Common/LinkedListQueue.cs b/src/Renci.SshNet/Common/LinkedListQueue.cs index b07f64846..57dd99d4b 100644 --- a/src/Renci.SshNet/Common/LinkedListQueue.cs +++ b/src/Renci.SshNet/Common/LinkedListQueue.cs @@ -93,10 +93,17 @@ public void CompleteAdding() /// /// true, if an item could be removed; otherwise false. /// The item to be removed from the queue. - public bool TryTake(out T item) + /// Wait for data or fail immediately if empty. + public bool TryTake(out T item, bool wait) { lock (_lock) { + if (_first == null && !wait) + { + item = default(T); + return false; + } + while (_first == null && !_isAddingCompleted) Monitor.Wait(_lock); diff --git a/src/Renci.SshNet/Common/PipeInputStream.cs b/src/Renci.SshNet/Common/PipeInputStream.cs index bc37d52fb..d12fe9aa6 100644 --- a/src/Renci.SshNet/Common/PipeInputStream.cs +++ b/src/Renci.SshNet/Common/PipeInputStream.cs @@ -40,22 +40,32 @@ public override int Read(byte[] buffer, int offset, int count) if (_isDisposed) throw CreateObjectDisposedException(); - if (_current == null || _currentPosition == _current.Length) + var bytesRead = 0; + + while (bytesRead < count) { - if (_queue.IsCompleted || !_queue.TryTake(out _current)) - return 0; + if (_current == null || _currentPosition == _current.Length) + { + if (!_queue.TryTake(out _current, (bytesRead == 0))) + { + _current = null; + return bytesRead; + } - _currentPosition = 0; - } + _currentPosition = 0; + } - var avail = _current.Length - _currentPosition; - if (count > avail) - count = avail; + var toRead = _current.Length - _currentPosition; + if (toRead > count - bytesRead) + toRead = count - bytesRead; - Buffer.BlockCopy(_current, _currentPosition, buffer, offset, count); + Buffer.BlockCopy(_current, _currentPosition, buffer, offset + bytesRead, toRead); + + _currentPosition += toRead; + bytesRead += toRead; + } - _currentPosition += count; - return count; + return bytesRead; } public override void Write(byte[] buffer, int offset, int count) From 4572bdc90ac7dc53fe01463662ed6e7b2ca09ded Mon Sep 17 00:00:00 2001 From: mdarocha Date: Wed, 13 Jul 2022 18:15:10 +0200 Subject: [PATCH 14/15] Add InputStream --- src/Renci.SshNet/Common/ChannelInputStream.cs | 230 ++++++++++++++++++ src/Renci.SshNet/SshCommand.cs | 17 +- 2 files changed, 246 insertions(+), 1 deletion(-) create mode 100644 src/Renci.SshNet/Common/ChannelInputStream.cs diff --git a/src/Renci.SshNet/Common/ChannelInputStream.cs b/src/Renci.SshNet/Common/ChannelInputStream.cs new file mode 100644 index 000000000..0f0bcaf65 --- /dev/null +++ b/src/Renci.SshNet/Common/ChannelInputStream.cs @@ -0,0 +1,230 @@ +namespace Renci.SshNet.Common +{ + using System; + using System.IO; + using Renci.SshNet.Channels; + + /// + /// ChannelInputStream is a one direction stream intended for channel data. + /// + /// + /// Copyright (c) 2016 Toni Spets (toni.spets@iki.fi) + /// + /// 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 ChannelInputStream : Stream + { + #region Private members + + /// + /// Channel to send data to. + /// + private IChannelSession _channel; + + /// + /// Total bytes passed through the stream. + /// + private long _totalPosition; + + /// + /// Indicates whether the current is disposed. + /// + private bool _isDisposed; + + #endregion + + internal ChannelInputStream(IChannelSession channel) + { + _channel = channel; + } + + #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. + /// + /// An I/O error occurs. + /// Methods were called after the stream was closed. + /// + /// Once flushed, any subsequent read operations no longer block until requested bytes are available. Any write operation reactivates blocking + /// reads. + /// + public override void Flush() + { + } + + /// + /// When overridden in a derived class, sets the position within the current stream. + /// + /// + /// The new position within the current stream. + /// + /// A byte offset relative to the origin parameter. + /// A value of type indicating the reference point used to obtain the new position. + /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + + /// + /// When overridden in a derived class, sets the length of the current stream. + /// + /// The desired length of the current stream in bytes. + /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. + 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. + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + + /// + ///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. + public override void Write(byte[] buffer, int offset, int count) + { + if (buffer == null) + throw new ArgumentNullException("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 (_isDisposed) + throw CreateObjectDisposedException(); + if (count == 0) + return; + + _channel.SendData(buffer, offset, count); + + _totalPosition += 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. + /// + /// Disposing a will interrupt blocking read and write operations. + /// + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + if (!_isDisposed) + { + _isDisposed = true; + if (_totalPosition > 0 && _channel.IsOpen) { + _channel.SendEof(); + } + } + } + + /// + ///When overridden in a derived class, gets a value indicating whether the current stream supports reading. + /// + /// + ///true if the stream supports reading; otherwise, false. + /// + public override bool CanRead + { + get { return false; } + } + + /// + /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking. + /// + /// + /// true if the stream supports seeking; otherwise, false. + /// + public override bool CanSeek + { + get { return false; } + } + + /// + /// When overridden in a derived class, gets a value indicating whether the current stream supports writing. + /// + /// + /// true if the stream supports writing; otherwise, false. + /// + public override bool CanWrite + { + get { return true; } + } + + /// + /// When overridden in a derived class, gets the length in bytes of the stream. + /// + /// + /// A long value representing the length of the stream in bytes. + /// + /// A class derived from Stream does not support seeking. + /// Methods were called after the stream was closed. + public override long Length + { + get { throw new NotSupportedException(); } + } + + /// + /// When overridden in a derived class, gets or sets the position within the current stream. + /// + /// + /// The current position within the stream. + /// + /// The stream does not support seeking. + public override long Position + { + get { return _totalPosition; } + set { throw new NotSupportedException(); } + } + + #endregion + + private ObjectDisposedException CreateObjectDisposedException() + { + return new ObjectDisposedException(GetType().FullName); + } + } +} diff --git a/src/Renci.SshNet/SshCommand.cs b/src/Renci.SshNet/SshCommand.cs index 4a2a9bb27..fe4688a5b 100644 --- a/src/Renci.SshNet/SshCommand.cs +++ b/src/Renci.SshNet/SshCommand.cs @@ -74,6 +74,11 @@ public Stream ExtendedOutputStream get { return _stderrPipe.InputStream; } } + /// + /// Get the input stream. + /// + public Stream InputStream { get; private set; } + private StringBuilder _result; /// /// Gets the command execution result. @@ -248,7 +253,12 @@ public IAsyncResult BeginExecute(AsyncCallback callback, object state) _stderrPipe.Dispose(); } - // Initialize pipes + if (InputStream != null) + { + InputStream.Dispose(); + } + + // Initialize output pipes _stdoutPipe = new Pipe(); _stderrPipe = new Pipe(); @@ -260,6 +270,9 @@ public IAsyncResult BeginExecute(AsyncCallback callback, object state) _channel.Open(); _channel.SendExecRequest(CommandText); + // Initialize input stream + InputStream = new ChannelInputStream(_channel); + return _asyncResult; } @@ -538,6 +551,8 @@ protected virtual void Dispose(bool disposing) if (disposing) { + InputStream.Dispose(); + // unsubscribe from session events to ensure other objects that we're going to dispose // are not accessed while disposing var session = _session; From e38eb9065601c516249fd3f6351bdb2d6acf33cd Mon Sep 17 00:00:00 2001 From: mdarocha Date: Thu, 14 Jul 2022 22:30:23 +0200 Subject: [PATCH 15/15] Fix build on netstandard1.3 --- src/Renci.SshNet/Common/Pipe.cs | 5 ++--- src/Renci.SshNet/Common/PipeOutputStream.cs | 4 ++++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Renci.SshNet/Common/Pipe.cs b/src/Renci.SshNet/Common/Pipe.cs index 2ef08d49b..d8aa0e383 100644 --- a/src/Renci.SshNet/Common/Pipe.cs +++ b/src/Renci.SshNet/Common/Pipe.cs @@ -1,7 +1,6 @@ namespace Renci.SshNet.Common { using System; - using System.IO; /// /// A generic pipe to pass through data. @@ -14,13 +13,13 @@ internal class Pipe : IDisposable /// Gets the input stream. /// /// The input stream. - public Stream InputStream { get; private set; } + public PipeInputStream InputStream { get; private set; } /// /// Gets the output stream. /// /// The output stream. - public Stream OutputStream { get; private set; } + public PipeOutputStream OutputStream { get; private set; } public Pipe() { diff --git a/src/Renci.SshNet/Common/PipeOutputStream.cs b/src/Renci.SshNet/Common/PipeOutputStream.cs index 42905608f..0f7afca1d 100644 --- a/src/Renci.SshNet/Common/PipeOutputStream.cs +++ b/src/Renci.SshNet/Common/PipeOutputStream.cs @@ -83,7 +83,11 @@ public override long Position } } +#if NETSTANDARD1_3 + public void Close() +#else public override void Close() +#endif { if (!_queue.IsAddingCompleted) _queue.CompleteAdding();