Пример #1
0
        public IFileStorage GetFileStorage(IOConnectionInfo iocInfo, bool allowCache)
        {
            IFileStorage fileStorage;

            if (iocInfo.IsLocalFile())
            {
                fileStorage = new LocalFileStorage(this);
            }
            else
            {
                IFileStorage innerFileStorage = GetCloudFileStorage(iocInfo);

                if (DatabaseCacheEnabled && allowCache)
                {
                    fileStorage = new CachingFileStorage(innerFileStorage, Application.Context, this);
                }
                else
                {
                    fileStorage = innerFileStorage;
                }
            }
            if (fileStorage is IOfflineSwitchable)
            {
                ((IOfflineSwitchable)fileStorage).IsOffline = App.Kp2a.OfflineMode;
            }
            return(fileStorage);
        }
Пример #2
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            // Must work without a parent window
            Debug.Assert(this.StartPosition == FormStartPosition.CenterScreen);

            // The password text box should not be focused by default
            // in order to avoid a Caps Lock warning tooltip bug;
            // https://sourceforge.net/p/keepass/bugs/1807/
            Debug.Assert((m_tbPassword.TabIndex >= 2) && !m_tbPassword.Focused);

            InitAdvancedTab();             // After translation, before resize

            GlobalWindowManager.AddWindow(this);

            string strTitle = (m_bSave ? KPRes.UrlSaveTitle : KPRes.UrlOpenTitle);
            string strDesc  = (m_bSave ? KPRes.UrlSaveDesc : KPRes.UrlOpenDesc);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         KeePass.Properties.Resources.B48x48_WWW, strTitle, strDesc);
            this.Icon = AppIcons.Default;
            this.Text = strTitle;

            FontUtil.AssignDefaultBold(m_lblUrl);
            FontUtil.AssignDefaultBold(m_lblUserName);
            FontUtil.AssignDefaultBold(m_lblPassword);
            FontUtil.AssignDefaultBold(m_lblRemember);

            m_tbUrl.Text      = (m_ioc.IsLocalFile() ? string.Empty : m_ioc.Path);
            m_tbUserName.Text = m_ioc.UserName;
            m_tbPassword.Text = m_ioc.Password;

            m_cmbCredSaveMode.Items.Add(KPRes.CredSaveNone);
            m_cmbCredSaveMode.Items.Add(KPRes.CredSaveUserOnly);
            m_cmbCredSaveMode.Items.Add(KPRes.CredSaveAll);

            if (m_ioc.CredSaveMode == IOCredSaveMode.UserNameOnly)
            {
                m_cmbCredSaveMode.SelectedIndex = 1;
            }
            else if (m_ioc.CredSaveMode == IOCredSaveMode.SaveCred)
            {
                m_cmbCredSaveMode.SelectedIndex = 2;
            }
            else
            {
                m_cmbCredSaveMode.SelectedIndex = 0;
            }

            if (!m_bCanRememberCred)
            {
                m_cmbCredSaveMode.SelectedIndex = 0;
                m_cmbCredSaveMode.Enabled       = false;
            }

            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                try { InitAutoCompletions(); }
                catch (Exception) { Debug.Assert(false); }
            });
        }
Пример #3
0
        public bool IsReadOnly(IOConnectionInfo ioc, OptionalOut <UiStringKey> reason = null)
        {
            if (ioc.IsLocalFile())
            {
                if (IsLocalFileFlaggedReadOnly(ioc))
                {
                    if (reason != null)
                    {
                        reason.Result = UiStringKey.ReadOnlyReason_ReadOnlyFlag;
                    }
                    return(true);
                }

                if (IsReadOnlyBecauseKitkatRestrictions(ioc))
                {
                    if (reason != null)
                    {
                        reason.Result = UiStringKey.ReadOnlyReason_ReadOnlyKitKat;
                    }
                    return(true);
                }


                return(false);
            }
            //for remote files assume they can be written: (think positive! :-) )
            return(false);
        }
Пример #4
0
        private static bool CheckFileExsts(IOConnectionInfo ioc)
        {
            try
            {
                var fileStorage = App.Kp2a.GetFileStorage(ioc);

                //we're assuming that remote files always exist (if we have a file storage, i.e. we check after receiving a file storage)
                //The SkipIfNotExists switch only makes sense for local files, because remote files either exist for all devices or none
                //(Ok, there are exceptions like files available in a (W)LAN. But then we still have the device switch and caches.)
                //We cannot use OpenFileForRead on remote storages because this method is called from the main thread.
                if (!ioc.IsLocalFile())
                {
                    return(true);
                }

                using (var stream = fileStorage.OpenFileForRead(ioc))
                {
                }
            }
            catch (NoFileStorageFoundException e)
            {
                return(false);
            }
            catch (FileNotFoundException)
            {
                return(false);
            }
            return(true);
        }
Пример #5
0
        public string GetKeySource(IOConnectionInfo ioDatabase, bool bGetKeyFile)
        {
            if (ioDatabase == null)
            {
                throw new ArgumentNullException("ioDatabase");
            }

            string strDb = ioDatabase.Path;

            if ((strDb.Length > 0) && ioDatabase.IsLocalFile() &&
                !UrlUtil.IsAbsolutePath(strDb))
            {
                strDb = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strDb);
            }

            foreach (AceKeyAssoc kfp in m_vKeySources)
            {
                if (strDb.Equals(kfp.DatabasePath, StrUtil.CaseIgnoreCmp))
                {
                    return(bGetKeyFile ? kfp.KeyFilePath : kfp.KeyProvider);
                }
            }

            return(null);
        }
Пример #6
0
        public void PrepareFileUsage(IFileStorageSetupInitiatorActivity activity, IOConnectionInfo ioc, int requestCode, bool alwaysReturnSuccess)
        {
            //check if we need to request the external-storage-permission at runtime
            if (ioc.IsLocalFile())
            {
                bool requiresPermission = !(ioc.Path.StartsWith(activity.Activity.FilesDir.CanonicalPath) ||
                                            ioc.Path.StartsWith(IoUtil.GetInternalDirectory(activity.Activity).CanonicalPath) ||
                                            ioc.Path.StartsWith(IoUtil.GetInternalDirectory(activity.Activity).CanonicalPath));

                var extDirectory = activity.Activity.GetExternalFilesDir(null);
                if ((extDirectory != null) && (ioc.Path.StartsWith(extDirectory.CanonicalPath)))
                {
                    requiresPermission = false;
                }

                if (requiresPermission && (Build.VERSION.SdkInt >= BuildVersionCodes.M))
                {
                    if ((activity.Activity.CheckSelfPermission(Manifest.Permission.WriteExternalStorage) ==
                         Permission.Denied)
                        ||
                        (activity.Activity.CheckSelfPermission(Manifest.Permission.ReadExternalStorage) ==
                         Permission.Denied))

                    {
                        activity.StartFileUsageProcess(ioc, requestCode, alwaysReturnSuccess);
                        return;
                    }
                }
            }
            Intent intent = new Intent();

            activity.IocToIntent(intent, ioc);
            activity.OnImmediateResult(requestCode, (int)FileStorageResults.FileUsagePrepared, intent);
        }
Пример #7
0
        private static void ChangePathRelAbs(IOConnectionInfo ioc, bool bMakeAbsolute)
        {
            if (ioc == null)
            {
                Debug.Assert(false); return;
            }

            if (!ioc.IsLocalFile())
            {
                return;
            }

            // Update path separators for current system
            ioc.Path = UrlUtil.ConvertSeparators(ioc.Path);

            string strBase = WinUtil.GetExecutable();
            bool   bIsAbs  = UrlUtil.IsAbsolutePath(ioc.Path);

            if (bMakeAbsolute && !bIsAbs)
            {
                ioc.Path = UrlUtil.MakeAbsolutePath(strBase, ioc.Path);
            }
            else if (!bMakeAbsolute && bIsAbs)
            {
                ioc.Path = UrlUtil.MakeRelativePath(strBase, ioc.Path);
            }
        }
Пример #8
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            // Must work without a parent window
            Debug.Assert(this.StartPosition == FormStartPosition.CenterScreen);

            GlobalWindowManager.AddWindow(this);

            string strTitle = (m_bSave ? KPRes.UrlSaveTitle : KPRes.UrlOpenTitle);
            string strDesc  = (m_bSave ? KPRes.UrlSaveDesc : KPRes.UrlOpenDesc);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         KeePass.Properties.Resources.B48x48_WWW, strTitle, strDesc);
            this.Icon = Properties.Resources.KeePass;
            this.Text = strTitle;

            FontUtil.AssignDefaultBold(m_lblUrl);
            FontUtil.AssignDefaultBold(m_lblUserName);
            FontUtil.AssignDefaultBold(m_lblPassword);
            FontUtil.AssignDefaultBold(m_lblRemember);

            m_tbUrl.Text      = (m_ioc.IsLocalFile() ? string.Empty : m_ioc.Path);
            m_tbUserName.Text = m_ioc.UserName;
            m_tbPassword.Text = m_ioc.Password;

            m_cmbCredSaveMode.Items.Add(KPRes.CredSaveNone);
            m_cmbCredSaveMode.Items.Add(KPRes.CredSaveUserOnly);
            m_cmbCredSaveMode.Items.Add(KPRes.CredSaveAll);

            if (m_ioc.CredSaveMode == IOCredSaveMode.UserNameOnly)
            {
                m_cmbCredSaveMode.SelectedIndex = 1;
            }
            else if (m_ioc.CredSaveMode == IOCredSaveMode.SaveCred)
            {
                m_cmbCredSaveMode.SelectedIndex = 2;
            }
            else
            {
                m_cmbCredSaveMode.SelectedIndex = 0;
            }

            if (m_bCanRememberCred == false)
            {
                m_cmbCredSaveMode.SelectedIndex = 0;
                m_cmbCredSaveMode.Enabled       = false;
            }

            UIUtil.SetFocus(m_tbUrl, this);

            if ((m_tbUrl.TextLength > 0) && (m_tbUserName.TextLength > 0))
            {
                UIUtil.SetFocus(m_tbPassword, this);
            }
            else if (m_tbUrl.TextLength > 0)
            {
                UIUtil.SetFocus(m_tbUserName, this);
            }
        }
Пример #9
0
		private void Initialize(IOConnectionInfo iocBaseFile, bool bTransacted)
		{
			if(iocBaseFile == null) throw new ArgumentNullException("iocBaseFile");

			m_bTransacted = bTransacted;
			m_iocBase = iocBaseFile.CloneDeep();

			string strPath = m_iocBase.Path;

			if(m_iocBase.IsLocalFile())
			{
				try
				{
					if(File.Exists(strPath))
					{
						// Symbolic links are realized via reparse points;
						// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365503.aspx
						// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365680.aspx
						// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365006.aspx
						// Performing a file transaction on a symbolic link
						// would delete/replace the symbolic link instead of
						// writing to its target
						FileAttributes fa = File.GetAttributes(strPath);
						if((long)(fa & FileAttributes.ReparsePoint) != 0)
							m_bTransacted = false;
					}
				}
				catch(Exception) { Debug.Assert(false); }
			}

#if !KeePassUAP
			// Prevent transactions for FTP URLs under .NET 4.0 in order to
			// avoid/workaround .NET bug 621450:
			// https://connect.microsoft.com/VisualStudio/feedback/details/621450/problem-renaming-file-on-ftp-server-using-ftpwebrequest-in-net-framework-4-0-vs2010-only
			if(strPath.StartsWith("ftp:", StrUtil.CaseIgnoreCmp) &&
				(Environment.Version.Major >= 4) && !NativeLib.IsUnix())
				m_bTransacted = false;
#endif

			foreach(KeyValuePair<string, bool> kvp in g_dEnabled)
			{
				if(strPath.StartsWith(kvp.Key, StrUtil.CaseIgnoreCmp))
				{
					m_bTransacted = kvp.Value;
					break;
				}
			}

			if(m_bTransacted)
			{
				m_iocTemp = m_iocBase.CloneDeep();
				m_iocTemp.Path += StrTempSuffix;
			}
			else m_iocTemp = m_iocBase;
		}
Пример #10
0
 public string GetCurrentFileVersionFast(IOConnectionInfo ioc)
 {
     if (ioc.IsLocalFile())
     {
         return(File.GetLastWriteTimeUtc(ioc.Path).ToString(CultureInfo.InvariantCulture));
     }
     else
     {
         return(DateTime.MinValue.ToString(CultureInfo.InvariantCulture));
     }
 }
Пример #11
0
		private static string GetKeyAssocID(IOConnectionInfo iocDb)
		{
			if(iocDb == null) throw new ArgumentNullException("iocDb");

			string strDb = iocDb.Path;
			if((strDb.Length > 0) && iocDb.IsLocalFile() &&
				!UrlUtil.IsAbsolutePath(strDb))
				strDb = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strDb);

			return strDb;
		}
Пример #12
0
        private bool PrepareExchangeEx()
        {
            UpdateUIState();
            if (m_fmtCur == null)
            {
                return(false);
            }

            string strFiles = m_tbFile.Text;

            string[] vFiles = strFiles.Split(new char[] { ';' },
                                             StringSplitOptions.RemoveEmptyEntries);

            if (m_fmtCur.RequiresFile)
            {
                if (vFiles.Length == 0)
                {
                    return(false);
                }

                foreach (string strFile in vFiles)
                {
                    IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile);
                    if (ioc.IsLocalFile() && !UrlUtil.IsAbsolutePath(strFile))
                    {
                        MessageService.ShowWarning(strFile, KPRes.FilePathFullReq);
                        return(false);
                    }
                }

                // Allow only one file when exporting
                if (m_bExport && !CheckFilePath(strFiles))
                {
                    return(false);
                }
            }
            else
            {
                vFiles = new string[0];
            }

            if (m_piExport != null)
            {
                m_piExport.ExportMasterKeySpec = m_cbExportMasterKeySpec.Checked;
                m_piExport.ExportParentGroups  = m_cbExportParentGroups.Checked;
                m_piExport.ExportPostOpen      = m_cbExportPostOpen.Checked;
                m_piExport.ExportPostShow      = m_cbExportPostShow.Checked;
            }

            m_fmtFinal = m_fmtCur;
            m_vFiles   = vFiles;
            return(true);
        }
Пример #13
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            GlobalWindowManager.AddWindow(this);

            string strTitle = (m_bSave ? KPRes.UrlSaveTitle : KPRes.UrlOpenTitle);
            string strDesc  = (m_bSave ? KPRes.UrlSaveDesc : KPRes.UrlOpenDesc);

            m_bannerImage.Image = BannerFactory.CreateBanner(m_bannerImage.Width,
                                                             m_bannerImage.Height, BannerStyle.Default,
                                                             KeePass.Properties.Resources.B48x48_WWW, strTitle,
                                                             strDesc);
            this.Icon = Properties.Resources.KeePass;
            this.Text = strTitle;

            m_tbUrl.Text      = (m_ioc.IsLocalFile() ? string.Empty : m_ioc.Path);
            m_tbUserName.Text = m_ioc.UserName;
            m_tbPassword.Text = m_ioc.Password;

            m_cmbCredSaveMode.Items.Add(KPRes.CredSaveNone);
            m_cmbCredSaveMode.Items.Add(KPRes.CredSaveUserOnly);
            m_cmbCredSaveMode.Items.Add(KPRes.CredSaveAll);

            if (m_ioc.CredSaveMode == IOCredSaveMode.UserNameOnly)
            {
                m_cmbCredSaveMode.SelectedIndex = 1;
            }
            else if (m_ioc.CredSaveMode == IOCredSaveMode.SaveCred)
            {
                m_cmbCredSaveMode.SelectedIndex = 2;
            }
            else
            {
                m_cmbCredSaveMode.SelectedIndex = 0;
            }

            if (m_bCanRememberCred == false)
            {
                m_cmbCredSaveMode.SelectedIndex = 0;
                m_cmbCredSaveMode.Enabled       = false;
            }

            m_tbUrl.Focus();

            // Give the user name field the focus, if URL is specified
            if (m_ioc.Path.Length > 0)
            {
                this.ActiveControl = m_tbUserName;
                m_tbUserName.Focus();
            }
        }
Пример #14
0
        private static void OpenDatabaseFile(EcasAction a, EcasContext ctx)
        {
            string strPath = EcasUtil.GetParamString(a.Parameters, 0, true);

            if (string.IsNullOrEmpty(strPath))
            {
                return;
            }

            string strIOUserName = EcasUtil.GetParamString(a.Parameters, 1, true);
            string strIOPassword = EcasUtil.GetParamString(a.Parameters, 2, true);

            IOConnectionInfo ioc = IOFromParameters(strPath, strIOUserName, strIOPassword);

            if (ioc == null)
            {
                return;
            }

            string strPassword  = EcasUtil.GetParamString(a.Parameters, 3, true);
            string strKeyFile   = EcasUtil.GetParamString(a.Parameters, 4, true);
            bool   bUserAccount = StrUtil.StringToBool(EcasUtil.GetParamString(
                                                           a.Parameters, 5, true));

            CompositeKey cmpKey = null;

            if (!string.IsNullOrEmpty(strPassword) || !string.IsNullOrEmpty(strKeyFile) ||
                bUserAccount)
            {
                List <string> vArgs = new List <string>();
                if (!string.IsNullOrEmpty(strPassword))
                {
                    vArgs.Add("-" + AppDefs.CommandLineOptions.Password + ":" + strPassword);
                }
                if (!string.IsNullOrEmpty(strKeyFile))
                {
                    vArgs.Add("-" + AppDefs.CommandLineOptions.KeyFile + ":" + strKeyFile);
                }
                if (bUserAccount)
                {
                    vArgs.Add("-" + AppDefs.CommandLineOptions.UserAccount);
                }

                CommandLineArgs cmdArgs = new CommandLineArgs(vArgs.ToArray());
                cmpKey = KeyUtil.KeyFromCommandLine(cmdArgs);
            }

            Program.MainForm.OpenDatabase(ioc, cmpKey, ioc.IsLocalFile());
        }
Пример #15
0
 public bool CheckForFileChangeFast(IOConnectionInfo ioc, string previousFileVersion)
 {
     if (!ioc.IsLocalFile())
         return false;
     if (previousFileVersion == null)
         return false;
     DateTime previousDate;
     if (!DateTime.TryParse(previousFileVersion, CultureInfo.InvariantCulture, DateTimeStyles.None, out previousDate))
         return false;
     DateTime currentModificationDate = File.GetLastWriteTimeUtc(ioc.Path);
     TimeSpan diff = currentModificationDate - previousDate;
     return diff > TimeSpan.FromSeconds(1);
     //don't use > operator because milliseconds are truncated
     //return File.GetLastWriteTimeUtc(ioc.Path) - previousDate >= TimeSpan.FromSeconds(1);
 }
Пример #16
0
        public bool IsLocalBackup(IOConnectionInfo ioc)
        {
            if (!ioc.IsLocalFile())
            {
                return(false);
            }
            bool result;

            if (_isLocalBackupCache.TryGetValue(ioc.Path, out result))
            {
                return(result);
            }

            result = (PreferenceManager.GetDefaultSharedPreferences(Application.Context)
                      .GetBoolean(IoUtil.GetIocPrefKey(ioc, "is_local_backup"), false));
            _isLocalBackupCache[ioc.Path] = result;
            return(result);
        }
Пример #17
0
        private static void InitFileDialog(FileDialogEx dlg)
        {
            if (dlg == null)
            {
                Debug.Assert(false); return;
            }

            IOConnectionInfo ioDir = Program.Config.Application.LastUsedFile;

            if (!string.IsNullOrEmpty(ioDir.Path) && ioDir.IsLocalFile())
            {
                string strDir = UrlUtil.GetFileDirectory(ioDir.Path, false, true);
                if (Directory.Exists(strDir))
                {
                    dlg.InitialDirectory = strDir;
                }
            }
        }
Пример #18
0
        private void UpdateImportKeyfilePref()
        {
            var prefs           = PreferenceManager.GetDefaultSharedPreferences(Activity);
            var rememberKeyfile = prefs.GetBoolean(GetString(Resource.String.keyfile_key), Resources.GetBoolean(Resource.Boolean.keyfile_default));

            Preference importKeyfile = FindPreference("import_keyfile_prefs");
            Preference exportKeyfile = FindPreference("export_keyfile_prefs");

            importKeyfile.Summary = "";

            if (!rememberKeyfile)
            {
                importKeyfile.Summary = GetString(Resource.String.KeyfileMoveRequiresRememberKeyfile);
                importKeyfile.Enabled = false;
                exportKeyfile.Enabled = false;
                return;
            }
            CompositeKey masterKey = App.Kp2a.CurrentDb.KpDatabase.MasterKey;

            if (masterKey.ContainsType(typeof(KcpKeyFile)))
            {
                IOConnectionInfo iocKeyfile = ((KcpKeyFile)masterKey.GetUserKey(typeof(KcpKeyFile))).Ioc;
                if (iocKeyfile.IsLocalFile() && IoUtil.IsInInternalDirectory(iocKeyfile.Path, Activity))
                {
                    importKeyfile.Enabled          = false;
                    exportKeyfile.Enabled          = true;
                    exportKeyfile.PreferenceClick += (sender, args) => { ExportKeyfileFromInternalFolder(); };
                    importKeyfile.Summary          = GetString(Resource.String.FileIsInInternalDirectory);
                }
                else
                {
                    exportKeyfile.Enabled          = false;
                    importKeyfile.Enabled          = true;
                    importKeyfile.PreferenceClick += (sender, args) => { MoveKeyfileToInternalFolder(); };
                }
            }
            else
            {
                exportKeyfile.Enabled = false;
                importKeyfile.Enabled = false;
            }
        }
Пример #19
0
        private void InitAutoCompletions()
        {
            Dictionary <string, bool> dUrls  = new Dictionary <string, bool>();
            Dictionary <string, bool> dUsers = new Dictionary <string, bool>();

            MainForm mf = Program.MainForm;
            MruList  l  = ((mf != null) ? mf.FileMruList : null);

            if (l == null)
            {
                Debug.Assert(false); return;
            }

            for (uint u = 0; u < l.ItemCount; ++u)
            {
                IOConnectionInfo ioc = (l.GetItem(u).Value as IOConnectionInfo);
                if (ioc == null)
                {
                    Debug.Assert(false); continue;
                }
                if (ioc.IsLocalFile())
                {
                    continue;
                }

                string str = ioc.Path;
                if (!string.IsNullOrEmpty(str))
                {
                    dUrls[str] = true;
                }

                str = ioc.UserName;
                if (!string.IsNullOrEmpty(str))
                {
                    dUsers[str] = true;
                }
            }

            InitAutoCompletion(m_tbUrl, dUrls);
            InitAutoCompletion(m_tbUserName, dUsers);
        }
Пример #20
0
        /// <summary>
        /// returns a file storage object to be used when accessing the auxiliary OTP file
        /// </summary>
        /// The reason why this requires a different file storage is the different caching behavior.
        public IFileStorage GetOtpAuxFileStorage(IOConnectionInfo iocInfo)
        {
            if (iocInfo.IsLocalFile())
            {
                return(new LocalFileStorage(this));
            }
            else
            {
                IFileStorage innerFileStorage = GetCloudFileStorage(iocInfo);


                if (DatabaseCacheEnabled)
                {
                    return(new OtpAuxCachingFileStorage(innerFileStorage, Application.Context, new OtpAuxCacheSupervisor(this)));
                }
                else
                {
                    return(innerFileStorage);
                }
            }
        }
Пример #21
0
        private static void OpenDatabaseFile(EcasAction a, EcasContext ctx)
        {
            string strPath = EcasUtil.GetParamString(a.Parameters, 0, true);

            if (string.IsNullOrEmpty(strPath))
            {
                return;
            }

            string strIOUserName = EcasUtil.GetParamString(a.Parameters, 1, true);
            string strIOPassword = EcasUtil.GetParamString(a.Parameters, 2, true);

            IOConnectionInfo ioc = IOFromParameters(strPath, strIOUserName, strIOPassword);

            if (ioc == null)
            {
                return;
            }

            CompositeKey cmpKey = KeyFromParams(a, 3, 4, 5);

            Program.MainForm.OpenDatabase(ioc, cmpKey, ioc.IsLocalFile());
        }
Пример #22
0
        public bool CheckForFileChangeFast(IOConnectionInfo ioc, string previousFileVersion)
        {
            if (!ioc.IsLocalFile())
            {
                return(false);
            }
            if (previousFileVersion == null)
            {
                return(false);
            }
            DateTime previousDate;

            if (!DateTime.TryParse(previousFileVersion, CultureInfo.InvariantCulture, DateTimeStyles.None, out previousDate))
            {
                return(false);
            }
            DateTime currentModificationDate = File.GetLastWriteTimeUtc(ioc.Path);
            TimeSpan diff = currentModificationDate - previousDate;

            return(diff > TimeSpan.FromSeconds(1));
            //don't use > operator because milliseconds are truncated
            //return File.GetLastWriteTimeUtc(ioc.Path) - previousDate >= TimeSpan.FromSeconds(1);
        }
Пример #23
0
        private static void ChangePathRelAbs(IOConnectionInfo ioc, bool bMakeAbsolute)
        {
            if (ioc == null)
            {
                Debug.Assert(false); return;
            }

            if (ioc.IsLocalFile() == false)
            {
                return;
            }

            string strBase = WinUtil.GetExecutable();
            bool   bIsAbs  = UrlUtil.IsAbsolutePath(ioc.Path);

            if (bMakeAbsolute && !bIsAbs)
            {
                ioc.Path = UrlUtil.MakeAbsolutePath(strBase, ioc.Path);
            }
            else if (!bMakeAbsolute && bIsAbs)
            {
                ioc.Path = UrlUtil.MakeRelativePath(strBase, ioc.Path);
            }
        }
Пример #24
0
        private void AutoOpenEntryPriv(AutoExecItem a, bool bManual)
        {
            PwEntry    pe        = a.Entry;
            PwDatabase pdContext = a.Database;

            SprContext ctxNoEsc = new SprContext(pe, pdContext, SprCompileFlags.All);
            SprContext ctxEsc   = new SprContext(pe, pdContext, SprCompileFlags.All,
                                                 false, true);

            string strDb;

            if (!GetString(pe, PwDefs.UrlField, ctxEsc, true, out strDb))
            {
                return;
            }

            IOConnectionInfo ioc = IOConnectionInfo.FromPath(strDb);

            //TODO

            /*if (ioc.IsLocalFile() && !UrlUtil.IsAbsolutePath(strDb))
             *  ioc = IOConnectionInfo.FromPath(UrlUtil.MakeAbsolutePath(
             *      WinUtil.GetExecutable(), strDb));*/
            if (ioc.Path.Length == 0)
            {
                return;
            }

            string strIocUserName;

            if (GetString(pe, "IocUserName", ctxNoEsc, true, out strIocUserName))
            {
                ioc.UserName = strIocUserName;
            }

            string strIocPassword;

            if (GetString(pe, "IocPassword", ctxNoEsc, true, out strIocPassword))
            {
                ioc.Password = strIocPassword;
            }

            if ((strIocUserName.Length != 0) && (strIocPassword.Length != 0))
            {
                ioc.IsComplete = true;
            }

            string str;

            if (GetString(pe, "IocTimeout", ctxNoEsc, true, out str))
            {
                long l;
                if (long.TryParse(str, out l))
                {
                    ioc.Properties.SetLong(IocKnownProperties.Timeout, l);
                }
            }

            bool?ob = GetBoolEx(pe, "IocPreAuth", ctxNoEsc);

            if (ob.HasValue)
            {
                ioc.Properties.SetBool(IocKnownProperties.PreAuth, ob.Value);
            }

            if (GetString(pe, "IocUserAgent", ctxNoEsc, true, out str))
            {
                ioc.Properties.Set(IocKnownProperties.UserAgent, str);
            }

            ob = GetBoolEx(pe, "IocExpect100Continue", ctxNoEsc);
            if (ob.HasValue)
            {
                ioc.Properties.SetBool(IocKnownProperties.Expect100Continue, ob.Value);
            }

            ob = GetBoolEx(pe, "IocPassive", ctxNoEsc);
            if (ob.HasValue)
            {
                ioc.Properties.SetBool(IocKnownProperties.Passive, ob.Value);
            }

            ob = GetBoolEx(pe, "SkipIfNotExists", ctxNoEsc);
            if (!ob.HasValue) // Backw. compat.
            {
                ob = GetBoolEx(pe, "Skip if not exists", ctxNoEsc);
            }
            if (ob.HasValue && ob.Value)
            {
                if (!IOConnection.FileExists(ioc))
                {
                    return;
                }
            }

            CompositeKey ck = new CompositeKey();

            if (GetString(pe, PwDefs.PasswordField, ctxNoEsc, false, out str))
            {
                ck.AddUserKey(new KcpPassword(str));
            }

            if (GetString(pe, PwDefs.UserNameField, ctxNoEsc, false, out str))
            {
                string           strAbs = str;
                IOConnectionInfo iocKey = IOConnectionInfo.FromPath(strAbs);
                if (iocKey.IsLocalFile() && !UrlUtil.IsAbsolutePath(strAbs))
                {
                    //TODO
                    /*      strAbs = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strAbs);*/
                }


                ob = GetBoolEx(pe, "SkipIfKeyFileNotExists", ctxNoEsc);
                if (ob.HasValue && ob.Value)
                {
                    IOConnectionInfo iocKeyAbs = IOConnectionInfo.FromPath(strAbs);
                    if (!IOConnection.FileExists(iocKeyAbs))
                    {
                        return;
                    }
                }

                try { ck.AddUserKey(new KcpKeyFile(strAbs)); }
                catch (InvalidOperationException)
                {
                    //TODO
                    throw new Exception("TODO");
                    //throw new Exception(strAbs + MessageService.NewParagraph + KPRes.KeyFileError);
                }
                catch (Exception) { throw; }
            }
            else // Try getting key file from attachments
            {
                ProtectedBinary pBin = pe.Binaries.Get("KeyFile.bin");
                if (pBin != null)
                {
                    ck.AddUserKey(new KcpKeyFile(IOConnectionInfo.FromPath(
                                                     StrUtil.DataToDataUri(pBin.ReadData(), null))));
                }
            }

            if (GetString(pe, "KeyProvider", ctxNoEsc, true, out str))
            {
                /*TODO KeyProvider kp = m_host.KeyProviderPool.Get(str);
                 * if (kp == null)
                 *  throw new Exception(@"Unknown key provider: '" + str + @"'!");
                 *
                 * KeyProviderQueryContext ctxKP = new KeyProviderQueryContext(
                 *  ioc, false, false);
                 *
                 * bool bPerformHash = !kp.DirectKey;
                 * byte[] pbProvKey = kp.GetKey(ctxKP);
                 * if ((pbProvKey != null) && (pbProvKey.Length != 0))
                 * {
                 *  ck.AddUserKey(new KcpCustomKey(str, pbProvKey, bPerformHash));
                 *  MemUtil.ZeroByteArray(pbProvKey);
                 * }
                 * else return; // Provider has shown error message*/
                throw new Exception("KeyProvider not supported");
            }

            ob = GetBoolEx(pe, "UserAccount", ctxNoEsc);
            if (ob.HasValue && ob.Value)
            {
                ck.AddUserKey(new KcpUserAccount());
            }

            if (ck.UserKeyCount == 0)
            {
                return;
            }

            GetString(pe, "Focus", ctxNoEsc, true, out str);
            bool bRestoreFocus = str.Equals("Restore", StrUtil.CaseIgnoreCmp);

            /*TODO
             * PwDatabase pdPrev = m_host.MainWindow.ActiveDatabase;
             *
             * m_host.MainWindow.OpenDatabase(ioc, ck, true);
             *
             * if (bRestoreFocus && (pdPrev != null) && !bManual)
             * {
             *  PwDocument docPrev = m_host.MainWindow.DocumentManager.FindDocument(
             *      pdPrev);
             *  if (docPrev != null) m_host.MainWindow.MakeDocumentActive(docPrev);
             *  else { Debug.Assert(false); }
             * }*/
        }
Пример #25
0
		internal static IOConnectionInfo CompleteConnectionInfo(IOConnectionInfo ioc,
			bool bSave, bool bCanRememberCred, bool bTestConnection, bool bForceShow)
		{
			if(ioc == null) { Debug.Assert(false); return null; }
			if(!bForceShow && ((ioc.CredSaveMode == IOCredSaveMode.SaveCred) ||
				ioc.IsLocalFile() || ioc.IsComplete))
				return ioc.CloneDeep();

			IOConnectionForm dlg = new IOConnectionForm();
			dlg.InitEx(bSave, ioc.CloneDeep(), bCanRememberCred, bTestConnection);
			if(UIUtil.ShowDialogNotValue(dlg, DialogResult.OK)) return null;

			IOConnectionInfo iocResult = dlg.IOConnectionInfo;
			UIUtil.DestroyForm(dlg);
			return iocResult;
		}
Пример #26
0
        public static void Launch(Activity act, IOConnectionInfo ioc, AppTask appTask)
        {
            if (ioc.IsLocalFile())
            {
                Launch(act, ioc.Path, appTask);
                return;
            }

            Intent i = new Intent(act, typeof(PasswordActivity));

            PutIoConnectionToIntent(ioc, i);
            i.SetFlags(ActivityFlags.ForwardResult);

            appTask.ToIntent(i);

            act.StartActivity(i);
        }
Пример #27
0
 public bool RequiresCredentials(IOConnectionInfo ioc)
 {
     return((!ioc.IsLocalFile()) && (ioc.CredSaveMode != IOCredSaveMode.SaveCred));
 }
Пример #28
0
        public static bool AutoOpenEntry(Activity activity, AutoExecItem item, bool bManual,
                                         ActivityLaunchMode launchMode)
        {
            string           str;
            PwEntry          pe       = item.Entry;
            SprContext       ctxNoEsc = new SprContext(pe, item.Database, SprCompileFlags.All);
            IOConnectionInfo ioc;

            if (!TryGetDatabaseIoc(item, out ioc))
            {
                return(false);
            }

            var ob = GetBoolEx(pe, "SkipIfNotExists", ctxNoEsc);

            if (!ob.HasValue) // Backw. compat.
            {
                ob = GetBoolEx(pe, "Skip if not exists", ctxNoEsc);
            }
            if (ob.HasValue && ob.Value)
            {
                if (!CheckFileExsts(ioc))
                {
                    return(false);
                }
            }

            CompositeKey ck = new CompositeKey();

            if (GetString(pe, PwDefs.PasswordField, ctxNoEsc, false, out str))
            {
                ck.AddUserKey(new KcpPassword(str));
            }

            if (GetString(pe, PwDefs.UserNameField, ctxNoEsc, false, out str))
            {
                string           strAbs = str;
                IOConnectionInfo iocKey = IOConnectionInfo.FromPath(strAbs);
                if (iocKey.IsLocalFile() && !UrlUtil.IsAbsolutePath(strAbs))
                {
                    //local relative paths not supported on Android
                    return(false);
                }


                ob = GetBoolEx(pe, "SkipIfKeyFileNotExists", ctxNoEsc);
                if (ob.HasValue && ob.Value)
                {
                    IOConnectionInfo iocKeyAbs = IOConnectionInfo.FromPath(strAbs);
                    if (!CheckFileExsts(iocKeyAbs))
                    {
                        return(false);
                    }
                }

                try { ck.AddUserKey(new KcpKeyFile(strAbs)); }
                catch (InvalidOperationException)
                {
                    Toast.MakeText(Application.Context, Resource.String.error_adding_keyfile, ToastLength.Long).Show();
                    return(false);
                }
                catch (Exception) { throw; }
            }
            else // Try getting key file from attachments
            {
                ProtectedBinary pBin = pe.Binaries.Get("KeyFile.bin");
                if (pBin != null)
                {
                    ck.AddUserKey(new KcpKeyFile(IOConnectionInfo.FromPath(
                                                     StrUtil.DataToDataUri(pBin.ReadData(), null))));
                }
            }

            GetString(pe, "Focus", ctxNoEsc, true, out str);
            bool bRestoreFocus = str.Equals("Restore", StrUtil.CaseIgnoreCmp);

            PasswordActivity.Launch(activity, ioc, ck, launchMode, !
                                    bRestoreFocus);

            App.Kp2a.RegisterChildDatabase(ioc);

            return(true);
        }
Пример #29
0
        /// <summary>
        /// Rename/move a file. For local file system and WebDAV, the
        /// specified file is moved, i.e. the file destination can be
        /// in a different directory/path. In contrast, for FTP the
        /// file is renamed, i.e. its destination must be in the same
        /// directory/path.
        /// </summary>
        /// <param name="iocFrom">Source file path.</param>
        /// <param name="iocTo">Target file path.</param>
        public static void RenameFile(IOConnectionInfo iocFrom, IOConnectionInfo iocTo)
        {
            RaiseIOAccessPreEvent(iocFrom, iocTo, IOAccessType.Move);

            if(iocFrom.IsLocalFile()) { File.Move(iocFrom.Path, iocTo.Path); return; }

            #if (!KeePassLibSD && !KeePassRT)
            WebRequest req = CreateWebRequest(iocFrom);
            if(req != null)
            {
                if(req is HttpWebRequest)
                {
                    req.Method = "MOVE";
                    req.Headers.Set("Destination", iocTo.Path); // Full URL supported
                }
                else if(req is FtpWebRequest)
                {
                    req.Method = WebRequestMethods.Ftp.Rename;
                    string strTo = UrlUtil.GetFileName(iocTo.Path);

                    // We're affected by .NET bug 621450:
                    // https://connect.microsoft.com/VisualStudio/feedback/details/621450/problem-renaming-file-on-ftp-server-using-ftpwebrequest-in-net-framework-4-0-vs2010-only
                    // Prepending "./", "%2E/" or "Dummy/../" doesn't work.

                    ((FtpWebRequest)req).RenameTo = strTo;
                }
                else if(req is FileWebRequest)
                {
                    File.Move(UrlUtil.FileUrlToPath(iocFrom.Path),
                        UrlUtil.FileUrlToPath(iocTo.Path));
                    return;
                }
                else
                {
                    req.Method = WrmMoveFile;
                    req.Headers.Set(WrhMoveFileTo, iocTo.Path);
                }

                DisposeResponse(req.GetResponse(), true);
            }
            #endif

            // using(Stream sIn = IOConnection.OpenRead(iocFrom))
            // {
            //	using(Stream sOut = IOConnection.OpenWrite(iocTo))
            //	{
            //		MemUtil.CopyStream(sIn, sOut);
            //		sOut.Close();
            //	}
            //
            //	sIn.Close();
            // }
            // DeleteFile(iocFrom);
        }
Пример #30
0
        public void SetKeySource(IOConnectionInfo ioDatabase, string strKeySource,
                                 bool bIsKeyFile)
        {
            if (ioDatabase == null)
            {
                throw new ArgumentNullException("ioDatabase");
            }

            string strDb = ioDatabase.Path;

            if ((strDb.Length > 0) && ioDatabase.IsLocalFile() &&
                !UrlUtil.IsAbsolutePath(strDb))
            {
                strDb = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strDb);
            }

            string strKey = strKeySource;

            if (bIsKeyFile && !string.IsNullOrEmpty(strKey))
            {
                if (StrUtil.IsDataUri(strKey))
                {
                    strKey = null;                     // Don't remember data URIs
                }
                else if (!UrlUtil.IsAbsolutePath(strKey))
                {
                    strKey = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strKey);
                }
            }

            if (!m_bRememberKeySources)
            {
                strKey = null;
            }

            foreach (AceKeyAssoc kfp in m_vKeySources)
            {
                if (strDb.Equals(kfp.DatabasePath, StrUtil.CaseIgnoreCmp))
                {
                    if (string.IsNullOrEmpty(strKey))
                    {
                        m_vKeySources.Remove(kfp);
                    }
                    else
                    {
                        kfp.KeyFilePath = (bIsKeyFile ? strKey : string.Empty);
                        kfp.KeyProvider = (bIsKeyFile ? string.Empty : strKey);
                    }
                    return;
                }
            }

            if (string.IsNullOrEmpty(strKey))
            {
                return;
            }

            AceKeyAssoc kfpNew = new AceKeyAssoc();

            kfpNew.DatabasePath = strDb;
            if (bIsKeyFile)
            {
                kfpNew.KeyFilePath = strKey;
            }
            else
            {
                kfpNew.KeyProvider = strKey;
            }
            m_vKeySources.Add(kfpNew);
        }
Пример #31
0
		public static void DeleteFile(IOConnectionInfo ioc)
		{
			if(ioc.IsLocalFile()) { File.Delete(ioc.Path); return; }

#if !KeePassLibSD
			WebRequest req = CreateWebRequest(ioc);
			if(req != null)
			{
				if(req is HttpWebRequest) req.Method = "DELETE";
				else if(req is FtpWebRequest) req.Method = WebRequestMethods.Ftp.DeleteFile;
				else if(req is FileWebRequest)
				{
					File.Delete(UrlUtil.FileUrlToPath(ioc.Path));
					return;
				}
				else req.Method = WrmDeleteFile;

				req.GetResponse();
			}
#endif
		}
Пример #32
0
        public static Stream OpenRead(IOConnectionInfo ioc)
        {
            if(StrUtil.IsDataUri(ioc.Path))
            {
                byte[] pbData = StrUtil.DataUriToData(ioc.Path);
                if(pbData != null) return new MemoryStream(pbData, false);
            }

            if(ioc.IsLocalFile()) return OpenReadLocal(ioc);

            return CreateWebClient(ioc).OpenRead(new Uri(ioc.Path));
        }
Пример #33
0
        /// <summary>
        /// Rename/move a file. For local file system and WebDAV, the
        /// specified file is moved, i.e. the file destination can be
        /// in a different directory/path. In contrast, for FTP the
        /// file is renamed, i.e. its destination must be in the same
        /// directory/path.
        /// </summary>
        /// <param name="iocFrom">Source file path.</param>
        /// <param name="iocTo">Target file path.</param>
        public static void RenameFile(IOConnectionInfo iocFrom, IOConnectionInfo iocTo)
        {
            RaiseIOAccessPreEvent(iocFrom, iocTo, IOAccessType.Move);

            if(iocFrom.IsLocalFile()) { File.Move(iocFrom.Path, iocTo.Path); return; }

            #if (!KeePassLibSD && !KeePassRT)
            WebRequest req = CreateWebRequest(iocFrom);
            if(req != null)
            {
                if(req is HttpWebRequest)
                {
                    req.Method = "MOVE";
                    req.Headers.Set("Destination", iocTo.Path); // Full URL supported
                }
                else if(req is FtpWebRequest)
                {
                    req.Method = WebRequestMethods.Ftp.Rename;
                    ((FtpWebRequest)req).RenameTo = UrlUtil.GetFileName(iocTo.Path);
                }
                else if(req is FileWebRequest)
                {
                    File.Move(UrlUtil.FileUrlToPath(iocFrom.Path),
                        UrlUtil.FileUrlToPath(iocTo.Path));
                    return;
                }
                else
                {
                    req.Method = WrmMoveFile;
                    req.Headers.Set(WrhMoveFileTo, iocTo.Path);
                }

                DisposeResponse(req.GetResponse(), true);
            }
            #endif

            // using(Stream sIn = IOConnection.OpenRead(iocFrom))
            // {
            //	using(Stream sOut = IOConnection.OpenWrite(iocTo))
            //	{
            //		MemUtil.CopyStream(sIn, sOut);
            //		sOut.Close();
            //	}
            //
            //	sIn.Close();
            // }
            // DeleteFile(iocFrom);
        }
Пример #34
0
        public static Stream OpenWrite(IOConnectionInfo ioc)
        {
            if(ioc.IsLocalFile()) return OpenWriteLocal(ioc);

            return CreateWebClient(ioc).OpenWrite(new Uri(ioc.Path));
        }
Пример #35
0
        public static bool FileExists(IOConnectionInfo ioc, bool bThrowErrors)
        {
            if(ioc == null) { Debug.Assert(false); return false; }

            if(ioc.IsLocalFile()) return File.Exists(ioc.Path);

            try
            {
                Stream s = OpenRead(ioc);
                if(s == null) throw new FileNotFoundException();

                // For FTP clients we called RETR to get the file, but we never
                // followed-up and downloaded the file; close may produce a
                // 550 error -- that's okay
                try { s.Close(); }
                catch(Exception) { }
            }
            catch(Exception)
            {
                if(bThrowErrors) throw;
                return false;
            }

            return true;
        }
Пример #36
0
        private bool OnOpenButton(string filename, Dialog dialog)
        {
            IOConnectionInfo ioc = new IOConnectionInfo
            {
                Path = filename
            };

            // Make sure file name exists
            if (filename.Length == 0)
            {
                Toast.MakeText(_activity,
                               Resource.String.error_filename_required,
                               ToastLength.Long).Show();
                return(false);
            }


            int lastSlashPos = filename.LastIndexOf('/');
            int lastDotPos   = filename.LastIndexOf('.');

            if (lastSlashPos >= lastDotPos)             //no dot after last slash or == in case neither / nor .
            {
                ShowFilenameWarning(filename, () => { IocSelected(ioc); dialog.Dismiss(); }, () => { /* don't do anything, leave dialog open, let user try again*/ });
                //signal that the dialog should be kept open
                return(false);
            }

            IFileStorage fileStorage;

            try
            {
                fileStorage = App.Kp2a.GetFileStorage(ioc);
            }
            catch (NoFileStorageFoundException)
            {
                Toast.MakeText(_activity,
                               "Unexpected scheme in " + filename,
                               ToastLength.Long).Show();
                return(false);
            }

            if (_isForSave && ioc.IsLocalFile())
            {
                // Try to create the file
                File file = new File(filename);
                try
                {
                    File parent = file.ParentFile;

                    if (parent == null || (parent.Exists() && !parent.IsDirectory))
                    {
                        Toast.MakeText(_activity,
                                       Resource.String.error_invalid_path,
                                       ToastLength.Long).Show();
                        return(false);
                    }

                    if (!parent.Exists())
                    {
                        // Create parent dircetory
                        if (!parent.Mkdirs())
                        {
                            Toast.MakeText(_activity,
                                           Resource.String.error_could_not_create_parent,
                                           ToastLength.Long).Show();
                            return(false);
                        }
                    }
                    System.IO.File.Create(filename);
                }
                catch (IOException ex)
                {
                    Toast.MakeText(
                        _activity,
                        _activity.GetText(Resource.String.error_file_not_create) + " "
                        + ex.LocalizedMessage,
                        ToastLength.Long).Show();
                    return(false);
                }
            }
            if (fileStorage.RequiresCredentials(ioc))
            {
                Util.QueryCredentials(ioc, IocSelected, _activity);
            }
            else
            {
                IocSelected(ioc);
            }

            return(true);
        }
Пример #37
0
        public static void DeleteFile(IOConnectionInfo ioc)
        {
            RaiseIOAccessPreEvent(ioc, IOAccessType.Delete);

            //in case a user entered a directory instead of a filename, make sure we're never
            //deleting their whole WebDAV/FTP content
            if (ioc.Path.EndsWith("/"))
                throw new IOException("Delete file does not expect directory URIs.");

            if(ioc.IsLocalFile()) { File.Delete(ioc.Path); return; }

            #if (!KeePassLibSD && !KeePassRT)
            RepeatWithDigestOnFail(ioc, (WebRequest req) => {
                if(req != null)
                {
                    if(req is HttpWebRequest) req.Method = "DELETE";
                    else if(req is FtpWebRequest) req.Method = WebRequestMethods.Ftp.DeleteFile;
                    else if(req is FileWebRequest)
                    {
                        File.Delete(UrlUtil.FileUrlToPath(ioc.Path));
                        return;
                    }
                    else req.Method = WrmDeleteFile;

                    DisposeResponse(req.GetResponse(), true);
                }
            });
            #endif
        }
Пример #38
0
		public static bool FileExists(IOConnectionInfo ioc)
		{
			if(ioc.IsLocalFile()) return File.Exists(ioc.Path);

			try
			{
				Stream s = OpenRead(ioc);
				s.Close();
			}
			catch(Exception) { return false; }

			return true;
		}
Пример #39
0
        public static Stream OpenWrite(IOConnectionInfo ioc)
        {
            if(ioc == null) { Debug.Assert(false); return null; }

            RaiseIOAccessPreEvent(ioc, IOAccessType.Write);

            if(ioc.IsLocalFile()) return OpenWriteLocal(ioc);

            Uri uri = new Uri(ioc.Path);
            Stream s;

            // Mono does not set HttpWebRequest.Method to POST for writes,
            // so one needs to set the method to PUT explicitly
            if(NativeLib.IsUnix() && (uri.Scheme.Equals(Uri.UriSchemeHttp,
                StrUtil.CaseIgnoreCmp) || uri.Scheme.Equals(Uri.UriSchemeHttps,
                StrUtil.CaseIgnoreCmp)))
                s = CreateWebClient(ioc).OpenWrite(uri, WebRequestMethods.Http.Put);
            else s = CreateWebClient(ioc).OpenWrite(uri);

            return IocStream.WrapIfRequired(s);
        }
Пример #40
0
        private bool OnCreateButton(string filename, Dialog dialog)
        {
            // Make sure file name exists
            if (filename.Length == 0)
            {
                Toast.MakeText(this,
                                Resource.String.error_filename_required,
                                ToastLength.Long).Show();
                return false;
            }

            IOConnectionInfo ioc = new IOConnectionInfo { Path = filename };
            IFileStorage fileStorage;
            try
            {
                fileStorage = App.Kp2a.GetFileStorage(ioc);
            }
            catch (NoFileStorageFoundException)
            {
                Toast.MakeText(this,
                                "Unexpected scheme in "+filename,
                                ToastLength.Long).Show();
                return false;
            }

            if (ioc.IsLocalFile())
            {
                // Try to create the file
                File file = new File(filename);
                try
                {
                    File parent = file.ParentFile;

                    if (parent == null || (parent.Exists() && !parent.IsDirectory))
                    {
                        Toast.MakeText(this,
                                        Resource.String.error_invalid_path,
                                        ToastLength.Long).Show();
                        return false;
                    }

                    if (!parent.Exists())
                    {
                        // Create parent dircetory
                        if (!parent.Mkdirs())
                        {
                            Toast.MakeText(this,
                                            Resource.String.error_could_not_create_parent,
                                            ToastLength.Long).Show();
                            return false;

                        }
                    }
                    System.IO.File.Create(filename);

                }
                catch (IOException ex)
                {
                    Toast.MakeText(
                        this,
                        GetText(Resource.String.error_file_not_create) + " "
                        + ex.LocalizedMessage,
                        ToastLength.Long).Show();
                    return false;
                }

            }
            if (fileStorage.RequiresCredentials(ioc))
            {
                Util.QueryCredentials(ioc, AfterQueryCredentials, this);
            }
            else
            {
                _ioc = ioc;
                UpdateIocView();
            }

            return true;
        }
Пример #41
0
        public bool IsReadOnly(IOConnectionInfo ioc)
        {
            if (ioc.IsLocalFile())
            {
                if (IsLocalFileFlaggedReadOnly(ioc))
                    return true;
                if (IsReadOnlyBecauseKitkatRestrictions(ioc))
                    return true;

                return false;
            }
            //for remote files assume they can be written: (think positive! :-) )
            return false;
        }
Пример #42
0
		public static Stream OpenWrite(IOConnectionInfo ioc)
		{
			if(ioc == null) { Debug.Assert(false); return null; }

			if(ioc.IsLocalFile()) return OpenWriteLocal(ioc);

			return CreateWebClient(ioc).OpenWrite(new Uri(ioc.Path));
		}
Пример #43
0
 public string GetCurrentFileVersionFast(IOConnectionInfo ioc)
 {
     if (ioc.IsLocalFile())
     {
         return File.GetLastWriteTimeUtc(ioc.Path).ToString(CultureInfo.InvariantCulture);
     }
     else
     {
         return DateTime.MinValue.ToString(CultureInfo.InvariantCulture);
     }
 }
Пример #44
0
        public void SetKeySource(IOConnectionInfo ioDatabase, string strKeySource,
            bool bIsKeyFile)
        {
            if(ioDatabase == null) throw new ArgumentNullException("ioDatabase");

            string strDb = ioDatabase.Path;
            if((strDb.Length > 0) && ioDatabase.IsLocalFile() &&
                !UrlUtil.IsAbsolutePath(strDb))
                strDb = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strDb);

            string strKey = strKeySource;
            if(bIsKeyFile && !string.IsNullOrEmpty(strKey))
            {
                if(StrUtil.IsDataUri(strKey))
                    strKey = null; // Don't remember data URIs
                else if(!UrlUtil.IsAbsolutePath(strKey))
                    strKey = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strKey);
            }

            if(!m_bRememberKeySources) strKey = null;

            foreach(AceKeyAssoc kfp in m_vKeySources)
            {
                if(strDb.Equals(kfp.DatabasePath, StrUtil.CaseIgnoreCmp))
                {
                    if(string.IsNullOrEmpty(strKey)) m_vKeySources.Remove(kfp);
                    else
                    {
                        kfp.KeyFilePath = (bIsKeyFile ? strKey : string.Empty);
                        kfp.KeyProvider = (bIsKeyFile ? string.Empty : strKey);
                    }
                    return;
                }
            }

            if(string.IsNullOrEmpty(strKey)) return;

            AceKeyAssoc kfpNew = new AceKeyAssoc();
            kfpNew.DatabasePath = strDb;
            if(bIsKeyFile) kfpNew.KeyFilePath = strKey;
            else kfpNew.KeyProvider = strKey;
            m_vKeySources.Add(kfpNew);
        }
Пример #45
0
        public string GetKeySource(IOConnectionInfo ioDatabase, bool bGetKeyFile)
        {
            if(ioDatabase == null) throw new ArgumentNullException("ioDatabase");

            string strDb = ioDatabase.Path;
            if((strDb.Length > 0) && ioDatabase.IsLocalFile() &&
                !UrlUtil.IsAbsolutePath(strDb))
                strDb = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strDb);

            foreach(AceKeyAssoc kfp in m_vKeySources)
            {
                if(strDb.Equals(kfp.DatabasePath, StrUtil.CaseIgnoreCmp))
                    return (bGetKeyFile ? kfp.KeyFilePath : kfp.KeyProvider);
            }

            return null;
        }
Пример #46
0
 public bool RequiresCredentials(IOConnectionInfo ioc)
 {
     return (!ioc.IsLocalFile()) && (ioc.CredSaveMode != IOCredSaveMode.SaveCred);
 }
Пример #47
0
		private static void ChangePathRelAbs(IOConnectionInfo ioc, bool bMakeAbsolute)
		{
			if(ioc == null) { Debug.Assert(false); return; }

			if(ioc.IsLocalFile() == false) return;

			string strBase = WinUtil.GetExecutable();
			bool bIsAbs = UrlUtil.IsAbsolutePath(ioc.Path);

			if(bMakeAbsolute && !bIsAbs)
				ioc.Path = UrlUtil.MakeAbsolutePath(strBase, ioc.Path);
			else if(!bMakeAbsolute && bIsAbs)
				ioc.Path = UrlUtil.MakeRelativePath(strBase, ioc.Path);
		}
Пример #48
0
        public static Stream OpenRead(IOConnectionInfo ioc)
        {
            RaiseIOAccessPreEvent(ioc, IOAccessType.Read);

            if(StrUtil.IsDataUri(ioc.Path))
            {
                byte[] pbData = StrUtil.DataUriToData(ioc.Path);
                if(pbData != null) return new MemoryStream(pbData, false);
            }

            if(ioc.IsLocalFile()) return OpenReadLocal(ioc);

            return IocStream.WrapIfRequired(CreateWebClient(ioc).OpenRead(
                new Uri(ioc.Path)));
        }
Пример #49
0
		private PwDatabase OpenDatabaseInternal(IOConnectionInfo ioc,
			CompositeKey cmpKey, out bool bAbort)
		{
			bAbort = false;

			PerformSelfTest();

			ShowWarningsLogger swLogger = CreateShowWarningsLogger();
			swLogger.StartLogging(KPRes.OpeningDatabase, true);

			PwDocument ds = null;
			string strPathNrm = ioc.Path.Trim().ToLower();
			for(int iScan = 0; iScan < m_docMgr.Documents.Count; ++iScan)
			{
				if(m_docMgr.Documents[iScan].LockedIoc.Path.Trim().ToLower() == strPathNrm)
					ds = m_docMgr.Documents[iScan];
				else if(m_docMgr.Documents[iScan].Database.IOConnectionInfo.Path == strPathNrm)
					ds = m_docMgr.Documents[iScan];
			}

			PwDatabase pwDb;
			if(ds == null) pwDb = m_docMgr.CreateNewDocument(true).Database;
			else pwDb = ds.Database;

			Exception ex = null;
			try
			{
				pwDb.Open(ioc, cmpKey, swLogger);

#if DEBUG
				byte[] pbDiskDirect = WinUtil.HashFile(ioc);
				Debug.Assert(MemUtil.ArraysEqual(pbDiskDirect, pwDb.HashOfFileOnDisk));
#endif
			}
			catch(Exception exLoad)
			{
				ex = exLoad;
				pwDb = null;
			}

			swLogger.EndLogging();

			if(pwDb == null)
			{
				if(ds == null) m_docMgr.CloseDatabase(m_docMgr.ActiveDatabase);
			}

			if(ex != null)
			{
				string strMsg = MessageService.GetLoadWarningMessage(
					ioc.GetDisplayName(), ex,
					(Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null));

				bool bShowStd = true;
				if(!ioc.IsLocalFile())
				{
					VistaTaskDialog vtd = new VistaTaskDialog();
					vtd.CommandLinks = false;
					vtd.Content = strMsg;
					vtd.DefaultButtonID = (int)DialogResult.Cancel;
					// vtd.VerificationText = KPRes.CredSpecifyDifferent;
					vtd.WindowTitle = PwDefs.ShortProductName;

					vtd.SetIcon(VtdIcon.Warning);
					vtd.AddButton((int)DialogResult.Cancel, KPRes.Ok, null);
					vtd.AddButton((int)DialogResult.Retry,
						KPRes.CredSpecifyDifferent, null);

					if(vtd.ShowDialog(this))
					{
						bShowStd = false;

						// if(vtd.ResultVerificationChecked)
						if(vtd.Result == (int)DialogResult.Retry)
						{
							IOConnectionInfo iocNew = ioc.CloneDeep();
							// iocNew.ClearCredentials(false);
							iocNew.CredSaveMode = IOCredSaveMode.NoSave;
							iocNew.IsComplete = false;
							// iocNew.Password = string.Empty;

							OpenDatabase(iocNew, null, false);

							bAbort = true;
						}
					}
				}

				if(bShowStd) MessageService.ShowWarning(strMsg);
				// MessageService.ShowLoadWarning(ioc.GetDisplayName(), ex,
				//	(Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null));
			}

			return pwDb;
		}
Пример #50
0
        public static void DeleteFile(IOConnectionInfo ioc)
        {
            RaiseIOAccessPreEvent(ioc, IOAccessType.Delete);

            if(ioc.IsLocalFile()) { File.Delete(ioc.Path); return; }

            #if (!KeePassLibSD && !KeePassRT)
            WebRequest req = CreateWebRequest(ioc);
            if(req != null)
            {
                if(req is HttpWebRequest) req.Method = "DELETE";
                else if(req is FtpWebRequest)
                    req.Method = WebRequestMethods.Ftp.DeleteFile;
                else if(req is FileWebRequest)
                {
                    File.Delete(UrlUtil.FileUrlToPath(ioc.Path));
                    return;
                }
                else req.Method = WrmDeleteFile;

                DisposeResponse(req.GetResponse(), true);
            }
            #endif
        }
Пример #51
0
        private static string GetKeyAssocID(IOConnectionInfo iocDb)
        {
            if(iocDb == null) throw new ArgumentNullException("iocDb");

            string strDb = iocDb.Path;
            if((strDb.Length > 0) && iocDb.IsLocalFile() &&
                !UrlUtil.IsAbsolutePath(strDb))
                strDb = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strDb);

            return strDb;
        }
Пример #52
0
        public static bool FileExists(IOConnectionInfo ioc, bool bThrowErrors)
        {
            if(ioc == null) { Debug.Assert(false); return false; }

            RaiseIOAccessPreEvent(ioc, IOAccessType.Exists);

            if(ioc.IsLocalFile()) return File.Exists(ioc.Path);

            #if (!KeePassLibSD && !KeePassRT)
            if(ioc.Path.StartsWith("ftp://", StrUtil.CaseIgnoreCmp))
            {
                bool b = SendCommand(ioc, WebRequestMethods.Ftp.GetDateTimestamp);
                if(!b && bThrowErrors) throw new InvalidOperationException();
                return b;
            }
            #endif

            try
            {
                Stream s = OpenRead(ioc);
                if(s == null) throw new FileNotFoundException();

                try { s.ReadByte(); }
                catch(Exception) { }

                // We didn't download the file completely; close may throw
                // an exception -- that's okay
                try { s.Close(); }
                catch(Exception) { }
            }
            catch(Exception)
            {
                if(bThrowErrors) throw;
                return false;
            }

            return true;
        }
Пример #53
0
        private static void ChangePathRelAbs(IOConnectionInfo ioc, bool bMakeAbsolute)
        {
            if(ioc == null) { Debug.Assert(false); return; }

            if(!ioc.IsLocalFile()) return;

            // Update path separators for current system
            if(!UrlUtil.IsUncPath(ioc.Path))
                ioc.Path = UrlUtil.ConvertSeparators(ioc.Path);

            string strBase = WinUtil.GetExecutable();
            bool bIsAbs = UrlUtil.IsAbsolutePath(ioc.Path);

            if(bMakeAbsolute && !bIsAbs)
                ioc.Path = UrlUtil.MakeAbsolutePath(strBase, ioc.Path);
            else if(!bMakeAbsolute && bIsAbs)
                ioc.Path = UrlUtil.MakeRelativePath(strBase, ioc.Path);
        }
Пример #54
0
        public static Stream OpenRead(IOConnectionInfo ioc)
        {
            RaiseIOAccessPreEvent(ioc, IOAccessType.Read);

            if(StrUtil.IsDataUri(ioc.Path))
            {
                byte[] pbData = StrUtil.DataUriToData(ioc.Path);
                if (pbData != null)
                    return new MemoryStream(pbData, false);
            }

            if (ioc.IsLocalFile())
                return OpenReadLocal(ioc);

            try
            {
                return CreateWebClient(ioc, false).OpenRead(new Uri(ioc.Path));
            } catch (WebException ex)
            {
                if ((ex.Response is HttpWebResponse) && (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.Unauthorized))
                    return CreateWebClient(ioc, true).OpenRead(new Uri(ioc.Path));
                else
                    throw;
            }
        }