BaseClient.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. using System;
  2. using System.Threading;
  3. using Renci.SshNet.Common;
  4. namespace Renci.SshNet
  5. {
  6. /// <summary>
  7. /// Serves as base class for client implementations, provides common client functionality.
  8. /// </summary>
  9. public abstract class BaseClient : IDisposable
  10. {
  11. private static readonly TimeSpan Infinite = new TimeSpan(0, 0, 0, 0, -1);
  12. /// <summary>
  13. /// Holds value indicating whether the connection info is owned by this client.
  14. /// </summary>
  15. private readonly bool _ownsConnectionInfo;
  16. private TimeSpan _keepAliveInterval;
  17. private Timer _keepAliveTimer;
  18. private ConnectionInfo _connectionInfo;
  19. /// <summary>
  20. /// Gets current session.
  21. /// </summary>
  22. protected Session Session { get; private set; }
  23. /// <summary>
  24. /// Gets the connection info.
  25. /// </summary>
  26. /// <value>
  27. /// The connection info.
  28. /// </value>
  29. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  30. public ConnectionInfo ConnectionInfo
  31. {
  32. get
  33. {
  34. CheckDisposed();
  35. return _connectionInfo;
  36. }
  37. private set
  38. {
  39. _connectionInfo = value;
  40. }
  41. }
  42. /// <summary>
  43. /// Gets a value indicating whether this client is connected to the server.
  44. /// </summary>
  45. /// <value>
  46. /// <c>true</c> if this client is connected; otherwise, <c>false</c>.
  47. /// </value>
  48. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  49. public bool IsConnected
  50. {
  51. get
  52. {
  53. CheckDisposed();
  54. return this.Session != null && this.Session.IsConnected;
  55. }
  56. }
  57. /// <summary>
  58. /// Gets or sets the keep-alive interval.
  59. /// </summary>
  60. /// <value>
  61. /// The keep-alive interval. Specify negative one (-1) milliseconds to disable the
  62. /// keep-alive. This is the default value.
  63. /// </value>
  64. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  65. public TimeSpan KeepAliveInterval
  66. {
  67. get
  68. {
  69. CheckDisposed();
  70. return this._keepAliveInterval;
  71. }
  72. set
  73. {
  74. CheckDisposed();
  75. if (value == _keepAliveInterval)
  76. return;
  77. if (value == Infinite)
  78. {
  79. // stop the timer when the value is -1 milliseconds
  80. StopKeepAliveTimer();
  81. }
  82. else
  83. {
  84. // change the due time and interval of the timer if has already
  85. // been created (which means the client is connected)
  86. //
  87. // if the client is not yet connected, then the timer will be
  88. // created with the new interval when Connect() is invoked
  89. if (_keepAliveTimer != null)
  90. _keepAliveTimer.Change(value, value);
  91. }
  92. this._keepAliveInterval = value;
  93. }
  94. }
  95. /// <summary>
  96. /// Occurs when an error occurred.
  97. /// </summary>
  98. /// <example>
  99. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient Connect ErrorOccurred" language="C#" title="Handle ErrorOccurred event" />
  100. /// </example>
  101. public event EventHandler<ExceptionEventArgs> ErrorOccurred;
  102. /// <summary>
  103. /// Occurs when host key received.
  104. /// </summary>
  105. /// <example>
  106. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient Connect HostKeyReceived" language="C#" title="Handle HostKeyReceived event" />
  107. /// </example>
  108. public event EventHandler<HostKeyEventArgs> HostKeyReceived;
  109. /// <summary>
  110. /// Initializes a new instance of the <see cref="BaseClient"/> class.
  111. /// </summary>
  112. /// <param name="connectionInfo">The connection info.</param>
  113. /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
  114. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
  115. /// <remarks>
  116. /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
  117. /// connection info will be disposed when this instance is disposed.
  118. /// </remarks>
  119. protected BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
  120. {
  121. if (connectionInfo == null)
  122. throw new ArgumentNullException("connectionInfo");
  123. ConnectionInfo = connectionInfo;
  124. _ownsConnectionInfo = ownsConnectionInfo;
  125. _keepAliveInterval = Infinite;
  126. }
  127. /// <summary>
  128. /// Connects client to the server.
  129. /// </summary>
  130. /// <exception cref="InvalidOperationException">The client is already connected.</exception>
  131. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  132. public void Connect()
  133. {
  134. CheckDisposed();
  135. if (Session != null && Session.IsConnected)
  136. throw new InvalidOperationException("The client is already connected.");
  137. OnConnecting();
  138. Session = new Session(ConnectionInfo);
  139. Session.HostKeyReceived += Session_HostKeyReceived;
  140. Session.ErrorOccured += Session_ErrorOccured;
  141. Session.Connect();
  142. StartKeepAliveTimer();
  143. OnConnected();
  144. }
  145. /// <summary>
  146. /// Disconnects client from the server.
  147. /// </summary>
  148. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  149. public void Disconnect()
  150. {
  151. CheckDisposed();
  152. OnDisconnecting();
  153. StopKeepAliveTimer();
  154. if (Session != null)
  155. Session.Disconnect();
  156. OnDisconnected();
  157. }
  158. /// <summary>
  159. /// Sends keep-alive message to the server.
  160. /// </summary>
  161. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  162. public void SendKeepAlive()
  163. {
  164. CheckDisposed();
  165. if (Session != null && Session.IsConnected)
  166. Session.SendKeepAlive();
  167. }
  168. /// <summary>
  169. /// Called when client is connecting to the server.
  170. /// </summary>
  171. protected virtual void OnConnecting()
  172. {
  173. }
  174. /// <summary>
  175. /// Called when client is connected to the server.
  176. /// </summary>
  177. protected virtual void OnConnected()
  178. {
  179. }
  180. /// <summary>
  181. /// Called when client is disconnecting from the server.
  182. /// </summary>
  183. protected virtual void OnDisconnecting()
  184. {
  185. if (Session != null)
  186. Session.OnDisconnecting();
  187. }
  188. /// <summary>
  189. /// Called when client is disconnected from the server.
  190. /// </summary>
  191. protected virtual void OnDisconnected()
  192. {
  193. }
  194. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  195. {
  196. var handler = this.ErrorOccurred;
  197. if (handler != null)
  198. {
  199. handler(this, e);
  200. }
  201. }
  202. private void Session_HostKeyReceived(object sender, HostKeyEventArgs e)
  203. {
  204. var handler = this.HostKeyReceived;
  205. if (handler != null)
  206. {
  207. handler(this, e);
  208. }
  209. }
  210. #region IDisposable Members
  211. private bool _isDisposed;
  212. /// <summary>
  213. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  214. /// </summary>
  215. public void Dispose()
  216. {
  217. Dispose(true);
  218. GC.SuppressFinalize(this);
  219. }
  220. /// <summary>
  221. /// Releases unmanaged and - optionally - managed resources
  222. /// </summary>
  223. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  224. protected virtual void Dispose(bool disposing)
  225. {
  226. // Check to see if Dispose has already been called.
  227. if (!this._isDisposed)
  228. {
  229. // If disposing equals true, dispose all managed
  230. // and unmanaged ResourceMessages.
  231. if (disposing)
  232. {
  233. // stop sending keep-alive messages before we close the
  234. // session
  235. StopKeepAliveTimer();
  236. if (this.Session != null)
  237. {
  238. this.Session.ErrorOccured -= Session_ErrorOccured;
  239. this.Session.HostKeyReceived -= Session_HostKeyReceived;
  240. this.Session.Dispose();
  241. this.Session = null;
  242. }
  243. if (_ownsConnectionInfo && _connectionInfo != null)
  244. {
  245. var connectionInfoDisposable = _connectionInfo as IDisposable;
  246. if (connectionInfoDisposable != null)
  247. connectionInfoDisposable.Dispose();
  248. _connectionInfo = null;
  249. }
  250. }
  251. // Note disposing has been done.
  252. _isDisposed = true;
  253. }
  254. }
  255. /// <summary>
  256. /// Check if the current instance is disposed.
  257. /// </summary>
  258. /// <exception cref="ObjectDisposedException">THe current instance is disposed.</exception>
  259. protected void CheckDisposed()
  260. {
  261. if (_isDisposed)
  262. throw new ObjectDisposedException(GetType().FullName);
  263. }
  264. /// <summary>
  265. /// Releases unmanaged resources and performs other cleanup operations before the
  266. /// <see cref="BaseClient"/> is reclaimed by garbage collection.
  267. /// </summary>
  268. ~BaseClient()
  269. {
  270. // Do not re-create Dispose clean-up code here.
  271. // Calling Dispose(false) is optimal in terms of
  272. // readability and maintainability.
  273. Dispose(false);
  274. }
  275. #endregion
  276. /// <summary>
  277. /// Stops the keep-alive timer, and waits until all timer callbacks have been
  278. /// executed.
  279. /// </summary>
  280. private void StopKeepAliveTimer()
  281. {
  282. if (_keepAliveTimer == null)
  283. return;
  284. var timerDisposed = new ManualResetEvent(false);
  285. _keepAliveTimer.Dispose(timerDisposed);
  286. timerDisposed.WaitOne();
  287. timerDisposed.Dispose();
  288. _keepAliveTimer = null;
  289. }
  290. /// <summary>
  291. /// Starts the keep-alive timer.
  292. /// </summary>
  293. /// <remarks>
  294. /// When <see cref="KeepAliveInterval"/> is negative one (-1) milliseconds, then
  295. /// the timer will not be started.
  296. /// </remarks>
  297. private void StartKeepAliveTimer()
  298. {
  299. if (_keepAliveInterval == Infinite)
  300. return;
  301. if (_keepAliveTimer == null)
  302. _keepAliveTimer = new Timer(state => this.SendKeepAlive());
  303. _keepAliveTimer.Change(_keepAliveInterval, _keepAliveInterval);
  304. }
  305. }
  306. }