2
0

SubsystemSession.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. 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. {
  137. var exception = this._exception;
  138. this._exception = null;
  139. throw exception;
  140. }
  141. case 1:
  142. throw new SshException("Channel was closed.");
  143. case System.Threading.WaitHandle.WaitTimeout:
  144. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Operation has timed out."));
  145. default:
  146. break;
  147. }
  148. }
  149. private void Session_Disconnected(object sender, EventArgs e)
  150. {
  151. if (this.Disconnected != null)
  152. {
  153. this.Disconnected(this, new EventArgs());
  154. }
  155. this.RaiseError(new SshException("Connection was lost"));
  156. }
  157. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  158. {
  159. this.RaiseError(e.Exception);
  160. }
  161. #region IDisposable Members
  162. private bool _isDisposed = false;
  163. /// <summary>
  164. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  165. /// </summary>
  166. public void Dispose()
  167. {
  168. Dispose(true);
  169. GC.SuppressFinalize(this);
  170. }
  171. /// <summary>
  172. /// Releases unmanaged and - optionally - managed resources
  173. /// </summary>
  174. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  175. protected virtual void Dispose(bool disposing)
  176. {
  177. // Check to see if Dispose has already been called.
  178. if (!this._isDisposed)
  179. {
  180. if (this._channel != null)
  181. {
  182. this._channel.DataReceived -= Channel_DataReceived;
  183. this._channel.Dispose();
  184. this._channel = null;
  185. }
  186. this._session.ErrorOccured -= Session_ErrorOccured;
  187. this._session.Disconnected -= Session_Disconnected;
  188. // If disposing equals true, dispose all managed
  189. // and unmanaged resources.
  190. if (disposing)
  191. {
  192. // Dispose managed resources.
  193. if (this._errorOccuredWaitHandle != null)
  194. {
  195. this._errorOccuredWaitHandle.Dispose();
  196. this._errorOccuredWaitHandle = null;
  197. }
  198. if (this._channelClosedWaitHandle != null)
  199. {
  200. this._channelClosedWaitHandle.Dispose();
  201. this._channelClosedWaitHandle = null;
  202. }
  203. }
  204. // Note disposing has been done.
  205. _isDisposed = true;
  206. }
  207. }
  208. /// <summary>
  209. /// Finalizes an instance of the <see cref="SubsystemSession" /> class.
  210. /// </summary>
  211. ~SubsystemSession()
  212. {
  213. // Do not re-create Dispose clean-up code here.
  214. // Calling Dispose(false) is optimal in terms of
  215. // readability and maintainability.
  216. Dispose(false);
  217. }
  218. #endregion
  219. }
  220. }