ShellStream.cs 19 KB

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