Shell.cs 11 KB

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