2
0

SubsystemSession.cs 7.5 KB

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