SubsystemSession.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. using System;
  2. using System.Text;
  3. using System.Threading;
  4. using Renci.SshNet.Channels;
  5. using Renci.SshNet.Common;
  6. using System.Globalization;
  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. this._errorOccuredWaitHandle.Set();
  110. if (this.ErrorOccurred != null)
  111. {
  112. this.ErrorOccurred(this, new ExceptionEventArgs(error));
  113. }
  114. }
  115. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  116. {
  117. this.OnDataReceived(e.DataTypeCode, e.Data);
  118. }
  119. private void Channel_Closed(object sender, ChannelEventArgs e)
  120. {
  121. this._channelClosedWaitHandle.Set();
  122. }
  123. internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan operationTimeout)
  124. {
  125. var waitHandles = new[]
  126. {
  127. this._errorOccuredWaitHandle,
  128. this._channelClosedWaitHandle,
  129. waitHandle
  130. };
  131. switch (WaitHandle.WaitAny(waitHandles, operationTimeout))
  132. {
  133. case 0:
  134. throw this._exception;
  135. case 1:
  136. throw new SshException("Channel was closed.");
  137. case WaitHandle.WaitTimeout:
  138. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Operation has timed out."));
  139. }
  140. }
  141. private void Session_Disconnected(object sender, EventArgs e)
  142. {
  143. if (this.Disconnected != null)
  144. {
  145. this.Disconnected(this, new EventArgs());
  146. }
  147. this.RaiseError(new SshException("Connection was lost"));
  148. }
  149. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  150. {
  151. this.RaiseError(e.Exception);
  152. }
  153. #region IDisposable Members
  154. private bool _isDisposed;
  155. /// <summary>
  156. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  157. /// </summary>
  158. public void Dispose()
  159. {
  160. Dispose(true);
  161. GC.SuppressFinalize(this);
  162. }
  163. /// <summary>
  164. /// Releases unmanaged and - optionally - managed resources
  165. /// </summary>
  166. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  167. protected virtual void Dispose(bool disposing)
  168. {
  169. // Check to see if Dispose has already been called.
  170. if (!this._isDisposed)
  171. {
  172. if (this._channel != null)
  173. {
  174. this._channel.DataReceived -= Channel_DataReceived;
  175. this._channel.Dispose();
  176. this._channel = null;
  177. }
  178. this._session.ErrorOccured -= Session_ErrorOccured;
  179. this._session.Disconnected -= Session_Disconnected;
  180. // If disposing equals true, dispose all managed
  181. // and unmanaged resources.
  182. if (disposing)
  183. {
  184. // Dispose managed resources.
  185. if (this._errorOccuredWaitHandle != null)
  186. {
  187. this._errorOccuredWaitHandle.Dispose();
  188. this._errorOccuredWaitHandle = null;
  189. }
  190. if (this._channelClosedWaitHandle != null)
  191. {
  192. this._channelClosedWaitHandle.Dispose();
  193. this._channelClosedWaitHandle = null;
  194. }
  195. }
  196. // Note disposing has been done.
  197. _isDisposed = true;
  198. }
  199. }
  200. /// <summary>
  201. /// Finalizes an instance of the <see cref="SubsystemSession" /> class.
  202. /// </summary>
  203. ~SubsystemSession()
  204. {
  205. // Do not re-create Dispose clean-up code here.
  206. // Calling Dispose(false) is optimal in terms of
  207. // readability and maintainability.
  208. Dispose(false);
  209. }
  210. #endregion
  211. }
  212. }