BaseClient.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 IsSessionConnected();
  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 (IsSessionConnected())
  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 (IsSessionConnected())
  202. throw new InvalidOperationException("The client is already connected.");
  203. OnConnecting();
  204. Session = CreateAndConnectSession();
  205. try
  206. {
  207. // Even though the method we invoke makes you believe otherwise, at this point only
  208. // the SSH session itself is connected.
  209. OnConnected();
  210. }
  211. catch
  212. {
  213. // Only dispose the session as Disconnect() would have side-effects (such as remove forwarded
  214. // ports in SshClient).
  215. DisposeSession();
  216. throw;
  217. }
  218. StartKeepAliveTimer();
  219. }
  220. /// <summary>
  221. /// Disconnects client from the server.
  222. /// </summary>
  223. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  224. public void Disconnect()
  225. {
  226. DiagnosticAbstraction.Log("Disconnecting client.");
  227. CheckDisposed();
  228. OnDisconnecting();
  229. // stop sending keep-alive messages before we close the session
  230. StopKeepAliveTimer();
  231. // dispose the SSH session
  232. DisposeSession();
  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. var session = Session;
  267. if (session != null)
  268. {
  269. session.OnDisconnecting();
  270. }
  271. }
  272. /// <summary>
  273. /// Called when client is disconnected from the server.
  274. /// </summary>
  275. protected virtual void OnDisconnected()
  276. {
  277. }
  278. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  279. {
  280. var handler = ErrorOccurred;
  281. if (handler != null)
  282. {
  283. handler(this, e);
  284. }
  285. }
  286. private void Session_HostKeyReceived(object sender, HostKeyEventArgs e)
  287. {
  288. var handler = HostKeyReceived;
  289. if (handler != null)
  290. {
  291. handler(this, e);
  292. }
  293. }
  294. #region IDisposable Members
  295. private bool _isDisposed;
  296. /// <summary>
  297. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  298. /// </summary>
  299. public void Dispose()
  300. {
  301. DiagnosticAbstraction.Log("Disposing client.");
  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 resources.</param>
  309. protected virtual void Dispose(bool disposing)
  310. {
  311. if (_isDisposed)
  312. return;
  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. _isDisposed = true;
  324. }
  325. }
  326. /// <summary>
  327. /// Check if the current instance is disposed.
  328. /// </summary>
  329. /// <exception cref="ObjectDisposedException">THe current instance is disposed.</exception>
  330. protected void CheckDisposed()
  331. {
  332. if (_isDisposed)
  333. throw new ObjectDisposedException(GetType().FullName);
  334. }
  335. /// <summary>
  336. /// Releases unmanaged resources and performs other cleanup operations before the
  337. /// <see cref="BaseClient"/> is reclaimed by garbage collection.
  338. /// </summary>
  339. ~BaseClient()
  340. {
  341. Dispose(false);
  342. }
  343. #endregion
  344. /// <summary>
  345. /// Stops the keep-alive timer, and waits until all timer callbacks have been
  346. /// executed.
  347. /// </summary>
  348. private void StopKeepAliveTimer()
  349. {
  350. if (_keepAliveTimer == null)
  351. return;
  352. _keepAliveTimer.Dispose();
  353. _keepAliveTimer = null;
  354. }
  355. private void SendKeepAliveMessage()
  356. {
  357. var session = Session;
  358. // do nothing if we have disposed or disconnected
  359. if (session == null)
  360. return;
  361. // do not send multiple keep-alive messages concurrently
  362. if (Monitor.TryEnter(_keepAliveLock))
  363. {
  364. try
  365. {
  366. session.TrySendMessage(new IgnoreMessage());
  367. }
  368. finally
  369. {
  370. Monitor.Exit(_keepAliveLock);
  371. }
  372. }
  373. }
  374. /// <summary>
  375. /// Starts the keep-alive timer.
  376. /// </summary>
  377. /// <remarks>
  378. /// When <see cref="KeepAliveInterval"/> is negative one (-1) milliseconds, then
  379. /// the timer will not be started.
  380. /// </remarks>
  381. private void StartKeepAliveTimer()
  382. {
  383. if (_keepAliveInterval == SshNet.Session.InfiniteTimeSpan)
  384. return;
  385. if (_keepAliveTimer != null)
  386. // timer is already started
  387. return;
  388. _keepAliveTimer = CreateKeepAliveTimer(_keepAliveInterval, _keepAliveInterval);
  389. }
  390. /// <summary>
  391. /// Creates a <see cref="Timer"/> with the specified due time and interval.
  392. /// </summary>
  393. /// <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>
  394. /// <param name="period">The time interval between attempts to send a keep-alive message. Specify negative one (-1) milliseconds to disable periodic signaling.</param>
  395. /// <returns>
  396. /// A <see cref="Timer"/> with the specified due time and interval.
  397. /// </returns>
  398. private Timer CreateKeepAliveTimer(TimeSpan dueTime, TimeSpan period)
  399. {
  400. return new Timer(state => SendKeepAliveMessage(), Session, dueTime, period);
  401. }
  402. private ISession CreateAndConnectSession()
  403. {
  404. var session = _serviceFactory.CreateSession(ConnectionInfo);
  405. session.HostKeyReceived += Session_HostKeyReceived;
  406. session.ErrorOccured += Session_ErrorOccured;
  407. try
  408. {
  409. session.Connect();
  410. return session;
  411. }
  412. catch
  413. {
  414. DisposeSession(session);
  415. throw;
  416. }
  417. }
  418. private void DisposeSession(ISession session)
  419. {
  420. session.ErrorOccured -= Session_ErrorOccured;
  421. session.HostKeyReceived -= Session_HostKeyReceived;
  422. session.Dispose();
  423. }
  424. /// <summary>
  425. /// Disposes the SSH session, and assigns <c>null</c> to <see cref="Session"/>.
  426. /// </summary>
  427. private void DisposeSession()
  428. {
  429. var session = Session;
  430. if (session != null)
  431. {
  432. Session = null;
  433. DisposeSession(session);
  434. }
  435. }
  436. /// <summary>
  437. /// Returns a value indicating whether the SSH session is established.
  438. /// </summary>
  439. /// <returns>
  440. /// <c>true</c> if the SSH session is established; otherwise, <c>false</c>.
  441. /// </returns>
  442. private bool IsSessionConnected()
  443. {
  444. var session = Session;
  445. return session != null && session.IsConnected;
  446. }
  447. }
  448. }