| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Diagnostics.CodeAnalysis; |
| | | 4 | | using System.Globalization; |
| | | 5 | | using System.IO; |
| | | 6 | | using System.Net; |
| | | 7 | | using System.Text.RegularExpressions; |
| | | 8 | | |
| | | 9 | | using Renci.SshNet.Channels; |
| | | 10 | | using Renci.SshNet.Common; |
| | | 11 | | |
| | | 12 | | namespace Renci.SshNet |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Provides SCP client functionality. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <remarks> |
| | | 18 | | /// <para> |
| | | 19 | | /// More information on the SCP protocol is available here: https://github.com/net-ssh/net-scp/blob/master/lib/net/s |
| | | 20 | | /// </para> |
| | | 21 | | /// <para> |
| | | 22 | | /// Known issues in OpenSSH: |
| | | 23 | | /// <list type="bullet"> |
| | | 24 | | /// <item> |
| | | 25 | | /// <description>Recursive download (-prf) does not deal well with specific UTF-8 and newline characters.</descr |
| | | 26 | | /// <description>Recursive update does not support empty path for uploading to home directory.</description> |
| | | 27 | | /// </item> |
| | | 28 | | /// </list> |
| | | 29 | | /// </para> |
| | | 30 | | /// </remarks> |
| | | 31 | | public partial class ScpClient : BaseClient |
| | | 32 | | { |
| | | 33 | | private const string Message = "filename"; |
| | 4 | 34 | | private static readonly Regex FileInfoRe = new Regex(@"C(?<mode>\d{4}) (?<length>\d+) (?<filename>.+)", RegexOpt |
| | 4 | 35 | | private static readonly byte[] SuccessConfirmationCode = { 0 }; |
| | 4 | 36 | | private static readonly byte[] ErrorConfirmationCode = { 1 }; |
| | 4 | 37 | | private static readonly Regex DirectoryInfoRe = new Regex(@"D(?<mode>\d{4}) (?<length>\d+) (?<filename>.+)", Reg |
| | 4 | 38 | | private static readonly Regex TimestampRe = new Regex(@"T(?<mtime>\d+) 0 (?<atime>\d+) 0", RegexOptions.Compiled |
| | | 39 | | |
| | | 40 | | private IRemotePathTransformation _remotePathTransformation; |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Gets or sets the operation timeout. |
| | | 44 | | /// </summary> |
| | | 45 | | /// <value> |
| | | 46 | | /// The timeout to wait until an operation completes. The default value is negative |
| | | 47 | | /// one (-1) milliseconds, which indicates an infinite time-out period. |
| | | 48 | | /// </value> |
| | 426 | 49 | | public TimeSpan OperationTimeout { get; set; } |
| | | 50 | | |
| | | 51 | | /// <summary> |
| | | 52 | | /// Gets or sets the size of the buffer. |
| | | 53 | | /// </summary> |
| | | 54 | | /// <value> |
| | | 55 | | /// The size of the buffer. The default buffer size is 16384 bytes. |
| | | 56 | | /// </value> |
| | 4236 | 57 | | public uint BufferSize { get; set; } |
| | | 58 | | |
| | | 59 | | /// <summary> |
| | | 60 | | /// Gets or sets the transformation to apply to remote paths. |
| | | 61 | | /// </summary> |
| | | 62 | | /// <value> |
| | | 63 | | /// The transformation to apply to remote paths. The default is <see cref="RemotePathTransformation.DoubleQuote" |
| | | 64 | | /// </value> |
| | | 65 | | /// <exception cref="ArgumentNullException"><paramref name="value"/> is <see langword="null"/>.</exception> |
| | | 66 | | /// <remarks> |
| | | 67 | | /// <para> |
| | | 68 | | /// This transformation is applied to the remote file or directory path that is passed to the |
| | | 69 | | /// <c>scp</c> command. |
| | | 70 | | /// </para> |
| | | 71 | | /// <para> |
| | | 72 | | /// See <see cref="SshNet.RemotePathTransformation"/> for the transformations that are supplied |
| | | 73 | | /// out-of-the-box with SSH.NET. |
| | | 74 | | /// </para> |
| | | 75 | | /// </remarks> |
| | | 76 | | public IRemotePathTransformation RemotePathTransformation |
| | | 77 | | { |
| | | 78 | | get |
| | 24 | 79 | | { |
| | 24 | 80 | | return _remotePathTransformation; |
| | 24 | 81 | | } |
| | | 82 | | set |
| | 51 | 83 | | { |
| | 51 | 84 | | if (value is null) |
| | 3 | 85 | | { |
| | 3 | 86 | | throw new ArgumentNullException(nameof(value)); |
| | | 87 | | } |
| | | 88 | | |
| | 48 | 89 | | _remotePathTransformation = value; |
| | 48 | 90 | | } |
| | | 91 | | } |
| | | 92 | | |
| | | 93 | | /// <summary> |
| | | 94 | | /// Occurs when downloading file. |
| | | 95 | | /// </summary> |
| | | 96 | | public event EventHandler<ScpDownloadEventArgs> Downloading; |
| | | 97 | | |
| | | 98 | | /// <summary> |
| | | 99 | | /// Occurs when uploading file. |
| | | 100 | | /// </summary> |
| | | 101 | | public event EventHandler<ScpUploadEventArgs> Uploading; |
| | | 102 | | |
| | | 103 | | /// <summary> |
| | | 104 | | /// Initializes a new instance of the <see cref="ScpClient"/> class. |
| | | 105 | | /// </summary> |
| | | 106 | | /// <param name="connectionInfo">The connection info.</param> |
| | | 107 | | /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</except |
| | | 108 | | public ScpClient(ConnectionInfo connectionInfo) |
| | 286 | 109 | | : this(connectionInfo, ownsConnectionInfo: false) |
| | 283 | 110 | | { |
| | 283 | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <summary> |
| | | 114 | | /// Initializes a new instance of the <see cref="ScpClient"/> class. |
| | | 115 | | /// </summary> |
| | | 116 | | /// <param name="host">Connection host.</param> |
| | | 117 | | /// <param name="port">Connection port.</param> |
| | | 118 | | /// <param name="username">Authentication username.</param> |
| | | 119 | | /// <param name="password">Authentication password.</param> |
| | | 120 | | /// <exception cref="ArgumentNullException"><paramref name="password"/> is <see langword="null"/>.</exception> |
| | | 121 | | /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is <s |
| | | 122 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.Mi |
| | | 123 | | [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in |
| | | 124 | | public ScpClient(string host, int port, string username, string password) |
| | 20 | 125 | | : this(new PasswordConnectionInfo(host, port, username, password), ownsConnectionInfo: true) |
| | 20 | 126 | | { |
| | 20 | 127 | | } |
| | | 128 | | |
| | | 129 | | /// <summary> |
| | | 130 | | /// Initializes a new instance of the <see cref="ScpClient"/> class. |
| | | 131 | | /// </summary> |
| | | 132 | | /// <param name="host">Connection host.</param> |
| | | 133 | | /// <param name="username">Authentication username.</param> |
| | | 134 | | /// <param name="password">Authentication password.</param> |
| | | 135 | | /// <exception cref="ArgumentNullException"><paramref name="password"/> is <see langword="null"/>.</exception> |
| | | 136 | | /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is <s |
| | | 137 | | public ScpClient(string host, string username, string password) |
| | 3 | 138 | | : this(host, ConnectionInfo.DefaultPort, username, password) |
| | 3 | 139 | | { |
| | 3 | 140 | | } |
| | | 141 | | |
| | | 142 | | /// <summary> |
| | | 143 | | /// Initializes a new instance of the <see cref="ScpClient"/> class. |
| | | 144 | | /// </summary> |
| | | 145 | | /// <param name="host">Connection host.</param> |
| | | 146 | | /// <param name="port">Connection port.</param> |
| | | 147 | | /// <param name="username">Authentication username.</param> |
| | | 148 | | /// <param name="keyFiles">Authentication private key file(s) .</param> |
| | | 149 | | /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <see langword="null"/>.</exception> |
| | | 150 | | /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is |
| | | 151 | | /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.Mi |
| | | 152 | | [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in |
| | | 153 | | public ScpClient(string host, int port, string username, params IPrivateKeySource[] keyFiles) |
| | 6 | 154 | | : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), ownsConnectionInfo: true) |
| | 6 | 155 | | { |
| | 6 | 156 | | } |
| | | 157 | | |
| | | 158 | | /// <summary> |
| | | 159 | | /// Initializes a new instance of the <see cref="ScpClient"/> class. |
| | | 160 | | /// </summary> |
| | | 161 | | /// <param name="host">Connection host.</param> |
| | | 162 | | /// <param name="username">Authentication username.</param> |
| | | 163 | | /// <param name="keyFiles">Authentication private key file(s) .</param> |
| | | 164 | | /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <see langword="null"/>.</exception> |
| | | 165 | | /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is |
| | | 166 | | public ScpClient(string host, string username, params IPrivateKeySource[] keyFiles) |
| | 3 | 167 | | : this(host, ConnectionInfo.DefaultPort, username, keyFiles) |
| | 3 | 168 | | { |
| | 3 | 169 | | } |
| | | 170 | | |
| | | 171 | | /// <summary> |
| | | 172 | | /// Initializes a new instance of the <see cref="ScpClient"/> class. |
| | | 173 | | /// </summary> |
| | | 174 | | /// <param name="connectionInfo">The connection info.</param> |
| | | 175 | | /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param> |
| | | 176 | | /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</except |
| | | 177 | | /// <remarks> |
| | | 178 | | /// If <paramref name="ownsConnectionInfo"/> is <see langword="true"/>, then the |
| | | 179 | | /// connection info will be disposed when this instance is disposed. |
| | | 180 | | /// </remarks> |
| | | 181 | | private ScpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo) |
| | 312 | 182 | | : this(connectionInfo, ownsConnectionInfo, new ServiceFactory()) |
| | 309 | 183 | | { |
| | 309 | 184 | | } |
| | | 185 | | |
| | | 186 | | /// <summary> |
| | | 187 | | /// Initializes a new instance of the <see cref="ScpClient"/> class. |
| | | 188 | | /// </summary> |
| | | 189 | | /// <param name="connectionInfo">The connection info.</param> |
| | | 190 | | /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param> |
| | | 191 | | /// <param name="serviceFactory">The factory to use for creating new services.</param> |
| | | 192 | | /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</except |
| | | 193 | | /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is <see langword="null"/>.</except |
| | | 194 | | /// <remarks> |
| | | 195 | | /// If <paramref name="ownsConnectionInfo"/> is <see langword="true"/>, then the |
| | | 196 | | /// connection info will be disposed when this instance is disposed. |
| | | 197 | | /// </remarks> |
| | | 198 | | internal ScpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory) |
| | 414 | 199 | | : base(connectionInfo, ownsConnectionInfo, serviceFactory) |
| | 411 | 200 | | { |
| | 411 | 201 | | OperationTimeout = SshNet.Session.InfiniteTimeSpan; |
| | 411 | 202 | | BufferSize = 1024 * 16; |
| | 411 | 203 | | _remotePathTransformation = serviceFactory.CreateRemotePathDoubleQuoteTransformation(); |
| | 411 | 204 | | } |
| | | 205 | | |
| | | 206 | | /// <summary> |
| | | 207 | | /// Uploads the specified stream to the remote host. |
| | | 208 | | /// </summary> |
| | | 209 | | /// <param name="source">The <see cref="Stream"/> to upload.</param> |
| | | 210 | | /// <param name="path">A relative or absolute path for the remote file.</param> |
| | | 211 | | /// <exception cref="ArgumentNullException"><paramref name="path" /> is <see langword="null"/>.</exception> |
| | | 212 | | /// <exception cref="ArgumentException"><paramref name="path"/> is a zero-length <see cref="string"/>.</exceptio |
| | | 213 | | /// <exception cref="ScpException">A directory with the specified path exists on the remote host.</exception> |
| | | 214 | | /// <exception cref="SshException">The secure copy execution request was rejected by the server.</exception> |
| | | 215 | | public void Upload(Stream source, string path) |
| | 186 | 216 | | { |
| | 186 | 217 | | var posixPath = PosixPath.CreateAbsoluteOrRelativeFilePath(path); |
| | | 218 | | |
| | 186 | 219 | | using (var input = ServiceFactory.CreatePipeStream()) |
| | 186 | 220 | | using (var channel = Session.CreateChannelSession()) |
| | 186 | 221 | | { |
| | 696 | 222 | | channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length); |
| | 186 | 223 | | channel.Open(); |
| | | 224 | | |
| | | 225 | | // Pass only the directory part of the path to the server, and use the (hidden) -d option to signal |
| | | 226 | | // that we expect the target to be a directory. |
| | 186 | 227 | | if (!channel.SendExecRequest(string.Format("scp -t -d {0}", _remotePathTransformation.Transform(posixPat |
| | 15 | 228 | | { |
| | 15 | 229 | | throw SecureExecutionRequestRejectedException(); |
| | | 230 | | } |
| | | 231 | | |
| | 171 | 232 | | CheckReturnCode(input); |
| | | 233 | | |
| | 170 | 234 | | UploadFileModeAndName(channel, input, source.Length, posixPath.File); |
| | 169 | 235 | | UploadFileContent(channel, input, source, posixPath.File); |
| | 169 | 236 | | } |
| | 169 | 237 | | } |
| | | 238 | | |
| | | 239 | | /// <summary> |
| | | 240 | | /// Uploads the specified file to the remote host. |
| | | 241 | | /// </summary> |
| | | 242 | | /// <param name="fileInfo">The file system info.</param> |
| | | 243 | | /// <param name="path">A relative or absolute path for the remote file.</param> |
| | | 244 | | /// <exception cref="ArgumentNullException"><paramref name="fileInfo" /> is <see langword="null"/>.</exception> |
| | | 245 | | /// <exception cref="ArgumentNullException"><paramref name="path" /> is <see langword="null"/>.</exception> |
| | | 246 | | /// <exception cref="ArgumentException"><paramref name="path"/> is a zero-length <see cref="string"/>.</exceptio |
| | | 247 | | /// <exception cref="ScpException">A directory with the specified path exists on the remote host.</exception> |
| | | 248 | | /// <exception cref="SshException">The secure copy execution request was rejected by the server.</exception> |
| | | 249 | | public void Upload(FileInfo fileInfo, string path) |
| | 68 | 250 | | { |
| | 68 | 251 | | if (fileInfo is null) |
| | 0 | 252 | | { |
| | 0 | 253 | | throw new ArgumentNullException(nameof(fileInfo)); |
| | | 254 | | } |
| | | 255 | | |
| | 68 | 256 | | var posixPath = PosixPath.CreateAbsoluteOrRelativeFilePath(path); |
| | | 257 | | |
| | 68 | 258 | | using (var input = ServiceFactory.CreatePipeStream()) |
| | 68 | 259 | | using (var channel = Session.CreateChannelSession()) |
| | 68 | 260 | | { |
| | 228 | 261 | | channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length); |
| | 68 | 262 | | channel.Open(); |
| | | 263 | | |
| | | 264 | | // Pass only the directory part of the path to the server, and use the (hidden) -d option to signal |
| | | 265 | | // that we expect the target to be a directory. |
| | 68 | 266 | | if (!channel.SendExecRequest($"scp -t -d {_remotePathTransformation.Transform(posixPath.Directory)}")) |
| | 15 | 267 | | { |
| | 15 | 268 | | throw SecureExecutionRequestRejectedException(); |
| | | 269 | | } |
| | | 270 | | |
| | 53 | 271 | | CheckReturnCode(input); |
| | | 272 | | |
| | 52 | 273 | | using (var source = fileInfo.OpenRead()) |
| | 52 | 274 | | { |
| | 52 | 275 | | UploadTimes(channel, input, fileInfo); |
| | 52 | 276 | | UploadFileModeAndName(channel, input, source.Length, posixPath.File); |
| | 51 | 277 | | UploadFileContent(channel, input, source, fileInfo.Name); |
| | 51 | 278 | | } |
| | 51 | 279 | | } |
| | 51 | 280 | | } |
| | | 281 | | |
| | | 282 | | /// <summary> |
| | | 283 | | /// Uploads the specified directory to the remote host. |
| | | 284 | | /// </summary> |
| | | 285 | | /// <param name="directoryInfo">The directory info.</param> |
| | | 286 | | /// <param name="path">A relative or absolute path for the remote directory.</param> |
| | | 287 | | /// <exception cref="ArgumentNullException"><paramref name="directoryInfo"/> is <see langword="null"/>.</excepti |
| | | 288 | | /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception> |
| | | 289 | | /// <exception cref="ArgumentException"><paramref name="path"/> is a zero-length string.</exception> |
| | | 290 | | /// <exception cref="ScpException"><paramref name="path"/> does not exist on the remote host, is not a directory |
| | | 291 | | /// <exception cref="SshException">The secure copy execution request was rejected by the server.</exception> |
| | | 292 | | public void Upload(DirectoryInfo directoryInfo, string path) |
| | 21 | 293 | | { |
| | 21 | 294 | | if (directoryInfo is null) |
| | 0 | 295 | | { |
| | 0 | 296 | | throw new ArgumentNullException(nameof(directoryInfo)); |
| | | 297 | | } |
| | | 298 | | |
| | 21 | 299 | | if (path is null) |
| | 0 | 300 | | { |
| | 0 | 301 | | throw new ArgumentNullException(nameof(path)); |
| | | 302 | | } |
| | | 303 | | |
| | 21 | 304 | | if (path.Length == 0) |
| | 0 | 305 | | { |
| | 0 | 306 | | throw new ArgumentException("The path cannot be a zero-length string.", nameof(path)); |
| | | 307 | | } |
| | | 308 | | |
| | 21 | 309 | | using (var input = ServiceFactory.CreatePipeStream()) |
| | 21 | 310 | | using (var channel = Session.CreateChannelSession()) |
| | 21 | 311 | | { |
| | 85 | 312 | | channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length); |
| | 21 | 313 | | channel.Open(); |
| | | 314 | | |
| | | 315 | | // start copy with the following options: |
| | | 316 | | // -p preserve modification and access times |
| | | 317 | | // -r copy directories recursively |
| | | 318 | | // -d expect path to be a directory |
| | | 319 | | // -t copy to remote |
| | 21 | 320 | | if (!channel.SendExecRequest($"scp -r -p -d -t {_remotePathTransformation.Transform(path)}")) |
| | 15 | 321 | | { |
| | 15 | 322 | | throw SecureExecutionRequestRejectedException(); |
| | | 323 | | } |
| | | 324 | | |
| | 6 | 325 | | CheckReturnCode(input); |
| | | 326 | | |
| | 4 | 327 | | UploadDirectoryContent(channel, input, directoryInfo); |
| | 4 | 328 | | } |
| | 4 | 329 | | } |
| | | 330 | | |
| | | 331 | | /// <summary> |
| | | 332 | | /// Downloads the specified file from the remote host to local file. |
| | | 333 | | /// </summary> |
| | | 334 | | /// <param name="filename">Remote host file name.</param> |
| | | 335 | | /// <param name="fileInfo">Local file information.</param> |
| | | 336 | | /// <exception cref="ArgumentNullException"><paramref name="fileInfo"/> is <see langword="null"/>.</exception> |
| | | 337 | | /// <exception cref="ArgumentException"><paramref name="filename"/> is <see langword="null"/> or empty.</excepti |
| | | 338 | | /// <exception cref="ScpException"><paramref name="filename"/> exists on the remote host, and is not a regular f |
| | | 339 | | /// <exception cref="SshException">The secure copy execution request was rejected by the server.</exception> |
| | | 340 | | public void Download(string filename, FileInfo fileInfo) |
| | 56 | 341 | | { |
| | 56 | 342 | | if (string.IsNullOrEmpty(filename)) |
| | 0 | 343 | | { |
| | 0 | 344 | | throw new ArgumentException("filename"); |
| | | 345 | | } |
| | | 346 | | |
| | 56 | 347 | | if (fileInfo is null) |
| | 0 | 348 | | { |
| | 0 | 349 | | throw new ArgumentNullException(nameof(fileInfo)); |
| | | 350 | | } |
| | | 351 | | |
| | 56 | 352 | | using (var input = ServiceFactory.CreatePipeStream()) |
| | 56 | 353 | | using (var channel = Session.CreateChannelSession()) |
| | 56 | 354 | | { |
| | 1449 | 355 | | channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length); |
| | 56 | 356 | | channel.Open(); |
| | | 357 | | |
| | | 358 | | // Send channel command request |
| | 56 | 359 | | if (!channel.SendExecRequest($"scp -pf {_remotePathTransformation.Transform(filename)}")) |
| | 15 | 360 | | { |
| | 15 | 361 | | throw SecureExecutionRequestRejectedException(); |
| | | 362 | | } |
| | | 363 | | |
| | | 364 | | // Send reply |
| | 41 | 365 | | SendSuccessConfirmation(channel); |
| | | 366 | | |
| | 41 | 367 | | InternalDownload(channel, input, fileInfo); |
| | 38 | 368 | | } |
| | 38 | 369 | | } |
| | | 370 | | |
| | | 371 | | /// <summary> |
| | | 372 | | /// Downloads the specified directory from the remote host to local directory. |
| | | 373 | | /// </summary> |
| | | 374 | | /// <param name="directoryName">Remote host directory name.</param> |
| | | 375 | | /// <param name="directoryInfo">Local directory information.</param> |
| | | 376 | | /// <exception cref="ArgumentException"><paramref name="directoryName"/> is <see langword="null"/> or empty.</ex |
| | | 377 | | /// <exception cref="ArgumentNullException"><paramref name="directoryInfo"/> is <see langword="null"/>.</excepti |
| | | 378 | | /// <exception cref="ScpException">File or directory with the specified path does not exist on the remote host.< |
| | | 379 | | /// <exception cref="SshException">The secure copy execution request was rejected by the server.</exception> |
| | | 380 | | public void Download(string directoryName, DirectoryInfo directoryInfo) |
| | 20 | 381 | | { |
| | 20 | 382 | | if (string.IsNullOrEmpty(directoryName)) |
| | 0 | 383 | | { |
| | 0 | 384 | | throw new ArgumentException("directoryName"); |
| | | 385 | | } |
| | | 386 | | |
| | 20 | 387 | | if (directoryInfo is null) |
| | 0 | 388 | | { |
| | 0 | 389 | | throw new ArgumentNullException(nameof(directoryInfo)); |
| | | 390 | | } |
| | | 391 | | |
| | 20 | 392 | | using (var input = ServiceFactory.CreatePipeStream()) |
| | 20 | 393 | | using (var channel = Session.CreateChannelSession()) |
| | 20 | 394 | | { |
| | 57 | 395 | | channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length); |
| | 20 | 396 | | channel.Open(); |
| | | 397 | | |
| | | 398 | | // Send channel command request |
| | 20 | 399 | | if (!channel.SendExecRequest($"scp -prf {_remotePathTransformation.Transform(directoryName)}")) |
| | 15 | 400 | | { |
| | 15 | 401 | | throw SecureExecutionRequestRejectedException(); |
| | | 402 | | } |
| | | 403 | | |
| | | 404 | | // Send reply |
| | 5 | 405 | | SendSuccessConfirmation(channel); |
| | | 406 | | |
| | 5 | 407 | | InternalDownload(channel, input, directoryInfo); |
| | 4 | 408 | | } |
| | 4 | 409 | | } |
| | | 410 | | |
| | | 411 | | /// <summary> |
| | | 412 | | /// Downloads the specified file from the remote host to the stream. |
| | | 413 | | /// </summary> |
| | | 414 | | /// <param name="filename">A relative or absolute path for the remote file.</param> |
| | | 415 | | /// <param name="destination">The <see cref="Stream"/> to download the remote file to.</param> |
| | | 416 | | /// <exception cref="ArgumentException"><paramref name="filename"/> is <see langword="null"/> or contains only w |
| | | 417 | | /// <exception cref="ArgumentNullException"><paramref name="destination"/> is <see langword="null"/>.</exception |
| | | 418 | | /// <exception cref="ScpException"><paramref name="filename"/> exists on the remote host, and is not a regular f |
| | | 419 | | /// <exception cref="SshException">The secure copy execution request was rejected by the server.</exception> |
| | | 420 | | public void Download(string filename, Stream destination) |
| | 110 | 421 | | { |
| | 110 | 422 | | if (string.IsNullOrWhiteSpace(filename)) |
| | 0 | 423 | | { |
| | 0 | 424 | | throw new ArgumentException(Message); |
| | | 425 | | } |
| | | 426 | | |
| | 110 | 427 | | if (destination is null) |
| | 0 | 428 | | { |
| | 0 | 429 | | throw new ArgumentNullException(nameof(destination)); |
| | | 430 | | } |
| | | 431 | | |
| | 110 | 432 | | using (var input = ServiceFactory.CreatePipeStream()) |
| | 110 | 433 | | using (var channel = Session.CreateChannelSession()) |
| | 110 | 434 | | { |
| | 542 | 435 | | channel.DataReceived += (sender, e) => input.Write(e.Data, 0, e.Data.Length); |
| | 110 | 436 | | channel.Open(); |
| | | 437 | | |
| | | 438 | | // Send channel command request |
| | 110 | 439 | | if (!channel.SendExecRequest(string.Concat("scp -f ", _remotePathTransformation.Transform(filename)))) |
| | 15 | 440 | | { |
| | 15 | 441 | | throw SecureExecutionRequestRejectedException(); |
| | | 442 | | } |
| | | 443 | | |
| | 95 | 444 | | SendSuccessConfirmation(channel); // Send reply |
| | | 445 | | |
| | 95 | 446 | | var message = ReadString(input); |
| | 91 | 447 | | var match = FileInfoRe.Match(message); |
| | | 448 | | |
| | 91 | 449 | | if (match.Success) |
| | 91 | 450 | | { |
| | | 451 | | // Read file |
| | 91 | 452 | | SendSuccessConfirmation(channel); // Send reply |
| | | 453 | | |
| | 91 | 454 | | var length = long.Parse(match.Result("${length}"), CultureInfo.InvariantCulture); |
| | 91 | 455 | | var fileName = match.Result("${filename}"); |
| | | 456 | | |
| | 91 | 457 | | InternalDownload(channel, input, destination, fileName, length); |
| | 91 | 458 | | } |
| | | 459 | | else |
| | 0 | 460 | | { |
| | 0 | 461 | | SendErrorConfirmation(channel, string.Format("\"{0}\" is not valid protocol message.", message)); |
| | 0 | 462 | | } |
| | 91 | 463 | | } |
| | 91 | 464 | | } |
| | | 465 | | |
| | | 466 | | private static void SendData(IChannel channel, byte[] buffer, int length) |
| | 3853 | 467 | | { |
| | 3853 | 468 | | channel.SendData(buffer, 0, length); |
| | 3853 | 469 | | } |
| | | 470 | | |
| | | 471 | | private static void SendData(IChannel channel, byte[] buffer) |
| | 705 | 472 | | { |
| | 705 | 473 | | channel.SendData(buffer); |
| | 705 | 474 | | } |
| | | 475 | | |
| | | 476 | | private static int ReadByte(Stream stream) |
| | 6497 | 477 | | { |
| | 6497 | 478 | | var b = stream.ReadByte(); |
| | | 479 | | |
| | 6497 | 480 | | if (b == -1) |
| | 0 | 481 | | { |
| | 0 | 482 | | throw new SshException("Stream has been closed."); |
| | | 483 | | } |
| | | 484 | | |
| | 6497 | 485 | | return b; |
| | 6497 | 486 | | } |
| | | 487 | | |
| | | 488 | | private static SshException SecureExecutionRequestRejectedException() |
| | 90 | 489 | | { |
| | 90 | 490 | | throw new SshException("Secure copy execution request was rejected by the server. Please consult the server |
| | | 491 | | } |
| | | 492 | | |
| | | 493 | | /// <summary> |
| | | 494 | | /// Sets mode, size and name of file being upload. |
| | | 495 | | /// </summary> |
| | | 496 | | /// <param name="channel">The channel to perform the upload in.</param> |
| | | 497 | | /// <param name="input">A <see cref="Stream"/> from which any feedback from the server can be read.</param> |
| | | 498 | | /// <param name="fileSize">The size of the content to upload.</param> |
| | | 499 | | /// <param name="serverFileName">The name of the file, without path, to which the content is to be uploaded.</pa |
| | | 500 | | /// <remarks> |
| | | 501 | | /// <para> |
| | | 502 | | /// When the SCP transfer is already initiated for a file, a zero-length <see cref="string"/> should |
| | | 503 | | /// be specified for <paramref name="serverFileName"/>. This prevents the server from uploading the |
| | | 504 | | /// content to a file with path <c><file path>/<paramref name="serverFileName"/></c> if there's |
| | | 505 | | /// already a directory with this path, and allows us to receive an error response. |
| | | 506 | | /// </para> |
| | | 507 | | /// </remarks> |
| | | 508 | | private void UploadFileModeAndName(IChannelSession channel, Stream input, long fileSize, string serverFileName) |
| | 234 | 509 | | { |
| | 234 | 510 | | SendData(channel, string.Format("C0644 {0} {1}\n", fileSize, serverFileName)); |
| | 234 | 511 | | CheckReturnCode(input); |
| | 232 | 512 | | } |
| | | 513 | | |
| | | 514 | | /// <summary> |
| | | 515 | | /// Uploads the content of a file. |
| | | 516 | | /// </summary> |
| | | 517 | | /// <param name="channel">The channel to perform the upload in.</param> |
| | | 518 | | /// <param name="input">A <see cref="Stream"/> from which any feedback from the server can be read.</param> |
| | | 519 | | /// <param name="source">The content to upload.</param> |
| | | 520 | | /// <param name="remoteFileName">The name of the remote file, without path, to which the content is uploaded.</p |
| | | 521 | | /// <remarks> |
| | | 522 | | /// <paramref name="remoteFileName"/> is only used for raising the <see cref="Uploading"/> event. |
| | | 523 | | /// </remarks> |
| | | 524 | | private void UploadFileContent(IChannelSession channel, Stream input, Stream source, string remoteFileName) |
| | 232 | 525 | | { |
| | 232 | 526 | | var totalLength = source.Length; |
| | 232 | 527 | | var buffer = new byte[BufferSize]; |
| | | 528 | | |
| | 232 | 529 | | var read = source.Read(buffer, 0, buffer.Length); |
| | | 530 | | |
| | 232 | 531 | | long totalRead = 0; |
| | | 532 | | |
| | 4085 | 533 | | while (read > 0) |
| | 3853 | 534 | | { |
| | 3853 | 535 | | SendData(channel, buffer, read); |
| | | 536 | | |
| | 3853 | 537 | | totalRead += read; |
| | | 538 | | |
| | 3853 | 539 | | RaiseUploadingEvent(remoteFileName, totalLength, totalRead); |
| | | 540 | | |
| | 3853 | 541 | | read = source.Read(buffer, 0, buffer.Length); |
| | 3853 | 542 | | } |
| | | 543 | | |
| | 232 | 544 | | SendSuccessConfirmation(channel); |
| | 232 | 545 | | CheckReturnCode(input); |
| | 232 | 546 | | } |
| | | 547 | | |
| | | 548 | | private void RaiseDownloadingEvent(string filename, long size, long downloaded) |
| | 3566 | 549 | | { |
| | 3566 | 550 | | Downloading?.Invoke(this, new ScpDownloadEventArgs(filename, size, downloaded)); |
| | 3566 | 551 | | } |
| | | 552 | | |
| | | 553 | | private void RaiseUploadingEvent(string filename, long size, long uploaded) |
| | 3853 | 554 | | { |
| | 3853 | 555 | | Uploading?.Invoke(this, new ScpUploadEventArgs(filename, size, uploaded)); |
| | 3853 | 556 | | } |
| | | 557 | | |
| | | 558 | | private static void SendSuccessConfirmation(IChannel channel) |
| | 705 | 559 | | { |
| | 705 | 560 | | SendData(channel, SuccessConfirmationCode); |
| | 705 | 561 | | } |
| | | 562 | | |
| | | 563 | | private void SendErrorConfirmation(IChannel channel, string message) |
| | 0 | 564 | | { |
| | 0 | 565 | | SendData(channel, ErrorConfirmationCode); |
| | 0 | 566 | | SendData(channel, string.Concat(message, "\n")); |
| | 0 | 567 | | } |
| | | 568 | | |
| | | 569 | | /// <summary> |
| | | 570 | | /// Checks the return code. |
| | | 571 | | /// </summary> |
| | | 572 | | /// <param name="input">The output stream.</param> |
| | | 573 | | private void CheckReturnCode(Stream input) |
| | 918 | 574 | | { |
| | 918 | 575 | | var b = ReadByte(input); |
| | | 576 | | |
| | 918 | 577 | | if (b > 0) |
| | 6 | 578 | | { |
| | 6 | 579 | | var errorText = ReadString(input); |
| | | 580 | | |
| | 6 | 581 | | throw new ScpException(errorText); |
| | | 582 | | } |
| | 912 | 583 | | } |
| | | 584 | | |
| | | 585 | | private void SendData(IChannel channel, string command) |
| | 320 | 586 | | { |
| | 320 | 587 | | channel.SendData(ConnectionInfo.Encoding.GetBytes(command)); |
| | 320 | 588 | | } |
| | | 589 | | |
| | | 590 | | /// <summary> |
| | | 591 | | /// Read a LF-terminated string from the <see cref="Stream"/>. |
| | | 592 | | /// </summary> |
| | | 593 | | /// <param name="stream">The <see cref="Stream"/> to read from.</param> |
| | | 594 | | /// <returns> |
| | | 595 | | /// The string without trailing LF. |
| | | 596 | | /// </returns> |
| | | 597 | | private string ReadString(Stream stream) |
| | 210 | 598 | | { |
| | 210 | 599 | | var hasError = false; |
| | | 600 | | |
| | 210 | 601 | | var buffer = new List<byte>(); |
| | | 602 | | |
| | 210 | 603 | | var b = ReadByte(stream); |
| | 210 | 604 | | if (b is 1 or 2) |
| | 8 | 605 | | { |
| | 8 | 606 | | hasError = true; |
| | 8 | 607 | | b = ReadByte(stream); |
| | 8 | 608 | | } |
| | | 609 | | |
| | 5571 | 610 | | while (b != SshNet.Session.LineFeed) |
| | 5361 | 611 | | { |
| | 5361 | 612 | | buffer.Add((byte) b); |
| | 5361 | 613 | | b = ReadByte(stream); |
| | 5361 | 614 | | } |
| | | 615 | | |
| | 210 | 616 | | var readBytes = buffer.ToArray(); |
| | | 617 | | |
| | 210 | 618 | | if (hasError) |
| | 8 | 619 | | { |
| | 8 | 620 | | throw new ScpException(ConnectionInfo.Encoding.GetString(readBytes, 0, readBytes.Length)); |
| | | 621 | | } |
| | | 622 | | |
| | 202 | 623 | | return ConnectionInfo.Encoding.GetString(readBytes, 0, readBytes.Length); |
| | 202 | 624 | | } |
| | | 625 | | |
| | | 626 | | /// <summary> |
| | | 627 | | /// Uploads the <see cref="FileSystemInfo.LastWriteTimeUtc"/> and <see cref="FileSystemInfo.LastAccessTimeUtc"/> |
| | | 628 | | /// of the next file or directory to upload. |
| | | 629 | | /// </summary> |
| | | 630 | | /// <param name="channel">The channel to perform the upload in.</param> |
| | | 631 | | /// <param name="input">A <see cref="Stream"/> from which any feedback from the server can be read.</param> |
| | | 632 | | /// <param name="fileOrDirectory">The file or directory to upload.</param> |
| | | 633 | | private void UploadTimes(IChannelSession channel, Stream input, FileSystemInfo fileOrDirectory) |
| | 70 | 634 | | { |
| | | 635 | | #if NET ||NETSTANDARD2_1_OR_GREATER |
| | 66 | 636 | | var zeroTime = DateTime.UnixEpoch; |
| | | 637 | | #else |
| | 4 | 638 | | var zeroTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); |
| | | 639 | | #endif |
| | 70 | 640 | | var modificationSeconds = (long) (fileOrDirectory.LastWriteTimeUtc - zeroTime).TotalSeconds; |
| | 70 | 641 | | var accessSeconds = (long) (fileOrDirectory.LastAccessTimeUtc - zeroTime).TotalSeconds; |
| | 70 | 642 | | SendData(channel, string.Format(CultureInfo.InvariantCulture, "T{0} 0 {1} 0\n", modificationSeconds, accessS |
| | 70 | 643 | | CheckReturnCode(input); |
| | 70 | 644 | | } |
| | | 645 | | |
| | | 646 | | /// <summary> |
| | | 647 | | /// Upload the files and subdirectories in the specified directory. |
| | | 648 | | /// </summary> |
| | | 649 | | /// <param name="channel">The channel to perform the upload in.</param> |
| | | 650 | | /// <param name="input">A <see cref="Stream"/> from which any feedback from the server can be read.</param> |
| | | 651 | | /// <param name="directoryInfo">The directory to upload.</param> |
| | | 652 | | private void UploadDirectoryContent(IChannelSession channel, Stream input, DirectoryInfo directoryInfo) |
| | 10 | 653 | | { |
| | | 654 | | // Upload files |
| | 10 | 655 | | var files = directoryInfo.GetFiles(); |
| | 54 | 656 | | foreach (var file in files) |
| | 12 | 657 | | { |
| | 12 | 658 | | using (var source = file.OpenRead()) |
| | 12 | 659 | | { |
| | 12 | 660 | | UploadTimes(channel, input, file); |
| | 12 | 661 | | UploadFileModeAndName(channel, input, source.Length, file.Name); |
| | 12 | 662 | | UploadFileContent(channel, input, source, file.Name); |
| | 12 | 663 | | } |
| | 12 | 664 | | } |
| | | 665 | | |
| | | 666 | | // Upload directories |
| | 10 | 667 | | var directories = directoryInfo.GetDirectories(); |
| | 42 | 668 | | foreach (var directory in directories) |
| | 6 | 669 | | { |
| | 6 | 670 | | UploadTimes(channel, input, directory); |
| | 6 | 671 | | UploadDirectoryModeAndName(channel, input, directory.Name); |
| | 6 | 672 | | UploadDirectoryContent(channel, input, directory); |
| | 6 | 673 | | } |
| | | 674 | | |
| | | 675 | | // Mark upload of current directory complete |
| | 10 | 676 | | SendData(channel, "E\n"); |
| | 10 | 677 | | CheckReturnCode(input); |
| | 10 | 678 | | } |
| | | 679 | | |
| | | 680 | | /// <summary> |
| | | 681 | | /// Sets mode and name of the directory being upload. |
| | | 682 | | /// </summary> |
| | | 683 | | private void UploadDirectoryModeAndName(IChannelSession channel, Stream input, string directoryName) |
| | 6 | 684 | | { |
| | 6 | 685 | | SendData(channel, string.Format("D0755 0 {0}\n", directoryName)); |
| | 6 | 686 | | CheckReturnCode(input); |
| | 6 | 687 | | } |
| | | 688 | | |
| | | 689 | | private void InternalDownload(IChannel channel, Stream input, Stream output, string filename, long length) |
| | 136 | 690 | | { |
| | 136 | 691 | | var buffer = new byte[Math.Min(length, BufferSize)]; |
| | 136 | 692 | | var needToRead = length; |
| | | 693 | | |
| | | 694 | | do |
| | 3430 | 695 | | { |
| | 3430 | 696 | | var read = input.Read(buffer, 0, (int) Math.Min(needToRead, BufferSize)); |
| | | 697 | | |
| | 3430 | 698 | | output.Write(buffer, 0, read); |
| | | 699 | | |
| | 3430 | 700 | | RaiseDownloadingEvent(filename, length, length - needToRead); |
| | | 701 | | |
| | 3430 | 702 | | needToRead -= read; |
| | 3430 | 703 | | } |
| | 3430 | 704 | | while (needToRead > 0); |
| | | 705 | | |
| | 136 | 706 | | output.Flush(); |
| | | 707 | | |
| | | 708 | | // Raise one more time when file downloaded |
| | 136 | 709 | | RaiseDownloadingEvent(filename, length, length - needToRead); |
| | | 710 | | |
| | | 711 | | // Send confirmation byte after last data byte was read |
| | 136 | 712 | | SendSuccessConfirmation(channel); |
| | | 713 | | |
| | 136 | 714 | | CheckReturnCode(input); |
| | 136 | 715 | | } |
| | | 716 | | |
| | | 717 | | private void InternalDownload(IChannelSession channel, Stream input, FileSystemInfo fileSystemInfo) |
| | 46 | 718 | | { |
| | 46 | 719 | | var modifiedTime = DateTime.Now; |
| | 46 | 720 | | var accessedTime = DateTime.Now; |
| | | 721 | | |
| | 46 | 722 | | var startDirectoryFullName = fileSystemInfo.FullName; |
| | 46 | 723 | | var currentDirectoryFullName = startDirectoryFullName; |
| | 46 | 724 | | var directoryCounter = 0; |
| | | 725 | | |
| | 109 | 726 | | while (true) |
| | 109 | 727 | | { |
| | 109 | 728 | | var message = ReadString(input); |
| | | 729 | | |
| | 105 | 730 | | if (message == "E") |
| | 5 | 731 | | { |
| | 5 | 732 | | SendSuccessConfirmation(channel); // Send reply |
| | | 733 | | |
| | 5 | 734 | | directoryCounter--; |
| | | 735 | | |
| | 5 | 736 | | currentDirectoryFullName = new DirectoryInfo(currentDirectoryFullName).Parent.FullName; |
| | | 737 | | |
| | 5 | 738 | | if (directoryCounter == 0) |
| | 3 | 739 | | { |
| | 3 | 740 | | break; |
| | | 741 | | } |
| | | 742 | | |
| | 2 | 743 | | continue; |
| | | 744 | | } |
| | | 745 | | |
| | 100 | 746 | | var match = DirectoryInfoRe.Match(message); |
| | 100 | 747 | | if (match.Success) |
| | 5 | 748 | | { |
| | 5 | 749 | | SendSuccessConfirmation(channel); // Send reply |
| | | 750 | | |
| | | 751 | | // Read directory |
| | 5 | 752 | | var filename = match.Result("${filename}"); |
| | | 753 | | |
| | | 754 | | DirectoryInfo newDirectoryInfo; |
| | 5 | 755 | | if (directoryCounter > 0) |
| | 2 | 756 | | { |
| | 2 | 757 | | newDirectoryInfo = Directory.CreateDirectory(Path.Combine(currentDirectoryFullName, filename)); |
| | 2 | 758 | | newDirectoryInfo.LastAccessTime = accessedTime; |
| | 2 | 759 | | newDirectoryInfo.LastWriteTime = modifiedTime; |
| | 2 | 760 | | } |
| | | 761 | | else |
| | 3 | 762 | | { |
| | | 763 | | // Don't create directory for first level |
| | 3 | 764 | | newDirectoryInfo = fileSystemInfo as DirectoryInfo; |
| | 3 | 765 | | } |
| | | 766 | | |
| | 5 | 767 | | directoryCounter++; |
| | | 768 | | |
| | 5 | 769 | | currentDirectoryFullName = newDirectoryInfo.FullName; |
| | 5 | 770 | | continue; |
| | | 771 | | } |
| | | 772 | | |
| | 95 | 773 | | match = FileInfoRe.Match(message); |
| | 95 | 774 | | if (match.Success) |
| | 45 | 775 | | { |
| | | 776 | | // Read file |
| | 45 | 777 | | SendSuccessConfirmation(channel); // Send reply |
| | | 778 | | |
| | 45 | 779 | | var length = long.Parse(match.Result("${length}"), CultureInfo.InvariantCulture); |
| | 45 | 780 | | var fileName = match.Result("${filename}"); |
| | | 781 | | |
| | 45 | 782 | | if (fileSystemInfo is not FileInfo fileInfo) |
| | 7 | 783 | | { |
| | 7 | 784 | | fileInfo = new FileInfo(Path.Combine(currentDirectoryFullName, fileName)); |
| | 7 | 785 | | } |
| | | 786 | | |
| | 45 | 787 | | using (var output = fileInfo.OpenWrite()) |
| | 45 | 788 | | { |
| | 45 | 789 | | InternalDownload(channel, input, output, fileName, length); |
| | 45 | 790 | | } |
| | | 791 | | |
| | 45 | 792 | | fileInfo.LastAccessTime = accessedTime; |
| | 45 | 793 | | fileInfo.LastWriteTime = modifiedTime; |
| | | 794 | | |
| | 45 | 795 | | if (directoryCounter == 0) |
| | 39 | 796 | | { |
| | 39 | 797 | | break; |
| | | 798 | | } |
| | | 799 | | |
| | 6 | 800 | | continue; |
| | | 801 | | } |
| | | 802 | | |
| | 50 | 803 | | match = TimestampRe.Match(message); |
| | 50 | 804 | | if (match.Success) |
| | 50 | 805 | | { |
| | | 806 | | // Read timestamp |
| | 50 | 807 | | SendSuccessConfirmation(channel); // Send reply |
| | | 808 | | |
| | 50 | 809 | | var mtime = long.Parse(match.Result("${mtime}"), CultureInfo.InvariantCulture); |
| | 50 | 810 | | var atime = long.Parse(match.Result("${atime}"), CultureInfo.InvariantCulture); |
| | | 811 | | |
| | | 812 | | #if NET || NETSTANDARD2_1_OR_GREATER |
| | 50 | 813 | | var zeroTime = DateTime.UnixEpoch; |
| | | 814 | | #else |
| | 0 | 815 | | var zeroTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); |
| | | 816 | | #endif |
| | 50 | 817 | | modifiedTime = zeroTime.AddSeconds(mtime); |
| | 50 | 818 | | accessedTime = zeroTime.AddSeconds(atime); |
| | 50 | 819 | | continue; |
| | | 820 | | } |
| | | 821 | | |
| | 0 | 822 | | SendErrorConfirmation(channel, string.Format("\"{0}\" is not valid protocol message.", message)); |
| | 0 | 823 | | } |
| | 42 | 824 | | } |
| | | 825 | | } |
| | | 826 | | } |