SubsystemSession.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. /// <summary>
  27. /// Specifies a timeout to wait for operation to complete
  28. /// </summary>
  29. protected TimeSpan _operationTimeout;
  30. /// <summary>
  31. /// Occurs when an error occurred.
  32. /// </summary>
  33. public event EventHandler<ExceptionEventArgs> ErrorOccurred;
  34. /// <summary>
  35. /// Gets the channel number.
  36. /// </summary>
  37. protected uint ChannelNumber
  38. {
  39. get
  40. {
  41. return this._channel.RemoteChannelNumber;
  42. }
  43. }
  44. /// <summary>
  45. /// Initializes a new instance of the SubsystemSession class.
  46. /// </summary>
  47. /// <exception cref="ArgumentNullException"><paramref name="session"/> or <paramref name="subsystemName"/> is null.</exception>
  48. public SubsystemSession(Session session, string subsystemName, TimeSpan operationTimeout)
  49. {
  50. if (session == null)
  51. throw new ArgumentNullException("session");
  52. if (subsystemName == null)
  53. throw new ArgumentNullException("subsystemName");
  54. this._session = session;
  55. this._subsystemName = subsystemName;
  56. this._operationTimeout = operationTimeout;
  57. }
  58. /// <summary>
  59. /// Connects subsystem on SSH channel.
  60. /// </summary>
  61. public void Connect()
  62. {
  63. this._channel = this._session.CreateChannel<ChannelSession>();
  64. this._session.ErrorOccured += Session_ErrorOccured;
  65. this._session.Disconnected += Session_Disconnected;
  66. this._channel.DataReceived += Channel_DataReceived;
  67. this._channel.Open();
  68. this._channel.SendSubsystemRequest(_subsystemName);
  69. this.OnChannelOpen();
  70. }
  71. /// <summary>
  72. /// Disconnects subsystem channel.
  73. /// </summary>
  74. public void Disconnect()
  75. {
  76. this._channel.SendEof();
  77. this._channel.Close();
  78. }
  79. /// <summary>
  80. /// Sends data to the subsystem.
  81. /// </summary>
  82. /// <param name="message">The message.</param>
  83. public void SendData(ChannelDataMessage message)
  84. {
  85. this._session.SendMessage(message);
  86. }
  87. /// <summary>
  88. /// Called when channel is open.
  89. /// </summary>
  90. protected abstract void OnChannelOpen();
  91. /// <summary>
  92. /// Called when data is received.
  93. /// </summary>
  94. /// <param name="dataTypeCode">The data type code.</param>
  95. /// <param name="data">The data.</param>
  96. protected abstract void OnDataReceived(uint dataTypeCode, byte[] data);
  97. /// <summary>
  98. /// Raises the error.
  99. /// </summary>
  100. /// <param name="error">The error.</param>
  101. protected void RaiseError(Exception error)
  102. {
  103. this._exception = error;
  104. this._errorOccuredWaitHandle.Set();
  105. if (this.ErrorOccurred != null)
  106. {
  107. this.ErrorOccurred(this, new ExceptionEventArgs(error));
  108. }
  109. }
  110. private void Channel_DataReceived(object sender, Common.ChannelDataEventArgs e)
  111. {
  112. this.OnDataReceived(e.DataTypeCode, e.Data);
  113. }
  114. internal void WaitHandle(WaitHandle waitHandle, TimeSpan operationTimeout)
  115. {
  116. var waitHandles = new WaitHandle[]
  117. {
  118. this._errorOccuredWaitHandle,
  119. waitHandle,
  120. };
  121. var index = EventWaitHandle.WaitAny(waitHandles, operationTimeout);
  122. if (index < 1)
  123. {
  124. throw this._exception;
  125. }
  126. else if (index > 1)
  127. {
  128. // throw time out error
  129. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Sftp operation has timed out."));
  130. }
  131. }
  132. private void Session_Disconnected(object sender, EventArgs e)
  133. {
  134. this.RaiseError(new SshException("Connection was lost"));
  135. }
  136. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  137. {
  138. this.RaiseError(e.Exception);
  139. }
  140. #region IDisposable Members
  141. private bool _isDisposed = false;
  142. /// <summary>
  143. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  144. /// </summary>
  145. public void Dispose()
  146. {
  147. Dispose(true);
  148. GC.SuppressFinalize(this);
  149. }
  150. /// <summary>
  151. /// Releases unmanaged and - optionally - managed resources
  152. /// </summary>
  153. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  154. protected virtual void Dispose(bool disposing)
  155. {
  156. // Check to see if Dispose has already been called.
  157. if (!this._isDisposed)
  158. {
  159. if (this._channel != null)
  160. {
  161. this._channel.DataReceived -= Channel_DataReceived;
  162. this._channel.Dispose();
  163. this._channel = null;
  164. }
  165. this._session.ErrorOccured -= Session_ErrorOccured;
  166. this._session.Disconnected -= Session_Disconnected;
  167. // If disposing equals true, dispose all managed
  168. // and unmanaged resources.
  169. if (disposing)
  170. {
  171. // Dispose managed resources.
  172. if (this._errorOccuredWaitHandle != null)
  173. {
  174. this._errorOccuredWaitHandle.Dispose();
  175. this._errorOccuredWaitHandle = null;
  176. }
  177. }
  178. // Note disposing has been done.
  179. _isDisposed = true;
  180. }
  181. }
  182. /// <summary>
  183. /// Releases unmanaged resources and performs other cleanup operations before the
  184. /// <see cref="SftpSession"/> is reclaimed by garbage collection.
  185. /// </summary>
  186. ~SubsystemSession()
  187. {
  188. // Do not re-create Dispose clean-up code here.
  189. // Calling Dispose(false) is optimal in terms of
  190. // readability and maintainability.
  191. Dispose(false);
  192. }
  193. #endregion
  194. }
  195. }