ShellStream.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using Renci.SshNet.Channels;
  7. using Renci.SshNet.Common;
  8. using System.Threading;
  9. using System.Text.RegularExpressions;
  10. namespace Renci.SshNet
  11. {
  12. /// <summary>
  13. /// Contains operation for working with SSH Shell.
  14. /// </summary>
  15. public class ShellStream : Stream
  16. {
  17. // TODO: Replace reading into StringBuilder with reading into Stack or byte array for better efficiency.
  18. private readonly Session _session;
  19. private ChannelSession _channel;
  20. private Encoding _encoding;
  21. private StringBuilder _dataBuffer;
  22. /// <summary>
  23. /// Occurs when data was received.
  24. /// </summary>
  25. public event EventHandler<ShellDataEventArgs> DataReceived;
  26. /// <summary>
  27. /// Occurs when an error occurred.
  28. /// </summary>
  29. public event EventHandler<ExceptionEventArgs> ErrorOccurred;
  30. /// <summary>
  31. /// Gets a value that indicates whether data is available on the <see cref="ShellStream"/> to be read.
  32. /// </summary>
  33. /// <value>
  34. /// <c>true</c> if data is available to be read; otherwise, <c>false</c>.
  35. /// </value>
  36. public bool DataAvailable
  37. {
  38. get
  39. {
  40. return this._dataBuffer.Length > 0;
  41. }
  42. }
  43. internal ShellStream(Session session, string terminalName, uint columns, uint rows, uint width, uint height, int maxLines, params KeyValuePair<TerminalModes, uint>[] terminalModeValues)
  44. {
  45. this._dataBuffer = new StringBuilder();
  46. this._encoding = new Renci.SshNet.Common.ASCIIEncoding();
  47. this._session = session;
  48. this._channel = this._session.CreateChannel<ChannelSession>();
  49. this._channel.DataReceived += new EventHandler<ChannelDataEventArgs>(Channel_DataReceived);
  50. this._channel.Closed += new EventHandler<ChannelEventArgs>(Channel_Closed);
  51. this._session.Disconnected += new EventHandler<EventArgs>(Session_Disconnected);
  52. this._session.ErrorOccured += new EventHandler<ExceptionEventArgs>(Session_ErrorOccured);
  53. this._channel.Open();
  54. this._channel.SendPseudoTerminalRequest(terminalName, columns, rows, width, height, terminalModeValues);
  55. this._channel.SendShellRequest();
  56. }
  57. #region Stream overide methods
  58. /// <summary>
  59. /// Gets a value indicating whether the current stream supports reading.
  60. /// </summary>
  61. /// <returns>true if the stream supports reading; otherwise, false.</returns>
  62. public override bool CanRead
  63. {
  64. get { return true; }
  65. }
  66. /// <summary>
  67. /// Gets a value indicating whether the current stream supports seeking.
  68. /// </summary>
  69. /// <returns>true if the stream supports seeking; otherwise, false.</returns>
  70. public override bool CanSeek
  71. {
  72. get { return false; }
  73. }
  74. /// <summary>
  75. /// Gets a value indicating whether the current stream supports writing.
  76. /// </summary>
  77. /// <returns>true if the stream supports writing; otherwise, false.</returns>
  78. public override bool CanWrite
  79. {
  80. get { return true; }
  81. }
  82. /// <summary>
  83. /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
  84. /// </summary>
  85. /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  86. public override void Flush()
  87. {
  88. throw new NotImplementedException();
  89. }
  90. /// <summary>
  91. /// Gets the length in bytes of the stream.
  92. /// </summary>
  93. /// <returns>A long value representing the length of the stream in bytes.</returns>
  94. ///
  95. /// <exception cref="T:System.NotSupportedException">A class derived from Stream does not support seeking. </exception>
  96. ///
  97. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  98. public override long Length
  99. {
  100. get { return this._dataBuffer.Length; }
  101. }
  102. /// <summary>
  103. /// Gets or sets the position within the current stream.
  104. /// </summary>
  105. /// <returns>The current position within the stream.</returns>
  106. ///
  107. /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  108. ///
  109. /// <exception cref="T:System.NotSupportedException">The stream does not support seeking. </exception>
  110. ///
  111. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  112. public override long Position
  113. {
  114. get { return 0; }
  115. set { throw new NotSupportedException(); }
  116. }
  117. /// <summary>
  118. /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
  119. /// </summary>
  120. /// <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>
  121. /// <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>
  122. /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
  123. /// <returns>
  124. /// 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.
  125. /// </returns>
  126. /// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length. </exception>
  127. ///
  128. /// <exception cref="T:System.ArgumentNullException">
  129. /// <paramref name="buffer"/> is null. </exception>
  130. ///
  131. /// <exception cref="T:System.ArgumentOutOfRangeException">
  132. /// <paramref name="offset"/> or <paramref name="count"/> is negative. </exception>
  133. ///
  134. /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  135. ///
  136. /// <exception cref="T:System.NotSupportedException">The stream does not support reading. </exception>
  137. ///
  138. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  139. public override int Read(byte[] buffer, int offset, int count)
  140. {
  141. var data = this._encoding.GetBytes(this._dataBuffer.ToString().ToCharArray(), 0, Math.Min(count, this._dataBuffer.Length));
  142. if (data.Length > 0)
  143. {
  144. Array.Copy(data, 0, buffer, offset, data.Length);
  145. this._dataBuffer.Remove(0, data.Length);
  146. }
  147. return data.Length;
  148. }
  149. /// <summary>
  150. /// This method is not supported.
  151. /// </summary>
  152. /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param>
  153. /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
  154. /// <returns>
  155. /// The new position within the current stream.
  156. /// </returns>
  157. /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  158. ///
  159. /// <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>
  160. ///
  161. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  162. public override long Seek(long offset, System.IO.SeekOrigin origin)
  163. {
  164. throw new NotSupportedException();
  165. }
  166. /// <summary>
  167. /// This method is not supported.
  168. /// </summary>
  169. /// <param name="value">The desired length of the current stream in bytes.</param>
  170. /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  171. ///
  172. /// <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>
  173. ///
  174. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  175. public override void SetLength(long value)
  176. {
  177. throw new NotSupportedException();
  178. }
  179. /// <summary>
  180. /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
  181. /// </summary>
  182. /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param>
  183. /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param>
  184. /// <param name="count">The number of bytes to be written to the current stream.</param>
  185. /// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is greater than the buffer length. </exception>
  186. ///
  187. /// <exception cref="T:System.ArgumentNullException">
  188. /// <paramref name="buffer"/> is null. </exception>
  189. ///
  190. /// <exception cref="T:System.ArgumentOutOfRangeException">
  191. /// <paramref name="offset"/> or <paramref name="count"/> is negative. </exception>
  192. ///
  193. /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  194. ///
  195. /// <exception cref="T:System.NotSupportedException">The stream does not support writing. </exception>
  196. ///
  197. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  198. public override void Write(byte[] buffer, int offset, int count)
  199. {
  200. this._channel.SendData(buffer.Skip(offset).Take(count).ToArray());
  201. }
  202. #endregion
  203. /// <summary>
  204. /// Expects the specified expression and performs action when one is found.
  205. /// </summary>
  206. /// <param name="expectActions">The expected expressions and actions to perform.</param>
  207. public void Expect(params ExpectAction[] expectActions)
  208. {
  209. var expectedFound = false;
  210. lock (this._dataBuffer)
  211. {
  212. do
  213. {
  214. if (this._dataBuffer.Length > 0)
  215. {
  216. foreach (var expectAction in expectActions)
  217. {
  218. var match = expectAction.Expect.Match(this._dataBuffer.ToString());
  219. if (match.Success)
  220. {
  221. var result = this._dataBuffer.ToString().Substring(0, match.Index + match.Length);
  222. // Clean buffer up to expected text
  223. this._dataBuffer.Remove(0, match.Index + match.Length);
  224. expectAction.Action(result);
  225. expectedFound = true;
  226. }
  227. }
  228. if (!expectedFound)
  229. Monitor.Wait(this._dataBuffer);
  230. }
  231. else
  232. {
  233. Monitor.Wait(this._dataBuffer);
  234. }
  235. }
  236. while (!expectedFound);
  237. }
  238. }
  239. /// <summary>
  240. /// Expects the expression specified by text.
  241. /// </summary>
  242. /// <param name="text">The text to expect.</param>
  243. /// <returns></returns>
  244. public string Expect(string text)
  245. {
  246. return this.Expect(new Regex(Regex.Escape(text)));
  247. }
  248. /// <summary>
  249. /// Expects the expression specified by regular expression.
  250. /// </summary>
  251. /// <param name="regex">The regular expresssion to expect.</param>
  252. /// <returns>Text available in the shell that contains all the text that ends with expected expression.</returns>
  253. public string Expect(Regex regex)
  254. {
  255. var result = string.Empty;
  256. lock (this._dataBuffer)
  257. {
  258. var match = regex.Match(this._dataBuffer.ToString());
  259. while (!match.Success)
  260. {
  261. Monitor.Wait(this._dataBuffer);
  262. match = regex.Match(this._dataBuffer.ToString());
  263. }
  264. result = this._dataBuffer.ToString().Substring(0, match.Index + match.Length);
  265. // Clean buffer up to expected text
  266. this._dataBuffer.Remove(0, match.Index + match.Length);
  267. }
  268. return result;
  269. }
  270. /// <summary>
  271. /// Reads the line from the shell. If line is not available it will block the execution and will wait for new line.
  272. /// </summary>
  273. /// <returns></returns>
  274. public string ReadLine()
  275. {
  276. string result = string.Empty;
  277. lock (this._dataBuffer)
  278. {
  279. var index = this._dataBuffer.ToString().IndexOf("\r\n");
  280. while (index < 0)
  281. {
  282. Monitor.Wait(this._dataBuffer);
  283. index = this._dataBuffer.ToString().IndexOf("\r\n");
  284. }
  285. result = this._dataBuffer.ToString().Substring(0, index);
  286. this._dataBuffer.Remove(0, index);
  287. }
  288. return result;
  289. }
  290. /// <summary>
  291. /// Reads text available in the shell.
  292. /// </summary>
  293. /// <returns></returns>
  294. public string Read()
  295. {
  296. string result = this._dataBuffer.ToString();
  297. lock (this._dataBuffer)
  298. {
  299. this._dataBuffer.Length = 0;
  300. }
  301. return result;
  302. }
  303. /// <summary>
  304. /// Writes the specified text to the shell.
  305. /// </summary>
  306. /// <param name="text">The text.</param>
  307. public void Write(string text)
  308. {
  309. var data = this._encoding.GetBytes(text);
  310. this._channel.SendData(data);
  311. }
  312. /// <summary>
  313. /// Writes the line to the shell.
  314. /// </summary>
  315. /// <param name="line">The line.</param>
  316. public void WriteLine(string line)
  317. {
  318. var commandText = string.Format("{0}{1}", line, "\r\n");
  319. this.Write(commandText);
  320. }
  321. /// <summary>
  322. /// Releases the unmanaged resources used by the <see cref="T:System.IO.Stream"/> and optionally releases the managed resources.
  323. /// </summary>
  324. /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
  325. protected override void Dispose(bool disposing)
  326. {
  327. base.Dispose(disposing);
  328. if (this._channel != null)
  329. {
  330. this._channel.Dispose();
  331. this._channel = null;
  332. }
  333. }
  334. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  335. {
  336. this.OnRaiseError(e);
  337. }
  338. private void Session_Disconnected(object sender, EventArgs e)
  339. {
  340. // If channel is open then close it to cause Channel_Closed method to be called
  341. if (this._channel != null && this._channel.IsOpen)
  342. {
  343. this._channel.SendEof();
  344. this._channel.Close();
  345. }
  346. }
  347. private void Channel_Closed(object sender, ChannelEventArgs e)
  348. {
  349. // TODO: Do we need to call dispose here ??
  350. this.Dispose();
  351. }
  352. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  353. {
  354. lock (this._dataBuffer)
  355. {
  356. this._dataBuffer.Append(this._encoding.GetString(e.Data, 0, e.Data.Length));
  357. Monitor.Pulse(this._dataBuffer);
  358. }
  359. this.OnDataReceived(e.Data);
  360. }
  361. private void OnRaiseError(ExceptionEventArgs e)
  362. {
  363. if (this.ErrorOccurred != null)
  364. this.ErrorOccurred(this, e);
  365. }
  366. private void OnDataReceived(byte[] data)
  367. {
  368. if (this.DataReceived != null)
  369. this.DataReceived(this, new ShellDataEventArgs(data));
  370. }
  371. }
  372. }