SubsystemSession.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 <c>null</c>.</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. UnsubscribeFromSessionEvents(_session);
  113. var channel = _channel;
  114. if (channel != null)
  115. {
  116. channel.DataReceived -= Channel_DataReceived;
  117. channel.Exception -= Channel_Exception;
  118. channel.Closed -= Channel_Closed;
  119. channel.Close();
  120. channel.Dispose();
  121. _channel = null;
  122. }
  123. }
  124. /// <summary>
  125. /// Sends data to the subsystem.
  126. /// </summary>
  127. /// <param name="data">The data to be sent.</param>
  128. public void SendData(byte[] data)
  129. {
  130. EnsureNotDisposed();
  131. EnsureSessionIsOpen();
  132. _channel.SendData(data);
  133. }
  134. /// <summary>
  135. /// Called when channel is open.
  136. /// </summary>
  137. protected abstract void OnChannelOpen();
  138. /// <summary>
  139. /// Called when data is received.
  140. /// </summary>
  141. /// <param name="data">The data.</param>
  142. protected abstract void OnDataReceived(byte[] data);
  143. /// <summary>
  144. /// Raises the error.
  145. /// </summary>
  146. /// <param name="error">The error.</param>
  147. protected void RaiseError(Exception error)
  148. {
  149. _exception = error;
  150. var errorOccuredWaitHandle = _errorOccuredWaitHandle;
  151. if (errorOccuredWaitHandle != null)
  152. errorOccuredWaitHandle.Set();
  153. SignalErrorOccurred(error);
  154. }
  155. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  156. {
  157. try
  158. {
  159. OnDataReceived(e.Data);
  160. }
  161. catch (Exception ex)
  162. {
  163. RaiseError(ex);
  164. }
  165. }
  166. private void Channel_Exception(object sender, ExceptionEventArgs e)
  167. {
  168. RaiseError(e.Exception);
  169. }
  170. private void Channel_Closed(object sender, ChannelEventArgs e)
  171. {
  172. var channelClosedWaitHandle = _channelClosedWaitHandle;
  173. if (channelClosedWaitHandle != null)
  174. channelClosedWaitHandle.Set();
  175. }
  176. /// <summary>
  177. /// Waits a specified time for a given <see cref="WaitHandle"/> to get signaled.
  178. /// </summary>
  179. /// <param name="waitHandle">The handle to wait for.</param>
  180. /// <param name="operationTimeout">The time to wait for <paramref name="waitHandle"/> to get signaled.</param>
  181. /// <exception cref="SshException">The connection was closed by the server.</exception>
  182. /// <exception cref="SshException">The channel was closed.</exception>
  183. /// <exception cref="SshOperationTimeoutException">The handle did not get signaled within the specified <paramref name="operationTimeout"/>.</exception>
  184. public void WaitOnHandle(WaitHandle waitHandle, TimeSpan operationTimeout)
  185. {
  186. var waitHandles = new[]
  187. {
  188. _errorOccuredWaitHandle,
  189. _sessionDisconnectedWaitHandle,
  190. _channelClosedWaitHandle,
  191. waitHandle
  192. };
  193. switch (WaitHandle.WaitAny(waitHandles, operationTimeout))
  194. {
  195. case 0:
  196. throw _exception;
  197. case 1:
  198. throw new SshException("Connection was closed by the server.");
  199. case 2:
  200. throw new SshException("Channel was closed.");
  201. case WaitHandle.WaitTimeout:
  202. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Operation has timed out."));
  203. }
  204. }
  205. private void Session_Disconnected(object sender, EventArgs e)
  206. {
  207. var sessionDisconnectedWaitHandle = _sessionDisconnectedWaitHandle;
  208. if (sessionDisconnectedWaitHandle != null)
  209. sessionDisconnectedWaitHandle.Set();
  210. SignalDisconnected();
  211. }
  212. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  213. {
  214. RaiseError(e.Exception);
  215. }
  216. private void SignalErrorOccurred(Exception error)
  217. {
  218. var errorOccurred = ErrorOccurred;
  219. if (errorOccurred != null)
  220. {
  221. errorOccurred(this, new ExceptionEventArgs(error));
  222. }
  223. }
  224. private void SignalDisconnected()
  225. {
  226. var disconnected = Disconnected;
  227. if (disconnected != null)
  228. {
  229. disconnected(this, new EventArgs());
  230. }
  231. }
  232. private void EnsureSessionIsOpen()
  233. {
  234. if (!IsOpen)
  235. throw new InvalidOperationException("The session is not open.");
  236. }
  237. /// <summary>
  238. /// Unsubscribes the current <see cref="SubsystemSession"/> from session events.
  239. /// </summary>
  240. /// <param name="session">The session.</param>
  241. /// <remarks>
  242. /// Does nothing when <paramref name="session"/> is <c>null</c>.
  243. /// </remarks>
  244. private void UnsubscribeFromSessionEvents(ISession session)
  245. {
  246. if (session == null)
  247. return;
  248. session.Disconnected -= Session_Disconnected;
  249. session.ErrorOccured -= Session_ErrorOccured;
  250. }
  251. #region IDisposable Members
  252. private bool _isDisposed;
  253. /// <summary>
  254. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  255. /// </summary>
  256. public void Dispose()
  257. {
  258. Dispose(true);
  259. GC.SuppressFinalize(this);
  260. }
  261. /// <summary>
  262. /// Releases unmanaged and - optionally - managed resources
  263. /// </summary>
  264. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  265. protected virtual void Dispose(bool disposing)
  266. {
  267. if (_isDisposed)
  268. return;
  269. if (disposing)
  270. {
  271. Disconnect();
  272. _session = null;
  273. var errorOccuredWaitHandle = _errorOccuredWaitHandle;
  274. if (errorOccuredWaitHandle != null)
  275. {
  276. errorOccuredWaitHandle.Dispose();
  277. _errorOccuredWaitHandle = null;
  278. }
  279. var sessionDisconnectedWaitHandle = _sessionDisconnectedWaitHandle;
  280. if (sessionDisconnectedWaitHandle != null)
  281. {
  282. sessionDisconnectedWaitHandle.Dispose();
  283. _sessionDisconnectedWaitHandle = null;
  284. }
  285. var channelClosedWaitHandle = _channelClosedWaitHandle;
  286. if (channelClosedWaitHandle != null)
  287. {
  288. channelClosedWaitHandle.Dispose();
  289. _channelClosedWaitHandle = null;
  290. }
  291. _isDisposed = true;
  292. }
  293. }
  294. /// <summary>
  295. /// Finalizes an instance of the <see cref="SubsystemSession" /> class.
  296. /// </summary>
  297. ~SubsystemSession()
  298. {
  299. Dispose(false);
  300. }
  301. private void EnsureNotDisposed()
  302. {
  303. if (_isDisposed)
  304. throw new ObjectDisposedException(GetType().FullName);
  305. }
  306. #endregion
  307. }
  308. }