BaseClient.cs 17 KB

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