SubsystemSession.cs 8.6 KB

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