Shell.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. _channel.SendData(buffer, 0, read);
  124. continue;
  125. }
  126. #elif FEATURE_STREAM_APM
  127. var asyncResult = _input.BeginRead(buffer, 0, buffer.Length, result =>
  128. {
  129. // If input stream is closed and disposed already don't finish reading the stream
  130. if (_input == null)
  131. return;
  132. var read = _input.EndRead(result);
  133. _channel.SendData(buffer, 0, read);
  134. }, null);
  135. WaitHandle.WaitAny(new[] { asyncResult.AsyncWaitHandle, _channelClosedWaitHandle });
  136. if (asyncResult.IsCompleted)
  137. continue;
  138. #else
  139. #error Async receive is not implemented.
  140. #endif
  141. break;
  142. }
  143. }
  144. catch (Exception exp)
  145. {
  146. RaiseError(new ExceptionEventArgs(exp));
  147. }
  148. finally
  149. {
  150. _dataReaderTaskCompleted.Set();
  151. }
  152. });
  153. IsStarted = true;
  154. if (Started != null)
  155. {
  156. Started(this, new EventArgs());
  157. }
  158. }
  159. /// <summary>
  160. /// Stops this shell.
  161. /// </summary>
  162. /// <exception cref="SshException">Shell is not started.</exception>
  163. public void Stop()
  164. {
  165. if (!IsStarted)
  166. {
  167. throw new SshException("Shell is not started.");
  168. }
  169. if (_channel != null)
  170. {
  171. _channel.Close();
  172. }
  173. }
  174. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  175. {
  176. RaiseError(e);
  177. }
  178. private void RaiseError(ExceptionEventArgs e)
  179. {
  180. var handler = ErrorOccurred;
  181. if (handler != null)
  182. {
  183. handler(this, e);
  184. }
  185. }
  186. private void Session_Disconnected(object sender, EventArgs e)
  187. {
  188. Stop();
  189. }
  190. private void Channel_ExtendedDataReceived(object sender, ChannelExtendedDataEventArgs e)
  191. {
  192. if (_extendedOutputStream != null)
  193. {
  194. _extendedOutputStream.Write(e.Data, 0, e.Data.Length);
  195. }
  196. }
  197. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  198. {
  199. if (_outputStream != null)
  200. {
  201. _outputStream.Write(e.Data, 0, e.Data.Length);
  202. }
  203. }
  204. private void Channel_Closed(object sender, ChannelEventArgs e)
  205. {
  206. if (Stopping != null)
  207. {
  208. // Handle event on different thread
  209. ThreadAbstraction.ExecuteThread(() => Stopping(this, new EventArgs()));
  210. }
  211. if (_channel.IsOpen)
  212. {
  213. _channel.Close();
  214. }
  215. _channelClosedWaitHandle.Set();
  216. _input.Dispose();
  217. _input = null;
  218. _dataReaderTaskCompleted.WaitOne(_session.ConnectionInfo.Timeout);
  219. _dataReaderTaskCompleted.Dispose();
  220. _dataReaderTaskCompleted = null;
  221. _channel.DataReceived -= Channel_DataReceived;
  222. _channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
  223. _channel.Closed -= Channel_Closed;
  224. UnsubscribeFromSessionEvents(_session);
  225. if (Stopped != null)
  226. {
  227. // Handle event on different thread
  228. ThreadAbstraction.ExecuteThread(() => Stopped(this, new EventArgs()));
  229. }
  230. _channel = null;
  231. }
  232. /// <summary>
  233. /// Unsubscribes the current <see cref="Shell"/> from session events.
  234. /// </summary>
  235. /// <param name="session">The session.</param>
  236. /// <remarks>
  237. /// Does nothing when <paramref name="session"/> is <c>null</c>.
  238. /// </remarks>
  239. private void UnsubscribeFromSessionEvents(ISession session)
  240. {
  241. if (session == null)
  242. return;
  243. session.Disconnected -= Session_Disconnected;
  244. session.ErrorOccured -= Session_ErrorOccured;
  245. }
  246. #region IDisposable Members
  247. private bool _disposed;
  248. /// <summary>
  249. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  250. /// </summary>
  251. public void Dispose()
  252. {
  253. Dispose(true);
  254. GC.SuppressFinalize(this);
  255. }
  256. /// <summary>
  257. /// Releases unmanaged and - optionally - managed resources
  258. /// </summary>
  259. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  260. protected virtual void Dispose(bool disposing)
  261. {
  262. if (_disposed)
  263. return;
  264. if (disposing)
  265. {
  266. UnsubscribeFromSessionEvents(_session);
  267. var channelClosedWaitHandle = _channelClosedWaitHandle;
  268. if (channelClosedWaitHandle != null)
  269. {
  270. channelClosedWaitHandle.Dispose();
  271. _channelClosedWaitHandle = null;
  272. }
  273. var channel = _channel;
  274. if (channel != null)
  275. {
  276. channel.Dispose();
  277. _channel = null;
  278. }
  279. var dataReaderTaskCompleted = _dataReaderTaskCompleted;
  280. if (dataReaderTaskCompleted != null)
  281. {
  282. dataReaderTaskCompleted.Dispose();
  283. _dataReaderTaskCompleted = null;
  284. }
  285. _disposed = true;
  286. }
  287. }
  288. /// <summary>
  289. /// Releases unmanaged resources and performs other cleanup operations before the
  290. /// <see cref="Shell"/> is reclaimed by garbage collection.
  291. /// </summary>
  292. ~Shell()
  293. {
  294. Dispose(false);
  295. }
  296. #endregion
  297. }
  298. }