Skip to content

Commit 2d0e03b

Browse files
realvizuferenc.vizkeletiWojciechNagorskiRob-Hague
authored
Added SshCommand.InputStream to allow writing to stdin of SshCommand (#1293)
* Making all unit tests pass locally. Excluded MD5 tests on net462 because I get System.InvalidOperationException: 'This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.' SshdConfig: do not throw for "Include", just do nothing. Modified failing dos2unix parameters in Dockerfile.TestServer. Forceing LF line ending for key files used by integration tests, otherwise using them causes error. SftpClientTest.Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each times out for maxFiles=10, decreasing to 2 to make the test pass. * Added SshCommand.InputStream. * Added an integration test for SshCommand.InputStream. * Reverting changes made to unit tests unrelated to this PR. * Moved ChannelInputStream's EOF sending from Write to Dispose. Replace SshCommand.InputStream with CreateInputStream to emphasise that a (disposable) resource is created here. EndExecute also closes the _inputStream to make sure that EOF is sent (in case the user forgot to dispose the input stream). Added more unit tests: sending the input one byte at a time, not disposing the input stream, calling CreateInputStream before BeginExecute or AfterEndExecute throws exception. * Fixing review comments. * Fix build error after #1286 --------- Co-authored-by: ferenc.vizkeleti <[email protected]> Co-authored-by: Wojciech Nagórski <[email protected]> Co-authored-by: Rob Hague <[email protected]>
1 parent bfe6718 commit 2d0e03b

File tree

6 files changed

+350
-6
lines changed

6 files changed

+350
-6
lines changed

.gitattributes

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,7 @@
1717
*.snk binary
1818

1919
# Ensure key files have LF endings for easier usage with ssh-keygen
20-
test/Data/* eol=lf
20+
# Also, the dockerfile used for integration tests fails if key files have cr-lf
21+
test/Data/* eol=lf
22+
test/Renci.SshNet.IntegrationTests/server/**/* eol=lf
23+
test/Renci.SshNet.IntegrationTests/user/* eol=lf
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
using System;
2+
using System.IO;
3+
4+
using Renci.SshNet.Channels;
5+
6+
namespace Renci.SshNet.Common
7+
{
8+
/// <summary>
9+
/// ChannelInputStream is a one direction stream intended for channel data.
10+
/// </summary>
11+
internal sealed class ChannelInputStream : Stream
12+
{
13+
/// <summary>
14+
/// Channel to send data to.
15+
/// </summary>
16+
private readonly IChannelSession _channel;
17+
18+
/// <summary>
19+
/// Total bytes passed through the stream.
20+
/// </summary>
21+
private long _totalPosition;
22+
23+
/// <summary>
24+
/// Indicates whether the current instance was disposed.
25+
/// </summary>
26+
private bool _isDisposed;
27+
28+
internal ChannelInputStream(IChannelSession channel)
29+
{
30+
_channel = channel;
31+
}
32+
33+
/// <summary>
34+
/// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
35+
/// </summary>
36+
/// <exception cref="IOException">An I/O error occurs.</exception>
37+
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
38+
/// <remarks>
39+
/// Once flushed, any subsequent read operations no longer block until requested bytes are available. Any write operation reactivates blocking
40+
/// reads.
41+
/// </remarks>
42+
public override void Flush()
43+
{
44+
}
45+
46+
/// <summary>
47+
/// When overridden in a derived class, sets the position within the current stream.
48+
/// </summary>
49+
/// <returns>
50+
/// The new position within the current stream.
51+
/// </returns>
52+
/// <param name="offset">A byte offset relative to the origin parameter.</param>
53+
/// <param name="origin">A value of type <see cref="SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
54+
/// <exception cref="NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output.</exception>
55+
public override long Seek(long offset, SeekOrigin origin)
56+
{
57+
throw new NotSupportedException();
58+
}
59+
60+
/// <summary>
61+
/// When overridden in a derived class, sets the length of the current stream.
62+
/// </summary>
63+
/// <param name="value">The desired length of the current stream in bytes.</param>
64+
/// <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>
65+
public override void SetLength(long value)
66+
{
67+
throw new NotSupportedException();
68+
}
69+
70+
/// <summary>
71+
/// 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.
72+
/// </summary>
73+
/// <returns>
74+
/// 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.
75+
/// </returns>
76+
/// <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>
77+
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
78+
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
79+
/// <exception cref="ArgumentException">The sum of offset and count is larger than the buffer length.</exception>
80+
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
81+
/// <exception cref="NotSupportedException">The stream does not support reading.</exception>
82+
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <c>null</c>.</exception>
83+
/// <exception cref="IOException">An I/O error occurs.</exception>
84+
/// <exception cref="ArgumentOutOfRangeException">offset or count is negative.</exception>
85+
public override int Read(byte[] buffer, int offset, int count)
86+
{
87+
throw new NotSupportedException();
88+
}
89+
90+
/// <summary>
91+
/// 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.
92+
/// </summary>
93+
/// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param>
94+
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
95+
/// <param name="count">The number of bytes to be written to the current stream.</param>
96+
/// <exception cref="IOException">An I/O error occurs.</exception>
97+
/// <exception cref="NotSupportedException">The stream does not support writing.</exception>
98+
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
99+
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <c>null</c>.</exception>
100+
/// <exception cref="ArgumentException">The sum of offset and count is greater than the buffer length.</exception>
101+
/// <exception cref="ArgumentOutOfRangeException">offset or count is negative.</exception>
102+
public override void Write(byte[] buffer, int offset, int count)
103+
{
104+
if (buffer == null)
105+
{
106+
throw new ArgumentNullException(nameof(buffer));
107+
}
108+
109+
if (offset + count > buffer.Length)
110+
{
111+
throw new ArgumentException("The sum of offset and count is greater than the buffer length.");
112+
}
113+
114+
if (offset < 0 || count < 0)
115+
{
116+
throw new ArgumentOutOfRangeException(nameof(offset), "offset or count is negative.");
117+
}
118+
119+
if (_isDisposed)
120+
{
121+
throw CreateObjectDisposedException();
122+
}
123+
124+
if (count == 0)
125+
{
126+
return;
127+
}
128+
129+
_channel.SendData(buffer, offset, count);
130+
_totalPosition += count;
131+
}
132+
133+
/// <summary>
134+
/// Releases the unmanaged resources used by the Stream and optionally releases the managed resources.
135+
/// </summary>
136+
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
137+
protected override void Dispose(bool disposing)
138+
{
139+
if (!_isDisposed)
140+
{
141+
_isDisposed = true;
142+
143+
// Closing the InputStream requires sending EOF.
144+
if (disposing && _totalPosition > 0 && _channel?.IsOpen == true)
145+
{
146+
_channel.SendEof();
147+
}
148+
}
149+
150+
base.Dispose(disposing);
151+
}
152+
153+
/// <summary>
154+
/// Gets a value indicating whether the current stream supports reading.
155+
/// </summary>
156+
/// <returns>
157+
/// true if the stream supports reading; otherwise, false.
158+
/// </returns>
159+
public override bool CanRead
160+
{
161+
get { return false; }
162+
}
163+
164+
/// <summary>
165+
/// Gets a value indicating whether the current stream supports seeking.
166+
/// </summary>
167+
/// <returns>
168+
/// <c>true</c> if the stream supports seeking; otherwise, <c>false</c>.
169+
/// </returns>
170+
public override bool CanSeek
171+
{
172+
get { return false; }
173+
}
174+
175+
/// <summary>
176+
/// Gets a value indicating whether the current stream supports writing.
177+
/// </summary>
178+
/// <returns>
179+
/// <c>true</c> if the stream supports writing; otherwise, <c>false</c>.
180+
/// </returns>
181+
public override bool CanWrite
182+
{
183+
get { return true; }
184+
}
185+
186+
/// <summary>
187+
/// Gets the length in bytes of the stream.
188+
/// </summary>
189+
/// <returns>
190+
/// A long value representing the length of the stream in bytes.
191+
/// </returns>
192+
/// <exception cref="NotSupportedException">A class derived from Stream does not support seeking.</exception>
193+
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
194+
public override long Length
195+
{
196+
get { throw new NotSupportedException(); }
197+
}
198+
199+
/// <summary>
200+
/// Gets or sets the position within the current stream.
201+
/// </summary>
202+
/// <returns>
203+
/// The current position within the stream.
204+
/// </returns>
205+
/// <exception cref="NotSupportedException">The stream does not support seeking.</exception>
206+
public override long Position
207+
{
208+
get { return _totalPosition; }
209+
set { throw new NotSupportedException(); }
210+
}
211+
212+
private ObjectDisposedException CreateObjectDisposedException()
213+
{
214+
return new ObjectDisposedException(GetType().FullName);
215+
}
216+
}
217+
}

src/Renci.SshNet/SshCommand.cs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ public class SshCommand : IDisposable
3131
private StringBuilder _error;
3232
private bool _hasError;
3333
private bool _isDisposed;
34+
private ChannelInputStream _inputStream;
3435

3536
/// <summary>
3637
/// Gets the command text.
@@ -64,6 +65,30 @@ public class SshCommand : IDisposable
6465
public Stream ExtendedOutputStream { get; private set; }
6566
#pragma warning restore CA1859 // Use concrete types when possible for improved performance
6667

68+
/// <summary>
69+
/// Creates and returns the input stream for the command.
70+
/// </summary>
71+
/// <returns>
72+
/// The stream that can be used to transfer data to the command's input stream.
73+
/// </returns>
74+
#pragma warning disable CA1859 // Use concrete types when possible for improved performance
75+
public Stream CreateInputStream()
76+
#pragma warning restore CA1859 // Use concrete types when possible for improved performance
77+
{
78+
if (_channel == null)
79+
{
80+
throw new InvalidOperationException($"The input stream can be used only after calling BeginExecute and before calling EndExecute.");
81+
}
82+
83+
if (_inputStream != null)
84+
{
85+
throw new InvalidOperationException($"The input stream already exists.");
86+
}
87+
88+
_inputStream = new ChannelInputStream(_channel);
89+
return _inputStream;
90+
}
91+
6792
/// <summary>
6893
/// Gets the command execution result.
6994
/// </summary>
@@ -217,7 +242,6 @@ public IAsyncResult BeginExecute(AsyncCallback callback, object state)
217242
AsyncState = state,
218243
};
219244

220-
// When command re-executed again, create a new channel
221245
if (_channel is not null)
222246
{
223247
throw new SshException("Invalid operation.");
@@ -252,6 +276,7 @@ public IAsyncResult BeginExecute(AsyncCallback callback, object state)
252276

253277
_channel = CreateChannel();
254278
_channel.Open();
279+
255280
_ = _channel.SendExecRequest(CommandText);
256281

257282
return _asyncResult;
@@ -301,6 +326,8 @@ public string EndExecute(IAsyncResult asyncResult)
301326
throw new ArgumentException("EndExecute can only be called once for each asynchronous operation.");
302327
}
303328

329+
_inputStream?.Close();
330+
304331
// wait for operation to complete (or time out)
305332
WaitOnHandle(_asyncResult.AsyncWaitHandle);
306333

@@ -552,6 +579,13 @@ protected virtual void Dispose(bool disposing)
552579
_channel = null;
553580
}
554581

582+
var inputStream = _inputStream;
583+
if (inputStream != null)
584+
{
585+
inputStream.Dispose();
586+
_inputStream = null;
587+
}
588+
555589
var outputStream = OutputStream;
556590
if (outputStream != null)
557591
{

test/Renci.SshNet.IntegrationTests/Dockerfile.TestServer

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ RUN apk update && apk upgrade --no-cache && \
1010
apk add --no-cache openssh && \
1111
# install openssh-server-pam to allow for keyboard-interactive authentication
1212
apk add --no-cache openssh-server-pam && \
13-
dos2unix /etc/ssh/* && \
13+
# must not use * for dos2unix parameter otherwise it tries to process folders too and fails
14+
dos2unix /etc/ssh/ssh*key && \
1415
chmod 400 /etc/ssh/ssh*key && \
1516
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config && \
1617
sed -i 's/#LogLevel\s*INFO/LogLevel DEBUG3/' /etc/ssh/sshd_config && \
@@ -28,7 +29,8 @@ RUN apk update && apk upgrade --no-cache && \
2829
adduser -D sshnet && \
2930
passwd -u sshnet && \
3031
echo 'sshnet:ssh4ever' | chpasswd && \
31-
dos2unix /home/sshnet/.ssh/* && \
32+
# must not use * for dos2unix parameter otherwise it tries to process folders too and fails
33+
dos2unix /home/sshnet/.ssh/*_key* && \
3234
chown -R sshnet:sshnet /home/sshnet && \
3335
chmod -R 700 /home/sshnet/.ssh && \
3436
chmod -R 644 /home/sshnet/.ssh/authorized_keys && \

0 commit comments

Comments
 (0)