Exemplo n.º 1
0
 public bool GetFile(string sourcePath, string destinationPath, IFileTransferHandler handler, bool ifNewer)
 {
     if (ifNewer)
     {
         var modified = File.GetLastWriteTimeUtc(destinationPath);
         var remoteModified = DateTime.MinValue;
         try
         {
             remoteModified = Sftp.GetLastWriteTimeUtc(sourcePath);
         }
         catch (SftpPathNotFoundException)
         {
         }
         if (remoteModified <= modified)
         {
             if (handler != null)
             {
                 handler.FileUpToDate();
             }
             return false;
         }
     }
     using (var file = File.OpenWrite(destinationPath))
     {
         var result = Sftp.BeginDownloadFile(
             sourcePath,
             file,
             r => handler.TransferCompleted(),
             new object(),
             handler.IncrementBytesTransferred);
         Sftp.EndDownloadFile(result);
     }
     return true;
 }
Exemplo n.º 2
0
 void OnTransferInvite(IFileTransferHandler invitation)
 {
     Dispatcher.Invoke(() =>
     {
         FlashWindow();
         if (invitation == null)
         {
             chatTextBox.AddInfo(Translation.Instance.ChatWindow_FileTransferInviteNotSupported);
             return;
         }
         string downloadsFolder = SquiggleUtility.GetDownloadsFolderPath();
         downloadsFolder        = Path.Combine(downloadsFolder, PrimaryBuddy.DisplayName);
         chatTextBox.AddFileReceiveRequest(invitation, downloadsFolder);
         fileTransfers.Add(invitation);
     });
     chatState.ChatStarted = true;
 }
Exemplo n.º 3
0
        public FileTransferControl(IFileTransferHandler fileTransfer, bool sending) : this()
        {
            this.fileTransfer = fileTransfer;
            this.sending      = sending;

            FileName = fileTransfer.Name;
            FileSize = fileTransfer.Size;
            Status   = sending ? Translation.Instance.FileTransfer_Waiting : ToReadableFileSize(FileSize);
            btnCancelTransfer.Content = sending ? Translation.Instance.Activity_Cancel : Translation.Instance.Activity_Reject;

            NotifyPropertyChanged();

            this.fileTransfer.ProgressChanged   += fileTransfer_ProgressChanged;
            this.fileTransfer.TransferStarted   += fileTransfer_TransferStarted;
            this.fileTransfer.TransferCancelled += fileTransfer_TransferCancelled;
            this.fileTransfer.TransferCompleted += fileTransfer_TransferCompleted;

            ShowWaiting();
        }
Exemplo n.º 4
0
 public bool GetFile(string sourcePath, string destinationPath, IFileTransferHandler handler, bool ifNewer)
 {
     return PutFile(destinationPath, sourcePath, handler, ifNewer);
 }
Exemplo n.º 5
0
        private static void CopyFile(Stream source, string destination, int bytesPerChunk, IFileTransferHandler handler)
        {
            using (var br = new BinaryReader(source))
            {
                using (var fsDest = new FileStream(destination, FileMode.Create))
                {
                    var bw = new BinaryWriter(fsDest);
                    var buffer = new byte[bytesPerChunk];
                    int bytesRead;

                    for (long i = 0; i < source.Length; i += bytesRead)
                    {
                        bytesRead = br.Read(buffer, 0, bytesPerChunk);
                        bw.Write(buffer, 0, bytesRead);
                        handler.IncrementBytesTransferred((ulong)bytesRead);
                    }
                }
            }
            handler.TransferCompleted();
        }
Exemplo n.º 6
0
 public void PutFile(Stream source, IPurePath destinationPath, IFileTransferHandler handler)
 {
     CopyFile(source, destinationPath.ToString(), 1024, handler);
 }
Exemplo n.º 7
0
 public void PutFile(Stream source, string destinationPath, IFileTransferHandler handler)
 {
     PutFile(source, Context.LocalEnv.CreatePurePath(destinationPath), handler);
 }
Exemplo n.º 8
0
 public void PutFile(Stream source, string destinationPath, IFileTransferHandler handler)
 {
     LogDryRun("PutFile", String.Format("Sending contents of a stream to a remote host " +
                     "and placing it at {0}.", destinationPath));
 }
Exemplo n.º 9
0
 /// <summary>
 /// Begins an asynchronous uploading the steam into remote file.
 /// </summary>
 /// <param name="input">Data input stream.</param>
 /// <param name="path">Remote file path.</param>
 /// <param name="handler">The object that handles callbacks for transferred data.</param>
 /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
 /// <exception cref="ArgumentNullException"><paramref name="input"/> is <b>null</b>.</exception>
 /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>
 /// <exception cref="SshConnectionException">Client is not connected.</exception>
 /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to list the contents of the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
 /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
 /// <remarks>Method calls made by this method to <paramref name="input"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>
 public IAsyncResult BeginUploadFile(Stream input, string path, IFileTransferHandler handler, object state)
 {
     return this.BeginUploadFile(input, path, true, handler, state);
 }
Exemplo n.º 10
0
 public void GetFile(string sourcePath, Stream destination, IFileTransferHandler handler)
 {
     LogDryRun("GetFile", String.Format("Retrieving the file {0} from a remote host " +
         "and writing it to a stream.", sourcePath));
 }
Exemplo n.º 11
0
        public static void AddFileReceiveRequest(this ChatTextBox textbox, IFileTransferHandler session, string downloadsFolder)
        {
            var item = new FileTransferItem(session, downloadsFolder);

            textbox.AddItem(item);
        }
Exemplo n.º 12
0
 public void PutFile(Stream source, IPurePath destinationPath, IFileTransferHandler handler)
 {
     var result = Sftp.BeginUploadFile(
         source,
         destinationPath.ToString(),
         r => handler.TransferCanceled(),
         new object(),
         handler.IncrementBytesTransferred);
     Sftp.EndUploadFile(result);
 }
Exemplo n.º 13
0
        public bool PutFile(IPurePath sourcePath, IPurePath destinationPath, IFileTransferHandler handler, bool ifNewer)
        {
            var filename = sourcePath.Filename;
            var source = Context.LocalEnv.CurrentDirectory.Join(sourcePath);
            var dest = Context.RemoteEnv.CurrentDirectory.Join(destinationPath);

            if (handler != null)
            {
                handler.Filename = filename;
            }

            if (!File.Exists(source.ToString()))
            {
                if (handler != null)
                {
                    handler.FileDoesNotExist();
                }
                return false;
            }

            if (String.IsNullOrEmpty(dest.Filename) ||
                Sftp.GetAttributes(dest.ToString()).IsDirectory)
            {
                dest = dest.WithFilename(filename);
            }

            if (ifNewer)
            {
                var modified = File.GetLastWriteTimeUtc(source.ToString());
                var remoteModified = DateTime.MinValue;
                try
                {
                    remoteModified = Sftp.GetLastWriteTimeUtc(dest.ToString());
                }
                catch (SftpPathNotFoundException)
                {
                }
                if (modified <= remoteModified)
                {
                    if (handler != null)
                    {
                        handler.FileUpToDate();
                    }
                    return false;
                }
            }
            using (var file = File.OpenRead(source.ToString()))
            {
                PutFile(file, dest, handler);
            }
            return true;
        }
Exemplo n.º 14
0
 public void GetFile(string sourcePath, Stream destination, IFileTransferHandler handler)
 {
     throw new NotImplementedException(); // TODO SFTP get to a stream.
 }
Exemplo n.º 15
0
        internal SftpFileStream(SftpSession session, string path, FileMode mode, FileAccess access, int bufferSize, bool useAsync, IFileTransferHandler handler)
        {
            // Validate the parameters.
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (bufferSize <= 0)
            {
                throw new ArgumentOutOfRangeException("bufferSize");
            }
            if (access < FileAccess.Read || access > FileAccess.ReadWrite)
            {
                throw new ArgumentOutOfRangeException("access");
            }
            if (mode < FileMode.CreateNew || mode > FileMode.Append)
            {
                throw new ArgumentOutOfRangeException("mode");
            }

            this.Timeout = TimeSpan.FromSeconds(30);
            this.Name = path;

            // Initialize the object state.
            this._session = session;
            this._access = access;
            this._ownsHandle = true;
            this._isAsync = useAsync;
            this._path = path;
            this._bufferSize = bufferSize;
            this._buffer = new byte[bufferSize];
            this._bufferPosn = 0;
            this._bufferLen = 0;
            this._bufferOwnedByWrite = false;
            this._canSeek = true;
            this._position = 0;
            this._fileTransferHandler = handler;

            var flags = Flags.None;

            switch (access)
            {
                case FileAccess.Read:
                    flags |= Flags.Read;
                    break;
                case FileAccess.Write:
                    flags |= Flags.Write;
                    break;
                case FileAccess.ReadWrite:
                    flags |= Flags.Read;
                    flags |= Flags.Write;
                    break;
                default:
                    break;
            }

            switch (mode)
            {
                case FileMode.Append:
                    flags |= Flags.Append;
                    break;
                case FileMode.Create:
                    this._handle = this._session.RequestOpen(path, flags | Flags.Truncate, true);
                    if (this._handle == null)
                    {
                        flags |= Flags.CreateNew;
                    }
                    else
                    {
                        flags |= Flags.Truncate;
                    }
                    break;
                case FileMode.CreateNew:
                    flags |= Flags.CreateNew;
                    break;
                case FileMode.Open:
                    break;
                case FileMode.OpenOrCreate:
                    flags |= Flags.CreateNewOrOpen;
                    break;
                case FileMode.Truncate:
                    flags |= Flags.Truncate;
                    break;
                default:
                    break;
            }

            if (this._handle == null)
                this._handle = this._session.RequestOpen(this._path, flags);

            this._attributes = this._session.RequestFStat(this._handle);

            if (mode == FileMode.Append)
            {
                this._position = this._attributes.Size;
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Performs SSH_FXP_WRITE request.
        /// </summary>
        /// <param name="handle">The handle.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="data">The data to send.</param>
        /// <param name="wait">The wait event handle if needed.</param>
        /// <param name="handler">The object that handles callbacks for transferred data.</param>
        internal void RequestWrite(byte[] handle, UInt64 offset, byte[] data, EventWaitHandle wait, IFileTransferHandler handler)
        {
            var maximumDataSize = 1024 * 32 - 52;

            if (data.Length < maximumDataSize + 1)
            {
                var request = new SftpWriteRequest(this.NextRequestId, handle, offset, data,
                    (response) =>
                    {
                        if (response.StatusCode == StatusCodes.Ok)
                        {
                            if (wait != null)
                                wait.Set();
                            if (handler != null)
                                handler.IncrementBytesTransferred((ulong)data.Length);
                        }
                        else
                        {
                            this.ThrowSftpException(response);
                        }
                    });

                this.SendRequest(request);

                if (wait != null)
                    this.WaitHandle(wait, this._operationTimeout);
            }
            else
            {
                var block = data.Length / maximumDataSize + 1;

                for (int i = 0; i < block; i++)
                {
                    var blockBufferSize = Math.Min(data.Length - maximumDataSize * i, maximumDataSize);
                    var blockBuffer = new byte[blockBufferSize];

                    Buffer.BlockCopy(data, i * maximumDataSize, blockBuffer, 0, blockBufferSize);

                    var request = new SftpWriteRequest(this.NextRequestId, handle, offset + (ulong)(i * maximumDataSize), blockBuffer,
                        (response) =>
                        {
                            if (response.StatusCode == StatusCodes.Ok)
                            {
                                if (wait != null)
                                    wait.Set();
                                if (handler != null)
                                    handler.IncrementBytesTransferred((ulong)blockBufferSize);
                            }
                            else
                            {
                                this.ThrowSftpException(response);
                            }
                        });

                    this.SendRequest(request);

                    if (wait != null)
                        this.WaitHandle(wait, this._operationTimeout);
                }
            }
        }
Exemplo n.º 17
0
 public void GetFile(string sourcePath, Stream destination, IFileTransferHandler handler)
 {
     PutFile(destination, sourcePath, handler);
 }
Exemplo n.º 18
0
        /// <exception cref="ArgumentNullException"><paramref name="input"/> is <b>null</b>.</exception>
        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace.</exception>
        /// <exception cref="SshConnectionException">Client not connected.</exception>
        private void InternalUploadFile(Stream input, string path, IFileTransferHandler handler, Flags flags)
        {
            if (input == null)
                throw new ArgumentNullException("input");

            if (path.IsNullOrWhiteSpace())
                throw new ArgumentException("path");

            //  Ensure that connection is established.
            this.EnsureConnection();

            var fullPath = this._sftpSession.GetCanonicalPath(path);

            var handle = this._sftpSession.RequestOpen(fullPath, flags);

            ulong offset = 0;

            var buffer = new byte[this.BufferSize];

            var uploadCompleted = false;

            do
            {
                var bytesRead = input.Read(buffer, 0, buffer.Length);

                if (bytesRead < this.BufferSize)
                {
                    var data = new byte[bytesRead];
                    Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
                    using (var wait = new AutoResetEvent(false))
                    {
                        this._sftpSession.RequestWrite(handle, offset, data, wait, handler);
                    }
                    uploadCompleted = true;
                }
                else
                {
                    this._sftpSession.RequestWrite(handle, offset, buffer, null, handler);
                }

                offset += (uint)bytesRead;

            } while (!uploadCompleted);

            this._sftpSession.RequestClose(handle);
        }
Exemplo n.º 19
0
        public static void AddFileSentRequest(this ChatTextBox textbox, IFileTransferHandler session)
        {
            var item = new FileTransferItem(session);

            textbox.AddItem(item);
        }
Exemplo n.º 20
0
 public bool GetFile(string sourcePath, string destinationPath, IFileTransferHandler handler, bool ifNewer)
 {
     LogDryRun("GetFile", String.Format("Retrieving the file {0} from a remote host " +
         "and placing it at {1}.", sourcePath, destinationPath));
     return false;
 }
Exemplo n.º 21
0
        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b> or contains whitespace.</exception>
        /// <exception cref="ArgumentException"><paramref name="output"/> is <b>null</b>.</exception>
        /// <exception cref="SshConnectionException">Client not connected.</exception>
        private void InternalDownloadFile(string path, Stream output, IFileTransferHandler handler)
        {
            if (output == null)
                throw new ArgumentNullException("output");

            if (path.IsNullOrWhiteSpace())
                throw new ArgumentException("path");

            //  Ensure that connection is established.
            this.EnsureConnection();

            var fullPath = this._sftpSession.GetCanonicalPath(path);

            var handle = this._sftpSession.RequestOpen(fullPath, Flags.Read);

            ulong offset = 0;

            var data = this._sftpSession.RequestRead(handle, offset, this.BufferSize);

            //  Read data while available
            while (data.Length > 0)
            {
                output.Write(data, 0, data.Length);

                output.Flush();

                offset += (ulong)data.Length;

                //  Call callback to report number of bytes read
                if (handler != null)
                {
                    handler.IncrementBytesTransferred((ulong)data.Length);
                }

                data = this._sftpSession.RequestRead(handle, offset, this.BufferSize);
            }

            this._sftpSession.RequestClose(handle);
        }
Exemplo n.º 22
0
 public bool PutFile(string sourcePath, string destinationPath, IFileTransferHandler handler, bool ifNewer)
 {
     var source = Context.LocalEnv.CreatePurePath(sourcePath);
     var dest = Context.LocalEnv.CreatePurePath(destinationPath);
     return PutFile(source, dest, handler, ifNewer);
 }
Exemplo n.º 23
0
        /// <summary>
        /// Begins an asynchronous file downloading into the stream.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="output">The output.</param>
        /// <param name="handler">The object that handles callbacks for transferred data.</param>
        /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
        /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="output"/> is <b>null</b>.</exception>
        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>
        /// <exception cref="SshConnectionException">Client is not connected.</exception>
        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
        /// <remarks>Method calls made by this method to <paramref name="output"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>
        public IAsyncResult BeginDownloadFile(string path, Stream output, IFileTransferHandler handler, object state)
        {
            if (path.IsNullOrWhiteSpace())
                throw new ArgumentException("path");

            if (output == null)
                throw new ArgumentNullException("output");

            //  Ensure that connection is established.
            this.EnsureConnection();

            AsyncCallback callback;
            if (handler != null)
            {
                callback = (r) => handler.TransferCompleted();
            }
            else
            {
                callback = (r) => { };
            }

            var asyncResult = new SftpDownloadAsyncResult(callback, state);

            this.ExecuteThread(() =>
            {
                try
                {
                    this.InternalDownloadFile(path, output, handler);

                    asyncResult.SetAsCompleted(null, false);
                }
                catch (Exception exp)
                {
                    asyncResult.SetAsCompleted(exp, false);
                }
            });

            return asyncResult;
        }
Exemplo n.º 24
0
        public bool PutFile(IPurePath sourcePath, IPurePath destinationPath, IFileTransferHandler handler, bool ifNewer)
        {
            var filename = sourcePath.Filename;
            var source = Context.LocalEnv.CurrentDirectory.Join(sourcePath);
            var dest = Context.LocalEnv.CurrentDirectory.Join(destinationPath);

            if (handler != null)
            {
                handler.Filename = filename;
            }

            if (!File.Exists(source.ToString()))
            {
                if (handler != null)
                {
                    handler.FileDoesNotExist();
                }
                return false;
            }

            if (String.IsNullOrEmpty(dest.Filename) ||
                Directory.Exists(dest.ToString()))
            {
                dest = dest.WithFilename(filename);
            }

            var sourceStr = source.ToString();
            var destStr = dest.ToString();

            if (ifNewer && File.Exists(destStr) &&
                File.GetLastWriteTimeUtc(sourceStr) <= File.GetLastWriteTimeUtc(destStr))
            {
                if (handler != null)
                {
                    handler.FileUpToDate();
                }
                return false;
            }
            using (var file = File.OpenRead(sourceStr))
            {

                PutFile(file, destStr, handler);
            }
            return true;
        }
Exemplo n.º 25
0
        /// <summary>
        /// Begins an asynchronous uploading the steam into remote file.
        /// </summary>
        /// <param name="input">Data input stream.</param>
        /// <param name="path">Remote file path.</param>
        /// <param name="canOverride">if set to <c>true</c> then existing file will be overwritten.</param>
        /// <param name="handler">The object that handles callbacks for transferred data.</param>
        /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="input"/> is <b>null</b>.</exception>
        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>
        /// <exception cref="SshConnectionException">Client is not connected.</exception>
        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to list the contents of the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
        /// <remarks>Method calls made by this method to <paramref name="input"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>
        public IAsyncResult BeginUploadFile(Stream input, string path, bool canOverride, IFileTransferHandler handler, object state)
        {
            if (input == null)
                throw new ArgumentNullException("input");

            if (path.IsNullOrWhiteSpace())
                throw new ArgumentException("path");

            var flags = Flags.Write | Flags.Truncate;

            if (canOverride)
                flags |= Flags.CreateNewOrOpen;
            else
                flags |= Flags.CreateNew;

            //  Ensure that connection is established.
            this.EnsureConnection();

            AsyncCallback callback;
            if (handler != null)
            {
                callback = (r) => handler.TransferCompleted();
            }
            else
            {
                callback = (r) => { };
            }
            var asyncResult = new SftpUploadAsyncResult(callback, state);

            this.ExecuteThread(() =>
            {
                try
                {
                    this.InternalUploadFile(input, path, handler, flags);

                    asyncResult.SetAsCompleted(null, false);
                }
                catch (Exception exp)
                {
                    asyncResult.SetAsCompleted(exp, false);
                }
            });

            return asyncResult;
        }
Exemplo n.º 26
0
 public bool PutFile(IPurePath sourcePath, IPurePath destinationPath, IFileTransferHandler handler, bool ifNewer)
 {
     return PutFile(sourcePath.ToString(), destinationPath.ToString(), handler, ifNewer);
 }