ServiceFactory.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Renci.SshNet.Common;
  6. using Renci.SshNet.Messages.Transport;
  7. using Renci.SshNet.Security;
  8. using Renci.SshNet.Sftp;
  9. using Renci.SshNet.Abstractions;
  10. using Renci.SshNet.Connection;
  11. namespace Renci.SshNet
  12. {
  13. /// <summary>
  14. /// Basic factory for creating new services.
  15. /// </summary>
  16. internal partial class ServiceFactory : IServiceFactory
  17. {
  18. /// <summary>
  19. /// Defines the number of times an authentication attempt with any given <see cref="IAuthenticationMethod"/>
  20. /// can result in <see cref="AuthenticationResult.PartialSuccess"/> before it is disregarded.
  21. /// </summary>
  22. private static int PartialSuccessLimit = 5;
  23. /// <summary>
  24. /// Creates a <see cref="IClientAuthentication"/>.
  25. /// </summary>
  26. /// <returns>
  27. /// A <see cref="IClientAuthentication"/>.
  28. /// </returns>
  29. public IClientAuthentication CreateClientAuthentication()
  30. {
  31. return new ClientAuthentication(PartialSuccessLimit);
  32. }
  33. /// <summary>
  34. /// Creates a new <see cref="ISession"/> with the specified <see cref="ConnectionInfo"/>.
  35. /// </summary>
  36. /// <param name="connectionInfo">The <see cref="ConnectionInfo"/> to use for creating a new session.</param>
  37. /// <returns>
  38. /// An <see cref="ISession"/> for the specified <see cref="ConnectionInfo"/>.
  39. /// </returns>
  40. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
  41. public ISession CreateSession(ConnectionInfo connectionInfo)
  42. {
  43. return new Session(connectionInfo, this);
  44. }
  45. /// <summary>
  46. /// Creates a new <see cref="ISftpSession"/> in a given <see cref="ISession"/> and with
  47. /// the specified operation timeout and encoding.
  48. /// </summary>
  49. /// <param name="session">The <see cref="ISession"/> to create the <see cref="ISftpSession"/> in.</param>
  50. /// <param name="operationTimeout">The number of milliseconds to wait for an operation to complete, or -1 to wait indefinitely.</param>
  51. /// <param name="encoding">The encoding.</param>
  52. /// <param name="sftpMessageFactory">The factory to use for creating SFTP messages.</param>
  53. /// <returns>
  54. /// An <see cref="ISftpSession"/>.
  55. /// </returns>
  56. public ISftpSession CreateSftpSession(ISession session, int operationTimeout, Encoding encoding, ISftpResponseFactory sftpMessageFactory)
  57. {
  58. return new SftpSession(session, operationTimeout, encoding, sftpMessageFactory);
  59. }
  60. /// <summary>
  61. /// Create a new <see cref="PipeStream"/>.
  62. /// </summary>
  63. /// <returns>
  64. /// A <see cref="PipeStream"/>.
  65. /// </returns>
  66. public PipeStream CreatePipeStream()
  67. {
  68. return new PipeStream();
  69. }
  70. /// <summary>
  71. /// Negotiates a key exchange algorithm, and creates a <see cref="IKeyExchange" /> for the negotiated
  72. /// algorithm.
  73. /// </summary>
  74. /// <param name="clientAlgorithms">A <see cref="IDictionary{String, Type}"/> of the key exchange algorithms supported by the client where key is the name of the algorithm, and value is the type implementing this algorithm.</param>
  75. /// <param name="serverAlgorithms">The names of the key exchange algorithms supported by the SSH server.</param>
  76. /// <returns>
  77. /// A <see cref="IKeyExchange"/> that was negotiated between client and server.
  78. /// </returns>
  79. /// <exception cref="ArgumentNullException"><paramref name="clientAlgorithms"/> is <c>null</c>.</exception>
  80. /// <exception cref="ArgumentNullException"><paramref name="serverAlgorithms"/> is <c>null</c>.</exception>
  81. /// <exception cref="SshConnectionException">No key exchange algorithms are supported by both client and server.</exception>
  82. public IKeyExchange CreateKeyExchange(IDictionary<string, Type> clientAlgorithms, string[] serverAlgorithms)
  83. {
  84. if (clientAlgorithms == null)
  85. throw new ArgumentNullException("clientAlgorithms");
  86. if (serverAlgorithms == null)
  87. throw new ArgumentNullException("serverAlgorithms");
  88. // find an algorithm that is supported by both client and server
  89. var keyExchangeAlgorithmType = (from c in clientAlgorithms
  90. from s in serverAlgorithms
  91. where s == c.Key
  92. select c.Value).FirstOrDefault();
  93. if (keyExchangeAlgorithmType == null)
  94. {
  95. throw new SshConnectionException("Failed to negotiate key exchange algorithm.", DisconnectReason.KeyExchangeFailed);
  96. }
  97. return keyExchangeAlgorithmType.CreateInstance<IKeyExchange>();
  98. }
  99. public ISftpFileReader CreateSftpFileReader(string fileName, ISftpSession sftpSession, uint bufferSize)
  100. {
  101. const int defaultMaxPendingReads = 3;
  102. // Issue #292: Avoid overlapping SSH_FXP_OPEN and SSH_FXP_LSTAT requests for the same file as this
  103. // causes a performance degradation on Sun SSH
  104. var openAsyncResult = sftpSession.BeginOpen(fileName, Flags.Read, null, null);
  105. var handle = sftpSession.EndOpen(openAsyncResult);
  106. var statAsyncResult = sftpSession.BeginLStat(fileName, null, null);
  107. long? fileSize;
  108. int maxPendingReads;
  109. var chunkSize = sftpSession.CalculateOptimalReadLength(bufferSize);
  110. // fallback to a default maximum of pending reads when remote server does not allow us to obtain
  111. // the attributes of the file
  112. try
  113. {
  114. var fileAttributes = sftpSession.EndLStat(statAsyncResult);
  115. fileSize = fileAttributes.Size;
  116. maxPendingReads = Math.Min(10, (int) Math.Ceiling((double) fileAttributes.Size / chunkSize) + 1);
  117. }
  118. catch (SshException ex)
  119. {
  120. fileSize = null;
  121. maxPendingReads = defaultMaxPendingReads;
  122. DiagnosticAbstraction.Log(string.Format("Failed to obtain size of file. Allowing maximum {0} pending reads: {1}", maxPendingReads, ex));
  123. }
  124. return sftpSession.CreateFileReader(handle, sftpSession, chunkSize, maxPendingReads, fileSize);
  125. }
  126. public ISftpResponseFactory CreateSftpResponseFactory()
  127. {
  128. return new SftpResponseFactory();
  129. }
  130. /// <summary>
  131. /// Creates a shell stream.
  132. /// </summary>
  133. /// <param name="session">The SSH session.</param>
  134. /// <param name="terminalName">The <c>TERM</c> environment variable.</param>
  135. /// <param name="columns">The terminal width in columns.</param>
  136. /// <param name="rows">The terminal width in rows.</param>
  137. /// <param name="width">The terminal height in pixels.</param>
  138. /// <param name="height">The terminal height in pixels.</param>
  139. /// <param name="terminalModeValues">The terminal mode values.</param>
  140. /// <param name="bufferSize">The size of the buffer.</param>
  141. /// <returns>
  142. /// The created <see cref="ShellStream"/> instance.
  143. /// </returns>
  144. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  145. /// <remarks>
  146. /// <para>
  147. /// The <c>TERM</c> environment variable contains an identifier for the text window's capabilities.
  148. /// You can get a detailed list of these cababilities by using the ‘infocmp’ command.
  149. /// </para>
  150. /// <para>
  151. /// The column/row dimensions override the pixel dimensions(when non-zero). Pixel dimensions refer
  152. /// to the drawable area of the window.
  153. /// </para>
  154. /// </remarks>
  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. /// <summary>
  160. /// Creates an <see cref="IRemotePathTransformation"/> that encloses a path in double quotes, and escapes
  161. /// any embedded double quote with a backslash.
  162. /// </summary>
  163. /// <returns>
  164. /// An <see cref="IRemotePathTransformation"/> that encloses a path in double quotes, and escapes any
  165. /// embedded double quote with a backslash.
  166. /// with a shell.
  167. /// </returns>
  168. public IRemotePathTransformation CreateRemotePathDoubleQuoteTransformation()
  169. {
  170. return RemotePathTransformation.DoubleQuote;
  171. }
  172. /// <summary>
  173. /// Creates an <see cref="IConnector"/> that can be used to establish a connection
  174. /// to the server identified by the specified <paramref name="connectionInfo"/>.
  175. /// </summary>
  176. /// <param name="connectionInfo">A <see cref="IConnectionInfo"/> detailing the server to establish a connection to.</param>
  177. /// <returns>
  178. /// An <see cref="IConnector"/> that can be used to establish a connection to the
  179. /// server identified by the specified <paramref name="connectionInfo"/>.
  180. /// </returns>
  181. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</exception>
  182. /// <exception cref="NotSupportedException">The <see cref="IConnectionInfo.ProxyType"/> value of <paramref name="connectionInfo"/> is not supported.</exception>
  183. public IConnector CreateConnector(IConnectionInfo connectionInfo)
  184. {
  185. if (connectionInfo == null)
  186. throw new ArgumentNullException("connectionInfo");
  187. switch (connectionInfo.ProxyType)
  188. {
  189. case ProxyTypes.None:
  190. return new DirectConnector();
  191. case ProxyTypes.Socks4:
  192. return new Socks4Connector();
  193. case ProxyTypes.Socks5:
  194. return new Socks5Connector();
  195. case ProxyTypes.Http:
  196. return new HttpConnector();
  197. default:
  198. throw new NotSupportedException(string.Format("ProxyTypes '{0}' is not supported.", connectionInfo.ProxyType));
  199. }
  200. }
  201. }
  202. }