ServiceFactory.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using Microsoft.Extensions.Logging;
  7. using Renci.SshNet.Common;
  8. using Renci.SshNet.Connection;
  9. using Renci.SshNet.Messages.Transport;
  10. using Renci.SshNet.NetConf;
  11. using Renci.SshNet.Security;
  12. using Renci.SshNet.Sftp;
  13. namespace Renci.SshNet
  14. {
  15. /// <summary>
  16. /// Basic factory for creating new services.
  17. /// </summary>
  18. internal sealed partial class ServiceFactory : IServiceFactory
  19. {
  20. /// <summary>
  21. /// Defines the number of times an authentication attempt with any given <see cref="IAuthenticationMethod"/>
  22. /// can result in <see cref="AuthenticationResult.PartialSuccess"/> before it is disregarded.
  23. /// </summary>
  24. private const int PartialSuccessLimit = 5;
  25. internal ServiceFactory()
  26. {
  27. }
  28. /// <summary>
  29. /// Creates an <see cref="IClientAuthentication"/>.
  30. /// </summary>
  31. /// <returns>
  32. /// An <see cref="IClientAuthentication"/>.
  33. /// </returns>
  34. public IClientAuthentication CreateClientAuthentication()
  35. {
  36. return new ClientAuthentication(PartialSuccessLimit);
  37. }
  38. /// <summary>
  39. /// Creates a new <see cref="ISession"/> with the specified <see cref="ConnectionInfo"/> and
  40. /// <see cref="ISocketFactory"/>.
  41. /// </summary>
  42. /// <param name="connectionInfo">The <see cref="ConnectionInfo"/> to use for creating a new session.</param>
  43. /// <param name="socketFactory">A factory to create <see cref="Socket"/> instances.</param>
  44. /// <returns>
  45. /// An <see cref="ISession"/> for the specified <see cref="ConnectionInfo"/>.
  46. /// </returns>
  47. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</exception>
  48. /// <exception cref="ArgumentNullException"><paramref name="socketFactory"/> is <see langword="null"/>.</exception>
  49. public ISession CreateSession(ConnectionInfo connectionInfo, ISocketFactory socketFactory)
  50. {
  51. return new Session(connectionInfo, this, socketFactory);
  52. }
  53. /// <summary>
  54. /// Creates a new <see cref="ISftpSession"/> in a given <see cref="ISession"/> and with
  55. /// the specified operation timeout and encoding.
  56. /// </summary>
  57. /// <param name="session">The <see cref="ISession"/> to create the <see cref="ISftpSession"/> in.</param>
  58. /// <param name="operationTimeout">The number of milliseconds to wait for an operation to complete, or <c>-1</c> to wait indefinitely.</param>
  59. /// <param name="encoding">The encoding.</param>
  60. /// <param name="sftpMessageFactory">The factory to use for creating SFTP messages.</param>
  61. /// <returns>
  62. /// An <see cref="ISftpSession"/>.
  63. /// </returns>
  64. public ISftpSession CreateSftpSession(ISession session, int operationTimeout, Encoding encoding, ISftpResponseFactory sftpMessageFactory)
  65. {
  66. return new SftpSession(session, operationTimeout, encoding, sftpMessageFactory);
  67. }
  68. /// <summary>
  69. /// Create a new <see cref="PipeStream"/>.
  70. /// </summary>
  71. /// <returns>
  72. /// A <see cref="PipeStream"/>.
  73. /// </returns>
  74. public PipeStream CreatePipeStream()
  75. {
  76. return new PipeStream();
  77. }
  78. /// <inheritdoc/>
  79. public IKeyExchange CreateKeyExchange(IDictionary<string, Func<IKeyExchange>> clientAlgorithms, string[] serverAlgorithms)
  80. {
  81. ThrowHelper.ThrowIfNull(clientAlgorithms);
  82. ThrowHelper.ThrowIfNull(serverAlgorithms);
  83. // find an algorithm that is supported by both client and server
  84. var keyExchangeAlgorithmFactory = (from c in clientAlgorithms
  85. from s in serverAlgorithms
  86. where s == c.Key
  87. select c.Value).FirstOrDefault();
  88. if (keyExchangeAlgorithmFactory is null)
  89. {
  90. throw new SshConnectionException($"No matching key exchange algorithm (server offers {serverAlgorithms.Join(",")})", DisconnectReason.KeyExchangeFailed);
  91. }
  92. return keyExchangeAlgorithmFactory();
  93. }
  94. /// <summary>
  95. /// Creates a new <see cref="INetConfSession"/> in a given <see cref="ISession"/>
  96. /// and with the specified operation timeout.
  97. /// </summary>
  98. /// <param name="session">The <see cref="ISession"/> to create the <see cref="INetConfSession"/> in.</param>
  99. /// <param name="operationTimeout">The number of milliseconds to wait for an operation to complete, or <c>-1</c> to wait indefinitely.</param>
  100. /// <returns>
  101. /// An <see cref="INetConfSession"/>.
  102. /// </returns>
  103. public INetConfSession CreateNetConfSession(ISession session, int operationTimeout)
  104. {
  105. return new NetConfSession(session, operationTimeout);
  106. }
  107. /// <summary>
  108. /// Creates an <see cref="ISftpFileReader"/> for the specified file and with the specified
  109. /// buffer size.
  110. /// </summary>
  111. /// <param name="fileName">The file to read.</param>
  112. /// <param name="sftpSession">The SFTP session to use.</param>
  113. /// <param name="bufferSize">The size of buffer.</param>
  114. /// <returns>
  115. /// An <see cref="ISftpFileReader"/>.
  116. /// </returns>
  117. public ISftpFileReader CreateSftpFileReader(string fileName, ISftpSession sftpSession, uint bufferSize)
  118. {
  119. const int defaultMaxPendingReads = 10;
  120. // Issue #292: Avoid overlapping SSH_FXP_OPEN and SSH_FXP_LSTAT requests for the same file as this
  121. // causes a performance degradation on Sun SSH
  122. var openAsyncResult = sftpSession.BeginOpen(fileName, Flags.Read, callback: null, state: null);
  123. var handle = sftpSession.EndOpen(openAsyncResult);
  124. var statAsyncResult = sftpSession.BeginLStat(fileName, callback: null, state: null);
  125. long? fileSize;
  126. int maxPendingReads;
  127. var chunkSize = sftpSession.CalculateOptimalReadLength(bufferSize);
  128. // fallback to a default maximum of pending reads when remote server does not allow us to obtain
  129. // the attributes of the file
  130. try
  131. {
  132. var fileAttributes = sftpSession.EndLStat(statAsyncResult);
  133. fileSize = fileAttributes.Size;
  134. maxPendingReads = Math.Min(100, (int)Math.Ceiling((double)fileAttributes.Size / chunkSize) + 1);
  135. }
  136. catch (SshException ex)
  137. {
  138. fileSize = null;
  139. maxPendingReads = defaultMaxPendingReads;
  140. sftpSession.SessionLoggerFactory.CreateLogger<ServiceFactory>().LogInformation(ex, "Failed to obtain size of file. Allowing maximum {MaxPendingReads} pending reads", maxPendingReads);
  141. }
  142. return sftpSession.CreateFileReader(handle, sftpSession, chunkSize, maxPendingReads, fileSize);
  143. }
  144. /// <summary>
  145. /// Creates a new <see cref="ISftpResponseFactory"/> instance.
  146. /// </summary>
  147. /// <returns>
  148. /// An <see cref="ISftpResponseFactory"/>.
  149. /// </returns>
  150. public ISftpResponseFactory CreateSftpResponseFactory()
  151. {
  152. return new SftpResponseFactory();
  153. }
  154. /// <inheritdoc/>
  155. public ShellStream CreateShellStream(ISession session, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModeValues, int bufferSize)
  156. {
  157. return new ShellStream(session, terminalName, columns, rows, width, height, terminalModeValues, bufferSize);
  158. }
  159. /// <inheritdoc/>
  160. public ShellStream CreateShellStreamNoTerminal(ISession session, int bufferSize)
  161. {
  162. return new ShellStream(session, bufferSize);
  163. }
  164. /// <summary>
  165. /// Creates an <see cref="IRemotePathTransformation"/> that encloses a path in double quotes, and escapes
  166. /// any embedded double quote with a backslash.
  167. /// </summary>
  168. /// <returns>
  169. /// An <see cref="IRemotePathTransformation"/> that encloses a path in double quotes, and escapes any
  170. /// embedded double quote with a backslash.
  171. /// with a shell.
  172. /// </returns>
  173. public IRemotePathTransformation CreateRemotePathDoubleQuoteTransformation()
  174. {
  175. return RemotePathTransformation.DoubleQuote;
  176. }
  177. /// <summary>
  178. /// Creates an <see cref="IConnector"/> that can be used to establish a connection
  179. /// to the server identified by the specified <paramref name="connectionInfo"/>.
  180. /// </summary>
  181. /// <param name="connectionInfo">A <see cref="IConnectionInfo"/> detailing the server to establish a connection to.</param>
  182. /// <param name="socketFactory">A factory to create <see cref="Socket"/> instances.</param>
  183. /// <returns>
  184. /// An <see cref="IConnector"/> that can be used to establish a connection to the
  185. /// server identified by the specified <paramref name="connectionInfo"/>.
  186. /// </returns>
  187. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</exception>
  188. /// <exception cref="ArgumentNullException"><paramref name="socketFactory"/> is <see langword="null"/>.</exception>
  189. /// <exception cref="NotSupportedException">The <see cref="IConnectionInfo.ProxyType"/> value of <paramref name="connectionInfo"/> is not supported.</exception>
  190. public IConnector CreateConnector(IConnectionInfo connectionInfo, ISocketFactory socketFactory)
  191. {
  192. ThrowHelper.ThrowIfNull(connectionInfo);
  193. ThrowHelper.ThrowIfNull(socketFactory);
  194. var loggerFactory = connectionInfo.LoggerFactory ?? SshNetLoggingConfiguration.LoggerFactory;
  195. switch (connectionInfo.ProxyType)
  196. {
  197. case ProxyTypes.None:
  198. return new DirectConnector(socketFactory, loggerFactory);
  199. case ProxyTypes.Socks4:
  200. return new Socks4Connector(socketFactory, loggerFactory);
  201. case ProxyTypes.Socks5:
  202. return new Socks5Connector(socketFactory, loggerFactory);
  203. case ProxyTypes.Http:
  204. return new HttpConnector(socketFactory, loggerFactory);
  205. default:
  206. throw new NotSupportedException(string.Format("ProxyTypes '{0}' is not supported.", connectionInfo.ProxyType));
  207. }
  208. }
  209. /// <summary>
  210. /// Creates an <see cref="IProtocolVersionExchange"/> that deals with the SSH protocol
  211. /// version exchange.
  212. /// </summary>
  213. /// <returns>
  214. /// An <see cref="IProtocolVersionExchange"/>.
  215. /// </returns>
  216. public IProtocolVersionExchange CreateProtocolVersionExchange()
  217. {
  218. return new ProtocolVersionExchange();
  219. }
  220. /// <summary>
  221. /// Creates a factory to create <see cref="Socket"/> instances.
  222. /// </summary>
  223. /// <returns>
  224. /// An <see cref="ISocketFactory"/>.
  225. /// </returns>
  226. public ISocketFactory CreateSocketFactory()
  227. {
  228. return new SocketFactory();
  229. }
  230. }
  231. }