Shell.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. using System;
  2. using System.Linq;
  3. using System.IO;
  4. using System.Threading;
  5. using Renci.SshNet.Channels;
  6. using Renci.SshNet.Common;
  7. using System.Collections.Generic;
  8. namespace Renci.SshNet
  9. {
  10. /// <summary>
  11. /// Represents instance of the SSH shell object
  12. /// </summary>
  13. public partial 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. ExecuteThread(() =>
  111. {
  112. try
  113. {
  114. var buffer = new byte[_bufferSize];
  115. while (_channel.IsOpen)
  116. {
  117. var asyncResult = _input.BeginRead(buffer, 0, buffer.Length, delegate(IAsyncResult result)
  118. {
  119. // If input stream is closed and disposed already dont finish reading the stream
  120. if (_input == null)
  121. return;
  122. var read = _input.EndRead(result);
  123. if (read > 0)
  124. {
  125. #if TUNING
  126. _channel.SendData(buffer, 0, read);
  127. #else
  128. _channel.SendData(buffer.Take(read).ToArray());
  129. #endif
  130. }
  131. }, null);
  132. EventWaitHandle.WaitAny(new WaitHandle[] { asyncResult.AsyncWaitHandle, _channelClosedWaitHandle });
  133. if (asyncResult.IsCompleted)
  134. continue;
  135. break;
  136. }
  137. }
  138. catch (Exception exp)
  139. {
  140. RaiseError(new ExceptionEventArgs(exp));
  141. }
  142. finally
  143. {
  144. _dataReaderTaskCompleted.Set();
  145. }
  146. });
  147. IsStarted = true;
  148. if (Started != null)
  149. {
  150. Started(this, new EventArgs());
  151. }
  152. }
  153. /// <summary>
  154. /// Stops this shell.
  155. /// </summary>
  156. /// <exception cref="SshException">Shell is not started.</exception>
  157. public void Stop()
  158. {
  159. if (!IsStarted)
  160. {
  161. throw new SshException("Shell is not started.");
  162. }
  163. if (_channel != null)
  164. {
  165. _channel.Close();
  166. }
  167. }
  168. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  169. {
  170. RaiseError(e);
  171. }
  172. private void RaiseError(ExceptionEventArgs e)
  173. {
  174. var handler = ErrorOccurred;
  175. if (handler != null)
  176. {
  177. handler(this, e);
  178. }
  179. }
  180. private void Session_Disconnected(object sender, EventArgs e)
  181. {
  182. Stop();
  183. }
  184. private void Channel_ExtendedDataReceived(object sender, ChannelExtendedDataEventArgs e)
  185. {
  186. if (_extendedOutputStream != null)
  187. {
  188. _extendedOutputStream.Write(e.Data, 0, e.Data.Length);
  189. }
  190. }
  191. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  192. {
  193. if (_outputStream != null)
  194. {
  195. _outputStream.Write(e.Data, 0, e.Data.Length);
  196. }
  197. }
  198. private void Channel_Closed(object sender, ChannelEventArgs e)
  199. {
  200. if (Stopping != null)
  201. {
  202. // Handle event on different thread
  203. ExecuteThread(() => Stopping(this, new EventArgs()));
  204. }
  205. if (_channel.IsOpen)
  206. {
  207. _channel.Close();
  208. }
  209. _channelClosedWaitHandle.Set();
  210. _input.Dispose();
  211. _input = null;
  212. _dataReaderTaskCompleted.WaitOne(_session.ConnectionInfo.Timeout);
  213. _dataReaderTaskCompleted.Dispose();
  214. _dataReaderTaskCompleted = null;
  215. _channel.DataReceived -= Channel_DataReceived;
  216. _channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
  217. _channel.Closed -= Channel_Closed;
  218. _session.Disconnected -= Session_Disconnected;
  219. _session.ErrorOccured -= Session_ErrorOccured;
  220. if (Stopped != null)
  221. {
  222. // Handle event on different thread
  223. ExecuteThread(() => Stopped(this, new EventArgs()));
  224. }
  225. _channel = null;
  226. }
  227. partial void ExecuteThread(Action action);
  228. #region IDisposable Members
  229. private bool _disposed;
  230. /// <summary>
  231. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  232. /// </summary>
  233. public void Dispose()
  234. {
  235. Dispose(true);
  236. GC.SuppressFinalize(this);
  237. }
  238. /// <summary>
  239. /// Releases unmanaged and - optionally - managed resources
  240. /// </summary>
  241. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  242. protected virtual void Dispose(bool disposing)
  243. {
  244. // Check to see if Dispose has already been called.
  245. if (!_disposed)
  246. {
  247. // If disposing equals true, dispose all managed
  248. // and unmanaged ResourceMessages.
  249. if (disposing)
  250. {
  251. if (_channelClosedWaitHandle != null)
  252. {
  253. _channelClosedWaitHandle.Dispose();
  254. _channelClosedWaitHandle = null;
  255. }
  256. if (_channel != null)
  257. {
  258. _channel.Dispose();
  259. _channel = null;
  260. }
  261. if (_dataReaderTaskCompleted != null)
  262. {
  263. _dataReaderTaskCompleted.Dispose();
  264. _dataReaderTaskCompleted = null;
  265. }
  266. }
  267. // Note disposing has been done.
  268. _disposed = true;
  269. }
  270. }
  271. /// <summary>
  272. /// Releases unmanaged resources and performs other cleanup operations before the
  273. /// <see cref="Session"/> is reclaimed by garbage collection.
  274. /// </summary>
  275. ~Shell()
  276. {
  277. // Do not re-create Dispose clean-up code here.
  278. // Calling Dispose(false) is optimal in terms of
  279. // readability and maintainability.
  280. Dispose(false);
  281. }
  282. #endregion
  283. }
  284. }