Shell.cs 12 KB

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