SubsystemSession.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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, IDisposable
  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 subsystem on SSH channel.
  84. /// </summary>
  85. public void Connect()
  86. {
  87. EnsureNotDisposed();
  88. if (IsOpen)
  89. throw new InvalidOperationException("The session is already connected.");
  90. // reset waithandles in case we're reconnecting
  91. _errorOccuredWaitHandle.Reset();
  92. _sessionDisconnectedWaitHandle.Reset();
  93. _sessionDisconnectedWaitHandle.Reset();
  94. _channelClosedWaitHandle.Reset();
  95. _session.ErrorOccured += Session_ErrorOccured;
  96. _session.Disconnected += Session_Disconnected;
  97. _channel = _session.CreateChannelSession();
  98. _channel.DataReceived += Channel_DataReceived;
  99. _channel.Exception += Channel_Exception;
  100. _channel.Closed += Channel_Closed;
  101. _channel.Open();
  102. _channel.SendSubsystemRequest(_subsystemName);
  103. OnChannelOpen();
  104. }
  105. /// <summary>
  106. /// Disconnects subsystem channel.
  107. /// </summary>
  108. public void Disconnect()
  109. {
  110. if (_session != null)
  111. {
  112. _session.ErrorOccured -= Session_ErrorOccured;
  113. _session.Disconnected -= Session_Disconnected;
  114. }
  115. if (_channel != null)
  116. {
  117. _channel.DataReceived -= Channel_DataReceived;
  118. _channel.Exception -= Channel_Exception;
  119. _channel.Closed -= Channel_Closed;
  120. _channel.Close();
  121. _channel.Dispose();
  122. _channel = null;
  123. }
  124. }
  125. /// <summary>
  126. /// Sends data to the subsystem.
  127. /// </summary>
  128. /// <param name="data">The data to be sent.</param>
  129. public void SendData(byte[] data)
  130. {
  131. EnsureNotDisposed();
  132. EnsureSessionIsOpen();
  133. _channel.SendData(data);
  134. }
  135. /// <summary>
  136. /// Called when channel is open.
  137. /// </summary>
  138. protected abstract void OnChannelOpen();
  139. /// <summary>
  140. /// Called when data is received.
  141. /// </summary>
  142. /// <param name="dataTypeCode">The data type code.</param>
  143. /// <param name="data">The data.</param>
  144. protected abstract void OnDataReceived(uint dataTypeCode, byte[] data);
  145. /// <summary>
  146. /// Raises the error.
  147. /// </summary>
  148. /// <param name="error">The error.</param>
  149. protected void RaiseError(Exception error)
  150. {
  151. _exception = error;
  152. var errorOccuredWaitHandle = _errorOccuredWaitHandle;
  153. if (errorOccuredWaitHandle != null)
  154. errorOccuredWaitHandle.Set();
  155. SignalErrorOccurred(error);
  156. }
  157. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  158. {
  159. try
  160. {
  161. OnDataReceived(e.DataTypeCode, e.Data);
  162. }
  163. catch (Exception ex)
  164. {
  165. RaiseError(ex);
  166. }
  167. }
  168. private void Channel_Exception(object sender, ExceptionEventArgs e)
  169. {
  170. RaiseError(e.Exception);
  171. }
  172. private void Channel_Closed(object sender, ChannelEventArgs e)
  173. {
  174. var channelClosedWaitHandle = _channelClosedWaitHandle;
  175. if (channelClosedWaitHandle != null)
  176. channelClosedWaitHandle.Set();
  177. }
  178. internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan operationTimeout)
  179. {
  180. var waitHandles = new[]
  181. {
  182. _errorOccuredWaitHandle,
  183. _sessionDisconnectedWaitHandle,
  184. _channelClosedWaitHandle,
  185. waitHandle
  186. };
  187. switch (WaitHandle.WaitAny(waitHandles, operationTimeout))
  188. {
  189. case 0:
  190. throw _exception;
  191. case 1:
  192. throw new SshException("Connection was closed by the server.");
  193. case 2:
  194. throw new SshException("Channel was closed.");
  195. case WaitHandle.WaitTimeout:
  196. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Operation has timed out."));
  197. }
  198. }
  199. private void Session_Disconnected(object sender, EventArgs e)
  200. {
  201. var sessionDisconnectedWaitHandle = _sessionDisconnectedWaitHandle;
  202. if (sessionDisconnectedWaitHandle != null)
  203. sessionDisconnectedWaitHandle.Set();
  204. SignalDisconnected();
  205. }
  206. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  207. {
  208. RaiseError(e.Exception);
  209. }
  210. private void SignalErrorOccurred(Exception error)
  211. {
  212. var errorOccurred = ErrorOccurred;
  213. if (errorOccurred != null)
  214. {
  215. errorOccurred(this, new ExceptionEventArgs(error));
  216. }
  217. }
  218. private void SignalDisconnected()
  219. {
  220. var disconnected = Disconnected;
  221. if (disconnected != null)
  222. {
  223. disconnected(this, new EventArgs());
  224. }
  225. }
  226. private void EnsureSessionIsOpen()
  227. {
  228. if (!IsOpen)
  229. throw new InvalidOperationException("The session is not open.");
  230. }
  231. #region IDisposable Members
  232. private bool _isDisposed;
  233. /// <summary>
  234. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  235. /// </summary>
  236. public void Dispose()
  237. {
  238. Dispose(true);
  239. GC.SuppressFinalize(this);
  240. }
  241. /// <summary>
  242. /// Releases unmanaged and - optionally - managed resources
  243. /// </summary>
  244. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  245. protected virtual void Dispose(bool disposing)
  246. {
  247. // Check to see if Dispose has already been called.
  248. if (!_isDisposed)
  249. {
  250. if (disposing)
  251. {
  252. Disconnect();
  253. _session = null;
  254. if (_errorOccuredWaitHandle != null)
  255. {
  256. _errorOccuredWaitHandle.Dispose();
  257. _errorOccuredWaitHandle = null;
  258. }
  259. if (_sessionDisconnectedWaitHandle != null)
  260. {
  261. _sessionDisconnectedWaitHandle.Dispose();
  262. _sessionDisconnectedWaitHandle = null;
  263. }
  264. if (_channelClosedWaitHandle != null)
  265. {
  266. _channelClosedWaitHandle.Dispose();
  267. _channelClosedWaitHandle = null;
  268. }
  269. }
  270. _isDisposed = true;
  271. }
  272. }
  273. /// <summary>
  274. /// Finalizes an instance of the <see cref="SubsystemSession" /> class.
  275. /// </summary>
  276. ~SubsystemSession()
  277. {
  278. // Do not re-create Dispose clean-up code here.
  279. // Calling Dispose(false) is optimal in terms of
  280. // readability and maintainability.
  281. Dispose(false);
  282. }
  283. private void EnsureNotDisposed()
  284. {
  285. if (_isDisposed)
  286. throw new ObjectDisposedException(GetType().FullName);
  287. }
  288. #endregion
  289. }
  290. }