Example #1
0
 /// <summary>
 /// Connect to the remote server, using the 
 /// account info found in Common.Profile
 /// </summary>
 public static void Connect()
 {
     if (FTP)
     {
         ftpc = new FtpClient(Common.Profile.Host, Common.Profile.Port);
         switch (Common.Profile.FtpsInvokeMethod)
         {
             case 0:
                 goto default;
             case FtpsMethod.Explicit:
                 ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                 ftpc.ValidateServerCertificate += (o, e) => e.IsCertificateValid = true;
                 break;
             case FtpsMethod.Implicit:
                 ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                 ftpc.ValidateServerCertificate += (o, e) => e.IsCertificateValid = true;
                 break;
             default:
                 ftpc.SecurityProtocol = FtpSecurityProtocol.None;
                 break;
         }
         ftpc.Open(Common.Profile.Username, Common.Profile.Password);
     }
     else
     {
         sftpc = new SftpClient(Common.Profile.Host, Common.Profile.Port,
                 Common.Profile.Username, Common.Profile.Password);
         sftpc.Connect();
     }
 }
Example #2
0
        public override int Run(string[] paths)
        {
            //this.path = paths[0];
            this.path = paths[0].Replace(@"\", "/");
            Console.WriteLine(path);
            // create a new FtpClient object with the host and port number to use
            // (optionally create a secure SSL connection)
            ftp = new Starksoft.Net.Ftp.FtpClient(host, 21);

            // specify a binary, passive connection with no zlib file compression
            ftp.FileTransferType = TransferType.Binary;
            ftp.DataTransferMode = TransferMode.Passive;

            // open a connection to the ftp server
            ftp.Open(username, password);

            // change to the directory on the ftp server specified in cmd line option
            //ftp.ChangeDirectory(path);

            // retrieve a listing of the files in the directory as a collection of FtpItem objects
            FtpItemCollection col = new FtpItemCollection();

            if (string.IsNullOrEmpty(recurse))
            {
                col = ftp.GetDirList(path);
            }
            else
            {
                col = ftp.GetDirListDeep(path);
            }

            foreach (FtpItem item in col)
            {
                Console.WriteLine("{0}\t{1}\t{2}", item.Modified.ToString(), item.ItemType.ToString(), item.FullPath);
            }

            // close connection to the ftp server
            ftp.Close();

            return 0;
        }
Example #3
0
        public FTP(FTPAccount account, int bufferSize = 8192)
        {
            Account = account;
            Client = new FtpClient(account.Host, account.Port);
            Client.TcpBufferSize = bufferSize;

            if (account.Protocol == FTPProtocol.FTP || account.FtpsSecurityProtocol == FtpSecurityProtocol.None)
            {
                Client.SecurityProtocol = (Starksoft.Net.Ftp.FtpSecurityProtocol)FtpSecurityProtocol.None;
            }
            else
            {
                Client.SecurityProtocol = (Starksoft.Net.Ftp.FtpSecurityProtocol)account.FtpsSecurityProtocol;

                if (!string.IsNullOrEmpty(account.FtpsCertLocation) && File.Exists(account.FtpsCertLocation))
                {
                    Client.SecurityCertificates.Add(X509Certificate.CreateFromSignedFile(account.FtpsCertLocation));
                }
                else
                {
                    Client.ValidateServerCertificate += (sender, e) => e.IsCertificateValid = true;
                }
            }

            Client.DataTransferMode = account.IsActive ? TransferMode.Active : TransferMode.Passive;

            if (ProxyInfo.Current != null)
            {
                IProxyClient proxy = ProxyInfo.Current.GetProxyClient();

                if (proxy != null)
                {
                    Client.Proxy = proxy;
                }
            }

            Client.TransferProgress += OnTransferProgressChanged;
            Client.ConnectionClosed += Client_ConnectionClosed;
        }
Example #4
0
        /// <summary>
        /// Asynchronous File Exchange Protocol (FXP) allows server-to-server transfer which can greatly speed up file transfers.
        /// </summary>
        /// <param name="fileName">The name of the file to transfer.</param>
        /// <param name="destination">The destination FTP server which must be supplied as an open and connected FtpClient object.</param>
        /// <remarks>
        /// Both servers must support and have FXP enabled before you can transfer files between two remote servers using FXP.  One FTP server must support PASV mode and the other server must allow PORT commands from a foreign address.  Finally, firewall settings may interfer with the ability of one server to access the other server.
        /// Starksoft FtpClient will coordinate the FTP negoitaion and necessary PORT and PASV transfer commands.
        /// </remarks>
        /// <seealso cref="FxpCopyAsyncCompleted"/>
        /// <seealso cref="FxpTransferTimeout"/>
        /// <seealso cref="FxpCopy"/>
        /// <seealso cref="FtpBase.CancelAsync"/>
        public void FxpCopyAsync(string fileName, FtpClient destination)
        {
            if (base.AsyncWorker != null && base.AsyncWorker.IsBusy)
                throw new InvalidOperationException("The FtpClient object is already busy executing another asynchronous operation.  You can only execute one asychronous method at a time.");

            base.CreateAsyncWorker();
            base.AsyncWorker.WorkerSupportsCancellation = true;
            base.AsyncWorker.DoWork += new DoWorkEventHandler(FxpCopyAsync_DoWork);
            base.AsyncWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(FxpCopyAsync_RunWorkerCompleted);
            Object[] args = new Object[2];
            args[0] = fileName;
            args[1] = destination;
            base.AsyncWorker.RunWorkerAsync(args);
        }
Example #5
0
        /// <summary>
        /// File Exchange Protocol (FXP) allows server-to-server transfer which can greatly speed up file transfers.
        /// </summary>
        /// <param name="fileName">The name of the file to transfer.</param>
        /// <param name="destination">The destination FTP server which must be supplied as an open and connected FtpClient object.</param>
        /// <remarks>
        /// Both servers must support and have FXP enabled before you can transfer files between two remote servers using FXP.  One FTP server must support PASV mode and the other server must allow PORT commands from a foreign address.  Finally, firewall settings may interfer with the ability of one server to access the other server.
        /// Starksoft FtpClient will coordinate the FTP negoitaion and necessary PORT and PASV transfer commands.
        /// </remarks>
        /// <seealso cref="FxpTransferTimeout"/>
        /// <seealso cref="FxpCopyAsync"/> 
        public void FxpCopy(string fileName, FtpClient destination)
        {
            if (this.IsConnected == false)
                throw new FtpException("The connection must be open before a transfer between servers can be intitiated.");

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

            if (destination.IsConnected == false)
                throw new FtpException("The destination object must be open and connected before a transfer between servers can be intitiated.");

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

            if (fileName.Length == 0)
                throw new ArgumentException("must have a value", "fileName");

            //  send command to destination FTP server to get passive port to be used from the source FTP server
            try
            {
                destination.SendRequest(new FtpRequest(base.CharacterEncoding, FtpCmd.Pasv));
            }
            catch (FtpException fex)
            {
                throw new FtpException(String.Format("An error occurred when trying to set up the passive connection on '{1}' for a destination to destination copy between '{0}' and '{1}'.", this.Host, destination.Host), base.LastResponse, fex);
            }

            //  get the begin and end positions to extract data from the response string
            int startIdx = destination.LastResponse.Text.IndexOf("(") + 1;
            int endIdx = destination.LastResponse.Text.IndexOf(")");
            string dataPortInfo = destination.LastResponse.Text.Substring(startIdx, endIdx - startIdx);

            //  send a command to the source server instructing it to connect to
            //  the local ip address and port that the destination server will be bound to
            try
            {
                this.SendRequest(new FtpRequest(base.CharacterEncoding, FtpCmd.Port, dataPortInfo));
            }
            catch (FtpException fex)
            {
                throw new FtpException(String.Format("Command instructing '{0}' to open connection failed.", this.Host), base.LastResponse, fex);
            }

            // send command to tell the source server to retrieve the file from the destination server
            try
            {
                this.SendRequest(new FtpRequest(base.CharacterEncoding, FtpCmd.Retr, fileName));
            }
            catch (FtpException fex)
            {
                throw new FtpException(String.Format("An error occurred transfering on a server to server copy between '{0}' and '{1}'.", this.Host, destination.Host), base.LastResponse, fex);
            }

            // send command to tell the destination to store the file
            try
            {
                destination.SendRequest(new FtpRequest(base.CharacterEncoding, FtpCmd.Stor, fileName));
            }
            catch (FtpException fex)
            {
                throw new FtpException(String.Format("An error occurred transfering on a server to server copy between '{0}' and '{1}'.", this.Host, destination.Host), base.LastResponse, fex);
            }

            // wait until we get a file completed response back from the destination server and the source server
            destination.WaitForHappyCodes(this.FxpTransferTimeout, FtpResponseCode.RequestedFileActionOkayAndCompleted, FtpResponseCode.ClosingDataConnection);
            this.WaitForHappyCodes(this.FxpTransferTimeout, FtpResponseCode.RequestedFileActionOkayAndCompleted, FtpResponseCode.ClosingDataConnection);
        }
Example #6
0
        /// <summary>
        /// Connect to the remote servers, with the details from Profile
        /// </summary>
        /// <param name="reconnecting">True if this is an attempt to re-establish a closed connection</param>
        public static void Connect(bool reconnecting = false)
        {
            Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting);
            Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting");

            if (FTP)
            {
                _ftpc = new FtpClient(Profile.Host, Profile.Port);
                _ftpc.ConnectionClosed += (o, e) =>
                {
                    Notifications.ChangeTrayText(MessageType.Nothing);
                    ConnectionClosed(null, new ConnectionClosedEventArgs { Text = _ftpc.LastResponse.Text });
                    Reconnect();
                };
                _ftpc.TransferProgress += (o, e) =>
                {
                    // if (e.KilobytesPerSecond > 0) Console.Write("\r Transferring at {0,6} kb/s Transferred: {1}\n", e.KilobytesPerSecond, e.BytesTransferred);
                };

                if (Profile.Protocol == FtpProtocol.FTPS)
                {
                    _ftpc.ValidateServerCertificate += (sender, x) =>
                    {
                        // if ValidateCertificate handler isn't set, accept the certificate and move on
                        if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(x.Certificate.Thumbprint))
                        {
                            Log.Write(l.Client, "Trusted: {0}", x.Certificate.Thumbprint);
                            x.IsCertificateValid = true;
                            return;
                        }

                        var e = new ValidateCertificateEventArgs
                        {
                            Fingerprint = x.Certificate.Thumbprint,
                            SerialNumber = x.Certificate.SerialNumber,
                            Algorithm = x.Certificate.SignatureAlgorithm.FriendlyName,
                            ValidFrom = x.Certificate.NotBefore.ToString("MM/dd/yy"),
                            ValidTo = x.Certificate.NotAfter.ToString("MM/dd/yy"),
                            Issuer = x.Certificate.IssuerName.Name
                        };

                        ValidateCertificate(null, e);
                        x.IsCertificateValid = e.IsTrusted;
                    };

                    // Change Security Protocol
                    if (Profile.FtpsInvokeMethod == FtpsMethod.Explicit)
                        _ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                    else if (Profile.FtpsInvokeMethod == FtpsMethod.Implicit)
                        _ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                }

                try
                {
                    _ftpc.Open(Profile.Username, Profile.Password);
                    _ftpc.CharacterEncoding = Encoding.Default;
                }
                catch (Exception)
                {
                    if (Profile.FtpsInvokeMethod == FtpsMethod.None)
                        throw;
                    bool connected = false;
                    // Try connecting with the other available Security Protocols
                    foreach (FtpSecurityProtocol p in Enum.GetValues(typeof(FtpSecurityProtocol)))
                    {
                        if ((Profile.FtpsInvokeMethod == FtpsMethod.Explicit && p.ToString().Contains("Explicit"))
                            || (Profile.FtpsInvokeMethod == FtpsMethod.Implicit && p.ToString().Contains("Implicit")))
                        {
                            Log.Write(l.Debug, "Testing with {0}", p.ToString());

                            try {
                                _ftpc.Close();
                                _ftpc.SecurityProtocol = p;
                                _ftpc.Open(Profile.Username, Profile.Password);
                            }
                            catch (Exception exe){
                                Log.Write(l.Warning, "Unable to connect: {0}", exe.GetType().ToString());
                                continue;
                            }
                            connected = true;
                            Profile.SecurityProtocol = p;
                            _ftpc.CharacterEncoding = Encoding.Default;
                            break;
                        }
                    }

                    if (!connected)
                    {
                        Notifications.ChangeTrayText(MessageType.Nothing);
                        throw;
                    }
                }
            }
            else // SFTP
            {
                _sftpc = new SftpClient(Profile.Host, Profile.Port, Profile.Username, Profile.Password);
                _sftpc.ConnectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage);

                _sftpc.HostKeyReceived += (o, x) =>
                {
                    var fingerPrint = x.FingerPrint.GetCertificateData();

                    // if ValidateCertificate handler isn't set, accept the certificate and move on
                    if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                    {
                        Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                        x.CanTrust = true;
                        return;
                    }

                    var e = new ValidateCertificateEventArgs
                    {
                        Fingerprint = fingerPrint,
                        Key = x.HostKeyName,
                        KeySize = x.KeyLength.ToString()
                    };
                    ValidateCertificate(null, e);
                    x.CanTrust = e.IsTrusted;
                };

                _sftpc.Connect();

                _sftpc.ErrorOccurred += (o, e) =>
                {
                    if (!isConnected) Notifications.ChangeTrayText(MessageType.Nothing);
                    ConnectionClosed(null, new ConnectionClosedEventArgs { Text = e.Exception.Message });

                    if (e.Exception is Renci.SshNet.Common.SftpPermissionDeniedException)
                        Log.Write(l.Warning, "Permission denied error occured");
                    if (e.Exception is Renci.SshNet.Common.SshConnectionException)
                        Reconnect();
                };
            }

            Profile.HomePath = WorkingDirectory;
            // Profile.HomePath = (Profile.HomePath.StartsWith("/")) ? Profile.HomePath.Substring(1) : Profile.HomePath;

            if (isConnected)
                if (!string.IsNullOrWhiteSpace(Profile.RemotePath) && !Profile.RemotePath.Equals("/"))
                    WorkingDirectory = Profile.RemotePath;

            Log.Write(l.Debug, "Client connected sucessfully");
            Notifications.ChangeTrayText(MessageType.Ready);

            if (Profile.IsDebugMode)
                LogServerInfo();
        }
Example #7
0
        private void bDone_Click(object sender, EventArgs e)
        {
            bool ftporsftp;
            bool ftps = false;
            bool ftpes = true;

            if (cMode.SelectedIndex == 0)
            {
                ftporsftp = true;
                if (cEncryption.SelectedIndex != 0)
                {
                    ftps = true;
                    if (cEncryption.SelectedIndex == 1)
                    {
                        Log.Write(l.Info, "FTPS Explicit");
                        ftpes = true;
                    }
                    else
                    {
                        Log.Write(l.Info, "FTPS Implicit");
                        ftpes = false;
                    }
                }
                else
                    Log.Write(l.Info, "Plain FTP");
            }
            else
            {
                ftporsftp = false;
                Log.Write(l.Info, "SFTP");
            }

            try
            {
                if (ftporsftp)
                {
                    ftpc = new FtpClient(tHost.Text, Convert.ToInt32(nPort.Value));

                    if (ftps)
                    {
                        if (ftpes)
                            ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                        else
                            ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                        ftpc.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                    }
                    ftpc.Open(tUsername.Text, tPass.Text);
                    Log.Write(l.Info, "Connected: " + ftpc.IsConnected.ToString());
                    ftpc.Close();
                }
                else
                {
                    string pass = AESEncryption.Encrypt(tPass.Text, decpass, salt, "SHA1", 2, "OFRna73m*aze01xY", 256);
                    ((frmMain)this.Tag).SetPass(pass);
                    //FTPbox.Properties.Settings.Default.ftpPass = tPass.Text;
                    sftp_login();
                    //MessageBox.Show("SFTP Connected");
                    sftpc.quit();
                }

                string hostEncr = AESEncryption.Encrypt(tHost.Text, decpass, salt, "SHA1", 2, "OFRna73m*aze01xY", 256);
                string unEncr = AESEncryption.Encrypt(tUsername.Text, decpass, salt, "SHA1", 2, "OFRna73m*aze01xY", 256);
                string passEncr = AESEncryption.Encrypt(tPass.Text, decpass, salt, "SHA1", 2, "OFRna73m*aze01xY", 256);

                ((frmMain)this.Tag).UpdateAccountInfo(hostEncr, unEncr, passEncr, Convert.ToInt32(nPort.Value), "", ftporsftp, ftps, ftpes);

                //FTPbox.Properties.Settings.Default.ftpHost = tHost.Text;
                //FTPbox.Properties.Settings.Default.ftpPort = Convert.ToInt32(nPort.Value);
                //FTPbox.Properties.Settings.Default.ftpUsername = tUsername.Text;
                //FTPbox.Properties.Settings.Default.ftpPass = tPass.Text;
                //FTPbox.Properties.Settings.Default.FTPorSFTP = ftporsftp;
                //FTPbox.Properties.Settings.Default.timedif = "";
                //FTPbox.Properties.Settings.Default.Save();

                Log.Write(l.Debug, "got new ftp acccount details");
                ((frmMain)this.Tag).ClearLog();
                ((frmMain)this.Tag).UpdateDetails();
                //((frmMain)this.Tag).GetServerTime();
                ((frmMain)this.Tag).loggedIn = true;
                fNewDir fnewdir = new fNewDir();
                fnewdir.ShowDialog();
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not connect to FTP server. Check your account details and try again." + Environment.NewLine + " Error message: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (ftporsftp)
                    Log.Write(l.Info, "Connected: " + ftpc.IsConnected.ToString());
            }
        }
Example #8
0
        /// <summary>
        /// Connect to the remote servers, with the details from Profile
        /// </summary>
        /// <param name="reconnecting">True if this is an attempt to re-establish a closed connection</param>
        public void Connect(bool reconnecting = false)
        {
            Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting);
            Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting");

            if (FTP)
            {
                _ftpc = new FtpClient(controller.Account.Host, controller.Account.Port);
                _ftpc.ConnectionClosed += (o, e) =>
                {
                    Notifications.ChangeTrayText(MessageType.Nothing);
                    if (ConnectionClosed != null) ConnectionClosed(null, new ConnectionClosedEventArgs { Text = _ftpc.LastResponse.Text });
                    Reconnect();
                };

                if (controller.Account.Protocol == FtpProtocol.FTPS)
                {
                    _ftpc.ValidateServerCertificate += (sender, x) =>
                    {
                        // if ValidateCertificate handler isn't set, accept the certificate and move on
                        if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(x.Certificate.Thumbprint))
                        {
                            Log.Write(l.Client, "Trusted: {0}", x.Certificate.Thumbprint);
                            x.IsCertificateValid = true;
                            return;
                        }

                        var e = new ValidateCertificateEventArgs
                        {
                            Fingerprint = x.Certificate.Thumbprint,
                            SerialNumber = x.Certificate.SerialNumber,
                            Algorithm = x.Certificate.SignatureAlgorithm.FriendlyName,
                            ValidFrom = x.Certificate.NotBefore.ToString("MM/dd/yy"),
                            ValidTo = x.Certificate.NotAfter.ToString("MM/dd/yy"),
                            Issuer = x.Certificate.IssuerName.Name
                        };

                        ValidateCertificate(null, e);
                        x.IsCertificateValid = e.IsTrusted;
                    };

                    // Change Security Protocol
                    if (controller.Account.FtpsMethod == FtpsMethod.Explicit)
                        _ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                    else if (controller.Account.FtpsMethod == FtpsMethod.Implicit)
                        _ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                }

                try
                {
                    _ftpc.Open(controller.Account.Username, controller.Account.Password);
                }
                catch (Exception)
                {
                    if (controller.Account.FtpsMethod == FtpsMethod.None)
                        throw;
                    bool connected = false;
                    // Try connecting with the other available Security Protocols
                    foreach (FtpSecurityProtocol p in Enum.GetValues(typeof(FtpSecurityProtocol)))
                    {
                        if ((controller.Account.FtpsMethod == FtpsMethod.Explicit && p.ToString().Contains("Explicit"))
                            || (controller.Account.FtpsMethod == FtpsMethod.Implicit && p.ToString().Contains("Implicit")))
                        {
                            Log.Write(l.Debug, "Testing with {0}", p.ToString());

                            try {
                                _ftpc.Close();
                                _ftpc.SecurityProtocol = p;
                                _ftpc.Open(controller.Account.Username, controller.Account.Password);
                            }
                            catch (Exception exe){
                                Log.Write(l.Warning, "Unable to connect: {0}", exe.GetType().ToString());
                                continue;
                            }
                            connected = true;
                            controller.Account.FtpSecurityProtocol = p;
                            break;
                        }
                    }

                    if (!connected)
                    {
                        Notifications.ChangeTrayText(MessageType.Nothing);
                        throw;
                    }
                }
            }
            else // SFTP
            {
                ConnectionInfo connectionInfo;
                if (controller.isPrivateKeyValid)
                    connectionInfo = new PrivateKeyConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, new PrivateKeyFile(controller.Account.PrivateKeyFile, controller.Account.Password));
                else
                    connectionInfo = new PasswordConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, controller.Account.Password);

                _sftpc = new SftpClient(connectionInfo);
                _sftpc.ConnectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage);

                _sftpc.HostKeyReceived += (o, x) =>
                {
                    var fingerPrint = x.FingerPrint.GetCertificateData();

                    // if ValidateCertificate handler isn't set, accept the certificate and move on
                    if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                    {
                        Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                        x.CanTrust = true;
                        return;
                    }

                    var e = new ValidateCertificateEventArgs
                    {
                        Fingerprint = fingerPrint,
                        Key = x.HostKeyName,
                        KeySize = x.KeyLength.ToString()
                    };
                    ValidateCertificate(null, e);
                    x.CanTrust = e.IsTrusted;
                };

                _sftpc.Connect();

                _sftpc.ErrorOccurred += (o, e) =>
                {
                    if (!isConnected) Notifications.ChangeTrayText(MessageType.Nothing);
                    if (ConnectionClosed != null) ConnectionClosed(null, new ConnectionClosedEventArgs { Text = e.Exception.Message });

                    if (e.Exception is Renci.SshNet.Common.SftpPermissionDeniedException)
                        Log.Write(l.Warning, "Permission denied error occured");
                    if (e.Exception is Renci.SshNet.Common.SshConnectionException)
                        Reconnect();
                };
            }

            controller.HomePath = WorkingDirectory;

            if (isConnected)
                if (!string.IsNullOrWhiteSpace(controller.Paths.Remote) && !controller.Paths.Remote.Equals("/"))
                    WorkingDirectory = controller.Paths.Remote;

            Log.Write(l.Debug, "Client connected sucessfully");
            Notifications.ChangeTrayText(MessageType.Ready);

            if (Settings.IsDebugMode)
                LogServerInfo();

            // Periodically send NOOP (KeepAlive) to server if a non-zero interval is set
            SetKeepAlive();
        }
Example #9
0
        public static void Connect()
        {
            Console.WriteLine("Connecting client...");
            if (FTP)
            {
                ftpc = new FtpClient(Profile.Host, Profile.Port);

                if (Profile.Protocol == FtpProtocol.FTPS)
                {
                    ftpc.SecurityProtocol = Profile.SecurityProtocol;
                    ftpc.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                }

                try
                {
                    ftpc.Open(Profile.Username, Profile.Password);
                    ftpc.CharacterEncoding = System.Text.Encoding.Default;
                }
                catch(Exception ex)
                {
                    if (Profile.FtpsInvokeMethod == FtpsMethod.None)
                        throw ex;
                    bool connected = false;

                    foreach (FtpSecurityProtocol p in Enum.GetValues(typeof(FtpSecurityProtocol)))
                    {
                        if ((Profile.FtpsInvokeMethod == FtpsMethod.Explicit && p.ToString().Contains("Explicit"))
                            || (Profile.FtpsInvokeMethod == FtpsMethod.Implicit && p.ToString().Contains("Implicit")))
                        {
                            Console.WriteLine("Testing with {0}", p.ToString());

                            try {
                                ftpc.Close();
                                ftpc.SecurityProtocol = p;
                                ftpc.Open(Profile.Username, Profile.Password);
                            }
                            catch (Exception exe){
                                Console.WriteLine("Exe: {0}", exe.Message);
                                continue;
                            }
                            connected = true;
                            Profile.SecurityProtocol = p;
                            ftpc.CharacterEncoding = System.Text.Encoding.Default;
                            break;
                        }
                    }

                    if (!connected)
                        throw ex;
                }
            }
            else
            {
                sftpc = new SftpClient(Profile.Host, Profile.Port, Profile.Username, Profile.Password);
                sftpc.Connect();
            }

            Profile.HomePath = WorkingDirectory;
            Profile.HomePath = (Profile.HomePath.StartsWith("/")) ? Profile.HomePath.Substring(1) : Profile.HomePath;

            Console.WriteLine("Client connected sucessfully");

            if (Profile.IsDebugMode)
                LogServerInfo();
        }
Example #10
0
        private void fNewDir_Load(object sender, EventArgs e)
        {
            try
            {
                host = ((frmMain)this.Tag).ftpHost();
                UN = ((frmMain)this.Tag).ftpUser();
                pass = ((frmMain)this.Tag).ftpPass();
                port = ((frmMain)this.Tag).ftpPort();
                ftporsftp = ((frmMain)this.Tag).FTP();
                ftps = ((frmMain)this.Tag).FTPS();
                ftpes = ((frmMain)this.Tag).FTPES();
                ((frmMain)this.Tag).SetParent(host);

                if (ftporsftp)
                {
                    ftpc = new FtpClient(host, port);

                    if (ftps)
                    {
                        if (ftpes)
                            ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                        else
                            ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                        ftpc.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                    }

                    ftpc.Open(UN, pass);
                    Log.Write(l.Info, "Connected: " + ftpc.IsConnected.ToString());
                }
                else
                {
                    sftp_login();
                    sftproot = sftpc.pwd();
                }

                if (((frmMain)this.Tag).ftpParent() == "")
                    tParent.Text = ((frmMain)this.Tag).ftpHost();
                else
                    tParent.Text = ((frmMain)this.Tag).ftpParent();

                tPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\FTPbox";

                Log.Write(l.Debug, ((frmMain)this.Tag).ftpParent() + " " + ((frmMain)this.Tag).ftpHost());

                treeView1.Nodes.Clear();

                TreeNode first = new TreeNode();
                first.Text = "/";
                treeView1.Nodes.Add(first);

                if (ftporsftp)
                {
                    foreach (FtpItem dir in ftpc.GetDirList())
                    {
                        if (dir.Name != "." && dir.Name != ".." && dir.ItemType == FtpItemType.Directory)
                        {
                            TreeNode ParentNode = new TreeNode();
                            ParentNode.Text = dir.Name;
                            treeView1.Nodes.Add(ParentNode);

                            TreeNode ChildNode = new TreeNode();
                            ChildNode.Text = dir.Name;
                            ParentNode.Nodes.Add(ChildNode);
                        }
                    }
                }
                else
                {
                    foreach (ChannelSftp.LsEntry lse in sftpc.ls("."))
                    {
                        SftpATTRS attrs = lse.getAttrs();
                        if (lse.getFilename() != "." && lse.getFilename() != ".." && attrs.getPermissionsString().StartsWith("d"))
                        {
                            TreeNode ParentNode = new TreeNode();
                            ParentNode.Text = lse.getFilename();
                            treeView1.Nodes.Add(ParentNode);

                            TreeNode ChildNode = new TreeNode();
                            ChildNode.Text = lse.getFilename();
                            ParentNode.Nodes.Add(ChildNode);
                        }
                    }
                }
                treeView1.SelectedNode = first;
                Set_Language(((frmMain)this.Tag).lang());
            }
            catch { this.Close(); }
        }
Example #11
0
        /// <summary>
        /// Connect the client to the server
        /// </summary>
        public void LoginFTP()
        {
            SetTray(MessageType.Connecting);

            if (FTP())
            {
                try
                {
                    ftpc.Close();
                }
                catch { }

                ftpc = new FtpClient(Profile.Host, Profile.Port); //ftpHost(), ftpPort());

                if (FTPS())
                {
                    if (FTPES())
                        ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                    else
                        ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;

                    ftpc.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                }
                Log.Write(l.Debug, "Connecting ftpc -> user: {0}", Profile.Username);
                ftpc.Open(Profile.Username, Profile.Password); //ftpUser(), ftpPass());

                Log.Write(l.Debug, "Connection opened");

                //ftpc.ConnectionClosed += new EventHandler<ConnectionClosedEventArgs>(FTPClosedConnection);
                //ftpc.TransferComplete += new EventHandler<TransferCompleteEventArgs>(FtpTransferComplete);

                if (LimitUpSpeed())
                    nUpLimit.Value = Convert.ToDecimal(UpLimit());
                if (LimitDownSpeed())
                    nDownLimit.Value = Convert.ToDecimal((DownLimit()));

                Log.Write(l.Debug, "Connected");
                Log.Write(l.Info, ftpc.IsConnected.ToString());

                Thread.Sleep(5000);
            }
            else
            {
                try
                {
                    sftpc.Disconnect();
                }
                catch { }

                sftpc = new SftpClient(ftpHost(), ftpPort(), ftpUser(), ftpPass());
                Log.Write(l.Info, "Connecting sftpc");
                sftpc.Connect();

                Log.Write(l.Info, sftpc.IsConnected.ToString());

                SftpHome = sftpc.WorkingDirectory;
                SftpHome = (SftpHome.StartsWith("/")) ? SftpHome.Substring(1) : SftpHome;
                //sftpc.ChangeDirectory(rPath());
                Profile.SftpHome = SftpHome;
            }

            SetTray(MessageType.Ready);
        }
Example #12
0
        /// <summary>
        /// checks if account's information used the last time has changed
        /// </summary>
        private void CheckAccount()
        {
            try
            {
                if (FTP())
                {
                    ftpc = new FtpClient(ftpHost(), ftpPort());

                    if (FTPS())
                    {
                        if (FTPES())
                            ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                        else
                            ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                        ftpc.ServerResponse += new EventHandler<FtpResponseEventArgs>(ftp_gotresponsefromserver);
                        ftpc.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                    }
                    Log.Write(l.Info, "Connecting ftpc");
                    ftpc.Open(ftpUser(), ftpPass());
                    Log.Write(l.Info, "Connected ftpc: {0}", ftpc.IsConnected.ToString());

                    //and the background client:

                    ftpcbg = new FtpClient(ftpHost(), ftpPort());

                    if (FTPS())
                    {
                        if (FTPES())
                            ftpcbg.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                        else
                            ftpcbg.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                        ftpcbg.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                    }

                    Log.Write(l.Info, "Connecting ftpcbg");
                    ftpcbg.Open(ftpUser(), ftpPass());
                    Log.Write(l.Info, "Connected ftpcbg: " + ftpcbg.IsConnected.ToString());

                    this.ShowInTaskbar = false;
                    this.Hide();
                    this.ShowInTaskbar = true;
                    loggedIn = true;
                }
                else
                {
                    sftp_login();
                    this.ShowInTaskbar = false;
                    this.Hide();
                    this.ShowInTaskbar = true;
                    loggedIn = true;
                }

            }
            catch
            {
                fNewFtp.ShowDialog();
                if (!loggedIn)
                {
                    try
                    {
                        Process p = Process.GetCurrentProcess();
                        p.Kill();
                    }
                    catch { }
                }

                if (FTP())
                {
                    Log.Write(l.Info, "FTP");

                    try
                    {
                        ftpc.Close();
                        ftpcbg.Close();
                    }
                    catch (Exception ex)
                    {
                        //Log.Write(l.Error, "Couldnt close connection, msg: {0}", ex.Message);
                    }

                    ftpc = new FtpClient(ftpHost(), ftpPort());

                    if (FTPS())
                    {
                        if (FTPES())
                            ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                        else
                            ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                        ftpc.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                    }
                    Log.Write(l.Info, "opening ftpc...");
                    ftpc.Open(ftpUser(), ftpPass());

                    //and the background client:

                    ftpcbg = new FtpClient(ftpHost(), ftpPort());

                    if (FTPS())
                    {
                        if (FTPES())
                            ftpcbg.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                        else
                            ftpcbg.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                        ftpcbg.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                    }
                    Log.Write(l.Info, "opening ftpcbg...");
                    ftpcbg.Open(ftpUser(), ftpPass());
                    Log.Write(l.Info, "Connected: " + ftpc.IsConnected.ToString());

                    this.ShowInTaskbar = false;
                    this.Hide();
                    this.ShowInTaskbar = true;
                    loggedIn = true;
                }
                else
                {
                    Log.Write(l.Info, "SFTP");
                    sftp_login();
                    this.ShowInTaskbar = false;
                    this.Hide();
                    this.ShowInTaskbar = true;
                    loggedIn = true;
                }
                newDir.ShowDialog();
            }
        }
Example #13
0
        public void RecursiveDeleteFTP(string path, bool RemFromLog, ref FtpClient ftpclient)
        {
            foreach (FtpItem fi in ftpclient.GetDirList(path))
            {
                if (fi.ItemType == FtpItemType.File)
                {
                    string fpath = string.Format("{0}/{1}", path, fi.Name);
                    Log.Write(l.Info, "Gon'delete: {0}", fpath);
                    ftpclient.DeleteFile(fpath);
                    if (RemFromLog)
                        RemoveFromLog(fpath);
                }
                else if (fi.ItemType == FtpItemType.Directory)
                {
                    if (fi.Name != "." && fi.Name != "..")
                    {
                        string fpath = string.Format("{0}/{1}", noSlashes(path), fi.Name);
                        RecursiveDeleteFTP(fpath, RemFromLog, ref ftpclient);
                    }
                }
            }

            ftpclient.DeleteDirectory(path);
            if (RemFromLog)
                RemoveFromLog(path);
        }
Example #14
0
        public void ftp_reconnect()
        {
            try
            {
                ftpc.Close();
            }
            catch { }
            try
            {
                ftpcbg.Close();
            }
            catch { }

            try
            {
                ftpc = new FtpClient(ftpHost(), ftpPort());

                if (FTPS())
                {
                    if (FTPES())
                        ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                    else
                        ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                    ftpc.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                }
                ftpc.Open(ftpUser(), ftpPass());
                //and the background client:

                if (!FTPS())
                    ftpcbg = new FtpClient(ftpHost(), ftpPort());
                else
                {
                    ftpcbg = new FtpClient(ftpHost(), ftpPort());
                    ftpcbg.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                }

                ftpcbg.Open(ftpUser(), ftpPass());
            }
            catch { CheckAccount(); }
        }
Example #15
0
        public void Connect()
        {
            if (FTP)
            {
                ftpc = new FtpClient(Profile.Host, Profile.Port);
                switch (Profile.FtpsInvokeMethod)
                {
                    case 0:
                        goto default;
                    case FtpsMethod.Explicit:
                        ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                        ftpc.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                        break;
                    case FtpsMethod.Implicit:
                        ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                        ftpc.ValidateServerCertificate += new EventHandler<ValidateServerCertificateEventArgs>(ftp_ValidateServerCertificate);
                        break;
                    default:
                        ftpc.SecurityProtocol = FtpSecurityProtocol.None;
                        break;
                }

                ftpc.Open(Profile.Username, Profile.Password);
            }
            else
            {
                sftpc = new SftpClient(Profile.Host, Profile.Port, Profile.Username, Profile.Password);
                sftpc.Connect();
            }
        }