SubsystemSession.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. using System;
  2. using System.Globalization;
  3. using System.Text;
  4. using System.Threading;
  5. using Renci.SshNet.Channels;
  6. using Renci.SshNet.Common;
  7. namespace Renci.SshNet
  8. {
  9. /// <summary>
  10. /// Base class for SSH subsystem implementations
  11. /// </summary>
  12. internal abstract class SubsystemSession : ISubsystemSession
  13. {
  14. private ISession _session;
  15. private readonly string _subsystemName;
  16. private IChannelSession _channel;
  17. private Exception _exception;
  18. private EventWaitHandle _errorOccuredWaitHandle = new ManualResetEvent(false);
  19. private EventWaitHandle _sessionDisconnectedWaitHandle = new ManualResetEvent(false);
  20. private EventWaitHandle _channelClosedWaitHandle = new ManualResetEvent(false);
  21. /// <summary>
  22. /// Specifies a timeout to wait for operation to complete
  23. /// </summary>
  24. protected TimeSpan OperationTimeout { get; private set; }
  25. /// <summary>
  26. /// Occurs when an error occurred.
  27. /// </summary>
  28. public event EventHandler<ExceptionEventArgs> ErrorOccurred;
  29. /// <summary>
  30. /// Occurs when the server has disconnected from the session.
  31. /// </summary>
  32. public event EventHandler<EventArgs> Disconnected;
  33. /// <summary>
  34. /// Gets the channel associated with this session.
  35. /// </summary>
  36. /// <value>
  37. /// The channel associated with this session.
  38. /// </value>
  39. internal IChannelSession Channel
  40. {
  41. get
  42. {
  43. EnsureNotDisposed();
  44. return _channel;
  45. }
  46. }
  47. /// <summary>
  48. /// Gets a value indicating whether this session is open.
  49. /// </summary>
  50. /// <value>
  51. /// <c>true</c> if this session is open; otherwise, <c>false</c>.
  52. /// </value>
  53. public bool IsOpen
  54. {
  55. get { return _channel != null && _channel.IsOpen; }
  56. }
  57. /// <summary>
  58. /// Gets the character encoding to use.
  59. /// </summary>
  60. protected Encoding Encoding { get; private set; }
  61. /// <summary>
  62. /// Initializes a new instance of the SubsystemSession class.
  63. /// </summary>
  64. /// <param name="session">The session.</param>
  65. /// <param name="subsystemName">Name of the subsystem.</param>
  66. /// <param name="operationTimeout">The operation timeout.</param>
  67. /// <param name="encoding">The character encoding to use.</param>
  68. /// <exception cref="ArgumentNullException"><paramref name="session" /> or <paramref name="subsystemName" /> or <paramref name="encoding"/>is null.</exception>
  69. protected SubsystemSession(ISession session, string subsystemName, TimeSpan operationTimeout, Encoding encoding)
  70. {
  71. if (session == null)
  72. throw new ArgumentNullException("session");
  73. if (subsystemName == null)
  74. throw new ArgumentNullException("subsystemName");
  75. if (encoding == null)
  76. throw new ArgumentNullException("encoding");
  77. _session = session;
  78. _subsystemName = subsystemName;
  79. OperationTimeout = operationTimeout;
  80. Encoding = encoding;
  81. }
  82. /// <summary>
  83. /// Connects the subsystem using a new SSH channel session.
  84. /// </summary>
  85. /// <exception cref="InvalidOperationException">The session is already connected.</exception>
  86. /// <exception cref="ObjectDisposedException">The method was called after the session was disposed.</exception>
  87. public void Connect()
  88. {
  89. EnsureNotDisposed();
  90. if (IsOpen)
  91. throw new InvalidOperationException("The session is already connected.");
  92. // reset waithandles in case we're reconnecting
  93. _errorOccuredWaitHandle.Reset();
  94. _sessionDisconnectedWaitHandle.Reset();
  95. _sessionDisconnectedWaitHandle.Reset();
  96. _channelClosedWaitHandle.Reset();
  97. _session.ErrorOccured += Session_ErrorOccured;
  98. _session.Disconnected += Session_Disconnected;
  99. _channel = _session.CreateChannelSession();
  100. _channel.DataReceived += Channel_DataReceived;
  101. _channel.Exception += Channel_Exception;
  102. _channel.Closed += Channel_Closed;
  103. _channel.Open();
  104. _channel.SendSubsystemRequest(_subsystemName);
  105. OnChannelOpen();
  106. }
  107. /// <summary>
  108. /// Disconnects the subsystem channel.
  109. /// </summary>
  110. public void Disconnect()
  111. {
  112. if (_session != null)
  113. {
  114. _session.ErrorOccured -= Session_ErrorOccured;
  115. _session.Disconnected -= Session_Disconnected;
  116. }
  117. if (_channel != null)
  118. {
  119. _channel.DataReceived -= Channel_DataReceived;
  120. _channel.Exception -= Channel_Exception;
  121. _channel.Closed -= Channel_Closed;
  122. _channel.Close();
  123. _channel.Dispose();
  124. _channel = null;
  125. }
  126. }
  127. /// <summary>
  128. /// Sends data to the subsystem.
  129. /// </summary>
  130. /// <param name="data">The data to be sent.</param>
  131. public void SendData(byte[] data)
  132. {
  133. EnsureNotDisposed();
  134. EnsureSessionIsOpen();
  135. _channel.SendData(data);
  136. }
  137. /// <summary>
  138. /// Called when channel is open.
  139. /// </summary>
  140. protected abstract void OnChannelOpen();
  141. /// <summary>
  142. /// Called when data is received.
  143. /// </summary>
  144. /// <param name="data">The data.</param>
  145. protected abstract void OnDataReceived(byte[] data);
  146. /// <summary>
  147. /// Raises the error.
  148. /// </summary>
  149. /// <param name="error">The error.</param>
  150. protected void RaiseError(Exception error)
  151. {
  152. _exception = error;
  153. var errorOccuredWaitHandle = _errorOccuredWaitHandle;
  154. if (errorOccuredWaitHandle != null)
  155. errorOccuredWaitHandle.Set();
  156. SignalErrorOccurred(error);
  157. }
  158. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  159. {
  160. try
  161. {
  162. OnDataReceived(e.Data);
  163. }
  164. catch (Exception ex)
  165. {
  166. RaiseError(ex);
  167. }
  168. }
  169. private void Channel_Exception(object sender, ExceptionEventArgs e)
  170. {
  171. RaiseError(e.Exception);
  172. }
  173. private void Channel_Closed(object sender, ChannelEventArgs e)
  174. {
  175. var channelClosedWaitHandle = _channelClosedWaitHandle;
  176. if (channelClosedWaitHandle != null)
  177. channelClosedWaitHandle.Set();
  178. }
  179. /// <summary>
  180. /// Waits a specified time for a given <see cref="WaitHandle"/> to get signaled.
  181. /// </summary>
  182. /// <param name="waitHandle">The handle to wait for.</param>
  183. /// <param name="operationTimeout">The time to wait for <paramref name="waitHandle"/> to get signaled.</param>
  184. /// <exception cref="SshException">The connection was closed by the server.</exception>
  185. /// <exception cref="SshException">The channel was closed.</exception>
  186. /// <exception cref="SshOperationTimeoutException">The handle did not get signaled within the specified <paramref name="operationTimeout"/>.</exception>
  187. public void WaitOnHandle(WaitHandle waitHandle, TimeSpan operationTimeout)
  188. {
  189. var waitHandles = new[]
  190. {
  191. _errorOccuredWaitHandle,
  192. _sessionDisconnectedWaitHandle,
  193. _channelClosedWaitHandle,
  194. waitHandle
  195. };
  196. switch (WaitHandle.WaitAny(waitHandles, operationTimeout))
  197. {
  198. case 0:
  199. throw _exception;
  200. case 1:
  201. throw new SshException("Connection was closed by the server.");
  202. case 2:
  203. throw new SshException("Channel was closed.");
  204. case WaitHandle.WaitTimeout:
  205. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Operation has timed out."));
  206. }
  207. }
  208. private void Session_Disconnected(object sender, EventArgs e)
  209. {
  210. var sessionDisconnectedWaitHandle = _sessionDisconnectedWaitHandle;
  211. if (sessionDisconnectedWaitHandle != null)
  212. sessionDisconnectedWaitHandle.Set();
  213. SignalDisconnected();
  214. }
  215. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  216. {
  217. RaiseError(e.Exception);
  218. }
  219. private void SignalErrorOccurred(Exception error)
  220. {
  221. var errorOccurred = ErrorOccurred;
  222. if (errorOccurred != null)
  223. {
  224. errorOccurred(this, new ExceptionEventArgs(error));
  225. }
  226. }
  227. private void SignalDisconnected()
  228. {
  229. var disconnected = Disconnected;
  230. if (disconnected != null)
  231. {
  232. disconnected(this, new EventArgs());
  233. }
  234. }
  235. private void EnsureSessionIsOpen()
  236. {
  237. if (!IsOpen)
  238. throw new InvalidOperationException("The session is not open.");
  239. }
  240. #region IDisposable Members
  241. private bool _isDisposed;
  242. /// <summary>
  243. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  244. /// </summary>
  245. public void Dispose()
  246. {
  247. Dispose(true);
  248. GC.SuppressFinalize(this);
  249. }
  250. /// <summary>
  251. /// Releases unmanaged and - optionally - managed resources
  252. /// </summary>
  253. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  254. protected virtual void Dispose(bool disposing)
  255. {
  256. // Check to see if Dispose has already been called.
  257. if (!_isDisposed)
  258. {
  259. if (disposing)
  260. {
  261. Disconnect();
  262. _session = null;
  263. if (_errorOccuredWaitHandle != null)
  264. {
  265. _errorOccuredWaitHandle.Dispose();
  266. _errorOccuredWaitHandle = null;
  267. }
  268. if (_sessionDisconnectedWaitHandle != null)
  269. {
  270. _sessionDisconnectedWaitHandle.Dispose();
  271. _sessionDisconnectedWaitHandle = null;
  272. }
  273. if (_channelClosedWaitHandle != null)
  274. {
  275. _channelClosedWaitHandle.Dispose();
  276. _channelClosedWaitHandle = null;
  277. }
  278. }
  279. _isDisposed = true;
  280. }
  281. }
  282. /// <summary>
  283. /// Finalizes an instance of the <see cref="SubsystemSession" /> class.
  284. /// </summary>
  285. ~SubsystemSession()
  286. {
  287. // Do not re-create Dispose clean-up code here.
  288. // Calling Dispose(false) is optimal in terms of
  289. // readability and maintainability.
  290. Dispose(false);
  291. }
  292. private void EnsureNotDisposed()
  293. {
  294. if (_isDisposed)
  295. throw new ObjectDisposedException(GetType().FullName);
  296. }
  297. #endregion
  298. }
  299. }