public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            PwDatabase pd = (pwExportInfo.ContextDatabase ?? new PwDatabase());

            PwObjectList <PwDeletedObject> vDel = null;

            if (pwExportInfo.ExportDeletedObjects == false)
            {
                vDel = pd.DeletedObjects.CloneShallow();
                pd.DeletedObjects.Clear();
            }

            Kdb4File kdb = new Kdb4File(pd);

            kdb.Save(sOutput, pwExportInfo.DataGroup, Kdb4Format.PlainXml, slLogger);

            // Restore deleted objects list
            if (vDel != null)
            {
                pd.DeletedObjects.Add(vDel);
            }

            return(true);
        }
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            Kdb4File kdb4 = new Kdb4File(pwStorage);

            kdb4.Load(sInput, Kdb4Format.PlainXml, slLogger);
        }
Beispiel #3
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            Kdb4File kdb4 = new Kdb4File(pwExportInfo.ContextDatabase);

            kdb4.Save(sOutput, pwExportInfo.DataGroup, Kdb4Format.Default, slLogger);
            return(true);
        }
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            Kdb4File kdb4 = new Kdb4File(pwStorage);

            // CappedByteStream s = new CappedByteStream(sInput, 64);

            kdb4.RepairMode = true;

            try { kdb4.Load(sInput, Kdb4Format.Default, slLogger); }
            catch (Exception) { }
        }
Beispiel #5
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            string         strFilter = UIUtil.CreateFileTypeFilter("xsl", KPRes.XslFileType, true);
            OpenFileDialog dlgXsl    = UIUtil.CreateOpenFileDialog(KPRes.XslSelectFile,
                                                                   strFilter, 1, "xsl", false, false);

            if (dlgXsl.ShowDialog() != DialogResult.OK)
            {
                return(false);
            }

            string strXslFile        = dlgXsl.FileName;
            XslCompiledTransform xsl = new XslCompiledTransform();

            try { xsl.Load(strXslFile); }
            catch (Exception exXsl)
            {
                throw new NotSupportedException(strXslFile + MessageService.NewParagraph +
                                                KPRes.NoXslFile + MessageService.NewParagraph + exXsl.Message);
            }

            MemoryStream msDataXml = new MemoryStream();

            PwDatabase pd  = (pwExportInfo.ContextDatabase ?? new PwDatabase());
            Kdb4File   kdb = new Kdb4File(pd);

            kdb.Save(msDataXml, pwExportInfo.DataGroup, Kdb4Format.PlainXml, slLogger);

            byte[] pbData = msDataXml.ToArray();
            msDataXml.Close();
            MemoryStream msDataRead    = new MemoryStream(pbData, false);
            XmlReader    xmlDataReader = XmlReader.Create(msDataRead);

            XmlWriterSettings xws = new XmlWriterSettings();

            xws.CheckCharacters    = false;
            xws.Encoding           = new UTF8Encoding(false);
            xws.NewLineChars       = MessageService.NewLine;
            xws.NewLineHandling    = NewLineHandling.None;
            xws.OmitXmlDeclaration = true;
            xws.ConformanceLevel   = ConformanceLevel.Auto;

            XmlWriter xmlWriter = XmlWriter.Create(sOutput, xws);

            xsl.Transform(xmlDataReader, xmlWriter);
            xmlWriter.Close();
            xmlDataReader.Close();
            msDataRead.Close();

            Array.Clear(pbData, 0, pbData.Length);
            return(true);
        }
Beispiel #6
0
 public Kdb4Reader(Kdb4File kdb4File, 
     IEncryptionEngine databaseDecryptor,
     IKeyTransformer keyTransformer, 
     ICanSHA256Hash hasher,
     IGZipStreamFactory gZipFactory)
 {            
     file = kdb4File;
     _encryptionEngine = databaseDecryptor;
     _keyTransformer = keyTransformer;
     _hasher = hasher;
     _gZipFactory = gZipFactory;
 }
Beispiel #7
0
        public static void PasteEntriesFromClipboard(PwDatabase pwDatabase, PwGroup pgStorage)
        {
            if (Clipboard.ContainsData(ClipFormatEntries) == false)
            {
                return;
            }

            byte[] pbEnc = (byte[])Clipboard.GetData(ClipFormatEntries);

            byte[]       pbPlain = ProtectedData.Unprotect(pbEnc, AdditionalEntropy, DataProtectionScope.CurrentUser);
            MemoryStream ms      = new MemoryStream(pbPlain, false);
            GZipStream   gz      = new GZipStream(ms, CompressionMode.Decompress);

            List <PwEntry> vEntries = Kdb4File.ReadEntries(pwDatabase, gz);

            // Adjust protection settings and add entries
            foreach (PwEntry pe in vEntries)
            {
                ProtectedString ps = pe.Strings.Get(PwDefs.TitleField);
                if (ps != null)
                {
                    ps.EnableProtection(pwDatabase.MemoryProtection.ProtectTitle);
                }

                ps = pe.Strings.Get(PwDefs.UserNameField);
                if (ps != null)
                {
                    ps.EnableProtection(pwDatabase.MemoryProtection.ProtectUserName);
                }

                ps = pe.Strings.Get(PwDefs.PasswordField);
                if (ps != null)
                {
                    ps.EnableProtection(pwDatabase.MemoryProtection.ProtectPassword);
                }

                ps = pe.Strings.Get(PwDefs.UrlField);
                if (ps != null)
                {
                    ps.EnableProtection(pwDatabase.MemoryProtection.ProtectUrl);
                }

                ps = pe.Strings.Get(PwDefs.NotesField);
                if (ps != null)
                {
                    ps.EnableProtection(pwDatabase.MemoryProtection.ProtectNotes);
                }

                pgStorage.AddEntry(pe, true, true);
            }

            gz.Close(); ms.Close();
        }
Beispiel #8
0
        public static void CopyEntriesToClipboard(PwDatabase pwDatabase, PwEntry[] vEntries)
        {
            MemoryStream ms = new MemoryStream();
            GZipStream   gz = new GZipStream(ms, CompressionMode.Compress);

            Kdb4File.WriteEntries(gz, pwDatabase, vEntries);

            byte[] pbFinal = ProtectedData.Protect(ms.ToArray(), AdditionalEntropy, DataProtectionScope.CurrentUser);

            ClipboardUtil.Copy(pbFinal, ClipFormatEntries, true);

            gz.Close(); ms.Close();
        }
Beispiel #9
0
        private static void PasteEntriesFromClipboardPriv(PwDatabase pwDatabase,
                                                          PwGroup pgStorage)
        {
            if (!Clipboard.ContainsData(ClipFormatEntries))
            {
                return;
            }

            byte[] pbEnc = ClipboardUtil.GetEncodedData(ClipFormatEntries, IntPtr.Zero);
            if (pbEnc == null)
            {
                Debug.Assert(false); return;
            }

            byte[] pbPlain;
            if (WinUtil.IsWindows9x)
            {
                pbPlain = pbEnc;
            }
            else
            {
                pbPlain = ProtectedData.Unprotect(pbEnc, AdditionalEntropy,
                                                  DataProtectionScope.CurrentUser);
            }

            MemoryStream ms = new MemoryStream(pbPlain, false);
            GZipStream   gz = new GZipStream(ms, CompressionMode.Decompress);

            List <PwEntry> vEntries = Kdb4File.ReadEntries(gz);

            // Adjust protection settings and add entries
            foreach (PwEntry pe in vEntries)
            {
                pe.Strings.EnableProtection(PwDefs.TitleField,
                                            pwDatabase.MemoryProtection.ProtectTitle);
                pe.Strings.EnableProtection(PwDefs.UserNameField,
                                            pwDatabase.MemoryProtection.ProtectUserName);
                pe.Strings.EnableProtection(PwDefs.PasswordField,
                                            pwDatabase.MemoryProtection.ProtectPassword);
                pe.Strings.EnableProtection(PwDefs.UrlField,
                                            pwDatabase.MemoryProtection.ProtectUrl);
                pe.Strings.EnableProtection(PwDefs.NotesField,
                                            pwDatabase.MemoryProtection.ProtectNotes);

                pgStorage.AddEntry(pe, true, true);
            }

            gz.Close(); ms.Close();
        }
Beispiel #10
0
        /// <summary>
        /// Common program initialization function that can also be
        /// used by applications that use KeePass as a library
        /// (like e.g. KPScript).
        /// </summary>
        public static bool CommonInit()
        {
            int nRandomSeed = (int)DateTime.UtcNow.Ticks;

            // Prevent overflow (see Random class constructor)
            if (nRandomSeed == int.MinValue)
            {
                nRandomSeed = 17;
            }
            m_rndGlobal = new Random(nRandomSeed);

            InitEnvSecurity();

            try { SelfTest.TestFipsComplianceProblems(); }
            catch (Exception exFips)
            {
                MessageService.ShowWarning(KPRes.SelfTestFailed, exFips);
                return(false);
            }

            // Set global localized strings
            PwDatabase.LocalizedAppName = PwDefs.ShortProductName;
            Kdb4File.DetermineLanguageId();

            m_appConfig = AppConfigSerializer.Load();
            if (m_appConfig.Logging.Enabled)
            {
                AppLogEx.Open(PwDefs.ShortProductName);
            }

            AppPolicy.Current = m_appConfig.Security.Policy.CloneDeep();
            IOConnection.SetProxy(m_appConfig.Integration.ProxyType,
                                  m_appConfig.Integration.ProxyAddress, m_appConfig.Integration.ProxyPort,
                                  m_appConfig.Integration.ProxyUserName, m_appConfig.Integration.ProxyPassword);

            m_ecasTriggers = m_appConfig.Application.TriggerSystem;
            m_ecasTriggers.SetToInitialState();

            string strHelpFile = UrlUtil.StripExtension(WinUtil.GetExecutable()) + ".chm";

            AppHelp.LocalHelpFile = strHelpFile;

            LoadTranslation();
            return(true);
        }
Beispiel #11
0
        /// <summary>
        /// Open a database. The URL may point to any supported data source.
        /// </summary>
        /// <param name="ioSource">IO connection to load the database from.</param>
        /// <param name="pwKey">Key used to open the specified database.</param>
        /// <param name="slLogger">Logger, which gets all status messages.</param>
        public void Open(IOConnectionInfo ioSource, CompositeKey pwKey,
                         IStatusLogger slLogger)
        {
            Debug.Assert(ioSource != null);
            if (ioSource == null)
            {
                throw new ArgumentNullException("ioSource");
            }
            Debug.Assert(pwKey != null);
            if (pwKey == null)
            {
                throw new ArgumentNullException("pwKey");
            }

            this.Close();

            try
            {
                m_pgRootGroup = new PwGroup(true, true, UrlUtil.StripExtension(
                                                UrlUtil.GetFileName(ioSource.Path)), PwIcon.FolderOpen);
                m_pgRootGroup.IsExpanded = true;

                m_pwUserKey = pwKey;

                m_bModified = false;

                Kdb4File kdb4 = new Kdb4File(this);
                Stream   s    = IOConnection.OpenRead(ioSource);
                kdb4.Load(s, Kdb4Format.Default, slLogger);
                s.Close();

                m_pbHashOfLastIO     = kdb4.HashOfFileOnDisk;
                m_pbHashOfFileOnDisk = kdb4.HashOfFileOnDisk;
                Debug.Assert(m_pbHashOfFileOnDisk != null);

                m_bDatabaseOpened = true;
                m_ioSource        = ioSource;
            }
            catch (Exception)
            {
                this.Clear();
                throw;
            }
        }
        public void WriteHeaders(BinaryWriter dataWriter, Kdb4File file)
        {
            //Write Signature and Version
            Write(dataWriter,BitConverter.GetBytes(KdbConstants.FileSignature1));
            Write(dataWriter,BitConverter.GetBytes(KdbConstants.FileSignature2));
            Write(dataWriter, BitConverter.GetBytes(KdbConstants.Kdb4Version));

            WriteHeaderField(dataWriter, Kdb4HeaderFieldID.CipherID, file.pwDatabase.DataCipherUuid.UuidBytes);
            var compressionId = (uint) file.pwDatabase.Compression;
            WriteHeaderField(dataWriter, Kdb4HeaderFieldID.CompressionFlags,BitConverter.GetBytes(compressionId));
            WriteHeaderField(dataWriter, Kdb4HeaderFieldID.MasterSeed, file.pbMasterSeed);
            WriteHeaderField(dataWriter, Kdb4HeaderFieldID.TransformSeed, file.pbTransformSeed);     
            WriteHeaderField(dataWriter, Kdb4HeaderFieldID.TransformRounds, BitConverter.GetBytes(file.pwDatabase.KeyEncryptionRounds));
            WriteHeaderField(dataWriter, Kdb4HeaderFieldID.EncryptionIV, file.pbEncryptionIV);
            WriteHeaderField(dataWriter, Kdb4HeaderFieldID.ProtectedStreamKey, file.pbProtectedStreamKey);
            WriteHeaderField(dataWriter, Kdb4HeaderFieldID.StreamStartBytes, file.pbStreamStartBytes);
            var crsAlg = (uint)CrsAlgorithm.Salsa20;
            WriteHeaderField(dataWriter, Kdb4HeaderFieldID.InnerRandomStreamID, BitConverter.GetBytes(crsAlg));
            WriteHeaderField(dataWriter, Kdb4HeaderFieldID.EndOfHeader, new byte[] { (byte)'\r', (byte)'\n', (byte)'\r', (byte)'\n' });
        }
Beispiel #13
0
        /// <summary>
        /// Save the currently opened database. The file is written to the location
        /// it has been opened from.
        /// </summary>
        /// <param name="slLogger">Logger that recieves status information.</param>
        public void Save(IStatusLogger slLogger)
        {
            bool bMadeUnhidden = UrlUtil.UnhideFile(m_ioSource.Path);

            Stream s = IOConnection.OpenWrite(m_ioSource);

            Kdb4File kdb = new Kdb4File(this);

            kdb.Save(s, null, Kdb4Format.Default, slLogger);

            if (bMadeUnhidden)
            {
                UrlUtil.HideFile(m_ioSource.Path, true);                           // Hide again
            }
            m_pbHashOfLastIO     = kdb.HashOfFileOnDisk;
            m_pbHashOfFileOnDisk = kdb.HashOfFileOnDisk;
            Debug.Assert(m_pbHashOfFileOnDisk != null);

            m_bModified = false;
        }
Beispiel #14
0
        // AppConfigEx with KeePass.XmlSerializers.dll: 811 ms
        // AppConfigEx with own deserializer: 312 ms

        /* public object Deserialize(Stream s)
         * {
         *      int tStart = Environment.TickCount;
         *      object o = Deserialize_(s);
         *      MessageService.ShowInfo(Environment.TickCount - tStart);
         *      return o;
         * } */

        public object Deserialize(Stream s)
        {
            object oResult = null;

            if ((m_t == typeof(AppConfigEx)) || (m_t == typeof(KPTranslation)))
            {
                XmlReaderSettings xrs = Kdb4File.CreateStdXmlReaderSettings();
                XmlReader         xr  = XmlReader.Create(s, xrs);

                string strRootName = GetXmlName(m_t);
                bool   bRootFound  = SkipToRoot(xr, strRootName);

                if (!bRootFound)
                {
                    Debug.Assert(false);
                }
                else if (m_t == typeof(AppConfigEx))
                {
                    oResult = ReadAppConfigEx(xr);
                }
                else if (m_t == typeof(KPTranslation))
                {
                    oResult = ReadKPTranslation(xr);
                }
                else
                {
                    Debug.Assert(false);
                }                                             // See top-level 'if'

                xr.Close();
            }
            if (oResult != null)
            {
                return(oResult);
            }

            XmlSerializer xs = new XmlSerializer(m_t);

            return(xs.Deserialize(s));
        }
		/// <summary>
		/// Save the currently opened database. The file is written to the location
		/// it has been opened from.
		/// </summary>
		/// <param name="slLogger">Logger that recieves status information.</param>
		public void Save(IStatusLogger slLogger)
		{
			Debug.Assert(ValidateUuidUniqueness());

			// bool bMadeUnhidden = UrlUtil.UnhideFile(m_ioSource.Path);
			// Stream s = IOConnection.OpenWrite(m_ioSource);

			FileTransactionEx ft = new FileTransactionEx(m_ioSource, m_bUseFileTransactions);
			Stream s = ft.OpenWrite();

			Kdb4File kdb = new Kdb4File(this);
			kdb.Save(s, null, Kdb4Format.Default, slLogger);

			ft.CommitWrite();

			// if(bMadeUnhidden) UrlUtil.HideFile(m_ioSource.Path, true); // Hide again

			m_pbHashOfLastIO = kdb.HashOfFileOnDisk;
			m_pbHashOfFileOnDisk = kdb.HashOfFileOnDisk;
			Debug.Assert(m_pbHashOfFileOnDisk != null);

			m_bModified = false;
		}
Beispiel #16
0
        public static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.DoEvents();             // Required

            InitEnvSecurity();

            int nRandomSeed = (int)DateTime.Now.Ticks;

            // Prevent overflow (see Random class constructor)
            if (nRandomSeed == int.MinValue)
            {
                nRandomSeed = 17;
            }
            m_rndGlobal = new Random(nRandomSeed);

            // Set global localized strings
            PwDatabase.LocalizedAppName = PwDefs.ShortProductName;
            Kdb4File.DetermineLanguageId();

            m_appConfig = AppConfigSerializer.Load();
            if (m_appConfig.Logging.Enabled)
            {
                AppLogEx.Open(PwDefs.ShortProductName);
            }

            AppPolicy.Current = m_appConfig.Security.Policy.CloneDeep();

            m_ecasTriggers = m_appConfig.Application.TriggerSystem;
            m_ecasTriggers.SetToInitialState();

            string strHelpFile = UrlUtil.StripExtension(WinUtil.GetExecutable()) + ".chm";

            AppHelp.LocalHelpFile = strHelpFile;

            string strLangFile = m_appConfig.Application.LanguageFile;

            if ((strLangFile != null) && (strLangFile.Length > 0))
            {
                strLangFile = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(), true,
                                                       false) + strLangFile;

                try
                {
                    m_kpTranslation = KPTranslation.LoadFromFile(strLangFile);

                    KPRes.SetTranslatedStrings(
                        m_kpTranslation.SafeGetStringTableDictionary(
                            "KeePass.Resources.KPRes"));
                    KLRes.SetTranslatedStrings(
                        m_kpTranslation.SafeGetStringTableDictionary(
                            "KeePassLib.Resources.KLRes"));

                    StrUtil.RightToLeft = m_kpTranslation.Properties.RightToLeft;
                }
                catch (FileNotFoundException) { }                // Ignore
                catch (Exception) { Debug.Assert(false); }
            }

            if (m_appConfig.Application.Start.PluginCacheClearOnce)
            {
                PlgxCache.Clear();
                m_appConfig.Application.Start.PluginCacheClearOnce = false;
                AppConfigSerializer.Save(Program.Config);
            }

            m_cmdLineArgs = new CommandLineArgs(args);

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtRegister] != null)
            {
                ShellUtil.RegisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId,
                                            KPRes.FileExtName, WinUtil.GetExecutable(), PwDefs.ShortProductName, false);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtUnregister] != null)
            {
                ShellUtil.UnregisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoad] != null)
            {
                // All important .NET assemblies are in memory now already
                try { SelfTest.Perform(); }
                catch (Exception) { Debug.Assert(false); }
                MainCleanUp();
                return;
            }

            /* else if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadRegister] != null)
             * {
             *      string strPreLoadPath = WinUtil.GetExecutable().Trim();
             *      if(strPreLoadPath.StartsWith("\"") == false)
             *              strPreLoadPath = "\"" + strPreLoadPath + "\"";
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, strPreLoadPath,
             *              @"--" + AppDefs.CommandLineOptions.PreLoad, true);
             *      MainCleanUp();
             *      return;
             * }
             * else if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadUnregister] != null)
             * {
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, string.Empty,
             *              string.Empty, false);
             *      MainCleanUp();
             *      return;
             * } */
            else if ((m_cmdLineArgs[AppDefs.CommandLineOptions.Help] != null) ||
                     (m_cmdLineArgs[AppDefs.CommandLineOptions.HelpLong] != null))
            {
                AppHelp.ShowHelp(AppDefs.HelpTopics.CommandLine, null);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetUrlOverride];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigClearUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = string.Empty;
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigGetUrlOverride] != null)
            {
                try
                {
                    string strFileOut = UrlUtil.EnsureTerminatingSeparator(
                        Path.GetTempPath(), false) + "KeePass_UrlOverride.tmp";
                    string strContent = ("[KeePass]\r\nKeeURLOverride=" +
                                         Program.Config.Integration.UrlOverride + "\r\n");
                    File.WriteAllText(strFileOut, strContent);
                }
                catch (Exception) { Debug.Assert(false); }
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetLanguageFile] != null)
            {
                Program.Config.Application.LanguageFile = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetLanguageFile];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreate] != null)
            {
                PlgxPlugin.CreateFromCommandLine();
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreateInfo] != null)
            {
                PlgxPlugin.CreateInfoFile(m_cmdLineArgs.FileName);
                MainCleanUp();
                return;
            }
#if (DEBUG && !KeePassLibSD)
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakePopularPasswordTable] != null)
            {
                PopularPasswords.MakeList();
                MainCleanUp();
                return;
            }
#endif

            try { m_nAppMessage = NativeMethods.RegisterWindowMessage(m_strWndMsgID); }
            catch (Exception) { Debug.Assert(false); }

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ExitAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Exit);
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoType] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.AutoType);
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.OpenEntryUrl] != null)
            {
                string strEntryUuid = m_cmdLineArgs[AppDefs.CommandLineOptions.Uuid];
                if (!string.IsNullOrEmpty(strEntryUuid))
                {
                    IpcParamEx ipUrl = new IpcParamEx(IpcUtilEx.CmdOpenEntryUrl,
                                                      strEntryUuid, null, null, null, null);
                    IpcUtilEx.SendGlobalMessage(ipUrl);
                }

                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.LockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Lock);
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.UnlockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Unlock);
                return;
            }

            Mutex mSingleLock = TrySingleInstanceLock(AppDefs.MutexName, true);
            if ((mSingleLock == null) && m_appConfig.Integration.LimitToSingleInstance)
            {
                ActivatePreviousInstance(args);
                MainCleanUp();
                return;
            }

            Mutex mGlobalNotify = TryGlobalInstanceNotify(AppDefs.MutexNameGlobal);

            AutoType.InitStatic();

            UserActivityNotifyFilter nfActivity = new UserActivityNotifyFilter();
            Application.AddMessageFilter(nfActivity);

#if DEBUG
            m_formMain = new MainForm();
            Application.Run(m_formMain);
#else
            try
            {
                m_formMain = new MainForm();
                Application.Run(m_formMain);
            }
            catch (Exception exPrg) { MessageService.ShowFatal(exPrg); }
#endif

            Application.RemoveMessageFilter(nfActivity);

            Debug.Assert(GlobalWindowManager.WindowCount == 0);
            Debug.Assert(MessageService.CurrentMessageCount == 0);

            MainCleanUp();

            if (mGlobalNotify != null)
            {
                GC.KeepAlive(mGlobalNotify);
            }
            if (mSingleLock != null)
            {
                GC.KeepAlive(mSingleLock);
            }
        }
Beispiel #17
0
        public static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.DoEvents();

            int nRandomSeed = (int)DateTime.Now.Ticks;

            // Prevent overflow (see Random class constructor)
            if (nRandomSeed == int.MinValue)
            {
                nRandomSeed = 17;
            }
            m_rndGlobal = new Random(nRandomSeed);

            // Set global localized strings
            PwDatabase.LocalizedAppName = PwDefs.ShortProductName;
            Kdb4File.DetermineLanguageId();

            m_appConfig = AppConfigSerializer.Load();
            if (m_appConfig.Logging.Enabled)
            {
                AppLogEx.Open(PwDefs.ShortProductName);
            }

            AppPolicy.Current = m_appConfig.Security.Policy.CloneDeep();

            string strHelpFile = UrlUtil.StripExtension(WinUtil.GetExecutable()) +
                                 ".chm";

            AppHelp.LocalHelpFile = strHelpFile;

            string strLangFile = m_appConfig.Application.LanguageFile;

            if ((strLangFile != null) && (strLangFile.Length > 0))
            {
                strLangFile = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(), true) +
                              strLangFile;

                try
                {
                    m_kpTranslation = KPTranslation.LoadFromFile(strLangFile);

                    KPRes.SetTranslatedStrings(
                        m_kpTranslation.SafeGetStringTableDictionary(
                            "KeePass.Resources.KPRes"));
                    KLRes.SetTranslatedStrings(
                        m_kpTranslation.SafeGetStringTableDictionary(
                            "KeePassLib.Resources.KLRes"));
                }
                catch (FileNotFoundException) { }                // Ignore
                catch (Exception) { Debug.Assert(false); }
            }

            m_cmdLineArgs = new CommandLineArgs(args);

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtRegister] != null)
            {
                ShellUtil.RegisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId,
                                            KPRes.FileExtName, WinUtil.GetExecutable(), PwDefs.ShortProductName, false);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtUnregister] != null)
            {
                ShellUtil.UnregisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId);
                MainCleanUp();
                return;
            }
            else if ((m_cmdLineArgs[AppDefs.CommandLineOptions.Help] != null) ||
                     (m_cmdLineArgs[AppDefs.CommandLineOptions.HelpLong] != null))
            {
                AppHelp.ShowHelp(AppDefs.HelpTopics.CommandLine, null);
                MainCleanUp();
                return;
            }

            try { m_nAppMessage = NativeMethods.RegisterWindowMessage(m_strWndMsgID); }
            catch (Exception) { Debug.Assert(false); }

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ExitAll] != null)
            {
                try
                {
                    NativeMethods.SendMessage((IntPtr)NativeMethods.HWND_BROADCAST,
                                              m_nAppMessage, (IntPtr)AppMessage.Exit, IntPtr.Zero);
                }
                catch (Exception) { Debug.Assert(false); }

                MainCleanUp();
                return;
            }

            Mutex mSingleLock = TrySingleInstanceLock(AppDefs.MutexName, true);

            if ((mSingleLock == null) && m_appConfig.Integration.LimitToSingleInstance)
            {
                ActivatePreviousInstance(args);
                MainCleanUp();
                return;
            }

            Mutex mGlobalNotify = TryGlobalInstanceNotify(AppDefs.MutexNameGlobal);

#if DEBUG
            m_formMain = new MainForm();
            Application.Run(m_formMain);
#else
            try
            {
                m_formMain = new MainForm();
                Application.Run(m_formMain);
            }
            catch (Exception exPrg)
            {
                MessageService.ShowFatal(exPrg);
            }
#endif

            Debug.Assert(GlobalWindowManager.WindowCount == 0);
            Debug.Assert(MessageService.CurrentMessageCount == 0);

            MainCleanUp();

            if (mGlobalNotify != null)
            {
                GC.KeepAlive(mGlobalNotify);
            }
            if (mSingleLock != null)
            {
                GC.KeepAlive(mSingleLock);
            }
        }