ServiceFactory.cs 8.8 KB

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