Shell.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. var readTask = _input.ReadAsync(buffer, 0, buffer.Length);
  118. var readWaitHandle = ((IAsyncResult) readTask).AsyncWaitHandle;
  119. if (WaitHandle.WaitAny(new[] {readWaitHandle, _channelClosedWaitHandle}) == 0)
  120. {
  121. var read = readTask.GetAwaiter().GetResult();
  122. _channel.SendData(buffer, 0, read);
  123. continue;
  124. }
  125. break;
  126. }
  127. }
  128. catch (Exception exp)
  129. {
  130. RaiseError(new ExceptionEventArgs(exp));
  131. }
  132. finally
  133. {
  134. _dataReaderTaskCompleted.Set();
  135. }
  136. });
  137. IsStarted = true;
  138. if (Started != null)
  139. {
  140. Started(this, new EventArgs());
  141. }
  142. }
  143. /// <summary>
  144. /// Stops this shell.
  145. /// </summary>
  146. /// <exception cref="SshException">Shell is not started.</exception>
  147. public void Stop()
  148. {
  149. if (!IsStarted)
  150. {
  151. throw new SshException("Shell is not started.");
  152. }
  153. if (_channel != null)
  154. {
  155. _channel.Dispose();
  156. }
  157. }
  158. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  159. {
  160. RaiseError(e);
  161. }
  162. private void RaiseError(ExceptionEventArgs e)
  163. {
  164. var handler = ErrorOccurred;
  165. if (handler != null)
  166. {
  167. handler(this, e);
  168. }
  169. }
  170. private void Session_Disconnected(object sender, EventArgs e)
  171. {
  172. Stop();
  173. }
  174. private void Channel_ExtendedDataReceived(object sender, ChannelExtendedDataEventArgs e)
  175. {
  176. if (_extendedOutputStream != null)
  177. {
  178. _extendedOutputStream.Write(e.Data, 0, e.Data.Length);
  179. }
  180. }
  181. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  182. {
  183. if (_outputStream != null)
  184. {
  185. _outputStream.Write(e.Data, 0, e.Data.Length);
  186. }
  187. }
  188. private void Channel_Closed(object sender, ChannelEventArgs e)
  189. {
  190. if (Stopping != null)
  191. {
  192. // Handle event on different thread
  193. ThreadAbstraction.ExecuteThread(() => Stopping(this, new EventArgs()));
  194. }
  195. _channel.Dispose();
  196. _channelClosedWaitHandle.Set();
  197. _input.Dispose();
  198. _input = null;
  199. _dataReaderTaskCompleted.WaitOne(_session.ConnectionInfo.Timeout);
  200. _dataReaderTaskCompleted.Dispose();
  201. _dataReaderTaskCompleted = null;
  202. _channel.DataReceived -= Channel_DataReceived;
  203. _channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
  204. _channel.Closed -= Channel_Closed;
  205. UnsubscribeFromSessionEvents(_session);
  206. if (Stopped != null)
  207. {
  208. // Handle event on different thread
  209. ThreadAbstraction.ExecuteThread(() => Stopped(this, new EventArgs()));
  210. }
  211. _channel = null;
  212. }
  213. /// <summary>
  214. /// Unsubscribes the current <see cref="Shell"/> from session events.
  215. /// </summary>
  216. /// <param name="session">The session.</param>
  217. /// <remarks>
  218. /// Does nothing when <paramref name="session"/> is <c>null</c>.
  219. /// </remarks>
  220. private void UnsubscribeFromSessionEvents(ISession session)
  221. {
  222. if (session == null)
  223. return;
  224. session.Disconnected -= Session_Disconnected;
  225. session.ErrorOccured -= Session_ErrorOccured;
  226. }
  227. #region IDisposable Members
  228. private bool _disposed;
  229. /// <summary>
  230. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  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 resources.</param>
  241. protected virtual void Dispose(bool disposing)
  242. {
  243. if (_disposed)
  244. return;
  245. if (disposing)
  246. {
  247. UnsubscribeFromSessionEvents(_session);
  248. var channelClosedWaitHandle = _channelClosedWaitHandle;
  249. if (channelClosedWaitHandle != null)
  250. {
  251. channelClosedWaitHandle.Dispose();
  252. _channelClosedWaitHandle = null;
  253. }
  254. var channel = _channel;
  255. if (channel != null)
  256. {
  257. channel.Dispose();
  258. _channel = null;
  259. }
  260. var dataReaderTaskCompleted = _dataReaderTaskCompleted;
  261. if (dataReaderTaskCompleted != null)
  262. {
  263. dataReaderTaskCompleted.Dispose();
  264. _dataReaderTaskCompleted = null;
  265. }
  266. _disposed = true;
  267. }
  268. }
  269. /// <summary>
  270. /// Releases unmanaged resources and performs other cleanup operations before the
  271. /// <see cref="Shell"/> is reclaimed by garbage collection.
  272. /// </summary>
  273. ~Shell()
  274. {
  275. Dispose(false);
  276. }
  277. #endregion
  278. }
  279. }