Shell.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Threading;
  5. using Renci.SshNet.Abstractions;
  6. using Renci.SshNet.Channels;
  7. using Renci.SshNet.Common;
  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 readonly string _terminalName;
  17. private readonly uint _columns;
  18. private readonly uint _rows;
  19. private readonly uint _width;
  20. private readonly uint _height;
  21. private readonly IDictionary<TerminalModes, uint> _terminalModes;
  22. private readonly Stream _outputStream;
  23. private readonly Stream _extendedOutputStream;
  24. private readonly int _bufferSize;
  25. private ManualResetEvent _dataReaderTaskCompleted;
  26. private IChannelSession _channel;
  27. private AutoResetEvent _channelClosedWaitHandle;
  28. private Stream _input;
  29. /// <summary>
  30. /// Gets a value indicating whether this shell is started.
  31. /// </summary>
  32. /// <value>
  33. /// <see langword="true"/> if started is started; otherwise, <see langword="false"/>.
  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. Starting?.Invoke(this, EventArgs.Empty);
  95. _channel = _session.CreateChannelSession();
  96. _channel.DataReceived += Channel_DataReceived;
  97. _channel.ExtendedDataReceived += Channel_ExtendedDataReceived;
  98. _channel.Closed += Channel_Closed;
  99. _session.Disconnected += Session_Disconnected;
  100. _session.ErrorOccured += Session_ErrorOccured;
  101. _channel.Open();
  102. _ = _channel.SendPseudoTerminalRequest(_terminalName, _columns, _rows, _width, _height, _terminalModes);
  103. _ = _channel.SendShellRequest();
  104. _channelClosedWaitHandle = new AutoResetEvent(initialState: false);
  105. // Start input stream listener
  106. _dataReaderTaskCompleted = new ManualResetEvent(initialState: false);
  107. ThreadAbstraction.ExecuteThread(() =>
  108. {
  109. try
  110. {
  111. var buffer = new byte[_bufferSize];
  112. while (_channel.IsOpen)
  113. {
  114. var readTask = _input.ReadAsync(buffer, 0, buffer.Length);
  115. var readWaitHandle = ((IAsyncResult)readTask).AsyncWaitHandle;
  116. if (WaitHandle.WaitAny(new[] { readWaitHandle, _channelClosedWaitHandle }) == 0)
  117. {
  118. var read = readTask.GetAwaiter().GetResult();
  119. _channel.SendData(buffer, 0, read);
  120. continue;
  121. }
  122. break;
  123. }
  124. }
  125. catch (Exception exp)
  126. {
  127. RaiseError(new ExceptionEventArgs(exp));
  128. }
  129. finally
  130. {
  131. _ = _dataReaderTaskCompleted.Set();
  132. }
  133. });
  134. IsStarted = true;
  135. Started?.Invoke(this, EventArgs.Empty);
  136. }
  137. /// <summary>
  138. /// Stops this shell.
  139. /// </summary>
  140. /// <exception cref="SshException">Shell is not started.</exception>
  141. public void Stop()
  142. {
  143. if (!IsStarted)
  144. {
  145. throw new SshException("Shell is not started.");
  146. }
  147. _channel?.Dispose();
  148. }
  149. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  150. {
  151. RaiseError(e);
  152. }
  153. private void RaiseError(ExceptionEventArgs e)
  154. {
  155. ErrorOccurred?.Invoke(this, e);
  156. }
  157. private void Session_Disconnected(object sender, EventArgs e)
  158. {
  159. Stop();
  160. }
  161. private void Channel_ExtendedDataReceived(object sender, ChannelExtendedDataEventArgs e)
  162. {
  163. _extendedOutputStream?.Write(e.Data, 0, e.Data.Length);
  164. }
  165. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  166. {
  167. _outputStream?.Write(e.Data, 0, e.Data.Length);
  168. }
  169. private void Channel_Closed(object sender, ChannelEventArgs e)
  170. {
  171. if (Stopping is not null)
  172. {
  173. // Handle event on different thread
  174. ThreadAbstraction.ExecuteThread(() => Stopping(this, EventArgs.Empty));
  175. }
  176. _channel.Dispose();
  177. _ = _channelClosedWaitHandle.Set();
  178. _input.Dispose();
  179. _input = null;
  180. _ = _dataReaderTaskCompleted.WaitOne(_session.ConnectionInfo.Timeout);
  181. _dataReaderTaskCompleted.Dispose();
  182. _dataReaderTaskCompleted = null;
  183. _channel.DataReceived -= Channel_DataReceived;
  184. _channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
  185. _channel.Closed -= Channel_Closed;
  186. UnsubscribeFromSessionEvents(_session);
  187. if (Stopped != null)
  188. {
  189. // Handle event on different thread
  190. ThreadAbstraction.ExecuteThread(() => Stopped(this, EventArgs.Empty));
  191. }
  192. _channel = null;
  193. }
  194. /// <summary>
  195. /// Unsubscribes the current <see cref="Shell"/> from session events.
  196. /// </summary>
  197. /// <param name="session">The session.</param>
  198. /// <remarks>
  199. /// Does nothing when <paramref name="session"/> is <see langword="null"/>.
  200. /// </remarks>
  201. private void UnsubscribeFromSessionEvents(ISession session)
  202. {
  203. if (session is null)
  204. {
  205. return;
  206. }
  207. session.Disconnected -= Session_Disconnected;
  208. session.ErrorOccured -= Session_ErrorOccured;
  209. }
  210. private bool _disposed;
  211. /// <summary>
  212. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  213. /// </summary>
  214. public void Dispose()
  215. {
  216. Dispose(disposing: true);
  217. GC.SuppressFinalize(this);
  218. }
  219. /// <summary>
  220. /// Releases unmanaged and - optionally - managed resources.
  221. /// </summary>
  222. /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
  223. protected virtual void Dispose(bool disposing)
  224. {
  225. if (_disposed)
  226. {
  227. return;
  228. }
  229. if (disposing)
  230. {
  231. UnsubscribeFromSessionEvents(_session);
  232. var channelClosedWaitHandle = _channelClosedWaitHandle;
  233. if (channelClosedWaitHandle is not null)
  234. {
  235. channelClosedWaitHandle.Dispose();
  236. _channelClosedWaitHandle = null;
  237. }
  238. var channel = _channel;
  239. if (channel is not null)
  240. {
  241. channel.Dispose();
  242. _channel = null;
  243. }
  244. var dataReaderTaskCompleted = _dataReaderTaskCompleted;
  245. if (dataReaderTaskCompleted is not null)
  246. {
  247. dataReaderTaskCompleted.Dispose();
  248. _dataReaderTaskCompleted = null;
  249. }
  250. _disposed = true;
  251. }
  252. }
  253. /// <summary>
  254. /// Finalizes an instance of the <see cref="Shell"/> class.
  255. /// </summary>
  256. ~Shell()
  257. {
  258. Dispose(disposing: false);
  259. }
  260. }
  261. }