SubsystemSession.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using Renci.SshNet.Channels;
  7. using Renci.SshNet.Common;
  8. using System.Diagnostics;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  11. using Renci.SshNet.Sftp.Responses;
  12. using Renci.SshNet.Sftp.Requests;
  13. using Renci.SshNet.Messages.Connection;
  14. namespace Renci.SshNet.Sftp
  15. {
  16. /// <summary>
  17. /// Base class for SSH subsystem implementations
  18. /// </summary>
  19. public abstract class SubsystemSession : IDisposable
  20. {
  21. private Session _session;
  22. private string _subsystemName;
  23. private ChannelSession _channel;
  24. private Exception _exception;
  25. private EventWaitHandle _errorOccuredWaitHandle = new AutoResetEvent(false);
  26. private EventWaitHandle _channelClosedWaitHandle = new AutoResetEvent(false);
  27. /// <summary>
  28. /// Specifies a timeout to wait for operation to complete
  29. /// </summary>
  30. protected TimeSpan _operationTimeout;
  31. /// <summary>
  32. /// Occurs when an error occurred.
  33. /// </summary>
  34. public event EventHandler<ExceptionEventArgs> ErrorOccurred;
  35. /// <summary>
  36. /// Occurs when session has been disconnected form the server.
  37. /// </summary>
  38. public event EventHandler<EventArgs> Disconnected;
  39. /// <summary>
  40. /// Gets the channel number.
  41. /// </summary>
  42. protected uint ChannelNumber { get; private set; }
  43. /// <summary>
  44. /// Initializes a new instance of the SubsystemSession class.
  45. /// </summary>
  46. /// <param name="session">The session.</param>
  47. /// <param name="subsystemName">Name of the subsystem.</param>
  48. /// <param name="operationTimeout">The operation timeout.</param>
  49. /// <exception cref="System.ArgumentNullException">session</exception>
  50. /// <exception cref="ArgumentNullException"><paramref name="session" /> or <paramref name="subsystemName" /> is null.</exception>
  51. public SubsystemSession(Session session, string subsystemName, TimeSpan operationTimeout)
  52. {
  53. if (session == null)
  54. throw new ArgumentNullException("session");
  55. if (subsystemName == null)
  56. throw new ArgumentNullException("subsystemName");
  57. this._session = session;
  58. this._subsystemName = subsystemName;
  59. this._operationTimeout = operationTimeout;
  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, Common.ChannelDataEventArgs e)
  116. {
  117. this.OnDataReceived(e.DataTypeCode, e.Data);
  118. }
  119. private void Channel_Closed(object sender, Common.ChannelEventArgs e)
  120. {
  121. this._channelClosedWaitHandle.Set();
  122. }
  123. internal void WaitHandle(WaitHandle waitHandle, TimeSpan operationTimeout)
  124. {
  125. var waitHandles = new WaitHandle[]
  126. {
  127. this._errorOccuredWaitHandle,
  128. this._channelClosedWaitHandle,
  129. waitHandle,
  130. };
  131. switch (EventWaitHandle.WaitAny(waitHandles, operationTimeout))
  132. {
  133. case 0:
  134. throw this._exception;
  135. case 1:
  136. throw new SshException("Channel was closed.");
  137. case System.Threading.WaitHandle.WaitTimeout:
  138. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Operation has timed out."));
  139. default:
  140. break;
  141. }
  142. }
  143. private void Session_Disconnected(object sender, EventArgs e)
  144. {
  145. if (this.Disconnected != null)
  146. {
  147. this.Disconnected(this, new EventArgs());
  148. }
  149. this.RaiseError(new SshException("Connection was lost"));
  150. }
  151. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  152. {
  153. this.RaiseError(e.Exception);
  154. }
  155. #region IDisposable Members
  156. private bool _isDisposed = false;
  157. /// <summary>
  158. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  159. /// </summary>
  160. public void Dispose()
  161. {
  162. Dispose(true);
  163. GC.SuppressFinalize(this);
  164. }
  165. /// <summary>
  166. /// Releases unmanaged and - optionally - managed resources
  167. /// </summary>
  168. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  169. protected virtual void Dispose(bool disposing)
  170. {
  171. // Check to see if Dispose has already been called.
  172. if (!this._isDisposed)
  173. {
  174. if (this._channel != null)
  175. {
  176. this._channel.DataReceived -= Channel_DataReceived;
  177. this._channel.Dispose();
  178. this._channel = null;
  179. }
  180. this._session.ErrorOccured -= Session_ErrorOccured;
  181. this._session.Disconnected -= Session_Disconnected;
  182. // If disposing equals true, dispose all managed
  183. // and unmanaged resources.
  184. if (disposing)
  185. {
  186. // Dispose managed resources.
  187. if (this._errorOccuredWaitHandle != null)
  188. {
  189. this._errorOccuredWaitHandle.Dispose();
  190. this._errorOccuredWaitHandle = null;
  191. }
  192. if (this._channelClosedWaitHandle != null)
  193. {
  194. this._channelClosedWaitHandle.Dispose();
  195. this._channelClosedWaitHandle = null;
  196. }
  197. }
  198. // Note disposing has been done.
  199. _isDisposed = true;
  200. }
  201. }
  202. /// <summary>
  203. /// Finalizes an instance of the <see cref="SubsystemSession" /> class.
  204. /// </summary>
  205. ~SubsystemSession()
  206. {
  207. // Do not re-create Dispose clean-up code here.
  208. // Calling Dispose(false) is optimal in terms of
  209. // readability and maintainability.
  210. Dispose(false);
  211. }
  212. #endregion
  213. }
  214. }