Shell.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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.SendEof();
  166. this._channel.Close();
  167. }
  168. }
  169. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  170. {
  171. this.RaiseError(e);
  172. }
  173. private void RaiseError(ExceptionEventArgs e)
  174. {
  175. if (this.ErrorOccurred != null)
  176. {
  177. this.ErrorOccurred(this, e);
  178. }
  179. }
  180. private void Session_Disconnected(object sender, System.EventArgs e)
  181. {
  182. this.Stop();
  183. }
  184. private void Channel_ExtendedDataReceived(object sender, Common.ChannelDataEventArgs e)
  185. {
  186. if (this._extendedOutputStream != null)
  187. {
  188. this._extendedOutputStream.Write(e.Data, 0, e.Data.Length);
  189. }
  190. }
  191. private void Channel_DataReceived(object sender, Common.ChannelDataEventArgs e)
  192. {
  193. if (this._outputStream != null)
  194. {
  195. this._outputStream.Write(e.Data, 0, e.Data.Length);
  196. }
  197. }
  198. private void Channel_Closed(object sender, Common.ChannelEventArgs e)
  199. {
  200. if (this.Stopping != null)
  201. {
  202. // Handle event on different thread
  203. this.ExecuteThread(() => { this.Stopping(this, new EventArgs()); });
  204. }
  205. if (this._channel.IsOpen)
  206. {
  207. this._channel.SendEof();
  208. this._channel.Close();
  209. }
  210. this._channelClosedWaitHandle.Set();
  211. this._input.Dispose();
  212. this._input = null;
  213. this._dataReaderTaskCompleted.WaitOne(this._session.ConnectionInfo.Timeout);
  214. this._dataReaderTaskCompleted.Dispose();
  215. this._dataReaderTaskCompleted = null;
  216. this._channel.DataReceived -= Channel_DataReceived;
  217. this._channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
  218. this._channel.Closed -= Channel_Closed;
  219. this._session.Disconnected -= Session_Disconnected;
  220. this._session.ErrorOccured -= Session_ErrorOccured;
  221. if (this.Stopped != null)
  222. {
  223. // Handle event on different thread
  224. this.ExecuteThread(() => { this.Stopped(this, new EventArgs()); });
  225. }
  226. this._channel = null;
  227. }
  228. partial void ExecuteThread(Action action);
  229. #region IDisposable Members
  230. private bool _disposed = false;
  231. /// <summary>
  232. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  233. /// </summary>
  234. public void Dispose()
  235. {
  236. Dispose(true);
  237. GC.SuppressFinalize(this);
  238. }
  239. /// <summary>
  240. /// Releases unmanaged and - optionally - managed resources
  241. /// </summary>
  242. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  243. protected virtual void Dispose(bool disposing)
  244. {
  245. // Check to see if Dispose has already been called.
  246. if (!this._disposed)
  247. {
  248. // If disposing equals true, dispose all managed
  249. // and unmanaged ResourceMessages.
  250. if (disposing)
  251. {
  252. if (this._channelClosedWaitHandle != null)
  253. {
  254. this._channelClosedWaitHandle.Dispose();
  255. this._channelClosedWaitHandle = null;
  256. }
  257. if (this._channel != null)
  258. {
  259. this._channel.Dispose();
  260. this._channel = null;
  261. }
  262. if (this._dataReaderTaskCompleted != null)
  263. {
  264. this._dataReaderTaskCompleted.Dispose();
  265. this._dataReaderTaskCompleted = null;
  266. }
  267. }
  268. // Note disposing has been done.
  269. this._disposed = true;
  270. }
  271. }
  272. /// <summary>
  273. /// Releases unmanaged resources and performs other cleanup operations before the
  274. /// <see cref="Session"/> is reclaimed by garbage collection.
  275. /// </summary>
  276. ~Shell()
  277. {
  278. // Do not re-create Dispose clean-up code here.
  279. // Calling Dispose(false) is optimal in terms of
  280. // readability and maintainability.
  281. Dispose(false);
  282. }
  283. #endregion
  284. }
  285. }