BaseClient.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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="..\..\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="..\..\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 null.</exception>
  146. /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is null.</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. // only send keep-alive message when we still have a session
  237. if (Session != null)
  238. {
  239. // do not send multiple keep-alive messages concurrently
  240. if (Monitor.TryEnter(_keepAliveLock))
  241. {
  242. try
  243. {
  244. Session.TrySendMessage(new IgnoreMessage());
  245. }
  246. finally
  247. {
  248. Monitor.Exit(_keepAliveLock);
  249. }
  250. }
  251. }
  252. }
  253. /// <summary>
  254. /// Called when client is connecting to the server.
  255. /// </summary>
  256. protected virtual void OnConnecting()
  257. {
  258. }
  259. /// <summary>
  260. /// Called when client is connected to the server.
  261. /// </summary>
  262. protected virtual void OnConnected()
  263. {
  264. }
  265. /// <summary>
  266. /// Called when client is disconnecting from the server.
  267. /// </summary>
  268. protected virtual void OnDisconnecting()
  269. {
  270. if (Session != null)
  271. Session.OnDisconnecting();
  272. }
  273. /// <summary>
  274. /// Called when client is disconnected from the server.
  275. /// </summary>
  276. protected virtual void OnDisconnected()
  277. {
  278. }
  279. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  280. {
  281. var handler = ErrorOccurred;
  282. if (handler != null)
  283. {
  284. handler(this, e);
  285. }
  286. }
  287. private void Session_HostKeyReceived(object sender, HostKeyEventArgs e)
  288. {
  289. var handler = HostKeyReceived;
  290. if (handler != null)
  291. {
  292. handler(this, e);
  293. }
  294. }
  295. #region IDisposable Members
  296. private bool _isDisposed;
  297. /// <summary>
  298. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  299. /// </summary>
  300. public void Dispose()
  301. {
  302. Dispose(true);
  303. GC.SuppressFinalize(this);
  304. }
  305. /// <summary>
  306. /// Releases unmanaged and - optionally - managed resources
  307. /// </summary>
  308. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  309. protected virtual void Dispose(bool disposing)
  310. {
  311. if (!_isDisposed)
  312. {
  313. if (disposing)
  314. {
  315. Disconnect();
  316. if (_ownsConnectionInfo && _connectionInfo != null)
  317. {
  318. var connectionInfoDisposable = _connectionInfo as IDisposable;
  319. if (connectionInfoDisposable != null)
  320. connectionInfoDisposable.Dispose();
  321. _connectionInfo = null;
  322. }
  323. }
  324. _isDisposed = true;
  325. }
  326. }
  327. /// <summary>
  328. /// Check if the current instance is disposed.
  329. /// </summary>
  330. /// <exception cref="ObjectDisposedException">THe current instance is disposed.</exception>
  331. protected void CheckDisposed()
  332. {
  333. if (_isDisposed)
  334. throw new ObjectDisposedException(GetType().FullName);
  335. }
  336. /// <summary>
  337. /// Releases unmanaged resources and performs other cleanup operations before the
  338. /// <see cref="BaseClient"/> is reclaimed by garbage collection.
  339. /// </summary>
  340. ~BaseClient()
  341. {
  342. // Do not re-create Dispose clean-up code here.
  343. // Calling Dispose(false) is optimal in terms of
  344. // readability and maintainability.
  345. Dispose(false);
  346. }
  347. #endregion
  348. /// <summary>
  349. /// Stops the keep-alive timer, and waits until all timer callbacks have been
  350. /// executed.
  351. /// </summary>
  352. private void StopKeepAliveTimer()
  353. {
  354. if (_keepAliveTimer == null)
  355. return;
  356. var timerDisposed = new ManualResetEvent(false);
  357. _keepAliveTimer.Dispose(timerDisposed);
  358. timerDisposed.WaitOne();
  359. timerDisposed.Dispose();
  360. _keepAliveTimer = null;
  361. }
  362. /// <summary>
  363. /// Starts the keep-alive timer.
  364. /// </summary>
  365. /// <remarks>
  366. /// When <see cref="KeepAliveInterval"/> is negative one (-1) milliseconds, then
  367. /// the timer will not be started.
  368. /// </remarks>
  369. private void StartKeepAliveTimer()
  370. {
  371. if (_keepAliveInterval == SshNet.Session.InfiniteTimeSpan)
  372. return;
  373. if (_keepAliveTimer == null)
  374. _keepAliveTimer = new Timer(state => SendKeepAlive());
  375. _keepAliveTimer.Change(_keepAliveInterval, _keepAliveInterval);
  376. }
  377. }
  378. }