Shell.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using Renci.SshNet.Channels;
  5. using Renci.SshNet.Common;
  6. using System.Collections.Generic;
  7. using Renci.SshNet.Abstractions;
  8. namespace Renci.SshNet
  9. {
  10. /// <summary>
  11. /// Represents instance of the SSH shell object
  12. /// </summary>
  13. public class Shell : IDisposable
  14. {
  15. private readonly ISession _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(ISession 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. _session = session;
  73. _input = input;
  74. _outputStream = output;
  75. _extendedOutputStream = extendedOutput;
  76. _terminalName = terminalName;
  77. _columns = columns;
  78. _rows = rows;
  79. _width = width;
  80. _height = height;
  81. _terminalModes = terminalModes;
  82. _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 (IsStarted)
  91. {
  92. throw new SshException("Shell is started.");
  93. }
  94. if (Starting != null)
  95. {
  96. Starting(this, new EventArgs());
  97. }
  98. _channel = _session.CreateChannelSession();
  99. _channel.DataReceived += Channel_DataReceived;
  100. _channel.ExtendedDataReceived += Channel_ExtendedDataReceived;
  101. _channel.Closed += Channel_Closed;
  102. _session.Disconnected += Session_Disconnected;
  103. _session.ErrorOccured += Session_ErrorOccured;
  104. _channel.Open();
  105. _channel.SendPseudoTerminalRequest(_terminalName, _columns, _rows, _width, _height, _terminalModes);
  106. _channel.SendShellRequest();
  107. _channelClosedWaitHandle = new AutoResetEvent(false);
  108. // Start input stream listener
  109. _dataReaderTaskCompleted = new ManualResetEvent(false);
  110. ThreadAbstraction.ExecuteThread(() =>
  111. {
  112. try
  113. {
  114. var buffer = new byte[_bufferSize];
  115. while (_channel.IsOpen)
  116. {
  117. #if FEATURE_STREAM_TAP
  118. var readTask = _input.ReadAsync(buffer, 0, buffer.Length);
  119. var readWaitHandle = ((IAsyncResult) readTask).AsyncWaitHandle;
  120. if (WaitHandle.WaitAny(new[] {readWaitHandle, _channelClosedWaitHandle}) == 0)
  121. {
  122. var read = readTask.Result;
  123. #if TUNING
  124. _channel.SendData(buffer, 0, read);
  125. #else
  126. _channel.SendData(buffer.Take(read).ToArray());
  127. #endif
  128. continue;
  129. }
  130. #elif FEATURE_STREAM_APM
  131. var asyncResult = _input.BeginRead(buffer, 0, buffer.Length, delegate(IAsyncResult result)
  132. {
  133. // If input stream is closed and disposed already dont finish reading the stream
  134. if (_input == null)
  135. return;
  136. var read = _input.EndRead(result);
  137. if (read > 0)
  138. {
  139. #if TUNING
  140. _channel.SendData(buffer, 0, read);
  141. #else
  142. _channel.SendData(buffer.Take(read).ToArray());
  143. #endif
  144. }
  145. }, null);
  146. WaitHandle.WaitAny(new[] { asyncResult.AsyncWaitHandle, _channelClosedWaitHandle });
  147. if (asyncResult.IsCompleted)
  148. continue;
  149. #else
  150. #error Async receive is not implemented.
  151. #endif
  152. break;
  153. }
  154. }
  155. catch (Exception exp)
  156. {
  157. RaiseError(new ExceptionEventArgs(exp));
  158. }
  159. finally
  160. {
  161. _dataReaderTaskCompleted.Set();
  162. }
  163. });
  164. IsStarted = true;
  165. if (Started != null)
  166. {
  167. Started(this, new EventArgs());
  168. }
  169. }
  170. /// <summary>
  171. /// Stops this shell.
  172. /// </summary>
  173. /// <exception cref="SshException">Shell is not started.</exception>
  174. public void Stop()
  175. {
  176. if (!IsStarted)
  177. {
  178. throw new SshException("Shell is not started.");
  179. }
  180. if (_channel != null)
  181. {
  182. _channel.Close();
  183. }
  184. }
  185. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  186. {
  187. RaiseError(e);
  188. }
  189. private void RaiseError(ExceptionEventArgs e)
  190. {
  191. var handler = ErrorOccurred;
  192. if (handler != null)
  193. {
  194. handler(this, e);
  195. }
  196. }
  197. private void Session_Disconnected(object sender, EventArgs e)
  198. {
  199. Stop();
  200. }
  201. private void Channel_ExtendedDataReceived(object sender, ChannelExtendedDataEventArgs e)
  202. {
  203. if (_extendedOutputStream != null)
  204. {
  205. _extendedOutputStream.Write(e.Data, 0, e.Data.Length);
  206. }
  207. }
  208. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  209. {
  210. if (_outputStream != null)
  211. {
  212. _outputStream.Write(e.Data, 0, e.Data.Length);
  213. }
  214. }
  215. private void Channel_Closed(object sender, ChannelEventArgs e)
  216. {
  217. if (Stopping != null)
  218. {
  219. // Handle event on different thread
  220. ThreadAbstraction.ExecuteThread(() => Stopping(this, new EventArgs()));
  221. }
  222. if (_channel.IsOpen)
  223. {
  224. _channel.Close();
  225. }
  226. _channelClosedWaitHandle.Set();
  227. _input.Dispose();
  228. _input = null;
  229. _dataReaderTaskCompleted.WaitOne(_session.ConnectionInfo.Timeout);
  230. _dataReaderTaskCompleted.Dispose();
  231. _dataReaderTaskCompleted = null;
  232. _channel.DataReceived -= Channel_DataReceived;
  233. _channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
  234. _channel.Closed -= Channel_Closed;
  235. UnsubscribeFromSessionEvents(_session);
  236. if (Stopped != null)
  237. {
  238. // Handle event on different thread
  239. ThreadAbstraction.ExecuteThread(() => Stopped(this, new EventArgs()));
  240. }
  241. _channel = null;
  242. }
  243. /// <summary>
  244. /// Unsubscribes the current <see cref="Channel"/> from session events.
  245. /// </summary>
  246. /// <param name="session">The session.</param>
  247. /// <remarks>
  248. /// Does nothing when <paramref name="session"/> is <c>null</c>.
  249. /// </remarks>
  250. private void UnsubscribeFromSessionEvents(ISession session)
  251. {
  252. if (session == null)
  253. return;
  254. session.Disconnected -= Session_Disconnected;
  255. session.ErrorOccured -= Session_ErrorOccured;
  256. }
  257. #region IDisposable Members
  258. private bool _disposed;
  259. /// <summary>
  260. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  261. /// </summary>
  262. public void Dispose()
  263. {
  264. Dispose(true);
  265. GC.SuppressFinalize(this);
  266. }
  267. /// <summary>
  268. /// Releases unmanaged and - optionally - managed resources
  269. /// </summary>
  270. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  271. protected virtual void Dispose(bool disposing)
  272. {
  273. if (_disposed)
  274. return;
  275. if (disposing)
  276. {
  277. UnsubscribeFromSessionEvents(_session);
  278. if (_channelClosedWaitHandle != null)
  279. {
  280. _channelClosedWaitHandle.Dispose();
  281. _channelClosedWaitHandle = null;
  282. }
  283. if (_channel != null)
  284. {
  285. _channel.Dispose();
  286. _channel = null;
  287. }
  288. if (_dataReaderTaskCompleted != null)
  289. {
  290. _dataReaderTaskCompleted.Dispose();
  291. _dataReaderTaskCompleted = null;
  292. }
  293. _disposed = true;
  294. }
  295. else
  296. {
  297. UnsubscribeFromSessionEvents(_session);
  298. }
  299. }
  300. /// <summary>
  301. /// Releases unmanaged resources and performs other cleanup operations before the
  302. /// <see cref="Session"/> is reclaimed by garbage collection.
  303. /// </summary>
  304. ~Shell()
  305. {
  306. // Do not re-create Dispose clean-up code here.
  307. // Calling Dispose(false) is optimal in terms of
  308. // readability and maintainability.
  309. Dispose(false);
  310. }
  311. #endregion
  312. }
  313. }