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.RegularExpressions; using Renci.SshNet.Abstractions; namespace Renci.SshNet { /// /// Contains operation for working with SSH Shell. /// public class ShellStream : Stream { private const string CrLf = "\r\n"; private const int BufferSize = 1024; private readonly ISession _session; private readonly Encoding _encoding; private readonly Queue _incoming; private readonly Queue _outgoing; private IChannelSession _channel; private AutoResetEvent _dataReceived = new AutoResetEvent(false); private bool _isDisposed; /// /// Occurs when data was received. /// public event EventHandler DataReceived; /// /// Occurs when an error occurred. /// public event EventHandler ErrorOccurred; /// /// Gets a value that indicates whether data is available on the to be read. /// /// /// true if data is available to be read; otherwise, false. /// public bool DataAvailable { get { lock (_incoming) { return _incoming.Count > 0; } } } internal ShellStream(ISession session, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary terminalModeValues) { _encoding = session.ConnectionInfo.Encoding; _session = session; _incoming = new Queue(); _outgoing = new Queue(); _channel = _session.CreateChannelSession(); _channel.DataReceived += Channel_DataReceived; _channel.Closed += Channel_Closed; _session.Disconnected += Session_Disconnected; _session.ErrorOccured += Session_ErrorOccured; _channel.Open(); _channel.SendPseudoTerminalRequest(terminalName, columns, rows, width, height, terminalModeValues); _channel.SendShellRequest(); } #region Stream overide methods /// /// Gets a value indicating whether the current stream supports reading. /// /// /// true if the stream supports reading; otherwise, false. /// public override bool CanRead { get { return true; } } /// /// 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; } } /// /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// /// An I/O error occurs. public override void Flush() { if (_channel == null) { throw new ObjectDisposedException("ShellStream"); } _channel.SendData(_outgoing.ToArray()); _outgoing.Clear(); } /// /// 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 { lock (_incoming) { return _incoming.Count; } } } /// /// Gets or sets the position within the current stream. /// /// /// 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. 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. /// /// 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. public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// /// 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. 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) { _outgoing.Enqueue(b); continue; } Flush(); } } #endregion /// /// Expects the specified expression and performs action when one is found. /// /// The expected expressions and actions to perform. public void Expect(params ExpectAction[] expectActions) { Expect(TimeSpan.Zero, expectActions); } /// /// Expects the specified expression and performs action when one is found. /// /// Time to wait for input. /// The expected expressions and actions to perform, if the specified time elapsed and expected condition have not met, that method will exit without executing any action. public void Expect(TimeSpan timeout, params ExpectAction[] expectActions) { var expectedFound = false; var text = string.Empty; do { lock (_incoming) { if (_incoming.Count > 0) { text = _encoding.GetString(_incoming.ToArray(), 0, _incoming.Count); } if (text.Length > 0) { foreach (var expectAction in expectActions) { var match = expectAction.Expect.Match(text); if (match.Success) { var result = text.Substring(0, match.Index + match.Length); for (var i = 0; i < match.Index + match.Length && _incoming.Count > 0; i++) { // Remove processed items from the queue _incoming.Dequeue(); } expectAction.Action(result); expectedFound = true; } } } } if (!expectedFound) { if (timeout.Ticks > 0) { if (!_dataReceived.WaitOne(timeout)) { return; } } else { _dataReceived.WaitOne(); } } } while (!expectedFound); } /// /// Begins the expect. /// /// The expect actions. /// /// An that references the asynchronous operation. /// public IAsyncResult BeginExpect(params ExpectAction[] expectActions) { return BeginExpect(TimeSpan.Zero, null, null, expectActions); } /// /// Begins the expect. /// /// The callback. /// The expect actions. /// /// An that references the asynchronous operation. /// public IAsyncResult BeginExpect(AsyncCallback callback, params ExpectAction[] expectActions) { return BeginExpect(TimeSpan.Zero, callback, null, expectActions); } /// /// Begins the expect. /// /// The callback. /// The state. /// The expect actions. /// /// An that references the asynchronous operation. /// public IAsyncResult BeginExpect(AsyncCallback callback, object state, params ExpectAction[] expectActions) { return BeginExpect(TimeSpan.Zero, callback, state, expectActions); } /// /// Begins the expect. /// /// The timeout. /// The callback. /// The state. /// The expect actions. /// /// An that references the asynchronous operation. /// public IAsyncResult BeginExpect(TimeSpan timeout, AsyncCallback callback, object state, params ExpectAction[] expectActions) { var text = string.Empty; // Create new AsyncResult object var asyncResult = new ExpectAsyncResult(callback, state); // 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); } if (text.Length > 0) { foreach (var expectAction in expectActions) { var match = expectAction.Expect.Match(text); if (match.Success) { var result = text.Substring(0, match.Index + match.Length); for (var i = 0; i < match.Index + match.Length && _incoming.Count > 0; i++) { // Remove processed items from the queue _incoming.Dequeue(); } expectAction.Action(result); if (callback != null) { callback(asyncResult); } expectActionResult = result; } } } } if (expectActionResult != null) break; if (timeout.Ticks > 0) { if (!_dataReceived.WaitOne(timeout)) { if (callback != null) { callback(asyncResult); } break; } } else { _dataReceived.WaitOne(); } } while (true); asyncResult.SetAsCompleted(expectActionResult, true); } catch (Exception exp) { asyncResult.SetAsCompleted(exp, true); } }); return asyncResult; } /// /// 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) { 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; } /// /// Reads the line from the shell. If line is not available it will block the execution and will wait for new line. /// /// /// The line read from the shell. /// public string ReadLine() { return ReadLine(TimeSpan.Zero); } /// /// Reads a line from the shell. If line is not available it will block the execution and will wait for new line. /// /// Time to wait for input. /// /// The line read from the shell, or null when no input is received for the specified timeout. /// public string ReadLine(TimeSpan timeout) { var text = string.Empty; while (true) { lock (_incoming) { if (_incoming.Count > 0) { text = _encoding.GetString(_incoming.ToArray(), 0, _incoming.Count); } var index = text.IndexOf(CrLf, StringComparison.Ordinal); if (index >= 0) { text = text.Substring(0, index); // determine how many bytes to remove from buffer var bytesProcessed = _encoding.GetByteCount(text + CrLf); // remove processed bytes from the queue for (var i = 0; i < bytesProcessed; i++) _incoming.Dequeue(); break; } } if (timeout.Ticks > 0) { if (!_dataReceived.WaitOne(timeout)) { return null; } } else { _dataReceived.WaitOne(); } } return text; } /// /// Reads text available in the shell. /// /// /// The text available in the shell. /// public string Read() { string text; lock (_incoming) { text = _encoding.GetString(_incoming.ToArray(), 0, _incoming.Count); _incoming.Clear(); } return text; } /// /// Writes the specified text to the shell. /// /// The text to be written to the shell. /// /// If is null, nothing is written. /// public void Write(string text) { if (text == null) return; if (_channel == null) { throw new ObjectDisposedException("ShellStream"); } var data = _encoding.GetBytes(text); _channel.SendData(data); } /// /// Writes the line to the shell. /// /// The line to be written to the shell. /// /// If is null, only the line terminator is written. /// public void WriteLine(string line) { Write(line + "\r"); } /// /// 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 override void Dispose(bool disposing) { base.Dispose(disposing); if (_isDisposed) return; if (disposing) { UnsubscribeFromSessionEvents(_session); if (_channel != null) { _channel.DataReceived -= Channel_DataReceived; _channel.Closed -= Channel_Closed; _channel.Dispose(); _channel = null; } if (_dataReceived != null) { _dataReceived.Dispose(); _dataReceived = null; } _isDisposed = true; } else { UnsubscribeFromSessionEvents(_session); } } /// /// Unsubscribes the current from session events. /// /// The session. /// /// Does nothing when is null. /// private void UnsubscribeFromSessionEvents(ISession session) { if (session == null) return; session.Disconnected -= Session_Disconnected; session.ErrorOccured -= Session_ErrorOccured; } private void Session_ErrorOccured(object sender, ExceptionEventArgs e) { OnRaiseError(e); } private void Session_Disconnected(object sender, EventArgs e) { if (_channel != null) _channel.Dispose(); } private void Channel_Closed(object sender, ChannelEventArgs e) { // TODO: Do we need to call dispose here ?? Dispose(); } private void Channel_DataReceived(object sender, ChannelDataEventArgs e) { lock (_incoming) { foreach (var b in e.Data) _incoming.Enqueue(b); } if (_dataReceived != null) _dataReceived.Set(); OnDataReceived(e.Data); } private void OnRaiseError(ExceptionEventArgs e) { var handler = ErrorOccurred; if (handler != null) { handler(this, e); } } private void OnDataReceived(byte[] data) { var handler = DataReceived; if (handler != null) { handler(this, new ShellDataEventArgs(data)); } } } }