Shell.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. using System;
  2. using System.Linq;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Renci.SshNet.Channels;
  9. using Renci.SshNet.Common;
  10. using Renci.SshNet.Messages.Connection;
  11. namespace Renci.SshNet
  12. {
  13. /// <summary>
  14. /// Represents instance of the SSH shell object
  15. /// </summary>
  16. public class Shell : IDisposable
  17. {
  18. private readonly Session _session;
  19. private ChannelSession _channel;
  20. private EventWaitHandle _channelClosedWaitHandle;
  21. private Stream _input;
  22. private string _terminalName;
  23. private uint _columns;
  24. private uint _rows;
  25. private uint _width;
  26. private uint _height;
  27. private string _terminalMode;
  28. private Task _dataReaderTask;
  29. private Stream _outputStream;
  30. private Stream _extendedOutputStream;
  31. private int _bufferSize;
  32. /// <summary>
  33. /// Gets a value indicating whether this shell is started.
  34. /// </summary>
  35. /// <value>
  36. /// <c>true</c> if started is started; otherwise, <c>false</c>.
  37. /// </value>
  38. public bool IsStarted { get; private set; }
  39. /// <summary>
  40. /// Occurs when shell is starting.
  41. /// </summary>
  42. public event EventHandler<EventArgs> Starting;
  43. /// <summary>
  44. /// Occurs when shell is started.
  45. /// </summary>
  46. public event EventHandler<EventArgs> Started;
  47. /// <summary>
  48. /// Occurs when shell is stopping.
  49. /// </summary>
  50. public event EventHandler<EventArgs> Stopping;
  51. /// <summary>
  52. /// Occurs when shell is stopped.
  53. /// </summary>
  54. public event EventHandler<EventArgs> Stopped;
  55. /// <summary>
  56. /// Occurs when an error occurred.
  57. /// </summary>
  58. public event EventHandler<ExceptionEventArgs> ErrorOccurred;
  59. /// <summary>
  60. /// Initializes a new instance of the <see cref="Shell"/> class.
  61. /// </summary>
  62. /// <param name="session">The session.</param>
  63. /// <param name="input">The input.</param>
  64. /// <param name="output">The output.</param>
  65. /// <param name="extendedOutput">The extended output.</param>
  66. /// <param name="terminalName">Name of the terminal.</param>
  67. /// <param name="columns">The columns.</param>
  68. /// <param name="rows">The rows.</param>
  69. /// <param name="width">The width.</param>
  70. /// <param name="height">The height.</param>
  71. /// <param name="terminalMode">The terminal mode.</param>
  72. /// <param name="bufferSize">Size of the buffer for output stream.</param>
  73. internal Shell(Session session, Stream input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, string terminalMode, int bufferSize)
  74. {
  75. this._session = session;
  76. this._input = input;
  77. this._outputStream = output;
  78. this._extendedOutputStream = extendedOutput;
  79. this._terminalName = terminalName;
  80. this._columns = columns;
  81. this._rows = rows;
  82. this._width = width;
  83. this._height = height;
  84. this._terminalMode = terminalMode;
  85. this._bufferSize = bufferSize;
  86. }
  87. /// <summary>
  88. /// Starts this shell.
  89. /// </summary>
  90. public void Start()
  91. {
  92. if (this.IsStarted)
  93. {
  94. throw new SshException("Shell is started.");
  95. }
  96. if (this.Starting != null)
  97. {
  98. this.Starting(this, new EventArgs());
  99. }
  100. this._channel = this._session.CreateChannel<ChannelSession>();
  101. this._channel.DataReceived += Channel_DataReceived;
  102. this._channel.ExtendedDataReceived += Channel_ExtendedDataReceived;
  103. this._channel.Closed += Channel_Closed;
  104. this._session.Disconnected += Session_Disconnected;
  105. this._session.ErrorOccured += Session_ErrorOccured;
  106. this._channel.Open();
  107. this._channel.SendPseudoTerminalRequest(this._terminalName, this._columns, this._rows, this._width, this._height, this._terminalMode);
  108. this._channel.SendShellRequest();
  109. this._channelClosedWaitHandle = new AutoResetEvent(false);
  110. // Start input stream listener
  111. this._dataReaderTask = Task.Factory.StartNew(() =>
  112. {
  113. try
  114. {
  115. var buffer = new byte[this._bufferSize];
  116. while (this._channel.IsOpen)
  117. {
  118. var asyncResult = this._input.BeginRead(buffer, 0, buffer.Length, delegate(IAsyncResult result)
  119. {
  120. // If input stream is closed and disposed already dont finish reading the stream
  121. if (this._input == null)
  122. return;
  123. var read = this._input.EndRead(result);
  124. if (read > 0)
  125. {
  126. this._session.SendMessage(new ChannelDataMessage(this._channel.RemoteChannelNumber, buffer.Take(read).ToArray()));
  127. }
  128. }, null);
  129. EventWaitHandle.WaitAny(new WaitHandle[] {asyncResult.AsyncWaitHandle, this._channelClosedWaitHandle});
  130. if (asyncResult.IsCompleted)
  131. continue;
  132. else
  133. break;
  134. }
  135. }
  136. catch (Exception exp)
  137. {
  138. this.RaiseError(new ExceptionEventArgs(exp));
  139. }
  140. });
  141. this.IsStarted = true;
  142. if (this.Started != null)
  143. {
  144. this.Started(this, new EventArgs());
  145. }
  146. }
  147. /// <summary>
  148. /// Stops this shell.
  149. /// </summary>
  150. public void Stop()
  151. {
  152. if (!this.IsStarted)
  153. {
  154. throw new SshException("Shell is not started.");
  155. }
  156. // If channel is open then close it to cause Channel_Closed method to be called
  157. if (this._channel != null && this._channel.IsOpen)
  158. {
  159. this._channel.Close();
  160. }
  161. }
  162. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  163. {
  164. this.RaiseError(e);
  165. }
  166. private void RaiseError(ExceptionEventArgs e)
  167. {
  168. if (this.ErrorOccurred != null)
  169. {
  170. this.ErrorOccurred(this, e);
  171. }
  172. }
  173. private void Session_Disconnected(object sender, System.EventArgs e)
  174. {
  175. this.Stop();
  176. }
  177. private void Channel_ExtendedDataReceived(object sender, Common.ChannelDataEventArgs e)
  178. {
  179. if (this._extendedOutputStream != null)
  180. {
  181. this._extendedOutputStream.Write(e.Data, 0, e.Data.Length);
  182. }
  183. }
  184. private void Channel_DataReceived(object sender, Common.ChannelDataEventArgs e)
  185. {
  186. if (this._outputStream != null)
  187. {
  188. this._outputStream.Write(e.Data, 0, e.Data.Length);
  189. }
  190. }
  191. private void Channel_Closed(object sender, Common.ChannelEventArgs e)
  192. {
  193. if (this.Stopping != null)
  194. {
  195. // Handle event on different thread
  196. Task.Factory.StartNew(() => { this.Stopping(this, new EventArgs()); });
  197. }
  198. if (this._channel.IsOpen)
  199. this._channel.Close();
  200. this._channelClosedWaitHandle.Set();
  201. this._input.Dispose();
  202. this._input = null;
  203. this._dataReaderTask.Wait();
  204. this._channel.DataReceived -= Channel_DataReceived;
  205. this._channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
  206. this._channel.Closed -= Channel_Closed;
  207. this._session.Disconnected -= Session_Disconnected;
  208. this._session.ErrorOccured -= Session_ErrorOccured;
  209. if (this.Stopped != null)
  210. {
  211. // Handle event on different thread
  212. Task.Factory.StartNew(() => { this.Stopped(this, new EventArgs()); });
  213. }
  214. this._channel = null;
  215. }
  216. #region IDisposable Members
  217. private bool _disposed = false;
  218. /// <summary>
  219. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  220. /// </summary>
  221. public void Dispose()
  222. {
  223. Dispose(true);
  224. GC.SuppressFinalize(this);
  225. }
  226. /// <summary>
  227. /// Releases unmanaged and - optionally - managed resources
  228. /// </summary>
  229. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  230. protected virtual void Dispose(bool disposing)
  231. {
  232. // Check to see if Dispose has already been called.
  233. if (!this._disposed)
  234. {
  235. // If disposing equals true, dispose all managed
  236. // and unmanaged ResourceMessages.
  237. if (disposing)
  238. {
  239. if (this._channelClosedWaitHandle != null)
  240. {
  241. this._channelClosedWaitHandle.Dispose();
  242. this._channelClosedWaitHandle = null;
  243. }
  244. }
  245. // Note disposing has been done.
  246. this._disposed = true;
  247. }
  248. }
  249. /// <summary>
  250. /// Releases unmanaged resources and performs other cleanup operations before the
  251. /// <see cref="Session"/> is reclaimed by garbage collection.
  252. /// </summary>
  253. ~Shell()
  254. {
  255. // Do not re-create Dispose clean-up code here.
  256. // Calling Dispose(false) is optimal in terms of
  257. // readability and maintainability.
  258. Dispose(false);
  259. }
  260. #endregion
  261. }
  262. }