2
0

ScpClient.cs 16 KB

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