瀏覽代碼

Changed a bunch of things around, seems to function as intended.
Need to (re)add support for enforcing a buffer limit and perahps a line timeout.

GiantJunkBox_cp 13 年之前
父節點
當前提交
6b3e11b24b
共有 1 個文件被更改,包括 302 次插入274 次删除
  1. 302 274
      Renci.SshClient/Renci.SshNet/ShellStream.cs

+ 302 - 274
Renci.SshClient/Renci.SshNet/ShellStream.cs

@@ -6,379 +6,407 @@ using System.IO;
 using Renci.SshNet.Channels;
 using Renci.SshNet.Common;
 using System.Threading;
+using System.Text.RegularExpressions;
 
 namespace Renci.SshNet
 {
+    public enum LineMatchModes
+    {
+        Everything,
+        Compleated,
+        Partial,
+    }
+
     public class ShellStream : Stream
     {
-        private readonly Session _session;
+        int _maxLines = 0;
+
+        List<string> _compleatedLines;
+        StringBuilder _currentLine;
+
+        Regex[] _patternMatchers = null;
+        LineMatchModes _lineMatchMode;
+        int _patternMatcherIndex;
+        string _patternCaptureBuffer;
 
+        private readonly Session _session;
         private ChannelSession _channel;
 
-        private Queue<byte> _incoming;
+        public delegate void DataReceivedHandler(byte[] data);
+        public event DataReceivedHandler DataReceived;
 
-        private Queue<byte> _outgoing;
+        public delegate void LineReadHandler(string Line);
+        public event LineReadHandler LineRead;
 
-        private int _bufferSize;
+        public event EventHandler<ExceptionEventArgs> ErrorOccurred;
 
-        private EventWaitHandle _expectedTextWaitHandle = new AutoResetEvent(false);
+        internal ShellStream(Session session, string terminalName, uint columns, uint rows, uint width, uint height, int maxLines, params KeyValuePair<TerminalModes, uint>[] terminalModeValues)
+        {
+            this._session = session;
 
-        private string _expectedText;
+            _compleatedLines = new List<string>();
+            _currentLine = new StringBuilder();
 
-        private int _expectedIndex;
+            this._channel = this._session.CreateChannel<ChannelSession>();
+            this._channel.DataReceived += new EventHandler<ChannelDataEventArgs>(_channel_DataReceived);
+            this._channel.Closed += new EventHandler<ChannelEventArgs>(_channel_Closed);
+            this._session.Disconnected += new EventHandler<EventArgs>(_session_Disconnected);
+            this._session.ErrorOccured += new EventHandler<ExceptionEventArgs>(_session_ErrorOccured);
 
-        private StringBuilder _expectedBuffer;
+            this._channel.Open();
+            this._channel.SendPseudoTerminalRequest(terminalName, columns, rows, width, height, terminalModeValues);
+            this._channel.SendShellRequest();
+        }
 
-        /// <summary>
-        /// Occurs when an error occurred.
-        /// </summary>
-        public event EventHandler<ExceptionEventArgs> ErrorOccurred;
+        void _session_ErrorOccured(object sender, ExceptionEventArgs e)
+        {
+            this.OnRaiseError(e);
+        }
 
-        /// <summary>
-        /// Gets a value that indicates whether data is available on the <see cref="ShellStream"/> to be read.
-        /// </summary>
-        /// <value>
-        ///   <c>true</c> if can be read; otherwise, <c>false</c>.
-        /// </value>
-        public bool DataAvailable
+        void _session_Disconnected(object sender, EventArgs e)
         {
-            get
+            //  If channel is open then close it to cause Channel_Closed method to be called
+            if (this._channel != null && this._channel.IsOpen)
             {
-                lock (this._incoming)
-                {
-                    //Monitor.Wait(this._incoming);
-                    var result = this._incoming.Count > 0;
-                    //Monitor.Pulse(this._incoming);
-                    return result;
-                }
+                this._channel.SendEof();
+
+                this._channel.Close();
             }
         }
 
-        public EventWaitHandle DataAvailableWaitHandle { get; private set; }
+        void _channel_Closed(object sender, ChannelEventArgs e)
+        {
+            this.Dispose();
+        }
 
-        /// <summary>
-        /// Initializes a new instance of the <see cref="ShellStream"/> class.
-        /// </summary>
-        /// <param name="session">The session.</param>
-        /// <param name="terminalName">Name of the terminal.</param>
-        /// <param name="columns">The columns.</param>
-        /// <param name="rows">The rows.</param>
-        /// <param name="width">The width.</param>
-        /// <param name="height">The height.</param>
-        /// <param name="bufferSize">Size of the buffer.</param>
-        /// <param name="terminalModeValues">The terminal mode values.</param>
-        internal ShellStream(Session session, string terminalName, uint columns, uint rows, uint width, uint height, int bufferSize, params KeyValuePair<TerminalModes, uint>[] terminalModeValues)
+        void _channel_DataReceived(object sender, ChannelDataEventArgs e)
         {
-            this._session = session;
+            lock (this._compleatedLines)
+            {
+                OnDataReceived(e.Data);
 
-            this._incoming = new Queue<byte>(bufferSize);
-            this._outgoing = new Queue<byte>(bufferSize);
+                int startingBufferCount = this._compleatedLines.Count();
 
-            this.DataAvailableWaitHandle = new AutoResetEvent(false);
+                for (int bufferOffset = 0; bufferOffset < e.Data.Length; bufferOffset++)
+                {
+                    // we got a line terminator, save the last line to the line queue
+                    if (e.Data[bufferOffset] == '\n')
+                    {
+                        // Check if there was a \r preceading the \n and remove it
+                        if (this._currentLine.Length > 0 && _currentLine[_currentLine.Length - 1] == '\r')
+                            this._currentLine.Remove(_currentLine.Length - 1, 1);
 
-            this._bufferSize = bufferSize;
+                        // move the current line to the end of the line buffer
+                        string lineBuffer = _currentLine.ToString();
+                        this._compleatedLines.Add(lineBuffer);
+                        this._currentLine.Clear();
 
-            this._channel = this._session.CreateChannel<ChannelSession>();
-            this._channel.DataReceived += Channel_DataReceived;
-            this._channel.Closed += Channel_Closed;
-            this._session.Disconnected += Session_Disconnected;
-            this._session.ErrorOccured += Session_ErrorOccured;
+                        // raise a OnLineRead event
+                        OnLineRead(lineBuffer);
+                    }
+                    else
+                    {
+                        // Everything else, add it to the current line
+                        this._currentLine.Append((char)e.Data[bufferOffset]);
+                    }
+                }
+
+                // If there are any pattern matchers defined, from an existing call to ReadLines, check to see if any of the new lines match it
+                if (this._patternMatchers != null)
+                {
+                    string results = ExtractCaptureBuffer(this._compleatedLines, this._patternMatchers, out this._patternMatcherIndex, _currentLine, this._lineMatchMode, startingBufferCount);
+                    if (results != null)
+                    {
+                        this._patternCaptureBuffer = results;
+                        // Signal ReadLines to continue
+                        Monitor.Pulse(this._compleatedLines);
+                    }
+                }
+            }
 
-            this._channel.Open();
-            this._channel.SendPseudoTerminalRequest(terminalName, columns, rows, width, height, terminalModeValues);
-            this._channel.SendShellRequest();
         }
 
-        public void Expect(string expected, TimeSpan timeout)
+        private void OnRaiseError(ExceptionEventArgs e)
         {
-            this._expectedText = expected;
-            this._expectedIndex = 0;
-
-            this._expectedTextWaitHandle.WaitOne(timeout);
-
-            this._expectedText = null;
+            if (this.ErrorOccurred != null)
+                this.ErrorOccurred(this, e);
         }
 
-        #region Stream overide methods
+        #region Not Implemented Stream Methods
 
-        /// <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
+        public override long Seek(long offset, SeekOrigin origin)
         {
-            get { return true; }
+            throw new NotImplementedException();
         }
 
-        /// <summary>
-        /// Gets a value indicating whether the current stream supports seeking.
-        /// </summary>
-        /// <returns>true if the stream supports seeking; otherwise, false.</returns>
-        public override bool CanSeek
+        public override void SetLength(long value)
         {
-            get { return false; }
+            throw new NotImplementedException();
         }
 
-        /// <summary>
-        /// Gets a value indicating whether the current stream supports writing.
-        /// </summary>
-        /// <returns>true if the stream supports writing; otherwise, false.</returns>
-        public override bool CanWrite
+        public override void Flush()
         {
-            get { return true; }
+            throw new NotImplementedException();
         }
 
-        /// <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="T:System.NotSupportedException">A class derived from Stream does not support seeking. </exception>
-        ///   
-        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
         public override long Length
         {
-            get { return this._incoming.Count; }
+            get { throw new NotImplementedException(); }
         }
 
-        /// <summary>
-        /// Gets or sets the position within the current stream.
-        /// </summary>
-        /// <returns>The current position within the stream.</returns>
-        ///   
-        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
-        ///   
-        /// <exception cref="T:System.NotSupportedException">The stream does not support seeking. </exception>
-        ///   
-        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
         public override long Position
         {
-            get { return 0; }
-            set { throw new NotSupportedException(); }
-        }
-
-        /// <summary>
-        /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
-        /// </summary>
-        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param>
-        /// <param name="offset">The zero-based byte offset in <paramref name="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>
-        /// <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 (0) if the end of the stream has been reached.
-        /// </returns>
-        /// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length. </exception>
-        ///   
-        /// <exception cref="T:System.ArgumentNullException">
-        ///   <paramref name="buffer"/> is null. </exception>
-        ///   
-        /// <exception cref="T:System.ArgumentOutOfRangeException">
-        ///   <paramref name="offset"/> or <paramref name="count"/> is negative. </exception>
-        ///   
-        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
-        ///   
-        /// <exception cref="T:System.NotSupportedException">The stream does not support reading. </exception>
-        ///   
-        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
+            get
+            {
+                throw new NotImplementedException();
+            }
+            set
+            {
+                throw new NotImplementedException();
+            }
+        }
+
         public override int Read(byte[] buffer, int offset, int count)
         {
-            var read = 0;
-
-            if (this._incoming.Count > 0)
-            {
-                lock (this._incoming)
-                {
-                    while (this._incoming.Count < 1)
-                        Monitor.Wait(this._incoming);
+            throw new NotImplementedException();
+        }
 
-                    for (read = 0; read < count && this._incoming.Count > 0; read++)
-                    {
-                        buffer[offset + read] = this._incoming.Dequeue();
-                    }
+        #endregion
 
-                    Monitor.Pulse(this._incoming);
-                }
-            }
-            return read;
-        }
-
-        /// <summary>
-        /// Sets the position within the current stream.
-        /// </summary>
-        /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param>
-        /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
-        /// <returns>
-        /// The new position within the current stream.
-        /// </returns>
-        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
-        ///   
-        /// <exception cref="T:System.NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception>
-        ///   
-        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
-        public override long Seek(long offset, SeekOrigin origin)
+        #region Generic overridden Stream methods
+        public override bool CanRead
         {
-            throw new NotSupportedException();
+            get
+            {
+                return (false);
+            }
         }
 
-        /// <summary>
-        /// Sets the length of the current stream.
-        /// </summary>
-        /// <param name="value">The desired length of the current stream in bytes.</param>
-        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
-        ///   
-        /// <exception cref="T:System.NotSupportedException">The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. </exception>
-        ///   
-        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
-        public override void SetLength(long value)
+        public override bool CanSeek
         {
-            throw new NotSupportedException();
-        }
-
-        /// <summary>
-        /// 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 <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param>
-        /// <param name="offset">The zero-based byte offset in <paramref name="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="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is greater than the buffer length. </exception>
-        ///   
-        /// <exception cref="T:System.ArgumentNullException">
-        ///   <paramref name="buffer"/> is null. </exception>
-        ///   
-        /// <exception cref="T:System.ArgumentOutOfRangeException">
-        ///   <paramref name="offset"/> or <paramref name="count"/> is negative. </exception>
-        ///   
-        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
-        ///   
-        /// <exception cref="T:System.NotSupportedException">The stream does not support writing. </exception>
-        ///   
-        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
-        public override void Write(byte[] buffer, int offset, int count)
+            get
+            {
+                return (false);
+            }
+        }
+
+        public override bool CanWrite
         {
-            for (int i = 0; i < count; i++)
+            get
             {
-                this._outgoing.Enqueue(buffer[offset + i]);
-                if (this._outgoing.Count >= this._bufferSize)
-                {
-                    this.Flush();
-                }
+                return (true);
             }
         }
 
-        /// <summary>
-        /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
-        /// </summary>
-        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
-        public override void Flush()
+        public override void Write(byte[] buffer, int offset, int count)
         {
-            if (this._outgoing.Count > 0)
+            if (offset != 0 && count != buffer.Length)
             {
-                this._channel.SendData(this._outgoing.ToArray());
-                this._outgoing.Clear();
+                byte[] constrainedBuffer = new byte[count - offset];
+
+                Array.Copy(buffer, offset, constrainedBuffer, 0, count - offset);
+
+                this._channel.SendData(constrainedBuffer);
             }
+            else
+                this._channel.SendData(buffer);
         }
 
-        /// <summary>
-        /// Releases the unmanaged resources used by the <see cref="T:System.IO.Stream"/> and optionally releases the managed resources.
-        /// </summary>
-        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
-        protected override void Dispose(bool disposing)
+        #endregion
+
+        public void Write(string line)
         {
-            base.Dispose(disposing);
+            byte[] dataToSend = Encoding.ASCII.GetBytes(line);
 
-            if (this._channel != null)
-            {
-                if (this._channel.IsOpen)
-                {
-                    this._channel.SendEof();
+            this.Write(dataToSend, 0, dataToSend.Length);
+        }
 
-                    this._channel.Close();
-                }
+        public void WriteLine(string line)
+        {
+            this.Write(line + '\n');
+        }
 
-                //  TODO:   Check why this._channel could be null here, had an exception thrown here
-                this._channel.DataReceived -= Channel_DataReceived;
-                this._channel.Closed -= Channel_Closed;
+        public void WriteLine()
+        {
+            this.Write("\n");
+        }
 
-                this._channel = null;
-            }
 
-            this._session.Disconnected -= Session_Disconnected;
-            this._session.ErrorOccured -= Session_ErrorOccured;
+        private void OnDataReceived(byte[] data)
+        {
+            if (DataReceived != null)
+                DataReceived(data);
+        }
 
-            if (this.DataAvailableWaitHandle != null)
-            {
-                this.DataAvailableWaitHandle.Dispose();
-                this.DataAvailableWaitHandle = null;
-            }
+        private void OnLineRead(string line)
+        {
+            if (LineRead != null)
+                LineRead(line);
         }
 
-        #endregion
+        public void Clear()
+        {
+            this._compleatedLines.Clear();
+            this._currentLine.Clear();
+        }
 
-        private void Channel_DataReceived(object sender, Common.ChannelDataEventArgs e)
+        public string ExpectLine()
         {
-            lock (this._incoming)
-            {
-                // wait until the buffer isn't full
-                while (this._incoming.Count >= this._bufferSize)
-                    Monitor.Wait(this._incoming);
+            string result = ExpectLine(Timeout.Infinite);
 
-                for (int i = 0; i < e.Data.Length; i++)
-                {
-                    if (this._expectedText != null)
-                    {
-                        if (this._expectedText[_expectedIndex] == e.Data[i])
-                        {
-                            //  Expected character found
-                            this._expectedIndex++;
-
-                            //  Check if expected text is completely found
-                            if (this._expectedIndex == this._expectedText.Length)
-                            {
-                                this._expectedTextWaitHandle.Set();
-                            }
-                        }
-                        else
-                        {
-                            //  Still waiting for first expected character
-                            this._expectedIndex = 0;
-                        }
-                    }
-                    this._incoming.Enqueue(e.Data[i]);
-                }
+            return (result);
+        }
 
-                Monitor.Pulse(this._incoming); // signal that write has occurred
-            }
+        public string ExpectLine(int millisecondTimeout)
+        {
+            Regex matchAnything = new Regex("");
 
-            this.DataAvailableWaitHandle.Set();
+            string result = Expect(matchAnything, millisecondTimeout, LineMatchModes.Compleated);
 
+            return (result);
         }
 
-        private void Channel_Closed(object sender, Common.ChannelEventArgs e)
+        public string TryExpectLine()
         {
-            this.Dispose();
+            string result = ExpectLine(0);
+
+            return (result);
         }
 
-        private void Session_Disconnected(object sender, System.EventArgs e)
+        public string Expect(string SearchPattern, int millisecondTimeout, LineMatchModes MatchMode)
         {
-            //  If channel is open then close it to cause Channel_Closed method to be called
-            if (this._channel != null && this._channel.IsOpen)
+            Regex searchPattern = new Regex(Regex.Escape(SearchPattern));
+
+            string result = Expect(searchPattern, millisecondTimeout, MatchMode);
+
+            return (result);
+        }
+
+        public string Expect(Regex SearchPattern, int millisecondTimeout, LineMatchModes MatchMode)
+        {
+            int patternIndex = 0;
+            Regex[] searchPatternsArray = { SearchPattern };
+
+            string result = Expect(searchPatternsArray, out patternIndex, millisecondTimeout, MatchMode);
+
+            return (result);
+        }
+
+        public string Expect(Regex[] searchPatterns, out Regex matchedPattern, int millisecondTimeout, LineMatchModes matchMode)
+        {
+            int matchedIndex = 0;
+
+            string results = Expect(searchPatterns, out matchedIndex, millisecondTimeout, matchMode);
+
+            matchedPattern = searchPatterns[matchedIndex];
+
+            return (results);
+        }
+
+        public string Expect(out Regex matchedPattern, int millisecondTimeout, LineMatchModes matchMode, params Regex[] searchPatterns)
+        {
+            string result = Expect(searchPatterns, out matchedPattern, millisecondTimeout, matchMode);
+
+            return (result);
+        }
+
+        public string Expect(Regex[] searchPatterns, out int matchedIndex, int millisecondTimeout, LineMatchModes matchMode)
+        {
+            lock (this._compleatedLines)
             {
-                this._channel.SendEof();
+                string result = ExtractCaptureBuffer(this._compleatedLines, searchPatterns, out matchedIndex, _currentLine, matchMode, 0);
+                if (result != null)
+                    return (result);
+                else
+                {
+                    this._patternMatchers = searchPatterns;
+                    this._lineMatchMode = matchMode;
 
-                this._channel.Close();
+                    bool dataAvalableFlag = Monitor.Wait(this._compleatedLines, millisecondTimeout);
+
+                    this._patternMatchers = null;
+
+                    if (dataAvalableFlag)
+                    {
+                        matchedIndex = this._patternMatcherIndex;
+                        result = this._patternCaptureBuffer;
+
+                        this._patternCaptureBuffer = null;
+
+                        return (result);
+
+                    }
+                    else
+                        return (null);
+                }
             }
         }
 
-        private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
+        public string ReadAll()
         {
-            this.RaiseError(e);
+            lock (this._compleatedLines)
+            {
+
+                if (this._currentLine.Length > 0)
+                {
+                    this._currentLine.Insert(0,'\n');
+                    this._currentLine.Insert(0, String.Join("\n", this._compleatedLines));
+                }
+                
+                string results = this._currentLine.ToString();
+
+                this.Clear();
+
+                return (results);
+            }
         }
 
-        private void RaiseError(ExceptionEventArgs e)
+        private string ExtractCaptureBuffer(List<string> lineBufferToMatch, Regex[] matchedPatterns, out int matchedIndex, StringBuilder currentLine, LineMatchModes matchMode, int startIndex)
         {
-            if (this.ErrorOccurred != null)
+            // Check the line buffer to see if a compleated line matches
+            if (matchMode == LineMatchModes.Compleated || matchMode == LineMatchModes.Everything)
             {
-                this.ErrorOccurred(this, e);
+                for (int lineNumber = startIndex; lineNumber < lineBufferToMatch.Count; lineNumber++)
+                {
+                    for (int matcherIndex = 0; matcherIndex < matchedPatterns.Length; matcherIndex++)
+                    {
+                        if (matchedPatterns[matcherIndex].IsMatch(lineBufferToMatch[lineNumber]))
+                        {
+                            matchedIndex = matcherIndex;
+
+                            string[] result = lineBufferToMatch.GetRange(0, lineNumber + 1).ToArray();
+
+                            lineBufferToMatch.RemoveRange(0, lineNumber + 1);
+
+
+                            return (String.Join("\n", result));
+                        }
+                    }
+                }
             }
+
+            if (matchMode == LineMatchModes.Partial || matchMode == LineMatchModes.Everything)
+            {
+                for (int matcherIndex = 0; matcherIndex < matchedPatterns.Length; matcherIndex++)
+                {
+                    if (matchedPatterns[matcherIndex].IsMatch(currentLine.ToString()))
+                    {
+                        matchedIndex = matcherIndex;
+
+                        StringBuilder results = new StringBuilder();
+                        results.AppendLine(String.Join("\n", lineBufferToMatch.ToArray()));
+
+                        results.Append(currentLine.ToString());
+
+                        this.Clear();
+
+                        return (results.ToString());
+                    }
+                }
+            }
+
+            matchedIndex = 0;
+            return (null);
         }
     }
 }