BaseClient.cs 15 KB

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