public void SetEntry(PwEntry e)
                {
                    KpDatabase = new PwDatabase();
                    KpDatabase.New(new IOConnectionInfo(), new CompositeKey());

                    KpDatabase.RootGroup.AddEntry(e, true);
                }
Exemple #2
0
        private static PwDatabase CreateTargetDatabase(PwDatabase sourceDb, Settings settings, CompositeKey key)
        {
            // Default to same folder as sourceDb for target if no directory is specified
            if (!Path.IsPathRooted(settings.TargetFilePath))
            {
                string sourceDbPath = Path.GetDirectoryName(sourceDb.IOConnectionInfo.Path);
                if (sourceDbPath != null)
                {
                    settings.TargetFilePath = Path.Combine(sourceDbPath, settings.TargetFilePath);
                }
            }

            // Create a new database
            PwDatabase targetDatabase = new PwDatabase();

            if (!settings.OverrideTargetDatabase && File.Exists(settings.TargetFilePath))
            {
                // Connect the database object to the existing database
                targetDatabase.Open(new IOConnectionInfo()
                {
                    Path = settings.TargetFilePath
                }, key, new NullStatusLogger());
            }
            else
            {
                // Apply the created key to the new database
                targetDatabase.New(new IOConnectionInfo(), key);
            }

            return(targetDatabase);
        }
Exemple #3
0
        internal static void WriteGroup(Stream msOutput, PwDatabase pdContext,
                                        PwGroup pg)
        {
            if (msOutput == null)
            {
                throw new ArgumentNullException("msOutput");
            }
            // pdContext may be null
            if (pg == null)
            {
                throw new ArgumentNullException("pg");
            }

            PwDatabase pd = new PwDatabase();

            pd.New(new IOConnectionInfo(), new CompositeKey());

            pd.RootGroup             = pg.CloneDeep();
            pd.RootGroup.ParentGroup = null;

            PwDatabase.CopyCustomIcons(pdContext, pd, pd.RootGroup, true);

            KdbxFile f = new KdbxFile(pd);

            f.Save(msOutput, null, KdbxFormat.PlainXml, null);
        }
        public async Task Create(Credentials credentials, string name, DatabaseVersion version = DatabaseVersion.V4)
        {
            try
            {
                await Task.Run(() =>
                {
                    var compositeKey = CreateCompositeKey(credentials);
                    var ioConnection = IOConnectionInfo.FromByteArray(new byte[] {});

                    _pwDatabase.New(ioConnection, compositeKey);
                    _pwDatabase.Name           = name;
                    _pwDatabase.RootGroup.Name = name;

                    _credentials = credentials;

                    switch (version)
                    {
                    case DatabaseVersion.V4:
                        _pwDatabase.KdfParameters  = KdfPool.Get("Argon2").GetDefaultParameters();
                        _pwDatabase.DataCipherUuid = CipherPool.GlobalPool[1].CipherUuid;
                        break;
                    }
                });
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message, ex);
            }
        }
Exemple #5
0
        public void New_Test()
        {
            IFolder folder   = SpecialFolder.Current.Local;
            IFolder testData = folder.CreateFolderAsync("TestData",
                                                        CreationCollisionOption.OpenIfExists).Result;
            IFile file = testData.CreateFileAsync("1.kdbx",
                                                  CreationCollisionOption.ReplaceExisting).Result;

            var ci = new IOConnectionInfo();

            ci.Path = file.Path;
            var key = new CompositeKey();

            key.AddUserKey(new KcpPassword("0"));
            var db = new PwDatabase();

            db.New(ci, key);
            var initialEnitiesCount = db.RootGroup.GetEntriesCount(true);

            Assert.AreNotEqual(0, initialEnitiesCount);
            db.Save(null);
            db.Close();
            Assert.IsNull(db.RootGroup);
            db = new PwDatabase();
            db.Open(ci, key, null);
            Assert.AreEqual(initialEnitiesCount,
                            db.RootGroup.GetEntriesCount(true));
        }
Exemple #6
0
        public void TestCreateSaveAndLoad_TestIdenticalFiles_kdb()
        {
            string   filename = DefaultDirectory + "createsaveandload.kdb";
            IKp2aApp app      = SetupAppWithDatabase(filename);
            string   kdbxXml  = DatabaseToXml(app);

            //save it and reload it
            Android.Util.Log.Debug("KP2A", "-- Save DB -- ");
            SaveDatabase(app);
            Android.Util.Log.Debug("KP2A", "-- Load DB -- ");


            PwDatabase pwImp      = new PwDatabase();
            PwDatabase pwDatabase = app.GetDb().KpDatabase;

            pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
            pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
            pwImp.MasterKey        = pwDatabase.MasterKey;

            IOConnectionInfo ioc = new IOConnectionInfo()
            {
                Path = filename
            };

            using (Stream s = app.GetFileStorage(ioc).OpenFileForRead(ioc))
            {
                app.GetDb().DatabaseFormat.PopulateDatabaseFromStream(pwImp, s, null);
            }
            string kdbxReloadedXml = DatabaseToXml(app);

            RemoveKdbLines(ref kdbxReloadedXml);
            RemoveKdbLines(ref kdbxXml);

            Assert.AreEqual(kdbxXml, kdbxReloadedXml);
        }
Exemple #7
0
        private PwDatabase MergeDatabases()
        {
            PwDatabase dbAll = new PwDatabase();

            dbAll.New(new KeePassLib.Serialization.IOConnectionInfo(), new KeePassLib.Keys.CompositeKey());
            foreach (PwDatabase db in m_host.MainWindow.DocumentManager.GetOpenDatabases())
            {
                dbAll.RootGroup.AddGroup(db.RootGroup, false, false);
            }
            return(dbAll);
        }
Exemple #8
0
        public void TestSave()
        {
            var buffer = new byte[4096];

            using (var ms = new MemoryStream(buffer))
            {
                var database = new PwDatabase();
                database.New(new IOConnectionInfo(), new CompositeKey());
                var date = DateTime.Parse(testDate).ToUniversalTime();
                PwDatabase.LocalizedAppName = testLocalizedAppName;
                database.Name                              = testDatabaseName;
                database.NameChanged                       = date;
                database.Description                       = testDatabaseDescription;
                database.DescriptionChanged                = date;
                database.DefaultUserName                   = testDefaultUserName;
                database.DefaultUserNameChanged            = date;
                database.Color                             = Color.Red;
                database.MasterKeyChanged                  = date;
                database.RecycleBinChanged                 = date;
                database.EntryTemplatesGroupChanged        = date;
                database.RootGroup.Uuid                    = PwUuid.Zero;
                database.RootGroup.Name                    = testRootGroupName;
                database.RootGroup.Notes                   = testRootGroupNotes;
                database.RootGroup.DefaultAutoTypeSequence = testRootGroupDefaultAutoTypeSequence;
                database.RootGroup.CreationTime            = date;
                database.RootGroup.LastModificationTime    = date;
                database.RootGroup.LastAccessTime          = date;
                database.RootGroup.ExpiryTime              = date;
                database.RootGroup.LocationChanged         = date;
                var file = new KdbxFile(database);
                file.Save(ms, null, KdbxFormat.PlainXml, null);
            }

            var fileContents = Encoding.UTF8.GetString(buffer).Replace("\0", "");

            if (typeof(KdbxFile).Namespace.StartsWith("KeePassLib.") &&
                Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                // Upstream KeePassLib does not specify line endings for XmlTextWriter,
                // so it uses native line endings.
                fileContents = fileContents.Replace("\n", "\r\n");
            }

            Assert.That(fileContents, Is.EqualTo(testDatabase));
        }
Exemple #9
0
 private void OTPDB_Init(bool bCreateOpened)
 {
     OTPDB           = new PwDatabase();
     OTPDB.RootGroup = new PwGroup();
     FlagChanged(true);
     if (bCreateOpened)
     {
         OTPDB.New(new IOConnectionInfo(), new CompositeKey());
     }
     OTPDB.MasterKeyChangeRec       = -1;
     OTPDB.MasterKeyChangeForce     = -1;
     OTPDB.MasterKeyChangeForceOnce = false;
     OTPDB.RootGroup.Name           = DBNAME;
     OTPDB.RecycleBinEnabled        = false;
     OTPDB.SettingsChanged          = INITTIME;
     OTPDB_Exists = true;
     OTPDB_Opened = OTPDB.IsOpen;
 }
Exemple #10
0
        /// <summary>
        /// Write entries to a stream.
        /// </summary>
        /// <param name="msOutput">Output stream to which the entries will be written.</param>
        /// <param name="vEntries">Entries to serialize.</param>
        /// <returns>Returns <c>true</c>, if the entries were written successfully
        /// to the stream.</returns>
        public static bool WriteEntries(Stream msOutput, PwEntry[] vEntries)
        {
            /* KdbxFile f = new KdbxFile(pwDatabase);
             * f.m_format = KdbxFormat.PlainXml;
             *
             * XmlTextWriter xtw = null;
             * try { xtw = new XmlTextWriter(msOutput, StrUtil.Utf8); }
             * catch(Exception) { Debug.Assert(false); return false; }
             * if(xtw == null) { Debug.Assert(false); return false; }
             *
             * f.m_xmlWriter = xtw;
             *
             * xtw.Formatting = Formatting.Indented;
             * xtw.IndentChar = '\t';
             * xtw.Indentation = 1;
             *
             * xtw.WriteStartDocument(true);
             * xtw.WriteStartElement(ElemRoot);
             *
             * foreach(PwEntry pe in vEntries)
             *      f.WriteEntry(pe, false);
             *
             * xtw.WriteEndElement();
             * xtw.WriteEndDocument();
             *
             * xtw.Flush();
             * xtw.Close();
             * return true; */

            PwDatabase pd = new PwDatabase();

            pd.New(new IOConnectionInfo(), new CompositeKey());

            foreach (PwEntry peCopy in vEntries)
            {
                pd.RootGroup.AddEntry(peCopy.CloneDeep(), true);
            }

            KdbxFile f = new KdbxFile(pd);

            f.Save(msOutput, null, KdbxFormat.PlainXml, null);
            return(true);
        }
Exemple #11
0
        private PwDatabase CreateTestDatabase(
            out IOConnectionInfo ci,
            out CompositeKey key,
            out IFile file)
        {
            IFolder folder   = SpecialFolder.Current.Local;
            IFolder testData = folder.CreateFolderAsync("TestData",
                                                        CreationCollisionOption.OpenIfExists).Result;

            file = testData.CreateFileAsync("1.kdbx",
                                            CreationCollisionOption.ReplaceExisting).Result;

            ci      = new IOConnectionInfo();
            ci.Path = file.Path;
            key     = new CompositeKey();
            key.AddUserKey(new KcpPassword("0"));
            var db = new PwDatabase();

            db.New(ci, key);
            return(db);
        }
Exemple #12
0
        public KeePassApi(IConfiguration config)
        {
            var dbpath   = config.GetValue <string>("KeePassFile");
            var masterpw = config.GetValue <string>("KeePassword");

            var ioConnInfo = new IOConnectionInfo {
                Path = dbpath
            };
            var compKey = new CompositeKey();

            compKey.AddUserKey(new KcpPassword(masterpw));

            if (!File.Exists(dbpath))
            {
                var newDb = new PwDatabase();
                newDb.New(ioConnInfo, compKey);
                newDb.Save(null);
                newDb.Close();
            }

            _db = new PwDatabase();
            _db.Open(ioConnInfo, compKey, null);
        }
Exemple #13
0
        /// <summary>
        /// Exports all entries with the given tag to a new database at the given path.
        /// </summary>
        /// <param name="sourceDb">The source database.</param>
        /// <param name="settings">The settings for this job.</param>
        private static void CopyToNewDb(PwDatabase sourceDb, Settings settings)
        {
            // Create a key for the target database
            CompositeKey key = new CompositeKey();

            bool hasPassword = false;
            bool hasKeyFile  = false;

            if (!settings.Password.IsEmpty)
            {
                byte[] passwordByteArray = settings.Password.ReadUtf8();
                key.AddUserKey(new KcpPassword(passwordByteArray));
                MemUtil.ZeroByteArray(passwordByteArray);
                hasPassword = true;
            }

            // Load a keyfile for the target database if requested (and add it to the key)
            if (!string.IsNullOrEmpty(settings.KeyFilePath))
            {
                bool bIsKeyProv = Program.KeyProviderPool.IsKeyProvider(settings.KeyFilePath);

                if (!bIsKeyProv)
                {
                    try
                    {
                        key.AddUserKey(new KcpKeyFile(settings.KeyFilePath, true));
                        hasKeyFile = true;
                    }
                    catch (InvalidDataException exId)
                    {
                        MessageService.ShowWarning(settings.KeyFilePath, exId);
                    }
                    catch (Exception exKf)
                    {
                        MessageService.ShowWarning(settings.KeyFilePath, KPRes.KeyFileError, exKf);
                    }
                }
                else
                {
                    KeyProviderQueryContext ctxKp = new KeyProviderQueryContext(
                        ConnectionInfo, true, false);

                    KeyProvider prov         = Program.KeyProviderPool.Get(settings.KeyFilePath);
                    bool        bPerformHash = !prov.DirectKey;
                    byte[]      pbCustomKey  = prov.GetKey(ctxKp);

                    if ((pbCustomKey != null) && (pbCustomKey.Length > 0))
                    {
                        try
                        {
                            key.AddUserKey(new KcpCustomKey(settings.KeyFilePath, pbCustomKey, bPerformHash));
                            hasKeyFile = true;
                        }
                        catch (Exception exCkp)
                        {
                            MessageService.ShowWarning(exCkp);
                        }

                        MemUtil.ZeroByteArray(pbCustomKey);
                    }
                }
            }

            // Check if at least a password or a keyfile have been added to the key object
            if (!hasPassword && !hasKeyFile)
            {
                // Fail if not
                throw new InvalidOperationException("For the target database at least a password or a keyfile is required.");
            }

            // Create a new database
            PwDatabase targetDatabase = new PwDatabase();

            // Apply the created key to the new database
            targetDatabase.New(new IOConnectionInfo(), key);

            // Copy database settings
            targetDatabase.Color                  = sourceDb.Color;
            targetDatabase.Compression            = sourceDb.Compression;
            targetDatabase.DataCipherUuid         = sourceDb.DataCipherUuid;
            targetDatabase.DefaultUserName        = sourceDb.DefaultUserName;
            targetDatabase.Description            = sourceDb.Description;
            targetDatabase.HistoryMaxItems        = sourceDb.HistoryMaxItems;
            targetDatabase.HistoryMaxSize         = sourceDb.HistoryMaxSize;
            targetDatabase.MaintenanceHistoryDays = sourceDb.MaintenanceHistoryDays;
            targetDatabase.MasterKeyChangeForce   = sourceDb.MasterKeyChangeForce;
            targetDatabase.MasterKeyChangeRec     = sourceDb.MasterKeyChangeRec;
            targetDatabase.Name = sourceDb.Name;
            targetDatabase.RecycleBinEnabled = sourceDb.RecycleBinEnabled;

            if (settings.KeyTransformationRounds == 0)
            {
                // keyTransformationRounds was not set -> use the one from the source database
                settings.KeyTransformationRounds = sourceDb.KdfParameters.GetUInt64(AesKdf.ParamRounds, 0);
            }

            // Set keyTransformationRounds (min PwDefs.DefaultKeyEncryptionRounds)
            targetDatabase.KdfParameters.SetUInt64(AesKdf.ParamRounds, Math.Max(PwDefs.DefaultKeyEncryptionRounds, settings.KeyTransformationRounds));

            // Assign the properties of the source root group to the target root group
            targetDatabase.RootGroup.AssignProperties(sourceDb.RootGroup, false, true);
            HandleCustomIcon(targetDatabase, sourceDb, sourceDb.RootGroup);

            // Overwrite the root group name if requested
            if (!string.IsNullOrEmpty(settings.RootGroupName))
            {
                targetDatabase.RootGroup.Name = settings.RootGroupName;
            }

            // Find all entries matching the tag
            PwObjectList <PwEntry> entries = new PwObjectList <PwEntry>();

            if (!string.IsNullOrEmpty(settings.Tag) && string.IsNullOrEmpty(settings.Group))
            {
                // Tag only export
                sourceDb.RootGroup.FindEntriesByTag(settings.Tag, entries, true);
            }
            else if (string.IsNullOrEmpty(settings.Tag) && !string.IsNullOrEmpty(settings.Group))
            {
                // Tag and group export
                PwGroup groupToExport = sourceDb.RootGroup.GetFlatGroupList().FirstOrDefault(g => g.Name == settings.Group);

                if (groupToExport == null)
                {
                    throw new ArgumentException("No group with the name of the Group-Setting found.");
                }

                entries = groupToExport.GetEntries(true);
            }
            else if (!string.IsNullOrEmpty(settings.Tag) && !string.IsNullOrEmpty(settings.Group))
            {
                // Tag and group export
                PwGroup groupToExport = sourceDb.RootGroup.GetFlatGroupList().FirstOrDefault(g => g.Name == settings.Group);

                if (groupToExport == null)
                {
                    throw new ArgumentException("No group with the name of the Group-Setting found.");
                }

                groupToExport.FindEntriesByTag(settings.Tag, entries, true);
            }
            else
            {
                throw new ArgumentException("At least one of Tag or ExportFolderName must be set.");
            }


            // Copy all entries to the new database
            foreach (PwEntry entry in entries)
            {
                // Get or create the target group in the target database (including hierarchy)
                PwGroup targetGroup = CreateTargetGroupInDatebase(entry, targetDatabase, sourceDb);

                // Clone entry
                PwEntry peNew = new PwEntry(false, false);
                peNew.Uuid = entry.Uuid;
                peNew.AssignProperties(entry, false, true, true);

                // Handle custom icon
                HandleCustomIcon(targetDatabase, sourceDb, entry);

                // Add entry to the target group in the new database
                targetGroup.AddEntry(peNew, true);
            }

            // Create target folder (if not exist)
            string targetFolder = Path.GetDirectoryName(settings.TargetFilePath);

            if (targetFolder == null)
            {
                throw new ArgumentException("Can't get target folder.");
            }
            Directory.CreateDirectory(targetFolder);

            // Save the new database under the target path
            KdbxFile kdbx = new KdbxFile(targetDatabase);

            using (FileStream outputStream = new FileStream(settings.TargetFilePath, FileMode.Create))
            {
                kdbx.Save(outputStream, null, KdbxFormat.Default, new NullStatusLogger());
            }
        }
Exemple #14
0
        /// <summary>
        /// Called when [file new].
        /// </summary>
        /// <remarks>Review whenever private KeePass.MainForm.OnFileNew method changes. Last reviewed 20180416</remarks>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        internal void CreateNewDatabase()
        {
            if (!AppPolicy.Try(AppPolicyId.SaveFile))
            {
                return;
            }

            DialogResult dr;
            string       strPath;

            using (SaveFileDialog sfd = UIUtil.CreateSaveFileDialog(KPRes.CreateNewDatabase,
                                                                    KPRes.NewDatabaseFileName, UIUtil.CreateFileTypeFilter(
                                                                        AppDefs.FileExtension.FileExt, KPRes.KdbxFiles, true), 1,
                                                                    AppDefs.FileExtension.FileExt, false))
            {
                GlobalWindowManager.AddDialog(sfd);
                dr = sfd.ShowDialog(_host.MainWindow);
                GlobalWindowManager.RemoveDialog(sfd);
                strPath = sfd.FileName;
            }

            if (dr != DialogResult.OK)
            {
                return;
            }

            KeePassLib.Keys.CompositeKey key       = null;
            bool showUsualKeePassKeyCreationDialog = false;

            using (KeyCreationSimpleForm kcsf = new KeyCreationSimpleForm())
            {
                // Don't show the simple key creation form if the user has set
                // security policies that restrict the allowable composite key sources
                if (KeePass.Program.Config.UI.KeyCreationFlags == 0)
                {
                    kcsf.InitEx(KeePassLib.Serialization.IOConnectionInfo.FromPath(strPath), true);
                    dr = kcsf.ShowDialog(_host.MainWindow);
                    if ((dr == DialogResult.Cancel) || (dr == DialogResult.Abort))
                    {
                        return;
                    }
                    if (dr == DialogResult.No)
                    {
                        showUsualKeePassKeyCreationDialog = true;
                    }
                    else
                    {
                        key = kcsf.CompositeKey;
                    }
                }
                else
                {
                    showUsualKeePassKeyCreationDialog = true;
                }

                if (showUsualKeePassKeyCreationDialog)
                {
                    using (KeyCreationForm kcf = new KeyCreationForm())
                    {
                        kcf.InitEx(KeePassLib.Serialization.IOConnectionInfo.FromPath(strPath), true);
                        dr = kcf.ShowDialog(_host.MainWindow);
                        if ((dr == DialogResult.Cancel) || (dr == DialogResult.Abort))
                        {
                            return;
                        }
                        key = kcf.CompositeKey;
                    }
                }

                PwDocument dsPrevActive = _host.MainWindow.DocumentManager.ActiveDocument;
                PwDatabase pd           = _host.MainWindow.DocumentManager.CreateNewDocument(true).Database;
                pd.New(KeePassLib.Serialization.IOConnectionInfo.FromPath(strPath), key);

                if (!string.IsNullOrEmpty(kcsf.DatabaseName))
                {
                    pd.Name        = kcsf.DatabaseName;
                    pd.NameChanged = DateTime.Now;
                }

                InsertStandardKeePassData(pd);

                var conf = pd.GetKPRPCConfig();
                pd.SetKPRPCConfig(conf);

                // save the new database & update UI appearance
                pd.Save(_host.MainWindow.CreateStatusBarLogger());
            }
            _host.MainWindow.UpdateUI(true, null, true, null, true, null, false);
        }
Exemple #15
0
        public static bool?Import(PwDatabase pwDatabase, FileFormatProvider fmtImp,
                                  IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
                                  bool bForceSave, Form fParent)
        {
            if (pwDatabase == null)
            {
                throw new ArgumentNullException("pwDatabase");
            }
            if (!pwDatabase.IsOpen)
            {
                return(null);
            }
            if (fmtImp == null)
            {
                throw new ArgumentNullException("fmtImp");
            }
            if (vConnections == null)
            {
                throw new ArgumentNullException("vConnections");
            }

            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(false);
            }
            if (!fmtImp.TryBeginImport())
            {
                return(false);
            }

            bool bUseTempDb  = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            IStatusLogger dlgStatus;

            if (Program.Config.UI.ShowImportStatusDialog)
            {
                dlgStatus = new OnDemandStatusDialog(false, fParent);
            }
            else
            {
                dlgStatus = new UIBlockerStatusLogger(fParent);
            }

            dlgStatus.StartLogging(PwDefs.ShortProductName + " - " + (bSynchronize ?
                                                                      KPRes.Synchronizing : KPRes.ImportingStatusMsg), false);
            dlgStatus.SetText(bSynchronize ? KPRes.Synchronizing :
                              KPRes.ImportingStatusMsg, LogStatusType.Info);

            if (vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, dlgStatus); }
                catch (Exception exSingular)
                {
                    if ((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        // slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                dlgStatus.EndLogging();
                return(true);
            }

            foreach (IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch (Exception exFile)
                {
                    // Transacted-file operations can leave behind intact *.kdbx.tmp files when
                    // the file rename doesn't get completed (can happen easily with slow/unreliable
                    // remote collections. We check if that's the case here and fix the situation if
                    // an kdbx file does *not* exist (to avoid possibly overwriting good data with bad
                    // data (i.e. an interrupted kdbx.tmp write).

                    // Make a copy of the IOC like FileTransactionEx.cs:Initialize does
                    IOConnectionInfo iocTemp = iocIn.CloneDeep();
                    iocTemp.Path += FileTransactionEx.StrTempSuffix;

                    if (IOConnection.FileExists(iocTemp) && !IOConnection.FileExists(iocIn))
                    {
                        // Try and rename iocTemp to ioc.Path, then retry file opening.
                        IOConnection.RenameFile(iocTemp, iocIn);
                        try {
                            s = IOConnection.OpenRead(iocIn);
                        } catch (Exception nexFile) {
                            MessageService.ShowWarning(iocIn.GetDisplayName(), nexFile);
                            bAllSuccess = false;
                            continue;
                        }
                    }
                    else
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                        bAllSuccess = false;
                        continue;
                    }
                }
                if (s == null)
                {
                    Debug.Assert(false); bAllSuccess = false; continue;
                }

                PwDatabase pwImp;
                if (bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else
                {
                    pwImp = pwDatabase;
                }

                if (fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn, false, true);

                    if (UIUtil.ShowDialogNotValue(kpf, DialogResult.OK))
                    {
                        s.Close(); continue;
                    }

                    pwImp.MasterKey = kpf.CompositeKey;
                    UIUtil.DestroyForm(kpf);
                }
                else if (bSynchronize)
                {
                    pwImp.MasterKey = pwDatabase.MasterKey;
                }

                dlgStatus.SetText((bSynchronize ? KPRes.Synchronizing :
                                   KPRes.ImportingStatusMsg) + " (" + iocIn.GetDisplayName() +
                                  ")", LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, dlgStatus); }
                catch (Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if (bSynchronize && (excpFmt is InvalidCompositeKeyException))
                    {
                        strMsgEx = KLRes.InvalidCompositeKey + MessageService.NewParagraph +
                                   KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if (bUseTempDb)
                {
                    PwMergeMethod mm;
                    if (!fmtImp.SupportsUuids)
                    {
                        mm = PwMergeMethod.CreateNewUuids;
                    }
                    else if (bSynchronize)
                    {
                        mm = PwMergeMethod.Synchronize;
                    }
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if (UIUtil.ShowDialogNotValue(imf, DialogResult.OK))
                        {
                            continue;
                        }
                        mm = imf.MergeMethod;
                        UIUtil.DestroyForm(imf);
                    }

                    try { pwDatabase.MergeIn(pwImp, mm, dlgStatus); }
                    catch (Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                                                   KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            if (bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if (uiOps == null)
                {
                    throw new ArgumentNullException("uiOps");
                }

                dlgStatus.SetText(KPRes.Synchronizing + " (" +
                                  KPRes.SavingDatabase + ")", LogStatusType.Info);

                MainForm mf = Program.MainForm;                 // Null for KPScript
                if (mf != null)
                {
                    try { mf.DocumentManager.ActiveDatabase = pwDatabase; }
                    catch (Exception) { Debug.Assert(false); }
                }

                if (uiOps.UIFileSave(bForceSave))
                {
                    foreach (IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            // dlgStatus.SetText(KPRes.Synchronizing + " (" +
                            //	KPRes.SavingDatabase + " " + ioc.GetDisplayName() +
                            //	")", LogStatusType.Info);

                            string strSource = pwDatabase.IOConnectionInfo.Path;
                            if (ioc.Path != strSource)
                            {
                                bool bSaveAs = true;

                                if (pwDatabase.IOConnectionInfo.IsLocalFile() &&
                                    ioc.IsLocalFile())
                                {
                                    // Do not try to copy an encrypted file;
                                    // https://sourceforge.net/p/keepass/discussion/329220/thread/9c9eb989/
                                    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363851.aspx
                                    if ((long)(File.GetAttributes(strSource) &
                                               FileAttributes.Encrypted) == 0)
                                    {
                                        File.Copy(strSource, ioc.Path, true);
                                        bSaveAs = false;
                                    }
                                }

                                if (bSaveAs)
                                {
                                    pwDatabase.SaveAs(ioc, false, null);
                                }
                            }
                            // else { } // No assert (sync on save)

                            if (mf != null)
                            {
                                mf.FileMruList.AddItem(ioc.GetDisplayName(),
                                                       ioc.CloneDeep());
                            }
                        }
                        catch (Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                                       pwDatabase.IOConnectionInfo.GetDisplayName() +
                                                       MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                                               pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }

            dlgStatus.EndLogging();
            return(bAllSuccess);
        }
Exemple #16
0
        public static bool?Import(PwDatabase pwDatabase, FileFormatProvider fmtImp,
                                  IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
                                  bool bForceSave, Form fParent)
        {
            if (pwDatabase == null)
            {
                throw new ArgumentNullException("pwDatabase");
            }
            if (!pwDatabase.IsOpen)
            {
                return(null);
            }
            if (fmtImp == null)
            {
                throw new ArgumentNullException("fmtImp");
            }
            if (vConnections == null)
            {
                throw new ArgumentNullException("vConnections");
            }

            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(false);
            }
            if (!fmtImp.TryBeginImport())
            {
                return(false);
            }

            bool bUseTempDb  = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            IStatusLogger dlgStatus;

            if (Program.Config.UI.ShowImportStatusDialog)
            {
                dlgStatus = new OnDemandStatusDialog(false, fParent);
            }
            else
            {
                dlgStatus = new UIBlockerStatusLogger(fParent);
            }

            dlgStatus.StartLogging(PwDefs.ShortProductName + " - " + (bSynchronize ?
                                                                      KPRes.Synchronizing : KPRes.ImportingStatusMsg), false);
            dlgStatus.SetText(bSynchronize ? KPRes.Synchronizing :
                              KPRes.ImportingStatusMsg, LogStatusType.Info);

            if (vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, dlgStatus); }
                catch (Exception exSingular)
                {
                    if ((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        // slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                dlgStatus.EndLogging();
                return(true);
            }

            foreach (IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch (Exception exFile)
                {
                    MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                    bAllSuccess = false;
                    continue;
                }
                if (s == null)
                {
                    Debug.Assert(false); bAllSuccess = false; continue;
                }

                PwDatabase pwImp;
                if (bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else
                {
                    pwImp = pwDatabase;
                }

                if (fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn, false, true);

                    if (kpf.ShowDialog() != DialogResult.OK)
                    {
                        s.Close(); continue;
                    }

                    pwImp.MasterKey = kpf.CompositeKey;
                }
                else if (bSynchronize)
                {
                    pwImp.MasterKey = pwDatabase.MasterKey;
                }

                dlgStatus.SetText((bSynchronize ? KPRes.Synchronizing :
                                   KPRes.ImportingStatusMsg) + " (" + iocIn.GetDisplayName() +
                                  ")", LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, dlgStatus); }
                catch (Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if (bSynchronize && (excpFmt is InvalidCompositeKeyException))
                    {
                        strMsgEx = KLRes.InvalidCompositeKey + MessageService.NewParagraph +
                                   KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if (bUseTempDb)
                {
                    PwMergeMethod mm;
                    if (!fmtImp.SupportsUuids)
                    {
                        mm = PwMergeMethod.CreateNewUuids;
                    }
                    else if (bSynchronize)
                    {
                        mm = PwMergeMethod.Synchronize;
                    }
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if (imf.ShowDialog() != DialogResult.OK)
                        {
                            continue;
                        }
                        mm = imf.MergeMethod;
                    }

                    // slf.SetText(KPRes.MergingData, LogStatusType.Info);

                    try { pwDatabase.MergeIn(pwImp, mm, dlgStatus); }
                    catch (Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                                                   KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            dlgStatus.EndLogging();

            if (bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if (uiOps == null)
                {
                    throw new ArgumentNullException("uiOps");
                }

                if (uiOps.UIFileSave(bForceSave))
                {
                    foreach (IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            if (ioc.Path != pwDatabase.IOConnectionInfo.Path)
                            {
                                if (pwDatabase.IOConnectionInfo.IsLocalFile() &&
                                    ioc.IsLocalFile())
                                {
                                    File.Copy(pwDatabase.IOConnectionInfo.Path,
                                              ioc.Path, true);
                                }
                                else
                                {
                                    pwDatabase.SaveAs(ioc, false, null);
                                }
                            }
                            else
                            {
                            }                                    // No assert (sync on save)

                            Program.MainForm.FileMruList.AddItem(ioc.GetDisplayName(),
                                                                 ioc.CloneDeep(), true);
                        }
                        catch (Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                                       pwDatabase.IOConnectionInfo.GetDisplayName() +
                                                       MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                                               pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }

            return(bAllSuccess);
        }
Exemple #17
0
        /// <summary>
        /// Write entries to a stream.
        /// </summary>
        /// <param name="msOutput">Output stream to which the entries will be written.</param>
        /// <param name="vEntries">Entries to serialize.</param>
        /// <returns>Returns <c>true</c>, if the entries were written successfully
        /// to the stream.</returns>
        public static bool WriteEntries(Stream msOutput, PwEntry[] vEntries)
        {
            /* KdbxFile f = new KdbxFile(pwDatabase);
            f.m_format = KdbxFormat.PlainXml;

            XmlTextWriter xtw = null;
            try { xtw = new XmlTextWriter(msOutput, StrUtil.Utf8); }
            catch(Exception) { Debug.Assert(false); return false; }
            if(xtw == null) { Debug.Assert(false); return false; }

            f.m_xmlWriter = xtw;

            xtw.Formatting = Formatting.Indented;
            xtw.IndentChar = '\t';
            xtw.Indentation = 1;

            xtw.WriteStartDocument(true);
            xtw.WriteStartElement(ElemRoot);

            foreach(PwEntry pe in vEntries)
                f.WriteEntry(pe, false);

            xtw.WriteEndElement();
            xtw.WriteEndDocument();

            xtw.Flush();
            xtw.Close();
            return true; */

            PwDatabase pd = new PwDatabase();
            pd.New(new IOConnectionInfo(), new CompositeKey());

            foreach(PwEntry peCopy in vEntries)
                pd.RootGroup.AddEntry(peCopy.CloneDeep(), true);

            KdbxFile f = new KdbxFile(pd);
            f.Save(msOutput, null, KdbxFormat.PlainXml, null);
            return true;
        }
		public static bool WriteEntries(Stream msOutput, PwDatabase pdContext,
			PwEntry[] vEntries)
		{
			if(msOutput == null) { Debug.Assert(false); return false; }
			// pdContext may be null
			if(vEntries == null) { Debug.Assert(false); return false; }

			/* KdbxFile f = new KdbxFile(pwDatabase);
			f.m_format = KdbxFormat.PlainXml;

			XmlTextWriter xtw = null;
			try { xtw = new XmlTextWriter(msOutput, StrUtil.Utf8); }
			catch(Exception) { Debug.Assert(false); return false; }
			if(xtw == null) { Debug.Assert(false); return false; }

			f.m_xmlWriter = xtw;

			xtw.Formatting = Formatting.Indented;
			xtw.IndentChar = '\t';
			xtw.Indentation = 1;

			xtw.WriteStartDocument(true);
			xtw.WriteStartElement(ElemRoot);

			foreach(PwEntry pe in vEntries)
				f.WriteEntry(pe, false);

			xtw.WriteEndElement();
			xtw.WriteEndDocument();

			xtw.Flush();
			xtw.Close();
			return true; */

			PwDatabase pd = new PwDatabase();
			pd.New(new IOConnectionInfo(), new CompositeKey());

			PwGroup pg = pd.RootGroup;
			if(pg == null) { Debug.Assert(false); return false; }

			foreach(PwEntry pe in vEntries)
			{
				PwUuid pu = pe.CustomIconUuid;
				if(!pu.Equals(PwUuid.Zero) && (pd.GetCustomIconIndex(pu) < 0))
				{
					int i = -1;
					if(pdContext != null) i = pdContext.GetCustomIconIndex(pu);
					if(i >= 0)
					{
						PwCustomIcon ci = pdContext.CustomIcons[i];
						pd.CustomIcons.Add(ci);
					}
					else { Debug.Assert(pdContext == null); }
				}

				PwEntry peCopy = pe.CloneDeep();
				pg.AddEntry(peCopy, true);
			}

			KdbxFile f = new KdbxFile(pd);
			f.Save(msOutput, null, KdbxFormat.PlainXml, null);
			return true;
		}
Exemple #19
0
        /// <summary>
        /// Called when [file new].
        /// </summary>
        /// <remarks>Review whenever private KeePass.MainForm.OnFileNew method changes.</remarks>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        internal void CreateNewDatabase()
        {
            if (!AppPolicy.Try(AppPolicyId.SaveFile))
            {
                return;
            }

            SaveFileDialog sfd = UIUtil.CreateSaveFileDialog(KPRes.CreateNewDatabase,
                                                             KPRes.NewDatabaseFileName, UIUtil.CreateFileTypeFilter(
                                                                 AppDefs.FileExtension.FileExt, KPRes.KdbxFiles, true), 1,
                                                             AppDefs.FileExtension.FileExt, false);

            GlobalWindowManager.AddDialog(sfd);
            DialogResult dr = sfd.ShowDialog(_host.MainWindow);

            GlobalWindowManager.RemoveDialog(sfd);

            string strPath = sfd.FileName;

            if (dr != DialogResult.OK)
            {
                return;
            }

            KeePassLib.Keys.CompositeKey key;
            KeyCreationSimpleForm        kcsf = new KeyCreationSimpleForm();

            kcsf.InitEx(KeePassLib.Serialization.IOConnectionInfo.FromPath(strPath), true);
            dr = kcsf.ShowDialog(_host.MainWindow);
            if ((dr == DialogResult.Cancel) || (dr == DialogResult.Abort))
            {
                return;
            }
            if (dr == DialogResult.No)
            {
                KeyCreationForm kcf = new KeyCreationForm();
                kcf.InitEx(KeePassLib.Serialization.IOConnectionInfo.FromPath(strPath), true);
                dr = kcf.ShowDialog(_host.MainWindow);
                if ((dr == DialogResult.Cancel) || (dr == DialogResult.Abort))
                {
                    return;
                }
                key = kcf.CompositeKey;
            }
            else
            {
                key = kcsf.CompositeKey;
            }

            PwDocument dsPrevActive = _host.MainWindow.DocumentManager.ActiveDocument;
            PwDatabase pd           = _host.MainWindow.DocumentManager.CreateNewDocument(true).Database;

            pd.New(KeePassLib.Serialization.IOConnectionInfo.FromPath(strPath), key);

            if (!string.IsNullOrEmpty(kcsf.DatabaseName))
            {
                pd.Name        = kcsf.DatabaseName;
                pd.NameChanged = DateTime.Now;
            }

            InsertStandardKeePassData(pd);



            InstallKeeFoxSampleEntries(pd);

            _host.MainWindow.UpdateUI(true, null, true, null, true, null, true);
        }
		/// <summary>
		/// Read entries from a stream.
		/// </summary>
		/// <param name="msData">Input stream to read the entries from.</param>
		/// <param name="pdContext">Context database (e.g. for storing icons).</param>
		/// <param name="bCopyIcons">If <c>true</c>, custom icons required by
		/// the loaded entries are copied to the context database.</param>
		/// <returns>Loaded entries.</returns>
		public static List<PwEntry> ReadEntries(Stream msData, PwDatabase pdContext,
			bool bCopyIcons)
		{
			List<PwEntry> lEntries = new List<PwEntry>();

			if(msData == null) { Debug.Assert(false); return lEntries; }
			// pdContext may be null

			/* KdbxFile f = new KdbxFile(pwDatabase);
			f.m_format = KdbxFormat.PlainXml;

			XmlDocument doc = new XmlDocument();
			doc.Load(msData);

			XmlElement el = doc.DocumentElement;
			if(el.Name != ElemRoot) throw new FormatException();

			List<PwEntry> vEntries = new List<PwEntry>();

			foreach(XmlNode xmlChild in el.ChildNodes)
			{
				if(xmlChild.Name == ElemEntry)
				{
					PwEntry pe = f.ReadEntry(xmlChild);
					pe.Uuid = new PwUuid(true);

					foreach(PwEntry peHistory in pe.History)
						peHistory.Uuid = pe.Uuid;

					vEntries.Add(pe);
				}
				else { Debug.Assert(false); }
			}

			return vEntries; */

			PwDatabase pd = new PwDatabase();
			pd.New(new IOConnectionInfo(), new CompositeKey());

			KdbxFile f = new KdbxFile(pd);
			f.Load(msData, KdbxFormat.PlainXml, null);

			foreach(PwEntry pe in pd.RootGroup.Entries)
			{
				pe.SetUuid(new PwUuid(true), true);
				lEntries.Add(pe);

				if(bCopyIcons && (pdContext != null))
				{
					PwUuid pu = pe.CustomIconUuid;
					if(!pu.Equals(PwUuid.Zero))
					{
						int iSrc = pd.GetCustomIconIndex(pu);
						int iDst = pdContext.GetCustomIconIndex(pu);

						if(iSrc < 0) { Debug.Assert(false); }
						else if(iDst < 0)
						{
							pdContext.CustomIcons.Add(pd.CustomIcons[iSrc]);

							pdContext.Modified = true;
							pdContext.UINeedsIconUpdate = true;
						}
					}
				}
			}

			return lEntries;
		}
Exemple #21
0
        private static bool PerformImport(PwDatabase pwDatabase, FileFormatProvider fmtImp,
                                          IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
                                          bool bForceSave)
        {
            if (fmtImp.TryBeginImport() == false)
            {
                return(false);
            }

            bool bUseTempDb  = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            StatusLoggerForm slf = new StatusLoggerForm();

            slf.InitEx(false);
            slf.Show();

            if (bSynchronize)
            {
                slf.StartLogging(KPRes.Synchronize, false);
            }
            else
            {
                slf.StartLogging(KPRes.ImportingStatusMsg, false);
            }

            if (vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, slf); }
                catch (Exception exSingular)
                {
                    if ((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                slf.EndLogging(); slf.Close();
                return(true);
            }

            foreach (IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch (Exception exFile)
                {
                    MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                    bAllSuccess = false;
                    continue;
                }

                if (s == null)
                {
                    Debug.Assert(false); bAllSuccess = false; continue;
                }

                PwDatabase pwImp;
                if (bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else
                {
                    pwImp = pwDatabase;
                }

                if (fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn.GetDisplayName(), false);

                    if (kpf.ShowDialog() != DialogResult.OK)
                    {
                        s.Close(); continue;
                    }

                    pwImp.MasterKey = kpf.CompositeKey;
                }
                else if (bSynchronize)
                {
                    pwImp.MasterKey = pwDatabase.MasterKey;
                }

                slf.SetText((bSynchronize ? KPRes.Synchronizing : KPRes.ImportingStatusMsg) +
                            " " + iocIn.GetDisplayName(), LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, slf); }
                catch (Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if (bSynchronize)
                    {
                        strMsgEx += MessageService.NewParagraph +
                                    KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if (bUseTempDb)
                {
                    PwMergeMethod mm;
                    if (!fmtImp.SupportsUuids)
                    {
                        mm = PwMergeMethod.CreateNewUuids;
                    }
                    else if (bSynchronize)
                    {
                        mm = PwMergeMethod.Synchronize;
                    }
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if (imf.ShowDialog() != DialogResult.OK)
                        {
                            continue;
                        }
                        mm = imf.MergeMethod;
                    }

                    slf.SetText(KPRes.MergingData, LogStatusType.Info);

                    try { pwDatabase.MergeIn(pwImp, mm); }
                    catch (Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                                                   KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            slf.EndLogging(); slf.Close();

            if (bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if (uiOps == null)
                {
                    throw new ArgumentNullException("uiOps");
                }

                if (uiOps.UIFileSave(bForceSave))
                {
                    foreach (IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            if (pwDatabase.IOConnectionInfo.IsLocalFile())
                            {
                                if ((pwDatabase.IOConnectionInfo.Path != ioc.Path) &&
                                    ioc.IsLocalFile())
                                {
                                    File.Copy(pwDatabase.IOConnectionInfo.Path,
                                              ioc.Path, true);
                                }
                            }
                            else
                            {
                                pwDatabase.SaveAs(ioc, false, null);
                            }
                        }
                        catch (Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                                       pwDatabase.IOConnectionInfo.GetDisplayName() +
                                                       MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                                               pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }
            else if (bSynchronize)            // Synchronized but not successfully imported
            {
                MessageService.ShowWarning(KPRes.SyncFailed,
                                           pwDatabase.IOConnectionInfo.GetDisplayName());

                bAllSuccess = false;
            }

            return(bAllSuccess);
        }