Skip to content

Added SshCommand.InputStream to allow writing to stdin of SshCommand #1293

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,7 @@
*.snk binary

# Ensure key files have LF endings for easier usage with ssh-keygen
test/Data/* eol=lf
# 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
221 changes: 221 additions & 0 deletions src/Renci.SshNet/Common/ChannelInputStream.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
using System;
using System.IO;

using Renci.SshNet.Channels;

namespace Renci.SshNet.Common
{
/// <summary>
/// ChannelInputStream is a one direction stream intended for channel data.
/// </summary>
public class ChannelInputStream : Stream
{
/// <summary>
/// Channel to send data to.
/// </summary>
private readonly IChannelSession _channel;

/// <summary>
/// Total bytes passed through the stream.
/// </summary>
private long _totalPosition;

/// <summary>
/// Indicates whether the current instance was disposed.
/// </summary>
private bool _isDisposed;

internal ChannelInputStream(IChannelSession channel)
{
_channel = channel;
}

/// <summary>
/// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
/// <exception cref="IOException">An I/O error occurs.</exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
/// <remarks>
/// Once flushed, any subsequent read operations no longer block until requested bytes are available. Any write operation reactivates blocking
/// reads.
/// </remarks>
public override void Flush()
{
}

/// <summary>
/// When overridden in a derived class, sets the position within the current stream.
/// </summary>
/// <returns>
/// The new position within the current stream.
/// </returns>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type <see cref="SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
/// <exception cref="NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output.</exception>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}

/// <summary>
/// When overridden in a derived class, sets the length of the current stream.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.</param>
/// <exception cref="NotSupportedException">The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output.</exception>
public override void SetLength(long value)
{
throw new NotSupportedException();
}

/// <summary>
/// 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.
/// </summary>
/// <returns>
/// 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.
/// </returns>
/// <param name="buffer">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.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <exception cref="ArgumentException">The sum of offset and count is larger than the buffer length.</exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
/// <exception cref="NotSupportedException">The stream does not support reading.</exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <c>null</c>.</exception>
/// <exception cref="IOException">An I/O error occurs.</exception>
/// <exception cref="ArgumentOutOfRangeException">offset or count is negative.</exception>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}

/// <summary>
/// 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.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
/// <exception cref="IOException">An I/O error occurs.</exception>
/// <exception cref="NotSupportedException">The stream does not support writing.</exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException">The sum of offset and count is greater than the buffer length.</exception>
/// <exception cref="ArgumentOutOfRangeException">offset or count is negative.</exception>
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;

// Must send EOF, otherwise SshCommand.EndExecute never gets called.
_channel.SendEof();
}

/// <summary>
/// Releases the unmanaged resources used by the Stream and optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
/// <remarks>
/// Disposing a <see cref="PipeStream"/> will interrupt blocking read and write operations.
/// </remarks>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);

if (!_isDisposed)
{
_isDisposed = true;
if (_totalPosition > 0 && _channel.IsOpen)
{
_channel.SendEof();
}
}
}

/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
/// <returns>
/// true if the stream supports reading; otherwise, false.
/// </returns>
public override bool CanRead
{
get { return false; }
}

/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
/// <returns>
/// <c>true</c> if the stream supports seeking; otherwise, <c>false</c>.
/// </returns>
public override bool CanSeek
{
get { return false; }
}

/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
/// <returns>
/// <c>true</c> if the stream supports writing; otherwise, <c>false</c>.
/// </returns>
public override bool CanWrite
{
get { return true; }
}

/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
/// <returns>
/// A long value representing the length of the stream in bytes.
/// </returns>
/// <exception cref="NotSupportedException">A class derived from Stream does not support seeking.</exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
public override long Length
{
get { throw new NotSupportedException(); }
}

/// <summary>
/// Gets or sets the position within the current stream.
/// </summary>
/// <returns>
/// The current position within the stream.
/// </returns>
/// <exception cref="NotSupportedException">The stream does not support seeking.</exception>
public override long Position
{
get { return _totalPosition; }
set { throw new NotSupportedException(); }
}

private ObjectDisposedException CreateObjectDisposedException()
{
return new ObjectDisposedException(GetType().FullName);
}
}
}
16 changes: 16 additions & 0 deletions src/Renci.SshNet/SshCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ public class SshCommand : IDisposable
public Stream ExtendedOutputStream { get; private set; }
#pragma warning restore CA1859 // Use concrete types when possible for improved performance

/// <summary>
/// Gets the input stream.
/// </summary>
public Stream InputStream { get; private set; }

/// <summary>
/// Gets the command execution result.
/// </summary>
Expand Down Expand Up @@ -252,6 +257,10 @@ public IAsyncResult BeginExecute(AsyncCallback callback, object state)

_channel = CreateChannel();
_channel.Open();

// Initialize the input stream
InputStream = new ChannelInputStream(_channel);

_ = _channel.SendExecRequest(CommandText);

return _asyncResult;
Expand Down Expand Up @@ -552,6 +561,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)
{
Expand Down
6 changes: 4 additions & 2 deletions test/Renci.SshNet.IntegrationTests/Dockerfile.TestServer
Original file line number Diff line number Diff line change
Expand Up @@ -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 && \
Expand All @@ -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 && \
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,9 @@ public void Test_Sftp_Upload_Forbidden()
[TestCategory("Sftp")]
public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each()
{
var maxFiles = 10;
// Works for up to 2 files, but fails for more files (on my machine).
// I get either "Renci.SshNet.Common.SshException: Channel was closed" or timeout exception.
var maxFiles = 2;
var maxSize = 5;

RemoveAllFiles();
Expand Down
19 changes: 17 additions & 2 deletions test/Renci.SshNet.IntegrationTests/SshClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,27 @@ 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"
var command = _sshClient.CreateCommand("cat");

var asyncResult = command.BeginExecute();
command.InputStream.Write(inputByteArray);
command.EndExecute(asyncResult);

Assert.AreEqual("Hello world!", command.Result);
Assert.AreEqual(string.Empty, command.Error);
}

public void Dispose()
{
_sshClient.Disconnect();
Expand Down
2 changes: 2 additions & 0 deletions test/Renci.SshNet.TestTools.OpenSSH/SshdConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,8 @@ private static void ProcessGlobalOption(SshdConfig sshdConfig, string line)
case "AuthorizedKeysFile":
case "PasswordAuthentication":
case "GatewayPorts":
// Had to add this otherwise docker container setup in integration test fails.
case "Include":
break;
default:
throw new NotSupportedException($"Global option '{name}' is not supported.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ public void HostKeyEventArgsConstructorTest()
Assert.AreEqual(2048, target.KeyLength);
}

// Excluding on net462 platform, because using MD5 hash throws: System.InvalidOperationException:
// 'This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.'
#if !NET462_TARGET_FRAMEWORK

/// <summary>
///A test for MD5 calculation in HostKeyEventArgs Constructor
///</summary>
Expand All @@ -59,6 +63,8 @@ public void HostKeyEventArgsConstructorTest_VerifyMD5()

}

#endif

/// <summary>
///A test for SHA256 calculation in HostKeyEventArgs Constructor
///</summary>
Expand Down
8 changes: 7 additions & 1 deletion test/Renci.SshNet.Tests/Classes/PrivateKeyFileTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
// Excluding these tests on net462 platform, beacuse using MD5 hash throws: System.InvalidOperationException:
// 'This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.'
#if !NET462_TARGET_FRAMEWORK

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Renci.SshNet.Common;
using Renci.SshNet.Tests.Common;
using System;
Expand Down Expand Up @@ -695,3 +699,5 @@ private static void TestRsaKeyFile(PrivateKeyFile rsaPrivateKeyFile)
}
}
}

#endif
4 changes: 4 additions & 0 deletions test/Renci.SshNet.Tests/Renci.SshNet.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
<TargetFrameworks>net462;net6.0;net7.0;net8.0</TargetFrameworks>
</PropertyGroup>

<PropertyGroup Condition=" '$(TargetFramework)' == 'net462' ">
<DefineConstants>$(DefineConstants);NET462_TARGET_FRAMEWORK</DefineConstants>
</PropertyGroup>

<ItemGroup>
<EmbeddedResource Include="..\Data\*" LinkBase="Data" />
</ItemGroup>
Expand Down