ScpClient.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. using System;
  2. using System.Text;
  3. using Renci.SshNet.Channels;
  4. using System.IO;
  5. using Renci.SshNet.Common;
  6. using System.Text.RegularExpressions;
  7. using System.Diagnostics.CodeAnalysis;
  8. using System.Net;
  9. namespace Renci.SshNet
  10. {
  11. /// <summary>
  12. /// Provides SCP client functionality.
  13. /// </summary>
  14. /// <remarks>
  15. /// More information on the SCP protocol is available here:
  16. /// https://github.com/net-ssh/net-scp/blob/master/lib/net/scp.rb
  17. /// </remarks>
  18. public partial class ScpClient : BaseClient
  19. {
  20. private static readonly Regex FileInfoRe = new Regex(@"C(?<mode>\d{4}) (?<length>\d+) (?<filename>.+)");
  21. private static char[] _byteToChar;
  22. /// <summary>
  23. /// Gets or sets the operation timeout.
  24. /// </summary>
  25. /// <value>
  26. /// The timeout to wait until an operation completes. The default value is negative
  27. /// one (-1) milliseconds, which indicates an infinite time-out period.
  28. /// </value>
  29. public TimeSpan OperationTimeout { get; set; }
  30. /// <summary>
  31. /// Gets or sets the size of the buffer.
  32. /// </summary>
  33. /// <value>
  34. /// The size of the buffer. The default buffer size is 16384 bytes.
  35. /// </value>
  36. public uint BufferSize { get; set; }
  37. /// <summary>
  38. /// Occurs when downloading file.
  39. /// </summary>
  40. public event EventHandler<ScpDownloadEventArgs> Downloading;
  41. /// <summary>
  42. /// Occurs when uploading file.
  43. /// </summary>
  44. public event EventHandler<ScpUploadEventArgs> Uploading;
  45. #region Constructors
  46. /// <summary>
  47. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  48. /// </summary>
  49. /// <param name="connectionInfo">The connection info.</param>
  50. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
  51. public ScpClient(ConnectionInfo connectionInfo)
  52. : this(connectionInfo, false)
  53. {
  54. }
  55. /// <summary>
  56. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  57. /// </summary>
  58. /// <param name="host">Connection host.</param>
  59. /// <param name="port">Connection port.</param>
  60. /// <param name="username">Authentication username.</param>
  61. /// <param name="password">Authentication password.</param>
  62. /// <exception cref="ArgumentNullException"><paramref name="password"/> is <c>null</c>.</exception>
  63. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is <c>null</c> or contains only whitespace characters.</exception>
  64. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="IPEndPoint.MaxPort"/>.</exception>
  65. [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
  66. public ScpClient(string host, int port, string username, string password)
  67. : this(new PasswordConnectionInfo(host, port, username, password), true)
  68. {
  69. }
  70. /// <summary>
  71. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  72. /// </summary>
  73. /// <param name="host">Connection host.</param>
  74. /// <param name="username">Authentication username.</param>
  75. /// <param name="password">Authentication password.</param>
  76. /// <exception cref="ArgumentNullException"><paramref name="password"/> is <c>null</c>.</exception>
  77. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is <c>null</c> or contains only whitespace characters.</exception>
  78. public ScpClient(string host, string username, string password)
  79. : this(host, ConnectionInfo.DefaultPort, username, password)
  80. {
  81. }
  82. /// <summary>
  83. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  84. /// </summary>
  85. /// <param name="host">Connection host.</param>
  86. /// <param name="port">Connection port.</param>
  87. /// <param name="username">Authentication username.</param>
  88. /// <param name="keyFiles">Authentication private key file(s) .</param>
  89. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <c>null</c>.</exception>
  90. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is <c>null</c> or contains only whitespace characters.</exception>
  91. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="IPEndPoint.MaxPort"/>.</exception>
  92. [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
  93. public ScpClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)
  94. : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), true)
  95. {
  96. }
  97. /// <summary>
  98. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  99. /// </summary>
  100. /// <param name="host">Connection host.</param>
  101. /// <param name="username">Authentication username.</param>
  102. /// <param name="keyFiles">Authentication private key file(s) .</param>
  103. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <c>null</c>.</exception>
  104. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is <c>null</c> or contains only whitespace characters.</exception>
  105. public ScpClient(string host, string username, params PrivateKeyFile[] keyFiles)
  106. : this(host, ConnectionInfo.DefaultPort, username, keyFiles)
  107. {
  108. }
  109. /// <summary>
  110. /// Initializes a new instance of the <see cref="ScpClient"/> class.
  111. /// </summary>
  112. /// <param name="connectionInfo">The connection info.</param>
  113. /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
  114. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
  115. /// <remarks>
  116. /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
  117. /// connection info will be disposed when this instance is disposed.
  118. /// </remarks>
  119. private ScpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
  120. : this(connectionInfo, ownsConnectionInfo, new ServiceFactory())
  121. {
  122. }
  123. /// <summary>
  124. /// Initializes a new instance of the <see cref="ScpClient"/> class.
  125. /// </summary>
  126. /// <param name="connectionInfo">The connection info.</param>
  127. /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
  128. /// <param name="serviceFactory">The factory to use for creating new services.</param>
  129. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
  130. /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is <c>null</c>.</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. internal ScpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
  136. : base(connectionInfo, ownsConnectionInfo, serviceFactory)
  137. {
  138. OperationTimeout = SshNet.Session.InfiniteTimeSpan;
  139. BufferSize = 1024 * 16;
  140. if (_byteToChar == null)
  141. {
  142. _byteToChar = new char[128];
  143. var ch = '\0';
  144. for (var i = 0; i < 128; i++)
  145. {
  146. _byteToChar[i] = ch++;
  147. }
  148. }
  149. }
  150. #endregion
  151. /// <summary>
  152. /// Uploads the specified stream to the remote host.
  153. /// </summary>
  154. /// <param name="source">Stream to upload.</param>
  155. /// <param name="path">Remote host file name.</param>
  156. public void Upload(Stream source, string path)
  157. {
  158. using (var input = ServiceFactory.CreatePipeStream())
  159. using (var channel = Session.CreateChannelSession())
  160. {
  161. channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length);
  162. channel.Open();
  163. var pathEnd = path.LastIndexOfAny(new[] { '\\', '/' });
  164. if (pathEnd != -1)
  165. {
  166. // split the path from the file
  167. var pathOnly = path.Substring(0, pathEnd);
  168. var fileOnly = path.Substring(pathEnd + 1);
  169. // Send channel command request
  170. channel.SendExecRequest(string.Format("scp -t \"{0}\"", pathOnly));
  171. CheckReturnCode(input);
  172. path = fileOnly;
  173. }
  174. InternalUpload(channel, input, source, path);
  175. }
  176. }
  177. /// <summary>
  178. /// Downloads the specified file from the remote host to the stream.
  179. /// </summary>
  180. /// <param name="filename">Remote host file name.</param>
  181. /// <param name="destination">The stream where to download remote file.</param>
  182. /// <exception cref="ArgumentException"><paramref name="filename"/> is <c>null</c> or contains only whitespace characters.</exception>
  183. /// <exception cref="ArgumentNullException"><paramref name="destination"/> is <c>null</c>.</exception>
  184. /// <remarks>
  185. /// Method calls made by this method to <paramref name="destination"/>, may under certain conditions result
  186. /// in exceptions thrown by the stream.
  187. /// </remarks>
  188. public void Download(string filename, Stream destination)
  189. {
  190. if (filename.IsNullOrWhiteSpace())
  191. throw new ArgumentException("filename");
  192. if (destination == null)
  193. throw new ArgumentNullException("destination");
  194. using (var input = ServiceFactory.CreatePipeStream())
  195. using (var channel = Session.CreateChannelSession())
  196. {
  197. channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length);
  198. channel.Open();
  199. // Send channel command request
  200. channel.SendExecRequest(string.Format("scp -f \"{0}\"", filename));
  201. SendConfirmation(channel); // Send reply
  202. var message = ReadString(input);
  203. var match = FileInfoRe.Match(message);
  204. if (match.Success)
  205. {
  206. // Read file
  207. SendConfirmation(channel); // Send reply
  208. var mode = match.Result("${mode}");
  209. var length = long.Parse(match.Result("${length}"));
  210. var fileName = match.Result("${filename}");
  211. InternalDownload(channel, input, destination, fileName, length);
  212. }
  213. else
  214. {
  215. SendConfirmation(channel, 1, string.Format("\"{0}\" is not valid protocol message.", message));
  216. }
  217. }
  218. }
  219. private static void InternalSetTimestamp(IChannelSession channel, Stream input, DateTime lastWriteTime, DateTime lastAccessime)
  220. {
  221. var zeroTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  222. var modificationSeconds = (long) (lastWriteTime - zeroTime).TotalSeconds;
  223. var accessSeconds = (long) (lastAccessime - zeroTime).TotalSeconds;
  224. SendData(channel, string.Format("T{0} 0 {1} 0\n", modificationSeconds, accessSeconds));
  225. CheckReturnCode(input);
  226. }
  227. private void InternalUpload(IChannelSession channel, Stream input, Stream source, string filename)
  228. {
  229. var length = source.Length;
  230. SendData(channel, string.Format("C0644 {0} {1}\n", length, Path.GetFileName(filename)));
  231. CheckReturnCode(input);
  232. var buffer = new byte[BufferSize];
  233. var read = source.Read(buffer, 0, buffer.Length);
  234. long totalRead = 0;
  235. while (read > 0)
  236. {
  237. SendData(channel, buffer, read);
  238. totalRead += read;
  239. RaiseUploadingEvent(filename, length, totalRead);
  240. read = source.Read(buffer, 0, buffer.Length);
  241. }
  242. SendConfirmation(channel);
  243. CheckReturnCode(input);
  244. }
  245. private void InternalDownload(IChannel channel, Stream input, Stream output, string filename, long length)
  246. {
  247. var buffer = new byte[Math.Min(length, BufferSize)];
  248. var needToRead = length;
  249. do
  250. {
  251. var read = input.Read(buffer, 0, (int) Math.Min(needToRead, BufferSize));
  252. output.Write(buffer, 0, read);
  253. RaiseDownloadingEvent(filename, length, length - needToRead);
  254. needToRead -= read;
  255. }
  256. while (needToRead > 0);
  257. output.Flush();
  258. // Raise one more time when file downloaded
  259. RaiseDownloadingEvent(filename, length, length - needToRead);
  260. // Send confirmation byte after last data byte was read
  261. SendConfirmation(channel);
  262. CheckReturnCode(input);
  263. }
  264. private void RaiseDownloadingEvent(string filename, long size, long downloaded)
  265. {
  266. if (Downloading != null)
  267. {
  268. Downloading(this, new ScpDownloadEventArgs(filename, size, downloaded));
  269. }
  270. }
  271. private void RaiseUploadingEvent(string filename, long size, long uploaded)
  272. {
  273. if (Uploading != null)
  274. {
  275. Uploading(this, new ScpUploadEventArgs(filename, size, uploaded));
  276. }
  277. }
  278. private static void SendConfirmation(IChannel channel)
  279. {
  280. SendData(channel, new byte[] { 0 });
  281. }
  282. private static void SendConfirmation(IChannel channel, byte errorCode, string message)
  283. {
  284. SendData(channel, new[] { errorCode });
  285. SendData(channel, string.Format("{0}\n", message));
  286. }
  287. /// <summary>
  288. /// Checks the return code.
  289. /// </summary>
  290. /// <param name="input">The output stream.</param>
  291. private static void CheckReturnCode(Stream input)
  292. {
  293. var b = ReadByte(input);
  294. if (b > 0)
  295. {
  296. var errorText = ReadString(input);
  297. throw new ScpException(errorText);
  298. }
  299. }
  300. private static void SendData(IChannel channel, string command)
  301. {
  302. channel.SendData(SshData.Utf8.GetBytes(command));
  303. }
  304. private static void SendData(IChannel channel, byte[] buffer, int length)
  305. {
  306. channel.SendData(buffer, 0, length);
  307. }
  308. private static void SendData(IChannel channel, byte[] buffer)
  309. {
  310. channel.SendData(buffer);
  311. }
  312. private static int ReadByte(Stream stream)
  313. {
  314. var b = stream.ReadByte();
  315. if (b == -1)
  316. throw new SshException("Stream has been closed.");
  317. return b;
  318. }
  319. private static string ReadString(Stream stream)
  320. {
  321. var hasError = false;
  322. var sb = new StringBuilder();
  323. var b = ReadByte(stream);
  324. if (b == 1 || b == 2)
  325. {
  326. hasError = true;
  327. b = ReadByte(stream);
  328. }
  329. var ch = _byteToChar[b];
  330. while (ch != '\n')
  331. {
  332. sb.Append(ch);
  333. b = ReadByte(stream);
  334. ch = _byteToChar[b];
  335. }
  336. if (hasError)
  337. throw new ScpException(sb.ToString());
  338. return sb.ToString();
  339. }
  340. }
  341. }