BaseClient.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. using System;
  2. using System.Net.Sockets;
  3. using System.Threading;
  4. using Renci.SshNet.Common;
  5. namespace Renci.SshNet
  6. {
  7. /// <summary>
  8. /// Serves as base class for client implementations, provides common client functionality.
  9. /// </summary>
  10. public abstract class BaseClient : IDisposable
  11. {
  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 == Session.InfiniteTimeSpan)
  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 = Session.InfiniteTimeSpan;
  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. /// <exception cref="SocketException">Socket connection to the SSH server or proxy server could not be established, or an error occurred while resolving the hostname.</exception>
  133. /// <exception cref="SshConnectionException">SSH session could not be established.</exception>
  134. /// <exception cref="SshAuthenticationException">Authentication of SSH session failed.</exception>
  135. /// <exception cref="ProxyException">Failed to establish proxy connection.</exception>
  136. public void Connect()
  137. {
  138. CheckDisposed();
  139. // TODO (see issue #1758):
  140. // we're not stopping the keep-alive timer and disposing the session here
  141. //
  142. // we could do this but there would still be side effects as concrete
  143. // implementations may still hang on to the original session
  144. //
  145. // therefore it would be better to actually invoke the Disconnect method
  146. // (and then the Dispose on the session) but even that would have side effects
  147. // eg. it would remove all forwarded ports from SshClient
  148. //
  149. // I think we should modify our concrete clients to better deal with a
  150. // disconnect. In case of SshClient this would mean not removing the
  151. // forwarded ports on disconnect (but only on dispose ?) and link a
  152. // forwarded port with a client instead of with a session
  153. //
  154. // To be discussed with Oleg (or whoever is interested)
  155. if (Session != null && Session.IsConnected)
  156. throw new InvalidOperationException("The client is already connected.");
  157. OnConnecting();
  158. Session = new Session(ConnectionInfo);
  159. Session.HostKeyReceived += Session_HostKeyReceived;
  160. Session.ErrorOccured += Session_ErrorOccured;
  161. Session.Connect();
  162. StartKeepAliveTimer();
  163. OnConnected();
  164. }
  165. /// <summary>
  166. /// Disconnects client from the server.
  167. /// </summary>
  168. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  169. public void Disconnect()
  170. {
  171. CheckDisposed();
  172. OnDisconnecting();
  173. StopKeepAliveTimer();
  174. if (Session != null)
  175. Session.Disconnect();
  176. OnDisconnected();
  177. }
  178. /// <summary>
  179. /// Sends keep-alive message to the server.
  180. /// </summary>
  181. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  182. public void SendKeepAlive()
  183. {
  184. CheckDisposed();
  185. if (Session != null && Session.IsConnected)
  186. Session.SendKeepAlive();
  187. }
  188. /// <summary>
  189. /// Called when client is connecting to the server.
  190. /// </summary>
  191. protected virtual void OnConnecting()
  192. {
  193. }
  194. /// <summary>
  195. /// Called when client is connected to the server.
  196. /// </summary>
  197. protected virtual void OnConnected()
  198. {
  199. }
  200. /// <summary>
  201. /// Called when client is disconnecting from the server.
  202. /// </summary>
  203. protected virtual void OnDisconnecting()
  204. {
  205. if (Session != null)
  206. Session.OnDisconnecting();
  207. }
  208. /// <summary>
  209. /// Called when client is disconnected from the server.
  210. /// </summary>
  211. protected virtual void OnDisconnected()
  212. {
  213. }
  214. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  215. {
  216. var handler = this.ErrorOccurred;
  217. if (handler != null)
  218. {
  219. handler(this, e);
  220. }
  221. }
  222. private void Session_HostKeyReceived(object sender, HostKeyEventArgs e)
  223. {
  224. var handler = this.HostKeyReceived;
  225. if (handler != null)
  226. {
  227. handler(this, e);
  228. }
  229. }
  230. #region IDisposable Members
  231. private bool _isDisposed;
  232. /// <summary>
  233. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  234. /// </summary>
  235. public void Dispose()
  236. {
  237. Dispose(true);
  238. GC.SuppressFinalize(this);
  239. }
  240. /// <summary>
  241. /// Releases unmanaged and - optionally - managed resources
  242. /// </summary>
  243. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  244. protected virtual void Dispose(bool disposing)
  245. {
  246. // Check to see if Dispose has already been called.
  247. if (!this._isDisposed)
  248. {
  249. // If disposing equals true, dispose all managed
  250. // and unmanaged ResourceMessages.
  251. if (disposing)
  252. {
  253. // stop sending keep-alive messages before we close the
  254. // session
  255. StopKeepAliveTimer();
  256. if (this.Session != null)
  257. {
  258. this.Session.ErrorOccured -= Session_ErrorOccured;
  259. this.Session.HostKeyReceived -= Session_HostKeyReceived;
  260. this.Session.Dispose();
  261. this.Session = null;
  262. }
  263. if (_ownsConnectionInfo && _connectionInfo != null)
  264. {
  265. var connectionInfoDisposable = _connectionInfo as IDisposable;
  266. if (connectionInfoDisposable != null)
  267. connectionInfoDisposable.Dispose();
  268. _connectionInfo = null;
  269. }
  270. }
  271. // Note disposing has been done.
  272. _isDisposed = true;
  273. }
  274. }
  275. /// <summary>
  276. /// Check if the current instance is disposed.
  277. /// </summary>
  278. /// <exception cref="ObjectDisposedException">THe current instance is disposed.</exception>
  279. protected void CheckDisposed()
  280. {
  281. if (_isDisposed)
  282. throw new ObjectDisposedException(GetType().FullName);
  283. }
  284. /// <summary>
  285. /// Releases unmanaged resources and performs other cleanup operations before the
  286. /// <see cref="BaseClient"/> is reclaimed by garbage collection.
  287. /// </summary>
  288. ~BaseClient()
  289. {
  290. // Do not re-create Dispose clean-up code here.
  291. // Calling Dispose(false) is optimal in terms of
  292. // readability and maintainability.
  293. Dispose(false);
  294. }
  295. #endregion
  296. /// <summary>
  297. /// Stops the keep-alive timer, and waits until all timer callbacks have been
  298. /// executed.
  299. /// </summary>
  300. private void StopKeepAliveTimer()
  301. {
  302. if (_keepAliveTimer == null)
  303. return;
  304. var timerDisposed = new ManualResetEvent(false);
  305. _keepAliveTimer.Dispose(timerDisposed);
  306. timerDisposed.WaitOne();
  307. timerDisposed.Dispose();
  308. _keepAliveTimer = null;
  309. }
  310. /// <summary>
  311. /// Starts the keep-alive timer.
  312. /// </summary>
  313. /// <remarks>
  314. /// When <see cref="KeepAliveInterval"/> is negative one (-1) milliseconds, then
  315. /// the timer will not be started.
  316. /// </remarks>
  317. private void StartKeepAliveTimer()
  318. {
  319. if (_keepAliveInterval == Session.InfiniteTimeSpan)
  320. return;
  321. if (_keepAliveTimer == null)
  322. _keepAliveTimer = new Timer(state => this.SendKeepAlive());
  323. _keepAliveTimer.Change(_keepAliveInterval, _keepAliveInterval);
  324. }
  325. }
  326. }