internal static DialogResult ShowDialog(IOConnectionInfo ioInfo, bool bCanExit, string strCustomTitle, out KeyPromptFormResult r) { bool bSecDesk = (Program.Config.Security.MasterKeyOnSecureDesktop && ProtectedDialog.IsSupported); GFunc <KeyPromptForm> fConstruct = delegate() { KeyPromptForm f = new KeyPromptForm(); f.InitEx(ioInfo, bCanExit, true, strCustomTitle); f.SecureDesktopMode = bSecDesk; return(f); }; GFunc <KeyPromptForm, KeyPromptFormResult> fResultBuilder = delegate( KeyPromptForm f) { KeyPromptFormResult rEx = new KeyPromptFormResult(); rEx.CompositeKey = f.CompositeKey; rEx.HasClosedWithExit = f.HasClosedWithExit; rEx.InvokeAfterClose = f.InvokeAfterClose; return(rEx); }; DialogResult dr = ProtectedDialog.ShowDialog <KeyPromptForm, KeyPromptFormResult>(bSecDesk, fConstruct, fResultBuilder, out r); GAction fIac = ((r != null) ? r.InvokeAfterClose : null); if (fIac != null) { fIac(); } return(dr); }
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(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); } // 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; }
private static void ImportIntoCurrentDatabase(EcasAction a, EcasContext ctx) { PwDatabase pd = Program.MainForm.ActiveDatabase; if((pd == null) || !pd.IsOpen) return; string strPath = EcasUtil.GetParamString(a.Parameters, 0, true); if(string.IsNullOrEmpty(strPath)) return; IOConnectionInfo ioc = IOConnectionInfo.FromPath(strPath); string strFormat = EcasUtil.GetParamString(a.Parameters, 1, true); if(string.IsNullOrEmpty(strFormat)) return; FileFormatProvider ff = Program.FileFormatPool.Find(strFormat); if(ff == null) throw new Exception(KPRes.Unknown + ": " + strFormat); uint uMethod = EcasUtil.GetParamUInt(a.Parameters, 2); Type tMM = Enum.GetUnderlyingType(typeof(PwMergeMethod)); object oMethod = Convert.ChangeType(uMethod, tMM); PwMergeMethod mm = PwMergeMethod.None; if(Enum.IsDefined(typeof(PwMergeMethod), oMethod)) mm = (PwMergeMethod)oMethod; else { Debug.Assert(false); } if(mm == PwMergeMethod.None) mm = PwMergeMethod.CreateNewUuids; CompositeKey cmpKey = KeyFromParams(a, 3, 4, 5); if((cmpKey == null) && ff.RequiresKey) { KeyPromptForm kpf = new KeyPromptForm(); kpf.InitEx(ioc, false, true); if(UIUtil.ShowDialogNotValue(kpf, DialogResult.OK)) return; cmpKey = kpf.CompositeKey; UIUtil.DestroyForm(kpf); } bool? b = true; try { b = ImportUtil.Import(pd, ff, ioc, mm, cmpKey); } finally { if(b.GetValueOrDefault(false)) Program.MainForm.UpdateUI(false, null, true, null, true, null, true); } }
public static bool ReAskKey(PwDatabase pwDatabase, bool bFailWithUI) { if(pwDatabase == null) { Debug.Assert(false); return false; } KeyPromptForm dlg = new KeyPromptForm(); dlg.InitEx(pwDatabase.IOConnectionInfo, false, true, KPRes.EnterCurrentCompositeKey); if(UIUtil.ShowDialogNotValue(dlg, DialogResult.OK)) return false; CompositeKey ck = dlg.CompositeKey; bool bResult = ck.EqualsValue(pwDatabase.MasterKey); if(!bResult) MessageService.ShowWarning(KLRes.InvalidCompositeKey, KLRes.InvalidCompositeKeyHint); UIUtil.DestroyForm(dlg); return bResult; }
private static Form OdKpfConstruct(object objParam) { OdKpfConstructParams p = (objParam as OdKpfConstructParams); if(p == null) { Debug.Assert(false); return null; } KeyPromptForm kpf = new KeyPromptForm(); kpf.InitEx(p.IOConnectionInfo, p.CanExit, true); kpf.SecureDesktopMode = p.SecureDesktopMode; return kpf; }
/// <summary> /// Open a database. This function opens the specified database and updates /// the user interface. /// </summary> public void OpenDatabase(IOConnectionInfo ioConnection, CompositeKey cmpKey, bool bOpenLocal) { // OnFileClose(null, null); // if(m_docMgr.ActiveDatabase.IsOpen) return; if(m_bFormLoading && Program.Config.Application.Start.MinimizedAndLocked && (ioConnection != null) && (ioConnection.Path.Length > 0)) { PwDocument ds = m_docMgr.CreateNewDocument(true); ds.LockedIoc = ioConnection.CloneDeep(); UpdateUI(true, ds, true, null, true, null, false); return; } IOConnectionInfo ioc; if(ioConnection == null) { if(bOpenLocal) { OpenFileDialog ofdDb = UIUtil.CreateOpenFileDialog(KPRes.OpenDatabaseFile, UIUtil.CreateFileTypeFilter(AppDefs.FileExtension.FileExt, KPRes.KdbxFiles, true), 1, null, false, false); GlobalWindowManager.AddDialog(ofdDb); DialogResult dr = ofdDb.ShowDialog(); GlobalWindowManager.RemoveDialog(ofdDb); if(dr != DialogResult.OK) return; ioc = IOConnectionInfo.FromPath(ofdDb.FileName); } else { ioc = CompleteConnectionInfo(new IOConnectionInfo(), false, true, true, true); if(ioc == null) return; } } else // ioConnection != null { ioc = CompleteConnectionInfo(ioConnection, false, true, true, false); if(ioc == null) return; } if(!ioc.CanProbablyAccess()) { MessageService.ShowWarning(ioc.GetDisplayName(), KPRes.FileNotFoundError); return; } if(OpenDatabaseRestoreIfOpened(ioc)) return; PwDatabase pwOpenedDb = null; if(cmpKey == null) { for(int iTry = 0; iTry < 3; ++iTry) { KeyPromptForm kpf = new KeyPromptForm(); kpf.InitEx(ioc, IsFileLocked(null), true); DialogResult dr; if(Program.Config.Security.MasterKeyOnSecureDesktop && WinUtil.IsAtLeastWindows2000 && !KeePassLib.Native.NativeLib.IsUnix()) { kpf.SecureDesktopMode = true; ProtectedDialog dlg = new ProtectedDialog(kpf); dr = dlg.ShowDialog(); if(dr == DialogResult.None) dr = DialogResult.Cancel; if(kpf.ShowHelpAfterClose) AppHelp.ShowHelp(AppDefs.HelpTopics.KeySources, null); } else dr = kpf.ShowDialog(); if(dr == DialogResult.Cancel) { UIUtil.DestroyForm(kpf); break; } else if(kpf.HasClosedWithExit) { Debug.Assert(dr == DialogResult.Abort); UIUtil.DestroyForm(kpf); OnFileExit(null, null); return; } pwOpenedDb = OpenDatabaseInternal(ioc, kpf.CompositeKey); UIUtil.DestroyForm(kpf); if(pwOpenedDb != null) break; } } else // cmpKey != null { pwOpenedDb = OpenDatabaseInternal(ioc, cmpKey); } if((pwOpenedDb == null) || !pwOpenedDb.IsOpen) return; string strName = pwOpenedDb.IOConnectionInfo.GetDisplayName(); m_mruList.AddItem(strName, pwOpenedDb.IOConnectionInfo.CloneDeep(), true); PwDocument dsExisting = m_docMgr.FindDocument(pwOpenedDb); if(dsExisting != null) m_docMgr.ActiveDocument = dsExisting; bool bCorrectDbActive = (m_docMgr.ActiveDocument.Database == pwOpenedDb); Debug.Assert(bCorrectDbActive); // AutoEnableVisualHiding(); SetLastUsedFile(pwOpenedDb.IOConnectionInfo); RememberKeyFilePath(pwOpenedDb); PwGroup pgRestoreSelect = null; if(bCorrectDbActive) { m_docMgr.ActiveDocument.LockedIoc = new IOConnectionInfo(); // Clear pgRestoreSelect = pwOpenedDb.RootGroup.FindGroup( pwOpenedDb.LastSelectedGroup, true); } UpdateUI(true, null, true, pgRestoreSelect, true, null, false); if(bCorrectDbActive) { SetTopVisibleGroup(pwOpenedDb.LastTopVisibleGroup); if(pgRestoreSelect != null) SetTopVisibleEntry(pgRestoreSelect.LastTopVisibleEntry); } UpdateColumnSortingIcons(); if((pwOpenedDb.MasterKeyChangeForce >= 0) && ((DateTime.Now - pwOpenedDb.MasterKeyChanged).Days >= pwOpenedDb.MasterKeyChangeForce)) { while(true) { MessageService.ShowInfo(pwOpenedDb.IOConnectionInfo.GetDisplayName() + MessageService.NewParagraph + KPRes.MasterKeyChangeForce + MessageService.NewParagraph + KPRes.MasterKeyChangeInfo); if(ChangeMasterKey(pwOpenedDb)) { UpdateUIState(true); break; } if(!AppPolicy.Current.ChangeMasterKey) break; // Prevent endless loop } } else if((pwOpenedDb.MasterKeyChangeRec >= 0) && ((DateTime.Now - pwOpenedDb.MasterKeyChanged).Days >= pwOpenedDb.MasterKeyChangeRec)) { if(MessageService.AskYesNo(pwOpenedDb.IOConnectionInfo.GetDisplayName() + MessageService.NewParagraph + KPRes.MasterKeyChangeRec + MessageService.NewParagraph + KPRes.MasterKeyChangeQ)) UpdateUIState(ChangeMasterKey(pwOpenedDb)); } if(this.FileOpened != null) { FileOpenedEventArgs ea = new FileOpenedEventArgs(pwOpenedDb); this.FileOpened(this, ea); } Program.TriggerSystem.RaiseEvent(EcasEventIDs.OpenedDatabaseFile, pwOpenedDb.IOConnectionInfo.Path); if(bCorrectDbActive && pwOpenedDb.IsOpen && Program.Config.Application.FileOpening.ShowSoonToExpireEntries) { ShowExpiredEntries(true, 7); // Avoid view being destroyed by the unlocking routine pwOpenedDb.LastSelectedGroup = PwUuid.Zero; } else if(bCorrectDbActive && pwOpenedDb.IsOpen && Program.Config.Application.FileOpening.ShowExpiredEntries) { ShowExpiredEntries(true, 0); // Avoid view being destroyed by the unlocking routine pwOpenedDb.LastSelectedGroup = PwUuid.Zero; } if(Program.Config.MainWindow.MinimizeAfterOpeningDatabase) this.WindowState = FormWindowState.Minimized; ResetDefaultFocus(null); }
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; }
/// <summary> /// Open a database. This function opens the specified database and updates /// the user interface. /// </summary> public void OpenDatabase(IOConnectionInfo ioConnection, CompositeKey cmpKey, bool bOpenLocal) { // OnFileClose(null, null); // if(m_docMgr.ActiveDatabase.IsOpen) return; if(m_bFormLoading && Program.Config.Application.Start.MinimizedAndLocked && (ioConnection != null) && (ioConnection.Path.Length > 0)) { DocumentStateEx ds = m_docMgr.CreateNewDocument(true); ds.LockedIoc = ioConnection.CloneDeep(); UpdateUI(true, ds, true, null, true, null, false); return; } IOConnectionInfo ioc; if(ioConnection == null) { if(bOpenLocal) { OpenFileDialog ofdDb = UIUtil.CreateOpenFileDialog(KPRes.OpenDatabaseFile, UIUtil.CreateFileTypeFilter("kdbx", KPRes.KdbxFiles, true), 1, null, false, false); GlobalWindowManager.AddDialog(ofdDb); DialogResult dr = ofdDb.ShowDialog(); GlobalWindowManager.RemoveDialog(ofdDb); if(dr != DialogResult.OK) return; ioc = IOConnectionInfo.FromPath(ofdDb.FileName); } else { IOConnectionForm iocf = new IOConnectionForm(); iocf.InitEx(false, new IOConnectionInfo(), true, true); if(iocf.ShowDialog() != DialogResult.OK) return; ioc = iocf.IOConnectionInfo; } } else // ioConnection != null { ioc = ioConnection.CloneDeep(); if((ioc.CredSaveMode != IOCredSaveMode.SaveCred) && (!ioc.IsLocalFile())) { IOConnectionForm iocf = new IOConnectionForm(); iocf.InitEx(false, ioc.CloneDeep(), true, true); if(iocf.ShowDialog() != DialogResult.OK) return; ioc = iocf.IOConnectionInfo; } } if((ioc == null) || !ioc.CanProbablyAccess()) { MessageService.ShowWarning(ioc.GetDisplayName(), KPRes.FileNotFoundError); return; } if(OpenDatabaseRestoreIfOpened(ioc)) return; PwDatabase pwOpenedDb = null; if(cmpKey == null) { for(int iTry = 0; iTry < 3; ++iTry) { KeyPromptForm kpf = new KeyPromptForm(); kpf.InitEx(ioc.GetDisplayName(), IsFileLocked(null)); DialogResult dr = kpf.ShowDialog(); if(dr == DialogResult.Cancel) break; else if(kpf.HasClosedWithExit) { Debug.Assert(dr == DialogResult.Abort); OnFileExit(null, null); return; } pwOpenedDb = OpenDatabaseInternal(ioc, kpf.CompositeKey); if(pwOpenedDb != null) break; } } else // cmpKey != null { pwOpenedDb = OpenDatabaseInternal(ioc, cmpKey); } if((pwOpenedDb == null) || !pwOpenedDb.IsOpen) return; string strName = pwOpenedDb.IOConnectionInfo.GetDisplayName(); m_mruList.AddItem(strName, pwOpenedDb.IOConnectionInfo.CloneDeep()); DocumentStateEx dsExisting = m_docMgr.FindDocument(pwOpenedDb); if(dsExisting != null) m_docMgr.ActiveDocument = dsExisting; bool bCorrectDbActive = (m_docMgr.ActiveDocument.Database == pwOpenedDb); Debug.Assert(bCorrectDbActive); AutoEnableVisualHiding(); if(Program.Config.Application.Start.OpenLastFile) Program.Config.Application.LastUsedFile = pwOpenedDb.IOConnectionInfo.CloneDeep(); else Program.Config.Application.LastUsedFile = new IOConnectionInfo(); if(bCorrectDbActive) m_docMgr.ActiveDocument.LockedIoc = new IOConnectionInfo(); // Clear if(this.FileOpened != null) { FileOpenedEventArgs ea = new FileOpenedEventArgs(pwOpenedDb); this.FileOpened(this, ea); } UpdateUI(true, null, true, null, true, null, false); UpdateColumnSortingIcons(); if(bCorrectDbActive && pwOpenedDb.IsOpen && Program.Config.Application.FileOpening.ShowSoonToExpireEntries) { ShowExpiredEntries(true, 7); // Avoid view being destroyed by the unlocking routine pwOpenedDb.LastSelectedGroup = PwUuid.Zero; } else if(bCorrectDbActive && pwOpenedDb.IsOpen && Program.Config.Application.FileOpening.ShowExpiredEntries) { ShowExpiredEntries(true, 0); // Avoid view being destroyed by the unlocking routine pwOpenedDb.LastSelectedGroup = PwUuid.Zero; } ResetDefaultFocus(null); }
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); 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) 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; }