Example #1
0
        public ReturnBox Unmount(Drive drive)
        {
            ReturnBox r = RunLocal("net.exe", "use /d " + drive.Name);

            if (!r.Success)
            {
                r.Error = r.Error;
                r.Drive = drive;
                return(r);
            }
            // TODO: clenup drive name and registry
            CleanExplorerDriveLabel(drive);
            Settings settings = LoadSettings();

            SaveSettings(settings);
            UpdateDrives(settings);
            r.MountStatus = MountStatus.OK;
            r.DriveStatus = DriveStatus.DISCONNECTED;
            r.Drive       = drive;
            return(r);
        }
Example #2
0
        public ReturnBox SetupSshWithUserKey(Drive drive, string userkey)
        {
            ReturnBox r = new ReturnBox();

            try
            {
                string pubkey = "";
                if (File.Exists(drive.AppKey) && File.Exists(drive.AppPubKey))
                {
                    pubkey = File.ReadAllText(drive.AppPubKey).Trim();
                }
                else
                {
                    pubkey = GenerateKeys(drive);
                }
                var       pk       = new PrivateKeyFile(userkey);
                var       keyFiles = new[] { pk };
                SshClient client   = new SshClient(drive.Host, drive.Port, drive.User, keyFiles);
                client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(5);
                client.Connect();
                string cmd = "";
                //bool linux = false;
                //if(linux)
                cmd = $"cd; umask 077; mkdir -p .ssh; echo '{pubkey}' >> .ssh/authorized_keys";
                //else
                //    cmd = $"mkdir %USERPROFILE%\\.ssh 2>NUL || echo {pubkey.Trim()} >> %USERPROFILE%\\.ssh\\authorized_keys";
                SshCommand command = client.CreateCommand(cmd);
                command.CommandTimeout = TimeSpan.FromSeconds(10);
                r.Output   = command.Execute();
                r.Error    = command.Error;
                r.ExitCode = command.ExitStatus;
            }
            catch (Exception ex)
            {
                r.Error = ex.Message;
                return(r);
            }

            return(TestSsh(drive, drive.AppKey));
        }
Example #3
0
        public List <Drive> GetUsedDrives()
        {
            List <Drive> drives = new List <Drive>();

            // get mounted drives using net use command
            var r = RunLocal("net.exe", "use");

            foreach (var line in r.Output.Split('\n'))
            {
                Match match = Regex.Match(line, @"^([A-Za-z]+)?\s+([A-Z]:)\s+(\\\\[^ ]+)");
                if (match.Success)
                {
                    try
                    {
                        Drive d = new Drive
                        {
                            //d.NetUseStatus = match.Groups[1].Value;
                            Letter      = match.Groups[2].Value[0].ToString(),
                            IsGoldDrive = match.Groups[3].Value.Contains(@"\\golddrive\")
                        };
                        if (d.IsGoldDrive == true)
                        {
                            //d.VolumeLabel = GetVolumeName(d.Letter);
                            //if (!String.IsNullOrEmpty(d.VolumeLabel) && d.VolumeLabel.Contains("@"))
                            //{
                            //    d.User = d.VolumeLabel.Split('@')[0];
                            //    d.Host = d.VolumeLabel.Split('@')[1];
                            //}
                            d.MountPoint = match.Groups[3].Value.Replace(@"\\golddrive\", "");
                            d.Label      = GetExplorerDriveLabel(d);
                        }
                        drives.Add(d);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            return(drives);
        }
Example #4
0
        public ReturnBox Mount(Drive drive)
        {
            ReturnBox r = RunLocal("net.exe", $"use { drive.Name } { drive.Remote } /persistent:yes");

            if (!r.Success)
            {
                r.MountStatus = MountStatus.UNKNOWN;
                r.Drive       = drive;
                return(r);
            }
            SetExplorerDriveLabel(drive);
            SetDriveIcon(drive, $@"{ AppPath }\golddrive.ico");
            Settings settings = LoadSettings();

            settings.AddDrive(drive);
            SaveSettings(settings);
            UpdateDrives(settings);
            r.MountStatus = MountStatus.OK;
            r.DriveStatus = DriveStatus.CONNECTED;
            r.Drive       = drive;
            return(r);
        }
Example #5
0
        private async void OnSettingsDelete(object obj)
        {
            Drive d = SelectedDrive;

            if (GoldDrives.Contains(d))
            {
                GoldDrives.Remove(d);
            }
            await Task.Run(() => {
                if (d.Status == DriveStatus.CONNECTED)
                {
                    _mountService.Unmount(d);
                }
                Settings settings = _mountService.LoadSettings();
                settings.Args     = GlobalArgs;
                settings.AddDrives(GoldDrives.ToList());
                _mountService.SaveSettings(settings);
                _mountService.UpdateDrives(settings);
            });

            UpdateObservableDrives(SelectedDrive);
        }
Example #6
0
        string GenerateKeys(Drive drive)
        {
            string pubkey = "";

            try
            {
                string dotssh = $@"{drive.UserProfile}\.ssh";
                if (!Directory.Exists(dotssh))
                {
                    Directory.CreateDirectory(dotssh);
                }
                ReturnBox r = RunLocal($@"""{AppPath}\ssh-keygen.exe""", $@"-m PEM -t rsa -N """" -f ""{drive.AppKey}""");
                if (File.Exists(drive.AppPubKey))
                {
                    pubkey = File.ReadAllText(drive.AppPubKey).Trim();
                }
            }
            catch (Exception ex)
            {
                Logger.Log("Error generating keys: " + ex.Message);
            }
            return(pubkey);
        }
Example #7
0
        //public List<Drive> GetGoldDrives(List<Drive> settingsDrives)
        //{
        //    //List<Drive> usedDrives = GetUsedDrives().Where(x => x.IsGoldDrive == true).ToList();
        //    //Settings settings = LoadSettings();

        //    //List<Drive> drives = settings.Drives.Values.ToList();
        //    foreach (Drive u in GoldDrives)
        //    {
        //        var d1 = settingsDrives.Find(x1 => x1.Letter == u.Letter);
        //        if(d1 == null)
        //        {
        //            settingsDrives.Add(u);
        //        }
        //        else
        //        {
        //            var d2 = settingsDrives.Find(x2 => (x2.Letter == u.Letter && x2.MountPoint == u.MountPoint));
        //            if(d2 == null)
        //            {
        //                d1.MountPoint = u.MountPoint;
        //            }
        //        }
        //    }
        //    return settingsDrives;
        //}
        public List <Drive> GetFreeDrives()
        {
            string       GOLDLETTERS = "GHIJKLMNOPQRSTUVWXYZ";
            List <char>  letters     = GOLDLETTERS.ToCharArray().ToList();
            List <Drive> freeDrives  = new List <Drive>();

            DriveInfo[] drives = DriveInfo.GetDrives();

            for (int i = 0; i < drives.Length; i++)
            {
                letters.Remove(drives[i].Name[0]);
            }
            foreach (char c in letters)
            {
                Drive d = new Drive
                {
                    Letter = c.ToString()
                };
                freeDrives.Add(d);
            }
            freeDrives.Reverse();
            return(freeDrives);
        }
Example #8
0
        public bool CheckIfDriveWorks(Drive drive)
        {
            // Fist try DriveInfo
            var  info = new DriveInfo(drive.Letter);
            bool ok   = false;

            try {
                ok = info.AvailableFreeSpace >= 0;
            } catch (IOException) {
                return(false);
            }
            return(ok);
            //if (works) {
            //    int epoch = (int)(DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
            //    string tempfile = $@"{ drive.Name }\tmp\{drive.User}@{drive.Host}.{epoch}";
            //    var r = RunLocal("type nul > " + tempfile);
            //    if (r.ExitCode == 0) {
            //        RunLocal("del " + tempfile);
            //        return true;
            //    }
            //}
            //return false;
        }
Example #9
0
        public ReturnBox Connect(Drive drive, IProgress <string> status)
        {
            ReturnBox r = new ReturnBox();

            if (!IsWinfspInstalled())
            {
                r.MountStatus = MountStatus.BAD_WINFSP;
                r.Error       = "Winfsp is not installed\n";
                return(r);
            }
            if (!IsCliInstalled())
            {
                r.MountStatus = MountStatus.BAD_CLI;
                r.Error       = "Goldrive CLI is not installed\n";
                return(r);
            }
            r = CheckDriveStatus(drive);
            if (r.DriveStatus != DriveStatus.DISCONNECTED)
            {
                r.MountStatus = MountStatus.BAD_DRIVE;
                return(r);
            }
            status?.Report("Checking server...");
            r = TestHost(drive);
            if (r.MountStatus != MountStatus.OK)
            {
                return(r);
            }
            status?.Report("Authenticating...");
            r = TestSsh(drive);
            if (r.MountStatus != MountStatus.OK)
            {
                return(r);
            }
            status?.Report("Mounting drive...");
            return(Mount(drive));
        }
Example #10
0
        public ReturnBox Connect(Drive drive)
        {
            ReturnBox r = new ReturnBox();

            if (!IsWinfspInstalled())
            {
                r.MountStatus = MountStatus.BAD_WINFSP;
                return(r);
            }
            r = CheckDriveStatus(drive);
            if (r.DriveStatus != DriveStatus.DISCONNECTED)
            {
                r.MountStatus = MountStatus.BAD_DRIVE;
                r.Error       = r.DriveStatus.ToString();
                return(r);
            }
            r = TestSsh(drive, drive.AppKey);
            if (r.MountStatus != MountStatus.OK)
            {
                return(r);
            }

            return(Mount(drive));
        }
Example #11
0
        internal void Load()
        {
            if (!File.Exists(Filename))
            {
                return;
            }

            try
            {
                string args = "";
                var    json = JsonConvert.DeserializeObject <Dictionary <string, object> >(File.ReadAllText(Filename));
                //if (json.ContainsKey("Args"))
                //    Args = json["Args"].ToString();
                //LogFile = "C:\\Users\\Sant\\Desktop\\golddrive.log";

                //if (json.ContainsKey("LogFile"))
                //    LogFile = json["LogFile"].ToString();
                if (json.ContainsKey("UsageUrl"))
                {
                    UsageUrl = json["UsageUrl"].ToString();
                }
                else
                {
                    // testing url logging
                    //UsageUrl = "https://192.168.100.201:5000";
                }
                if (json.ContainsKey("Selected"))
                {
                    Selected = json["Selected"].ToString();
                }
                if (!json.ContainsKey("Drives"))
                {
                    return;
                }
                var _drives = JsonConvert.DeserializeObject <Dictionary <string, object> >(json["Drives"].ToString());
                foreach (var _d in _drives.Keys)
                {
                    if (_d.Length < 2)
                    {
                        continue;
                    }
                    Drive d = new Drive
                    {
                        Letter = _d[0].ToString(),
                        Args   = args
                    };
                    var data = JsonConvert.DeserializeObject <Dictionary <string, object> >(_drives[_d].ToString());
                    if (data.ContainsKey("Args") && data["Args"] != null)
                    {
                        d.Args = data["Args"].ToString();
                    }
                    if (data.ContainsKey("Label") && data["Label"] != null)
                    {
                        d.Label = data["Label"].ToString();
                    }
                    if (data.ContainsKey("MountPoint") && data["MountPoint"] != null)
                    {
                        d.MountPoint = data["MountPoint"].ToString();
                    }
                    //if (data.ContainsKey("Hosts") && data["Hosts"] != null)
                    //    d.Hosts = JsonConvert.DeserializeObject<List<string>>(data["Hosts"].ToString());
                    Drives[d.Name] = d;
                }
                var selected = Drives.Values.ToList().Find(x => x.Name == Selected);
                if (selected != null)
                {
                    SelectedDrive = selected;
                }
            }
            catch (Exception ex)
            {
            }
        }
Example #12
0
        public ReturnBox TestSsh(Drive drive, string key)
        {
            ReturnBox r = new ReturnBox();

            //r = TestHost(drive);
            //if (r.MountStatus == MountStatus.BAD_HOST)
            //    return r;

            if (!File.Exists(key))
            {
                r.MountStatus = MountStatus.BAD_KEY;
                r.Error       = "No ssh key";
                return(r);
            }
            try
            {
                r.MountStatus = MountStatus.UNKNOWN;
                var       pk       = new PrivateKeyFile(key);
                var       keyFiles = new[] { pk };
                SshClient client   = new SshClient(drive.Host, drive.Port, drive.User, keyFiles);
                client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(5);
                client.Connect();
                client.Disconnect();
                r.MountStatus = MountStatus.OK;
            }
            catch (Exception ex)
            {
                r.Error = ex.Message;
                if (ex is SshAuthenticationException)
                {
                    r.MountStatus = MountStatus.BAD_KEY;
                }
                else if (ex is SocketException)
                {
                    if (ex.Message.Contains("actively refused it"))
                    {
                        r.MountStatus = MountStatus.BAD_KEY;
                    }
                    else
                    {
                        r.MountStatus = MountStatus.BAD_HOST;
                    }
                }
                else if (ex is SshConnectionException)
                {
                    r.MountStatus = MountStatus.BAD_HOST;
                }
                else if (ex is InvalidOperationException)
                {
                    r.MountStatus = MountStatus.BAD_HOST;
                }
                else
                {
                    if (ex.Message.Contains("milliseconds"))
                    {
                        r.Error       = "Host does not respond";
                        r.MountStatus = MountStatus.BAD_HOST;
                    }
                    else
                    {
                        r.MountStatus = MountStatus.UNKNOWN;
                    }
                }
            }
            return(r);
        }
Example #13
0
        //public ReturnBox DownloadFile(string src, string dst)
        //{
        //    ReturnBox r = new ReturnBox();
        //    if (Connected)
        //    {
        //        try
        //        {
        //            using (Stream fs = File.Create(dst))
        //            {
        //                Sftp.DownloadFile(src, fs);
        //            }
        //            r.Success = true;
        //        }
        //        catch (Exception ex)
        //        {
        //            r.Error = ex.Message;
        //        }
        //    }
        //    return r;
        //}

        //public ReturnBox UploadFile(string src, string dir, string filename)
        //{
        //    ReturnBox r = new ReturnBox();
        //    if (Connected)
        //    {
        //        try
        //        {
        //            using (var fs = new FileStream(src, FileMode.Open))
        //            {
        //                Sftp.BufferSize = 4 * 1024; // bypass Payload error large files
        //                Sftp.ChangeDirectory(dir);
        //                Sftp.UploadFile(fs, filename, true);
        //            }
        //            r.Success = true;
        //        }
        //        catch (Exception ex)
        //        {
        //            r.Error = ex.Message;
        //        }
        //    }
        //    return r;
        //}

        #endregion

        #region Local Drive Management


        public void UpdateDrives(Settings settings)
        {
            string      GOLDLETTERS = "GHIJKLMNOPQRSTUVWXYZ";
            List <char> letters     = GOLDLETTERS.ToCharArray().ToList();

            DriveInfo[] drives = DriveInfo.GetDrives();
            Drives.Clear();
            var settingsDrives = settings.Drives.Values.ToList();
            var netUseDrives   = GetUsedDrives();

            foreach (char c in letters)
            {
                //if (c == 'W')
                //    c.ToString();
                bool  used = false;
                Drive d    = new Drive {
                    Letter = c.ToString()
                };

                for (int i = 0; i < drives.Length; i++)
                {
                    try {
                        DriveInfo dinfo = drives[i];
                        if (dinfo.Name[0] == c)
                        {
                            d.Status = DriveStatus.UNKNOWN;
                            // this triggers IOException when drive is unavailable
                            d.IsGoldDrive = dinfo.DriveFormat == "FUSE-Golddrive";
                            used          = true;
                            if (d.IsGoldDrive == true)
                            {
                                d.MountPoint = dinfo.VolumeLabel.Replace("/", "\\");
                                d.Label      = GetExplorerDriveLabel(d);
                                if (dinfo.IsReady)
                                {
                                    d.Status = DriveStatus.CONNECTED;
                                }
                                else
                                {
                                    d.Status = DriveStatus.BROKEN;
                                }
                                var d1 = settingsDrives.Find(x => x.Letter == d.Letter);
                                if (d1 != null)
                                {
                                    //d.MountPoint = d1.MountPoint;
                                    d.Args  = d1.Args;
                                    d.Label = d1.Label;
                                }
                            }
                            Drives.Add(d);
                            break;
                        }
                    } catch (IOException e) {
                    } catch (Exception ex) {
                    }
                }

                if (!used)
                {
                    var d0 = netUseDrives.Find(x => x.Letter == d.Letter);
                    if (d0 != null)
                    {
                        d.IsGoldDrive = d0.IsGoldDrive;
                        d.Status      = d0.Status;
                        if (d.IsGoldDrive == true)
                        {
                            d.Status     = DriveStatus.BROKEN;
                            d.MountPoint = d0.MountPoint;
                            d.Label      = d0.Label;
                            var d1 = settingsDrives.Find(x1 => x1.Letter == d.Letter);
                            if (d1 != null)
                            {
                                d.Args  = d1.Args;
                                d.Label = d1.Label;
                            }
                        }
                        else
                        {
                            d.Status = DriveStatus.UNKNOWN;
                        }
                    }
                    else
                    {
                        var d1 = settingsDrives.Find(x1 => x1.Letter == d.Letter);
                        if (d1 != null)
                        {
                            d.Status      = DriveStatus.DISCONNECTED;
                            d.MountPoint  = d1.MountPoint;
                            d.Args        = d1.Args;
                            d.Label       = d1.Label;
                            d.IsGoldDrive = true;
                        }
                        else
                        {
                            d.Status = DriveStatus.FREE;
                        }
                    }
                    Drives.Add(d);
                }
            }
        }
Example #14
0
 public Drive(Drive d)
 {
     Clone(d);
 }
Example #15
0
        public ReturnBox TestSsh(Drive drive)
        {
            ReturnBox r = new ReturnBox();



            if (!File.Exists(drive.AppKey))
            {
                r.MountStatus = MountStatus.BAD_KEY;
                r.Error       = String.Format($"Password is required to connnect to {drive.CurrentUser}@{drive.Host}:{drive.CurrentPort}.\nSSH keys will be generated and used in future conections.");
                return(r);
            }
            try
            {
                r.MountStatus = MountStatus.UNKNOWN;

                var       pk       = new PrivateKeyFile(drive.AppKey);
                var       keyFiles = new[] { pk };
                SshClient client   = new SshClient(drive.Host, drive.CurrentPort, drive.CurrentUser, keyFiles);
                client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(TIMEOUT);
                client.Connect();
                client.Disconnect();
                r.MountStatus = MountStatus.OK;
                r.Success     = true;
            }
            catch (Exception ex)
            {
                r.Error = ex.Message;
                if (ex is SshAuthenticationException)
                {
                    r.MountStatus = MountStatus.BAD_KEY;
                }
                else if (ex is SocketException ||
                         ex is SshConnectionException ||
                         ex is InvalidOperationException ||
                         ex.Message.Contains("milliseconds"))
                {
                    r.Error       = "Host does not respond";
                    r.MountStatus = MountStatus.BAD_HOST;
                }
                else if (ex.Message.Contains("OPENSSH"))
                {
                    // openssh keys not supported by ssh.net yet
                    string args = $"-i \"{drive.AppKey}\" -p {drive.CurrentPort} -oPasswordAuthentication=no -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout={TIMEOUT} { drive.CurrentUser}@{drive.Host} \"echo ok\"";
                    var    r1   = RunLocal("ssh.exe", args, TIMEOUT);
                    var    ok   = r1.Output.Trim() == "ok";
                    if (ok)
                    {
                        r.MountStatus = MountStatus.OK;
                        r.Error       = "";
                        r.Success     = true;
                    }
                    else
                    {
                        r.MountStatus = MountStatus.BAD_KEY;
                        r.Error       = r1.Error;
                    }
                }
            }
            return(r);
        }
Example #16
0
        internal void Load()
        {
            if (!File.Exists(Filename))
            {
                return;
            }

            try
            {
                string args = "";
                var    json = JsonConvert.DeserializeObject <Dictionary <string, object> >(File.ReadAllText(Filename));
                if (json.ContainsKey("Args"))
                {
                    Args = json["Args"].ToString();
                }
                if (json.ContainsKey("Selected"))
                {
                    Selected = json["Selected"].ToString();
                }
                if (!json.ContainsKey("Drives"))
                {
                    return;
                }
                var _drives = JsonConvert.DeserializeObject <Dictionary <string, object> >(json["Drives"].ToString());
                foreach (var _d in _drives.Keys)
                {
                    if (_d.Length < 2)
                    {
                        continue;
                    }
                    Drive d = new Drive
                    {
                        Letter = _d[0].ToString(),
                        Args   = args
                    };
                    var data = JsonConvert.DeserializeObject <Dictionary <string, object> >(_drives[_d].ToString());
                    if (data.ContainsKey("Args"))
                    {
                        d.Args = data["Args"].ToString();
                    }
                    if (data.ContainsKey("Label"))
                    {
                        d.Label = data["Label"].ToString();
                    }
                    if (data.ContainsKey("MountPoint"))
                    {
                        d.MountPoint = data["MountPoint"].ToString();
                    }
                    if (data.ContainsKey("Hosts"))
                    {
                        d.Hosts = JsonConvert.DeserializeObject <List <string> >(data["Hosts"].ToString());
                    }
                    Drives[d.Name] = d;
                }
                var selected = Drives.Values.ToList().Find(x => x.Name == Selected);
                if (selected != null)
                {
                    SelectedDrive = selected;
                }
            }
            catch (Exception ex)
            {
            }
        }
Example #17
0
 private void OnSettingsEdit(object obj)
 {
     OriginalDrive = new Drive(SelectedDrive);
     IsDriveEdit   = true;
 }
Example #18
0
 public void AddDrive(Drive drive)
 {
     Drives[drive.Name] = drive;
 }
Example #19
0
 private void OnSettingsNew(object obj)
 {
     OriginalDrive = new Drive(SelectedDrive);
     SelectedDrive = FreeDriveList.First();
     IsDriveNew    = true;
 }