ScpClient.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Renci.SshNet.Channels;
  6. using System.IO;
  7. using Renci.SshNet.Common;
  8. using Renci.SshNet.Messages.Connection;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using System.Diagnostics;
  12. namespace Renci.SshNet
  13. {
  14. /// <summary>
  15. /// Provides SCP client functionality.
  16. /// </summary>
  17. public partial class ScpClient : BaseClient
  18. {
  19. private static Regex _fileInfoRe = new Regex(@"C(?<mode>\d{4}) (?<length>\d+) (?<filename>.+)");
  20. private static Regex _directoryInfoRe = new Regex(@"D(?<mode>\d{4}) (?<length>\d+) (?<filename>.+)");
  21. private static Regex _timestampRe = new Regex(@"T(?<mtime>\d+) 0 (?<atime>\d+) 0");
  22. private static char[] _byteToChar;
  23. /// <summary>
  24. /// Gets or sets the operation timeout.
  25. /// </summary>
  26. /// <value>The operation timeout.</value>
  27. public TimeSpan OperationTimeout { get; set; }
  28. /// <summary>
  29. /// Gets or sets the size of the buffer.
  30. /// </summary>
  31. /// <value>The size of the buffer.</value>
  32. public uint BufferSize { get; set; }
  33. /// <summary>
  34. /// Occurs when downloading file.
  35. /// </summary>
  36. public event EventHandler<ScpDownloadEventArgs> Downloading;
  37. /// <summary>
  38. /// Occurs when uploading file.
  39. /// </summary>
  40. public event EventHandler<ScpUploadEventArgs> Uploading;
  41. #region Constructors
  42. /// <summary>
  43. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  44. /// </summary>
  45. /// <param name="connectionInfo">The connection info.</param>
  46. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
  47. public ScpClient(ConnectionInfo connectionInfo)
  48. : base(connectionInfo)
  49. {
  50. this.OperationTimeout = new TimeSpan(0, 0, 0, 0, -1);
  51. this.BufferSize = 1024 * 32 - 38;
  52. if (_byteToChar == null)
  53. {
  54. _byteToChar = new char[128];
  55. var ch = '\0';
  56. for (int i = 0; i < 128; i++)
  57. {
  58. _byteToChar[i] = ch++;
  59. }
  60. }
  61. }
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  64. /// </summary>
  65. /// <param name="host">Connection host.</param>
  66. /// <param name="port">Connection port.</param>
  67. /// <param name="username">Authentication username.</param>
  68. /// <param name="password">Authentication password.</param>
  69. /// <exception cref="ArgumentNullException"><paramref name="password"/> is null.</exception>
  70. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception>
  71. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>
  72. public ScpClient(string host, int port, string username, string password)
  73. : this(new PasswordConnectionInfo(host, port, username, password))
  74. {
  75. }
  76. /// <summary>
  77. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  78. /// </summary>
  79. /// <param name="host">Connection host.</param>
  80. /// <param name="username">Authentication username.</param>
  81. /// <param name="password">Authentication password.</param>
  82. /// <exception cref="ArgumentNullException"><paramref name="password"/> is null.</exception>
  83. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception>
  84. public ScpClient(string host, string username, string password)
  85. : this(host, 22, username, password)
  86. {
  87. }
  88. /// <summary>
  89. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  90. /// </summary>
  91. /// <param name="host">Connection host.</param>
  92. /// <param name="port">Connection port.</param>
  93. /// <param name="username">Authentication username.</param>
  94. /// <param name="keyFiles">Authentication private key file(s) .</param>
  95. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is null.</exception>
  96. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is null or contains whitespace characters.</exception>
  97. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>
  98. public ScpClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)
  99. : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles))
  100. {
  101. }
  102. /// <summary>
  103. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  104. /// </summary>
  105. /// <param name="host">Connection host.</param>
  106. /// <param name="username">Authentication username.</param>
  107. /// <param name="keyFiles">Authentication private key file(s) .</param>
  108. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is null.</exception>
  109. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is null or contains whitespace characters.</exception>
  110. public ScpClient(string host, string username, params PrivateKeyFile[] keyFiles)
  111. : this(host, 22, username, keyFiles)
  112. {
  113. }
  114. #endregion
  115. /// <summary>
  116. /// Uploads the specified stream to the remote host.
  117. /// </summary>
  118. /// <param name="source">Stream to upload.</param>
  119. /// <param name="filename">Remote host file name.</param>
  120. public void Upload(Stream source, string filename)
  121. {
  122. using (var input = new PipeStream())
  123. using (var channel = this.Session.CreateChannel<ChannelSession>())
  124. {
  125. channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e)
  126. {
  127. input.Write(e.Data, 0, e.Data.Length);
  128. input.Flush();
  129. };
  130. channel.Open();
  131. // Send channel command request
  132. channel.SendExecRequest(string.Format("scp -qt \"{0}\"", filename));
  133. this.CheckReturnCode(input);
  134. this.InternalFileUpload(channel, input, source, filename);
  135. channel.Close();
  136. }
  137. }
  138. /// <summary>
  139. /// Downloads the specified file from the remote host to the stream.
  140. /// </summary>
  141. /// <param name="filename">Remote host file name.</param>
  142. /// <param name="destination">The stream where to download remote file.</param>
  143. public void Download(string filename, Stream destination)
  144. {
  145. using (var input = new PipeStream())
  146. using (var channel = this.Session.CreateChannel<ChannelSession>())
  147. {
  148. channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e)
  149. {
  150. input.Write(e.Data, 0, e.Data.Length);
  151. input.Flush();
  152. };
  153. channel.Open();
  154. // Send channel command request
  155. channel.SendExecRequest(string.Format("scp -qf \"{0}\"", filename));
  156. this.SendConfirmation(channel); // Send reply
  157. var message = ReadString(input);
  158. var match = _fileInfoRe.Match(message);
  159. if (match.Success)
  160. {
  161. // Read file
  162. this.SendConfirmation(channel); // Send reply
  163. var mode = match.Result("${mode}");
  164. var length = long.Parse(match.Result("${length}"));
  165. var fileName = match.Result("${filename}");
  166. this.InternalFileDownload(channel, input, destination, fileName, length);
  167. }
  168. else
  169. {
  170. this.SendConfirmation(channel, 1, string.Format("\"{0}\" is not valid protocol message.", message));
  171. }
  172. channel.Close();
  173. }
  174. }
  175. private void InternalSetTimestamp(ChannelSession channel, Stream input, DateTime lastWriteTime, DateTime lastAccessime)
  176. {
  177. var zeroTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  178. var modificationSeconds = (long)(lastWriteTime - zeroTime).TotalSeconds;
  179. var accessSeconds = (long)(lastAccessime - zeroTime).TotalSeconds;
  180. this.SendData(channel, string.Format("T{0} 0 {1} 0\n", modificationSeconds, accessSeconds));
  181. this.CheckReturnCode(input);
  182. }
  183. private void InternalFileUpload(ChannelSession channel, Stream input, Stream source, string filename)
  184. {
  185. var length = source.Length;
  186. this.SendData(channel, string.Format("C0644 {0} {1}\n", length, filename));
  187. var buffer = new byte[this.BufferSize];
  188. var read = source.Read(buffer, 0, buffer.Length);
  189. long totalRead = 0;
  190. while (read > 0)
  191. {
  192. this.SendData(channel, buffer, read);
  193. totalRead += read;
  194. this.RaiseUploadingEvent(filename, length, totalRead);
  195. read = source.Read(buffer, 0, buffer.Length);
  196. }
  197. this.SendConfirmation(channel);
  198. this.CheckReturnCode(input);
  199. }
  200. private void InternalFileDownload(ChannelSession channel, Stream input, Stream output, string filename, long length)
  201. {
  202. var buffer = new byte[Math.Min(length, this.BufferSize)];
  203. var needToRead = length;
  204. do
  205. {
  206. var read = input.Read(buffer, 0, (int)Math.Min(needToRead, this.BufferSize));
  207. output.Write(buffer, 0, read);
  208. this.RaiseDownloadingEvent(filename, length, length - needToRead);
  209. needToRead -= read;
  210. }
  211. while (needToRead > 0);
  212. output.Flush();
  213. // Raise one more time when file downloaded
  214. this.RaiseDownloadingEvent(filename, length, length - needToRead);
  215. // Send confirmation byte after last data byte was read
  216. this.SendConfirmation(channel);
  217. this.CheckReturnCode(input);
  218. }
  219. private void RaiseDownloadingEvent(string filename, long size, long downloaded)
  220. {
  221. if (this.Downloading != null)
  222. {
  223. this.Downloading(this, new ScpDownloadEventArgs(filename, size, downloaded));
  224. }
  225. }
  226. private void RaiseUploadingEvent(string filename, long size, long uploaded)
  227. {
  228. if (this.Uploading != null)
  229. {
  230. this.Uploading(this, new ScpUploadEventArgs(filename, size, uploaded));
  231. }
  232. }
  233. private void SendConfirmation(ChannelSession channel)
  234. {
  235. this.SendData(channel, new byte[] { 0 });
  236. }
  237. private void SendConfirmation(ChannelSession channel, byte errorCode, string message)
  238. {
  239. this.SendData(channel, new byte[] { errorCode });
  240. this.SendData(channel, string.Format("{0}\n", message));
  241. }
  242. /// <summary>
  243. /// Checks the return code.
  244. /// </summary>
  245. /// <param name="input">The output stream.</param>
  246. private void CheckReturnCode(Stream input)
  247. {
  248. var b = ReadByte(input);
  249. if (b > 0)
  250. {
  251. var errorText = ReadString(input);
  252. throw new ScpException(errorText);
  253. }
  254. }
  255. partial void SendData(ChannelSession channel, string command);
  256. private void SendData(ChannelSession channel, byte[] buffer, int length)
  257. {
  258. if (length == buffer.Length)
  259. {
  260. this.Session.SendMessage(new ChannelDataMessage(channel.RemoteChannelNumber, buffer));
  261. }
  262. else
  263. {
  264. this.Session.SendMessage(new ChannelDataMessage(channel.RemoteChannelNumber, buffer.Take(length).ToArray()));
  265. }
  266. }
  267. private void SendData(ChannelSession channel, byte[] buffer)
  268. {
  269. this.Session.SendMessage(new ChannelDataMessage(channel.RemoteChannelNumber, buffer));
  270. }
  271. private static int ReadByte(Stream stream)
  272. {
  273. var b = stream.ReadByte();
  274. while (b < 0)
  275. {
  276. Thread.Sleep(100);
  277. b = stream.ReadByte();
  278. }
  279. return b;
  280. }
  281. private static string ReadString(Stream stream)
  282. {
  283. var hasError = false;
  284. StringBuilder sb = new StringBuilder();
  285. var b = ReadByte(stream);
  286. if (b == 1 || b == 2)
  287. {
  288. hasError = true;
  289. b = ReadByte(stream);
  290. }
  291. var ch = _byteToChar[b];
  292. while (ch != '\n')
  293. {
  294. sb.Append(ch);
  295. b = ReadByte(stream);
  296. ch = _byteToChar[b];
  297. }
  298. if (hasError)
  299. throw new ScpException(sb.ToString());
  300. return sb.ToString();
  301. }
  302. }
  303. }