BaseClient.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 readonly IServiceFactory _serviceFactory;
  17. private TimeSpan _keepAliveInterval;
  18. private Timer _keepAliveTimer;
  19. private ConnectionInfo _connectionInfo;
  20. /// <summary>
  21. /// Gets current session.
  22. /// </summary>
  23. internal ISession Session { get; private set; }
  24. /// <summary>
  25. /// Gets the connection info.
  26. /// </summary>
  27. /// <value>
  28. /// The connection info.
  29. /// </value>
  30. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  31. public ConnectionInfo ConnectionInfo
  32. {
  33. get
  34. {
  35. CheckDisposed();
  36. return _connectionInfo;
  37. }
  38. private set
  39. {
  40. _connectionInfo = value;
  41. }
  42. }
  43. /// <summary>
  44. /// Gets a value indicating whether this client is connected to the server.
  45. /// </summary>
  46. /// <value>
  47. /// <c>true</c> if this client is connected; otherwise, <c>false</c>.
  48. /// </value>
  49. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  50. public bool IsConnected
  51. {
  52. get
  53. {
  54. CheckDisposed();
  55. return Session != null && Session.IsConnected;
  56. }
  57. }
  58. /// <summary>
  59. /// Gets or sets the keep-alive interval.
  60. /// </summary>
  61. /// <value>
  62. /// The keep-alive interval. Specify negative one (-1) milliseconds to disable the
  63. /// keep-alive. This is the default value.
  64. /// </value>
  65. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  66. public TimeSpan KeepAliveInterval
  67. {
  68. get
  69. {
  70. CheckDisposed();
  71. return _keepAliveInterval;
  72. }
  73. set
  74. {
  75. CheckDisposed();
  76. if (value == _keepAliveInterval)
  77. return;
  78. if (value == SshNet.Session.InfiniteTimeSpan)
  79. {
  80. // stop the timer when the value is -1 milliseconds
  81. StopKeepAliveTimer();
  82. }
  83. else
  84. {
  85. // change the due time and interval of the timer if has already
  86. // been created (which means the client is connected)
  87. //
  88. // if the client is not yet connected, then the timer will be
  89. // created with the new interval when Connect() is invoked
  90. if (_keepAliveTimer != null)
  91. _keepAliveTimer.Change(value, value);
  92. }
  93. _keepAliveInterval = value;
  94. }
  95. }
  96. /// <summary>
  97. /// Occurs when an error occurred.
  98. /// </summary>
  99. /// <example>
  100. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient Connect ErrorOccurred" language="C#" title="Handle ErrorOccurred event" />
  101. /// </example>
  102. public event EventHandler<ExceptionEventArgs> ErrorOccurred;
  103. /// <summary>
  104. /// Occurs when host key received.
  105. /// </summary>
  106. /// <example>
  107. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient Connect HostKeyReceived" language="C#" title="Handle HostKeyReceived event" />
  108. /// </example>
  109. public event EventHandler<HostKeyEventArgs> HostKeyReceived;
  110. /// <summary>
  111. /// Initializes a new instance of the <see cref="BaseClient"/> class.
  112. /// </summary>
  113. /// <param name="connectionInfo">The connection info.</param>
  114. /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
  115. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
  116. /// <remarks>
  117. /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
  118. /// connection info will be disposed when this instance is disposed.
  119. /// </remarks>
  120. protected BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
  121. : this(connectionInfo, ownsConnectionInfo, new ServiceFactory())
  122. {
  123. }
  124. /// <summary>
  125. /// Initializes a new instance of the <see cref="BaseClient"/> class.
  126. /// </summary>
  127. /// <param name="connectionInfo">The connection info.</param>
  128. /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
  129. /// <param name="serviceFactory">The factory to use for creating new services.</param>
  130. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
  131. /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is null.</exception>
  132. /// <remarks>
  133. /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
  134. /// connection info will be disposed when this instance is disposed.
  135. /// </remarks>
  136. internal BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
  137. {
  138. if (connectionInfo == null)
  139. throw new ArgumentNullException("connectionInfo");
  140. if (serviceFactory == null)
  141. throw new ArgumentNullException("serviceFactory");
  142. ConnectionInfo = connectionInfo;
  143. _ownsConnectionInfo = ownsConnectionInfo;
  144. _serviceFactory = serviceFactory;
  145. _keepAliveInterval = SshNet.Session.InfiniteTimeSpan;
  146. }
  147. /// <summary>
  148. /// Connects client to the server.
  149. /// </summary>
  150. /// <exception cref="InvalidOperationException">The client is already connected.</exception>
  151. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  152. /// <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>
  153. /// <exception cref="SshConnectionException">SSH session could not be established.</exception>
  154. /// <exception cref="SshAuthenticationException">Authentication of SSH session failed.</exception>
  155. /// <exception cref="ProxyException">Failed to establish proxy connection.</exception>
  156. public void Connect()
  157. {
  158. CheckDisposed();
  159. // TODO (see issue #1758):
  160. // we're not stopping the keep-alive timer and disposing the session here
  161. //
  162. // we could do this but there would still be side effects as concrete
  163. // implementations may still hang on to the original session
  164. //
  165. // therefore it would be better to actually invoke the Disconnect method
  166. // (and then the Dispose on the session) but even that would have side effects
  167. // eg. it would remove all forwarded ports from SshClient
  168. //
  169. // I think we should modify our concrete clients to better deal with a
  170. // disconnect. In case of SshClient this would mean not removing the
  171. // forwarded ports on disconnect (but only on dispose ?) and link a
  172. // forwarded port with a client instead of with a session
  173. //
  174. // To be discussed with Oleg (or whoever is interested)
  175. if (Session != null && Session.IsConnected)
  176. throw new InvalidOperationException("The client is already connected.");
  177. OnConnecting();
  178. Session = _serviceFactory.CreateSession(ConnectionInfo);
  179. Session.HostKeyReceived += Session_HostKeyReceived;
  180. Session.ErrorOccured += Session_ErrorOccured;
  181. Session.Connect();
  182. StartKeepAliveTimer();
  183. OnConnected();
  184. }
  185. /// <summary>
  186. /// Disconnects client from the server.
  187. /// </summary>
  188. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  189. public void Disconnect()
  190. {
  191. CheckDisposed();
  192. OnDisconnecting();
  193. StopKeepAliveTimer();
  194. if (Session != null)
  195. Session.Disconnect();
  196. OnDisconnected();
  197. }
  198. /// <summary>
  199. /// Sends keep-alive message to the server.
  200. /// </summary>
  201. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  202. public void SendKeepAlive()
  203. {
  204. CheckDisposed();
  205. if (Session != null && Session.IsConnected)
  206. Session.SendKeepAlive();
  207. }
  208. /// <summary>
  209. /// Called when client is connecting to the server.
  210. /// </summary>
  211. protected virtual void OnConnecting()
  212. {
  213. }
  214. /// <summary>
  215. /// Called when client is connected to the server.
  216. /// </summary>
  217. protected virtual void OnConnected()
  218. {
  219. }
  220. /// <summary>
  221. /// Called when client is disconnecting from the server.
  222. /// </summary>
  223. protected virtual void OnDisconnecting()
  224. {
  225. if (Session != null)
  226. Session.OnDisconnecting();
  227. }
  228. /// <summary>
  229. /// Called when client is disconnected from the server.
  230. /// </summary>
  231. protected virtual void OnDisconnected()
  232. {
  233. }
  234. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  235. {
  236. var handler = ErrorOccurred;
  237. if (handler != null)
  238. {
  239. handler(this, e);
  240. }
  241. }
  242. private void Session_HostKeyReceived(object sender, HostKeyEventArgs e)
  243. {
  244. var handler = HostKeyReceived;
  245. if (handler != null)
  246. {
  247. handler(this, e);
  248. }
  249. }
  250. #region IDisposable Members
  251. private bool _isDisposed;
  252. /// <summary>
  253. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  254. /// </summary>
  255. public void Dispose()
  256. {
  257. Dispose(true);
  258. GC.SuppressFinalize(this);
  259. }
  260. /// <summary>
  261. /// Releases unmanaged and - optionally - managed resources
  262. /// </summary>
  263. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  264. protected virtual void Dispose(bool disposing)
  265. {
  266. // Check to see if Dispose has already been called.
  267. if (!_isDisposed)
  268. {
  269. // If disposing equals true, dispose all managed
  270. // and unmanaged ResourceMessages.
  271. if (disposing)
  272. {
  273. // stop sending keep-alive messages before we close the
  274. // session
  275. StopKeepAliveTimer();
  276. if (Session != null)
  277. {
  278. Session.ErrorOccured -= Session_ErrorOccured;
  279. Session.HostKeyReceived -= Session_HostKeyReceived;
  280. Session.Dispose();
  281. Session = null;
  282. }
  283. if (_ownsConnectionInfo && _connectionInfo != null)
  284. {
  285. var connectionInfoDisposable = _connectionInfo as IDisposable;
  286. if (connectionInfoDisposable != null)
  287. connectionInfoDisposable.Dispose();
  288. _connectionInfo = null;
  289. }
  290. }
  291. // Note disposing has been done.
  292. _isDisposed = true;
  293. }
  294. }
  295. /// <summary>
  296. /// Check if the current instance is disposed.
  297. /// </summary>
  298. /// <exception cref="ObjectDisposedException">THe current instance is disposed.</exception>
  299. protected void CheckDisposed()
  300. {
  301. if (_isDisposed)
  302. throw new ObjectDisposedException(GetType().FullName);
  303. }
  304. /// <summary>
  305. /// Releases unmanaged resources and performs other cleanup operations before the
  306. /// <see cref="BaseClient"/> is reclaimed by garbage collection.
  307. /// </summary>
  308. ~BaseClient()
  309. {
  310. // Do not re-create Dispose clean-up code here.
  311. // Calling Dispose(false) is optimal in terms of
  312. // readability and maintainability.
  313. Dispose(false);
  314. }
  315. #endregion
  316. /// <summary>
  317. /// Stops the keep-alive timer, and waits until all timer callbacks have been
  318. /// executed.
  319. /// </summary>
  320. private void StopKeepAliveTimer()
  321. {
  322. if (_keepAliveTimer == null)
  323. return;
  324. var timerDisposed = new ManualResetEvent(false);
  325. _keepAliveTimer.Dispose(timerDisposed);
  326. timerDisposed.WaitOne();
  327. timerDisposed.Dispose();
  328. _keepAliveTimer = null;
  329. }
  330. /// <summary>
  331. /// Starts the keep-alive timer.
  332. /// </summary>
  333. /// <remarks>
  334. /// When <see cref="KeepAliveInterval"/> is negative one (-1) milliseconds, then
  335. /// the timer will not be started.
  336. /// </remarks>
  337. private void StartKeepAliveTimer()
  338. {
  339. if (_keepAliveInterval == SshNet.Session.InfiniteTimeSpan)
  340. return;
  341. if (_keepAliveTimer == null)
  342. _keepAliveTimer = new Timer(state => SendKeepAlive());
  343. _keepAliveTimer.Change(_keepAliveInterval, _keepAliveInterval);
  344. }
  345. }
  346. }