SubsystemSession.cs 9.1 KB

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