diff --git a/.gitattributes b/.gitattributes
index 83d35b020..fa94b297a 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -17,4 +17,7 @@
*.snk binary
# Ensure key files have LF endings for easier usage with ssh-keygen
-test/Data/* eol=lf
\ No newline at end of file
+# Also, the dockerfile used for integration tests fails if key files have cr-lf
+test/Data/* eol=lf
+test/Renci.SshNet.IntegrationTests/server/**/* eol=lf
+test/Renci.SshNet.IntegrationTests/user/* eol=lf
diff --git a/src/Renci.SshNet/Common/ChannelInputStream.cs b/src/Renci.SshNet/Common/ChannelInputStream.cs
new file mode 100644
index 000000000..f509ac38b
--- /dev/null
+++ b/src/Renci.SshNet/Common/ChannelInputStream.cs
@@ -0,0 +1,217 @@
+using System;
+using System.IO;
+
+using Renci.SshNet.Channels;
+
+namespace Renci.SshNet.Common
+{
+ ///
+ /// ChannelInputStream is a one direction stream intended for channel data.
+ ///
+ internal sealed class ChannelInputStream : Stream
+ {
+ ///
+ /// Channel to send data to.
+ ///
+ private readonly IChannelSession _channel;
+
+ ///
+ /// Total bytes passed through the stream.
+ ///
+ private long _totalPosition;
+
+ ///
+ /// Indicates whether the current instance was disposed.
+ ///
+ private bool _isDisposed;
+
+ internal ChannelInputStream(IChannelSession channel)
+ {
+ _channel = channel;
+ }
+
+ ///
+ /// 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.
+ ///
+ /// 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 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.
+ ///
+ /// 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 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(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(nameof(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.
+ protected override void Dispose(bool disposing)
+ {
+ if (!_isDisposed)
+ {
+ _isDisposed = true;
+
+ // Closing the InputStream requires sending EOF.
+ if (disposing && _totalPosition > 0 && _channel?.IsOpen == true)
+ {
+ _channel.SendEof();
+ }
+ }
+
+ base.Dispose(disposing);
+ }
+
+ ///
+ /// 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; }
+ }
+
+ ///
+ /// 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; }
+ }
+
+ ///
+ /// 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; }
+ }
+
+ ///
+ /// 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(); }
+ }
+
+ ///
+ /// 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(); }
+ }
+
+ private ObjectDisposedException CreateObjectDisposedException()
+ {
+ return new ObjectDisposedException(GetType().FullName);
+ }
+ }
+}
diff --git a/src/Renci.SshNet/SshCommand.cs b/src/Renci.SshNet/SshCommand.cs
index a7769ab2c..7aa013ad8 100644
--- a/src/Renci.SshNet/SshCommand.cs
+++ b/src/Renci.SshNet/SshCommand.cs
@@ -31,6 +31,7 @@ public class SshCommand : IDisposable
private StringBuilder _error;
private bool _hasError;
private bool _isDisposed;
+ private ChannelInputStream _inputStream;
///
/// Gets the command text.
@@ -64,6 +65,30 @@ public class SshCommand : IDisposable
public Stream ExtendedOutputStream { get; private set; }
#pragma warning restore CA1859 // Use concrete types when possible for improved performance
+ ///
+ /// Creates and returns the input stream for the command.
+ ///
+ ///
+ /// The stream that can be used to transfer data to the command's input stream.
+ ///
+ #pragma warning disable CA1859 // Use concrete types when possible for improved performance
+ public Stream CreateInputStream()
+#pragma warning restore CA1859 // Use concrete types when possible for improved performance
+ {
+ if (_channel == null)
+ {
+ throw new InvalidOperationException($"The input stream can be used only after calling BeginExecute and before calling EndExecute.");
+ }
+
+ if (_inputStream != null)
+ {
+ throw new InvalidOperationException($"The input stream already exists.");
+ }
+
+ _inputStream = new ChannelInputStream(_channel);
+ return _inputStream;
+ }
+
///
/// Gets the command execution result.
///
@@ -217,7 +242,6 @@ public IAsyncResult BeginExecute(AsyncCallback callback, object state)
AsyncState = state,
};
- // When command re-executed again, create a new channel
if (_channel is not null)
{
throw new SshException("Invalid operation.");
@@ -252,6 +276,7 @@ public IAsyncResult BeginExecute(AsyncCallback callback, object state)
_channel = CreateChannel();
_channel.Open();
+
_ = _channel.SendExecRequest(CommandText);
return _asyncResult;
@@ -301,6 +326,8 @@ public string EndExecute(IAsyncResult asyncResult)
throw new ArgumentException("EndExecute can only be called once for each asynchronous operation.");
}
+ _inputStream?.Close();
+
// wait for operation to complete (or time out)
WaitOnHandle(_asyncResult.AsyncWaitHandle);
@@ -552,6 +579,13 @@ protected virtual void Dispose(bool disposing)
_channel = null;
}
+ var inputStream = _inputStream;
+ if (inputStream != null)
+ {
+ inputStream.Dispose();
+ _inputStream = null;
+ }
+
var outputStream = OutputStream;
if (outputStream != null)
{
diff --git a/test/Renci.SshNet.IntegrationTests/Dockerfile.TestServer b/test/Renci.SshNet.IntegrationTests/Dockerfile.TestServer
index 19ef6e19e..628f1a88c 100644
--- a/test/Renci.SshNet.IntegrationTests/Dockerfile.TestServer
+++ b/test/Renci.SshNet.IntegrationTests/Dockerfile.TestServer
@@ -10,7 +10,8 @@ RUN apk update && apk upgrade --no-cache && \
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/* && \
+ # must not use * for dos2unix parameter otherwise it tries to process folders too and fails
+ dos2unix /etc/ssh/ssh*key && \
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 && \
@@ -28,7 +29,8 @@ RUN apk update && apk upgrade --no-cache && \
adduser -D sshnet && \
passwd -u sshnet && \
echo 'sshnet:ssh4ever' | chpasswd && \
- dos2unix /home/sshnet/.ssh/* && \
+ # must not use * for dos2unix parameter otherwise it tries to process folders too and fails
+ dos2unix /home/sshnet/.ssh/*_key* && \
chown -R sshnet:sshnet /home/sshnet && \
chmod -R 700 /home/sshnet/.ssh && \
chmod -R 644 /home/sshnet/.ssh/authorized_keys && \
diff --git a/test/Renci.SshNet.IntegrationTests/SshClientTests.cs b/test/Renci.SshNet.IntegrationTests/SshClientTests.cs
index b737b343f..2cfeb53c3 100644
--- a/test/Renci.SshNet.IntegrationTests/SshClientTests.cs
+++ b/test/Renci.SshNet.IntegrationTests/SshClientTests.cs
@@ -17,12 +17,99 @@ public SshClientTests()
[TestMethod]
public void Echo_Command_with_all_characters()
{
- var builder = new StringBuilder();
var response = _sshClient.RunCommand("echo $'test !@#$%^&*()_+{}:,./<>[];\\|'");
Assert.AreEqual("test !@#$%^&*()_+{}:,./<>[];\\|\n", response.Result);
}
-
+
+ [TestMethod]
+ public void Send_InputStream_to_Command()
+ {
+ var inputByteArray = Encoding.UTF8.GetBytes("Hello world!");
+
+ // Make the server echo back the input file with "cat"
+ using (var command = _sshClient.CreateCommand("cat"))
+ {
+ var asyncResult = command.BeginExecute();
+
+ using (var inputStream = command.CreateInputStream())
+ {
+ inputStream.Write(inputByteArray, 0, inputByteArray.Length);
+ }
+
+ command.EndExecute(asyncResult);
+
+ Assert.AreEqual("Hello world!", command.Result);
+ Assert.AreEqual(string.Empty, command.Error);
+ }
+ }
+
+ [TestMethod]
+ public void Send_InputStream_to_Command_OneByteAtATime()
+ {
+ var inputByteArray = Encoding.UTF8.GetBytes("Hello world!");
+
+ // Make the server echo back the input file with "cat"
+ using (var command = _sshClient.CreateCommand("cat"))
+ {
+ var asyncResult = command.BeginExecute();
+
+ using (var inputStream = command.CreateInputStream())
+ {
+ for (var i = 0; i < inputByteArray.Length; i++)
+ {
+ inputStream.WriteByte(inputByteArray[i]);
+ }
+ }
+
+ command.EndExecute(asyncResult);
+
+ Assert.AreEqual("Hello world!", command.Result);
+ Assert.AreEqual(string.Empty, command.Error);
+ }
+ }
+
+ [TestMethod]
+ public void Send_InputStream_to_Command_InputStreamNotInUsingBlock_StillWorks()
+ {
+ var inputByteArray = Encoding.UTF8.GetBytes("Hello world!");
+
+ // Make the server echo back the input file with "cat"
+ using (var command = _sshClient.CreateCommand("cat"))
+ {
+ var asyncResult = command.BeginExecute();
+
+ var inputStream = command.CreateInputStream();
+ for (var i = 0; i < inputByteArray.Length; i++)
+ {
+ inputStream.WriteByte(inputByteArray[i]);
+ }
+
+ command.EndExecute(asyncResult);
+
+ Assert.AreEqual("Hello world!", command.Result);
+ Assert.AreEqual(string.Empty, command.Error);
+ }
+ }
+
+ [TestMethod]
+ public void CreateInputStream_BeforeBeginExecute_ThrowsInvalidOperationException()
+ {
+ var command = _sshClient.CreateCommand("ls");
+
+ Assert.ThrowsException(command.CreateInputStream);
+ }
+
+ [TestMethod]
+ public void CreateInputStream_AfterEndExecute_ThrowsInvalidOperationException()
+ {
+ var command = _sshClient.CreateCommand("ls");
+ var asyncResult = command.BeginExecute();
+ command.EndExecute(asyncResult);
+
+ Assert.ThrowsException(command.CreateInputStream);
+ }
+
public void Dispose()
{
_sshClient.Disconnect();
diff --git a/test/Renci.SshNet.TestTools.OpenSSH/SshdConfig.cs b/test/Renci.SshNet.TestTools.OpenSSH/SshdConfig.cs
index 048e1ca77..e5609be7b 100644
--- a/test/Renci.SshNet.TestTools.OpenSSH/SshdConfig.cs
+++ b/test/Renci.SshNet.TestTools.OpenSSH/SshdConfig.cs
@@ -385,6 +385,7 @@ private static void ProcessGlobalOption(SshdConfig sshdConfig, string line)
case "AuthorizedKeysFile":
case "PasswordAuthentication":
case "GatewayPorts":
+ case "Include":
break;
default:
throw new NotSupportedException($"Global option '{name}' is not supported.");