SubsystemSession.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. using Renci.SshNet.Messages.Connection;
  8. namespace Renci.SshNet.Sftp
  9. {
  10. /// <summary>
  11. /// Base class for SSH subsystem implementations
  12. /// </summary>
  13. public abstract class SubsystemSession : IDisposable
  14. {
  15. private readonly Session _session;
  16. private readonly string _subsystemName;
  17. private ChannelSession _channel;
  18. private Exception _exception;
  19. private EventWaitHandle _errorOccuredWaitHandle = 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;
  25. /// <summary>
  26. /// Occurs when an error occurred.
  27. /// </summary>
  28. public event EventHandler<ExceptionEventArgs> ErrorOccurred;
  29. /// <summary>
  30. /// Occurs when session has been disconnected form the server.
  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 ChannelSession Channel
  40. {
  41. get { return _channel; }
  42. }
  43. /// <summary>
  44. /// Gets the character encoding to use.
  45. /// </summary>
  46. protected Encoding Encoding { get; private set; }
  47. /// <summary>
  48. /// Initializes a new instance of the SubsystemSession class.
  49. /// </summary>
  50. /// <param name="session">The session.</param>
  51. /// <param name="subsystemName">Name of the subsystem.</param>
  52. /// <param name="operationTimeout">The operation timeout.</param>
  53. /// <param name="encoding">The character encoding to use.</param>
  54. /// <exception cref="ArgumentNullException"><paramref name="session" /> or <paramref name="subsystemName" /> or <paramref name="encoding"/>is null.</exception>
  55. protected SubsystemSession(Session session, string subsystemName, TimeSpan operationTimeout, Encoding encoding)
  56. {
  57. if (session == null)
  58. throw new ArgumentNullException("session");
  59. if (subsystemName == null)
  60. throw new ArgumentNullException("subsystemName");
  61. if (encoding == null)
  62. throw new ArgumentNullException("encoding");
  63. this._session = session;
  64. this._subsystemName = subsystemName;
  65. this._operationTimeout = operationTimeout;
  66. this.Encoding = encoding;
  67. }
  68. /// <summary>
  69. /// Connects subsystem on SSH channel.
  70. /// </summary>
  71. public void Connect()
  72. {
  73. this._channel = this._session.CreateClientChannel<ChannelSession>();
  74. this._session.ErrorOccured += Session_ErrorOccured;
  75. this._session.Disconnected += Session_Disconnected;
  76. this._channel.DataReceived += Channel_DataReceived;
  77. this._channel.Closed += Channel_Closed;
  78. this._channel.Open();
  79. this._channel.SendSubsystemRequest(_subsystemName);
  80. this.OnChannelOpen();
  81. }
  82. /// <summary>
  83. /// Disconnects subsystem channel.
  84. /// </summary>
  85. public void Disconnect()
  86. {
  87. this._channel.SendEof();
  88. this._channel.Close();
  89. }
  90. /// <summary>
  91. /// Sends data to the subsystem.
  92. /// </summary>
  93. /// <param name="data">The data to be sent.</param>
  94. public void SendData(byte[] data)
  95. {
  96. this._channel.SendData(data);
  97. }
  98. /// <summary>
  99. /// Called when channel is open.
  100. /// </summary>
  101. protected abstract void OnChannelOpen();
  102. /// <summary>
  103. /// Called when data is received.
  104. /// </summary>
  105. /// <param name="dataTypeCode">The data type code.</param>
  106. /// <param name="data">The data.</param>
  107. protected abstract void OnDataReceived(uint dataTypeCode, byte[] data);
  108. /// <summary>
  109. /// Raises the error.
  110. /// </summary>
  111. /// <param name="error">The error.</param>
  112. protected void RaiseError(Exception error)
  113. {
  114. this._exception = error;
  115. var errorOccuredWaitHandle = _errorOccuredWaitHandle;
  116. if (errorOccuredWaitHandle != null)
  117. errorOccuredWaitHandle.Set();
  118. SignalErrorOccurred(error);
  119. }
  120. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  121. {
  122. this.OnDataReceived(e.DataTypeCode, e.Data);
  123. }
  124. private void Channel_Closed(object sender, ChannelEventArgs e)
  125. {
  126. var channelClosedWaitHandle = _channelClosedWaitHandle;
  127. if (channelClosedWaitHandle != null)
  128. channelClosedWaitHandle.Set();
  129. }
  130. internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan operationTimeout)
  131. {
  132. var waitHandles = new[]
  133. {
  134. this._errorOccuredWaitHandle,
  135. this._channelClosedWaitHandle,
  136. waitHandle
  137. };
  138. switch (WaitHandle.WaitAny(waitHandles, operationTimeout))
  139. {
  140. case 0:
  141. throw this._exception;
  142. case 1:
  143. throw new SshException("Channel was closed.");
  144. case WaitHandle.WaitTimeout:
  145. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Operation has timed out."));
  146. }
  147. }
  148. private void Session_Disconnected(object sender, EventArgs e)
  149. {
  150. SignalDisconnected();
  151. this.RaiseError(new SshException("Connection was lost"));
  152. }
  153. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  154. {
  155. this.RaiseError(e.Exception);
  156. }
  157. private void SignalErrorOccurred(Exception error)
  158. {
  159. var errorOccurred = ErrorOccurred;
  160. if (errorOccurred != null)
  161. {
  162. errorOccurred(this, new ExceptionEventArgs(error));
  163. }
  164. }
  165. private void SignalDisconnected()
  166. {
  167. var disconnected = Disconnected;
  168. if (disconnected != null)
  169. {
  170. disconnected(this, new EventArgs());
  171. }
  172. }
  173. #region IDisposable Members
  174. private bool _isDisposed;
  175. /// <summary>
  176. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  177. /// </summary>
  178. public void Dispose()
  179. {
  180. Dispose(true);
  181. GC.SuppressFinalize(this);
  182. }
  183. /// <summary>
  184. /// Releases unmanaged and - optionally - managed resources
  185. /// </summary>
  186. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  187. protected virtual void Dispose(bool disposing)
  188. {
  189. // Check to see if Dispose has already been called.
  190. if (!this._isDisposed)
  191. {
  192. if (this._channel != null)
  193. {
  194. this._channel.DataReceived -= Channel_DataReceived;
  195. this._channel.Closed -= Channel_Closed;
  196. this._channel.Dispose();
  197. this._channel = null;
  198. }
  199. this._session.ErrorOccured -= Session_ErrorOccured;
  200. this._session.Disconnected -= Session_Disconnected;
  201. // If disposing equals true, dispose all managed
  202. // and unmanaged resources.
  203. if (disposing)
  204. {
  205. // Dispose managed resources.
  206. if (this._errorOccuredWaitHandle != null)
  207. {
  208. this._errorOccuredWaitHandle.Dispose();
  209. this._errorOccuredWaitHandle = null;
  210. }
  211. if (this._channelClosedWaitHandle != null)
  212. {
  213. this._channelClosedWaitHandle.Dispose();
  214. this._channelClosedWaitHandle = null;
  215. }
  216. }
  217. // Note disposing has been done.
  218. _isDisposed = true;
  219. }
  220. }
  221. /// <summary>
  222. /// Finalizes an instance of the <see cref="SubsystemSession" /> class.
  223. /// </summary>
  224. ~SubsystemSession()
  225. {
  226. // Do not re-create Dispose clean-up code here.
  227. // Calling Dispose(false) is optimal in terms of
  228. // readability and maintainability.
  229. Dispose(false);
  230. }
  231. #endregion
  232. }
  233. }