Example #1
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
            IStatusLogger slLogger)
        {
            PwGroup pg = pwExportInfo.DataGroup;
            if(pg == null) { Debug.Assert(false); return true; }

            string strBaseName = FilterFileName(string.IsNullOrEmpty(
                Program.Config.Defaults.WinFavsBaseFolderName) ? PwDefs.ShortProductName :
                Program.Config.Defaults.WinFavsBaseFolderName);

            string strRootName = strBaseName + " - " + FilterFileName(pg.Name);
            if(pwExportInfo.ContextDatabase != null)
            {
                if(pg == pwExportInfo.ContextDatabase.RootGroup)
                    strRootName = strBaseName;
            }

            string strFavsRoot = Environment.GetFolderPath(
                Environment.SpecialFolder.Favorites);
            if(string.IsNullOrEmpty(strFavsRoot)) return false;

            string strFavsSub = UrlUtil.EnsureTerminatingSeparator(strFavsRoot,
                false) + strRootName;
            if(Directory.Exists(strFavsSub))
            {
                Directory.Delete(strFavsSub, true);
                WaitForDirCommit(strFavsSub, false);
            }

            ExportGroup(pwExportInfo.DataGroup, strFavsSub);
            return true;
        }
Example #2
0
            public override void Run()
            {
                StatusLogger.UpdateMessage(UiStringKey.exporting_database);
                var          pd     = _app.GetDb().KpDatabase;
                PwExportInfo pwInfo = new PwExportInfo(pd.RootGroup, pd, true);

                try
                {
                    using (var writeTransaction = _app.GetFileStorage(_targetIoc).OpenWriteTransaction(_targetIoc, _app.GetDb().KpDatabase.UseFileTransactions))
                    {
                        Stream sOut = writeTransaction.OpenFile();
                        _fileFormat.Export(pwInfo, sOut, new NullStatusLogger());

                        if (sOut != null)
                        {
                            sOut.Close();
                        }

                        writeTransaction.CommitWrite();
                    }
                    Finish(true);
                }
                catch (Exception ex)
                {
                    Finish(false, ex.Message);
                }
            }
Example #3
0
        // //////////////////////////////////////////////////////////////////
        // Export

        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!DOCTYPE NETSCAPE-Bookmark-file-1>");
            sb.AppendLine("<!-- This is an automatically generated file.");
            sb.AppendLine("     It will be read and overwritten.");
            sb.AppendLine("     DO NOT EDIT! -->");
            sb.AppendLine("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">");
            sb.AppendLine("<TITLE>Bookmarks</TITLE>");
            sb.AppendLine("<H1>Bookmarks</H1>");
            sb.AppendLine();
            sb.AppendLine("<DL><p>");

            ExportGroup(sb, pwExportInfo.DataGroup, 1, pwExportInfo.ContextDatabase);

            sb.AppendLine("</DL>");

            string strData = sb.ToString();

            strData = StrUtil.NormalizeNewLines(strData, false);

            byte[] pbData = StrUtil.Utf8.GetBytes(strData);
            sOutput.Write(pbData, 0, pbData.Length);
            sOutput.Close();
            return(true);
        }
Example #4
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;
		}
Example #5
0
        private void bExport_Click(object sender, EventArgs e)
        {
            PwDatabase db = m_dDB.ElementAt(lbDB.SelectedIndex).Key;

            RefreshHandler(db);
            //if (!m_handler.SetDB(db, false)) return;
            if (!AppPolicy.Current.ExportNoKey && !m_handler.ReAskKey())
            {
                return;
            }

            db = m_handler.OTPDB;
            PwGroup      pg     = db.RootGroup;
            PwExportInfo pwInfo = new PwExportInfo(pg, db, false);

            MessageService.ExternalIncrementMessageCount();
            ShowWarningsLogger swLogger = KeePass.Program.MainForm.CreateShowWarningsLogger();

            swLogger.StartLogging(KPRes.ExportingStatusMsg, true);

            ExportUtil.Export(pwInfo, swLogger);
            swLogger.SetText(string.Empty, KeePassLib.Interfaces.LogStatusType.Info);
            swLogger.EndLogging();
            MessageService.ExternalDecrementMessageCount();
        }
Example #6
0
        private void bExport_Click(object sender, EventArgs e)
        {
            PwDatabase db = m_dDB.ElementAt(lbDB.SelectedIndex).Key;

            RefreshHandler(db);
            //if (!m_handler.SetDB(db, false)) return;
            //If configured, KeePass 2.46 will ask for the masterkey during the export
            //No need to ask here
            if (Tools.KeePassVersion < new Version(2, 46))
            {
                if (!AppPolicy.Current.ExportNoKey && !m_handler.ReAskKey())
                {
                    return;
                }
            }

            db = m_handler.OTPDB;
            PwGroup      pg     = db.RootGroup;
            PwExportInfo pwInfo = new PwExportInfo(pg, db, false);

            MessageService.ExternalIncrementMessageCount();
            ShowWarningsLogger swLogger = KeePass.Program.MainForm.CreateShowWarningsLogger();

            swLogger.StartLogging(KPRes.ExportingStatusMsg, true);
            try
            {
                ExportUtil.Export(pwInfo, swLogger);
                swLogger.SetText(string.Empty, KeePassLib.Interfaces.LogStatusType.Info);
            }
            finally
            {
                swLogger.EndLogging();
                MessageService.ExternalDecrementMessageCount();
            }
        }
Example #7
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            ImageList il = null;
            MainForm  mf = Program.MainForm;

            if ((mf != null) && (mf.ActiveDatabase == pwExportInfo.ContextDatabase))
            {
                il = mf.ClientIcons;
            }

            PrintForm dlg = new PrintForm();

            dlg.InitEx(pwExportInfo.DataGroup, pwExportInfo.ContextDatabase, il,
                       false, -1);

            bool bResult = false;

            try
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    byte[] pb = StrUtil.Utf8.GetBytes(dlg.GeneratedHtml);
                    sOutput.Write(pb, 0, pb.Length);
                    sOutput.Close();

                    bResult = true;
                }
            }
            finally { UIUtil.DestroyForm(dlg); }

            return(bResult);
        }
Example #8
0
        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();
            }

            KdbxFile kdb = new KdbxFile(pd);

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

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

            return(true);
        }
Example #9
0
        private static string GetFolderName(bool bForceRoot, PwExportInfo pwExportInfo,
                                            PwGroup pg)
        {
            string strBaseName = UrlUtil.FilterFileName(string.IsNullOrEmpty(
                                                            Program.Config.Defaults.WinFavsBaseFolderName) ? PwDefs.ShortProductName :
                                                        Program.Config.Defaults.WinFavsBaseFolderName);

            if (bForceRoot || (pwExportInfo == null) || (pg == null))
            {
                return(strBaseName);
            }

            string strGroup    = UrlUtil.FilterFileName(pg.Name);
            string strRootName = strBaseName;

            if (strGroup.Length > 0)
            {
                strRootName += (" - " + strGroup);
            }

            if (pwExportInfo.ContextDatabase != null)
            {
                if (pg == pwExportInfo.ContextDatabase.RootGroup)
                {
                    strRootName = strBaseName;
                }
            }

            return(strRootName);
        }
Example #10
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            PwDatabase pd = (pwExportInfo.ContextDatabase ?? new PwDatabase());

            string strTempFile = Program.TempFilesPool.GetTempFileName(false);

            try
            {
                KdbFile kdb = new KdbFile(pd, slLogger);
                kdb.Save(strTempFile, pwExportInfo.DataGroup);

                byte[] pbKdb = File.ReadAllBytes(strTempFile);
                sOutput.Write(pbKdb, 0, pbKdb.Length);
                MemUtil.ZeroByteArray(pbKdb);
            }
            catch (Exception exKdb)
            {
                if (slLogger != null)
                {
                    slLogger.SetText(exKdb.Message, LogStatusType.Error);
                }

                return(false);
            }
            finally
            {
                Program.TempFilesPool.Delete(strTempFile);
            }

            return(true);
        }
        private static void ExportDatabaseFile(EcasAction a, EcasContext ctx)
        {
            string strPath = EcasUtil.GetParamString(a.Parameters, 0, true);
            // if(string.IsNullOrEmpty(strPath)) return; // Allow no-file exports
            string strFormat = EcasUtil.GetParamString(a.Parameters, 1, true);

            if (string.IsNullOrEmpty(strFormat))
            {
                return;
            }
            string strGroup = EcasUtil.GetParamString(a.Parameters, 2, true);
            string strTag   = EcasUtil.GetParamString(a.Parameters, 3, true);

            PwDatabase pd = Program.MainForm.ActiveDatabase;

            if ((pd == null) || !pd.IsOpen)
            {
                return;
            }

            PwGroup pg = pd.RootGroup;

            if (!string.IsNullOrEmpty(strGroup))
            {
                char    chSep = strGroup[0];
                PwGroup pgSub = pg.FindCreateSubTree(strGroup.Substring(1),
                                                     new char[] { chSep }, false);
                pg = (pgSub ?? (new PwGroup(true, true, KPRes.Group, PwIcon.Folder)));
            }

            if (!string.IsNullOrEmpty(strTag))
            {
                pg = pg.CloneDeep();

                GroupHandler gh = delegate(PwGroup pgSub)
                {
                    PwObjectList <PwEntry> l = pgSub.Entries;
                    long n = (long)l.UCount;
                    for (long i = n - 1; i >= 0; --i)
                    {
                        if (!l.GetAt((uint)i).HasTag(strTag))
                        {
                            l.RemoveAt((uint)i);
                        }
                    }

                    return(true);
                };

                gh(pg);
                pg.TraverseTree(TraversalMethod.PreOrder, gh, null);
            }

            PwExportInfo     pei = new PwExportInfo(pg, pd, true);
            IOConnectionInfo ioc = (!string.IsNullOrEmpty(strPath) ?
                                    IOConnectionInfo.FromPath(strPath) : null);

            ExportUtil.Export(pei, strFormat, ioc);
        }
Example #12
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            KdbxFile kdbx = new KdbxFile(pwExportInfo.ContextDatabase);

            kdbx.Save(sOutput, pwExportInfo.DataGroup, KdbxFormat.Default, slLogger);
            return(true);
        }
Example #13
0
        private bool ExportEx(PwExportInfo pwExportInfo, Stream sOutput,
                              IStatusLogger slLogger, string strXslFile)
        {
            XslCompiledTransform xsl = new XslCompiledTransform();

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

            byte[] pbData;
            using (MemoryStream ms = new MemoryStream())
            {
                PwDatabase pd = (pwExportInfo.ContextDatabase ?? new PwDatabase());
                KdbxFile   f  = new KdbxFile(pd);
                f.Save(ms, pwExportInfo.DataGroup, KdbxFormat.PlainXml, slLogger);

                pbData = ms.ToArray();
            }
            if (pbData == null)
            {
                throw new OutOfMemoryException();
            }

            XmlWriterSettings xws = xsl.OutputSettings;

            if (xws == null)
            {
                xws = new XmlWriterSettings();

                xws.CheckCharacters  = false;
                xws.ConformanceLevel = ConformanceLevel.Auto;
                xws.Encoding         = StrUtil.Utf8;
                // xws.Indent = false;
                xws.IndentChars        = "\t";
                xws.NewLineChars       = MessageService.NewLine;
                xws.NewLineHandling    = NewLineHandling.None;
                xws.OmitXmlDeclaration = true;
            }

            using (MemoryStream msIn = new MemoryStream(pbData, false))
            {
                using (XmlReader xrIn = XmlReader.Create(msIn))
                {
                    using (XmlWriter xwOut = XmlWriter.Create(sOutput, xws))
                    {
                        xsl.Transform(xrIn, xwOut);
                    }
                }
            }

            MemUtil.ZeroByteArray(pbData);
            return(true);
        }
Example #14
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            string           strFilter = UIUtil.CreateFileTypeFilter("xsl", KPRes.XslFileType, true);
            OpenFileDialogEx dlgXsl    = UIUtil.CreateOpenFileDialog(KPRes.XslSelectFile,
                                                                     strFilter, 1, "xsl", false, AppDefs.FileDialogContext.Xsl);

            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());
            KdbxFile   kdb = new KdbxFile(pd);

            kdb.Save(msDataXml, pwExportInfo.DataGroup, KdbxFormat.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);
        }
Example #15
0
		public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
			IStatusLogger slLogger)
		{
			string strXslFile;
			pwExportInfo.Parameters.TryGetValue(ParamXslFile, out strXslFile);

			if(string.IsNullOrEmpty(strXslFile))
				strXslFile = UIGetXslFile();
			if(string.IsNullOrEmpty(strXslFile))
				return false;

			return ExportEx(pwExportInfo, sOutput, slLogger, strXslFile);
		}
Example #16
0
		private bool ExportEx(PwExportInfo pwExportInfo, Stream sOutput,
			IStatusLogger slLogger, string strXslFile)
		{
			XslCompiledTransform xsl = new XslCompiledTransform();
			try { xsl.Load(strXslFile); }
			catch(Exception exXsl)
			{
				throw new NotSupportedException(strXslFile + MessageService.NewParagraph +
					KPRes.NoXslFile + MessageService.NewParagraph + exXsl.Message);
			}

			byte[] pbData;
			using(MemoryStream ms = new MemoryStream())
			{
				PwDatabase pd = (pwExportInfo.ContextDatabase ?? new PwDatabase());
				KdbxFile f = new KdbxFile(pd);
				f.Save(ms, pwExportInfo.DataGroup, KdbxFormat.PlainXml, slLogger);

				pbData = ms.ToArray();
			}
			if(pbData == null) throw new OutOfMemoryException();

			XmlWriterSettings xws = xsl.OutputSettings;
			if(xws == null)
			{
				xws = new XmlWriterSettings();

				xws.CheckCharacters = false;
				xws.ConformanceLevel = ConformanceLevel.Auto;
				xws.Encoding = StrUtil.Utf8;
				// xws.Indent = false;
				xws.IndentChars = "\t";
				xws.NewLineChars = MessageService.NewLine;
				xws.NewLineHandling = NewLineHandling.None;
				xws.OmitXmlDeclaration = true;
			}

			using(MemoryStream msIn = new MemoryStream(pbData, false))
			{
				using(XmlReader xrIn = XmlReader.Create(msIn))
				{
					using(XmlWriter xwOut = XmlWriter.Create(sOutput, xws))
					{
						xsl.Transform(xrIn, xwOut);
					}
				}
			}

			MemUtil.ZeroByteArray(pbData);
			return true;
		}
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput, IStatusLogger slLogger)
        {
            slLogger.SetText("Collecting entries...", LogStatusType.Info);

            var entries = ConvertGroup(pwExportInfo.DataGroup, slLogger);

            slLogger.SetText("Encrypting backup...", LogStatusType.Info);

            var filewriter = new StreamWriter(sOutput);

            filewriter.Write(entries);
            filewriter.Flush();

            return(true);
        }
Example #18
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
            IStatusLogger slLogger)
        {
            string strFilter = UIUtil.CreateFileTypeFilter("xsl", KPRes.XslFileType, true);
            OpenFileDialogEx dlgXsl = UIUtil.CreateOpenFileDialog(KPRes.XslSelectFile,
                strFilter, 1, "xsl", false, AppDefs.FileDialogContext.Xsl);

            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());
            KdbxFile kdb = new KdbxFile(pd);
            kdb.Save(msDataXml, pwExportInfo.DataGroup, KdbxFormat.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;
        }
Example #19
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            PwGroup pg = pwExportInfo.DataGroup;

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

            string strFavsRoot = Environment.GetFolderPath(
                Environment.SpecialFolder.Favorites);

            if (string.IsNullOrEmpty(strFavsRoot))
            {
                return(false);
            }

            uint uTotalGroups, uTotalEntries, uEntriesProcessed = 0;

            pwExportInfo.DataGroup.GetCounts(true, out uTotalGroups, out uTotalEntries);

            if (!m_bInRoot)            // In folder
            {
                string strRootName = GetFolderName(false, pwExportInfo, pg);

                string strFavsSub = UrlUtil.EnsureTerminatingSeparator(
                    strFavsRoot, false) + strRootName;
                if (Directory.Exists(strFavsSub))
                {
                    Directory.Delete(strFavsSub, true);
                    WaitForDirCommit(strFavsSub, false);
                }

                ExportGroup(pwExportInfo.DataGroup, strFavsSub, slLogger,
                            uTotalEntries, ref uEntriesProcessed, pwExportInfo);
            }
            else             // In root
            {
                DeletePreviousExport(strFavsRoot, slLogger);
                ExportGroup(pwExportInfo.DataGroup, strFavsRoot, slLogger,
                            uTotalEntries, ref uEntriesProcessed, pwExportInfo);
            }

            Debug.Assert(uEntriesProcessed == uTotalEntries);
            return(true);
        }
Example #20
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
            IStatusLogger slLogger)
        {
            PrintForm dlg = new PrintForm();
            dlg.InitEx(pwExportInfo.DataGroup, false);

            if(dlg.ShowDialog() == DialogResult.OK)
            {
                StreamWriter sw = new StreamWriter(sOutput, Encoding.UTF8);
                sw.Write(dlg.GeneratedHtml);
                sw.Close();

                return true;
            }

            return false;
        }
Example #21
0
		public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
			IStatusLogger slLogger)
		{
			PrintForm dlg = new PrintForm();
			dlg.InitEx(pwExportInfo.DataGroup, false, -1);

			if(dlg.ShowDialog() == DialogResult.OK)
			{
				byte[] pb = Encoding.UTF8.GetBytes(dlg.GeneratedHtml);
				sOutput.Write(pb, 0, pb.Length);
				sOutput.Close();

				return true;
			}

			return false;
		}
Example #22
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            PrintForm dlg = new PrintForm();

            dlg.InitEx(pwExportInfo.DataGroup, false, -1);

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                byte[] pb = Encoding.UTF8.GetBytes(dlg.GeneratedHtml);
                sOutput.Write(pb, 0, pb.Length);
                sOutput.Close();

                return(true);
            }

            return(false);
        }
Example #23
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            string strXslFile;

            pwExportInfo.Parameters.TryGetValue(ParamXslFile, out strXslFile);

            if (string.IsNullOrEmpty(strXslFile))
            {
                strXslFile = UIGetXslFile();
            }
            if (string.IsNullOrEmpty(strXslFile))
            {
                return(false);
            }

            return(ExportEx(pwExportInfo, sOutput, slLogger, strXslFile));
        }
Example #24
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            PrintForm dlg = new PrintForm();

            dlg.InitEx(pwExportInfo.DataGroup, false);

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                StreamWriter sw = new StreamWriter(sOutput, Encoding.UTF8);
                sw.Write(dlg.GeneratedHtml);
                sw.Close();

                return(true);
            }

            return(false);
        }
Example #25
0
        /// <summary>Writes to a xml file</summary>
        /// <param name="pwExportInfo">The information to be exported</param>
        /// <param name="sOutput">A stream to the xml file/entry</param>
        /// <param name="slLogger">Logger to be used</param>
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput, IStatusLogger slLogger)
        {
            XmlSerializer xml        = new XmlSerializer(typeof(WlanProfile));
            WlanProfile   curProfile = new WlanProfile();

            if (slLogger != null)
            {
                slLogger.SetText("Schreibe XML", LogStatusType.Info);
                slLogger.SetProgress(0);
            }

            double progress = 0;
            String name;

            foreach (PwEntry entry in pwExportInfo.DataGroup.GetEntries(true))
            {
                if (slLogger != null)
                {
                    name = entry.Strings.Get(PwDefs.TitleField).ReadString();
                    if ((name == null) || (name.Length == 0))
                    {
                        name = entry.Strings.Get(FieldNames.SSID).ReadString();
                        if ((name == null) || (name.Length == 0))
                        {
                            continue;
                        }
                    }

                    slLogger.SetText(String.Format("Schreibe Wifi-Information {0}", name), LogStatusType.Info);
                    progress += 50 / pwExportInfo.DataGroup.GetEntriesCount(true);
                    slLogger.SetProgress((uint)progress);
                }

                curProfile.LoadFrom(pwExportInfo.ContextDatabase, entry);
                xml.Serialize(sOutput, curProfile);
                if (slLogger != null)
                {
                    progress += 50 / pwExportInfo.DataGroup.GetEntriesCount(true);
                    slLogger.SetProgress((uint)progress);
                }
            }

            return(true);
        }
Example #26
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            PwGroup pg = pwExportInfo.DataGroup;

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

            string strBaseName = FilterFileName(string.IsNullOrEmpty(
                                                    Program.Config.Defaults.WinFavsBaseFolderName) ? PwDefs.ShortProductName :
                                                Program.Config.Defaults.WinFavsBaseFolderName);

            string strRootName = strBaseName + " - " + FilterFileName(pg.Name);

            if (pwExportInfo.ContextDatabase != null)
            {
                if (pg == pwExportInfo.ContextDatabase.RootGroup)
                {
                    strRootName = strBaseName;
                }
            }

            string strFavsRoot = Environment.GetFolderPath(
                Environment.SpecialFolder.Favorites);

            if (string.IsNullOrEmpty(strFavsRoot))
            {
                return(false);
            }

            string strFavsSub = UrlUtil.EnsureTerminatingSeparator(strFavsRoot,
                                                                   false) + strRootName;

            if (Directory.Exists(strFavsSub))
            {
                Directory.Delete(strFavsSub, true);
                WaitForDirCommit(strFavsSub, false);
            }

            ExportGroup(pwExportInfo.DataGroup, strFavsSub);
            return(true);
        }
Example #27
0
        private bool ExportEx(PwExportInfo pwExportInfo, Stream sOutput,
                              IStatusLogger slLogger, string strXslFile)
        {
            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());
            KdbxFile   kdb = new KdbxFile(pd);

            kdb.Save(msDataXml, pwExportInfo.DataGroup, KdbxFormat.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);
        }
Example #28
0
		public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
			IStatusLogger slLogger)
		{
			PrintForm dlg = new PrintForm();
			dlg.InitEx(pwExportInfo.DataGroup, false, -1);

			bool bResult = false;
			if(dlg.ShowDialog() == DialogResult.OK)
			{
				byte[] pb = StrUtil.Utf8.GetBytes(dlg.GeneratedHtml);
				sOutput.Write(pb, 0, pb.Length);
				sOutput.Close();

				bResult = true;
			}

			UIUtil.DestroyForm(dlg);
			return bResult;
		}
Example #29
0
		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;
		}
Example #30
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
			IStatusLogger slLogger)
        {
            PwGroup pg = (pwExportInfo.DataGroup ?? ((pwExportInfo.ContextDatabase !=
                null) ? pwExportInfo.ContextDatabase.RootGroup : null));

            StreamWriter sw = new StreamWriter(sOutput, StrUtil.Utf8);
            sw.Write("\"Account\",\"Login Name\",\"Password\",\"Web Site\",\"Comments\"\r\n");

            EntryHandler eh = delegate(PwEntry pe)
            {
                WriteCsvEntry(sw, pe);
                return true;
            };

            if(pg != null) pg.TraverseTree(TraversalMethod.PreOrder, null, eh);

            sw.Close();
            return true;
        }
Example #31
0
		private static string GetFolderName(bool bForceRoot, PwExportInfo pwExportInfo,
			PwGroup pg)
		{
			string strBaseName = UrlUtil.FilterFileName(string.IsNullOrEmpty(
				Program.Config.Defaults.WinFavsBaseFolderName) ? PwDefs.ShortProductName :
				Program.Config.Defaults.WinFavsBaseFolderName);
			if(bForceRoot || (pwExportInfo == null) || (pg == null))
				return strBaseName;

			string strGroup = UrlUtil.FilterFileName(pg.Name);
			string strRootName = strBaseName;
			if(strGroup.Length > 0) strRootName += (" - " + strGroup);

			if(pwExportInfo.ContextDatabase != null)
			{
				if(pg == pwExportInfo.ContextDatabase.RootGroup)
					strRootName = strBaseName;
			}

			return strRootName;
		}
Example #32
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            PrintForm dlg = new PrintForm();

            dlg.InitEx(pwExportInfo.DataGroup, false, -1);

            bool bResult = false;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                byte[] pb = StrUtil.Utf8.GetBytes(dlg.GeneratedHtml);
                sOutput.Write(pb, 0, pb.Length);
                sOutput.Close();

                bResult = true;
            }

            UIUtil.DestroyForm(dlg);
            return(bResult);
        }
Example #33
0
            private void OTPDB_Save()
            {
                if (!Valid || !OTPDB_Opened || !OTPDB.Modified)
                {
                    return;
                }
                OTPDB.Modified = false;
                UpdateDBHeader();
                PwExportInfo pei = new PwExportInfo(OTPDB.RootGroup, OTPDB);

                using (var s = new MemoryStream())
                {
                    IStatusLogger sl = Program.MainForm.CreateShowWarningsLogger();
                    sl.StartLogging(PluginTranslate.OTPDB_Save, true);
                    m_FFP.Export(pei, s, sl);
                    sl.EndLogging();
                    s.Flush();
                    SetOTPDBData(s.GetBuffer());
                }
                FlagChanged(false);
            }
Example #34
0
		private bool ExportEx(PwExportInfo pwExportInfo, Stream sOutput,
			IStatusLogger slLogger, string strXslFile)
		{
			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());
			KdbxFile kdb = new KdbxFile(pd);
			kdb.Save(msDataXml, pwExportInfo.DataGroup, KdbxFormat.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;
		}
Example #35
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput, IStatusLogger slLogger)
        {
            var form = new OptionForm();

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

            slLogger.SetText("Collecting entries...", LogStatusType.Info);

            var entries = ConvertGroup(pwExportInfo.DataGroup, slLogger);

            slLogger.SetText("Encrypting backup...", LogStatusType.Info);

            var pfp = new PfpConvert();

            pfp.Save(sOutput, form.MasterPassword, entries);

            slLogger.SetText($"Exported {entries.Count} entries.", LogStatusType.Info);

            return(true);
        }
Example #36
0
            public override void Run()
            {
                StatusLogger.UpdateMessage(UiStringKey.exporting_database);
                var          pd     = _app.CurrentDb.KpDatabase;
                PwExportInfo pwInfo = new PwExportInfo(pd.RootGroup, pd, true);

                try
                {
                    var fileStorage = _app.GetFileStorage(_targetIoc);
                    if (fileStorage is IOfflineSwitchable)
                    {
                        ((IOfflineSwitchable)fileStorage).IsOffline = false;
                    }
                    using (var writeTransaction = fileStorage.OpenWriteTransaction(_targetIoc, _app.GetBooleanPreference(PreferenceKey.UseFileTransactions)))
                    {
                        Stream sOut = writeTransaction.OpenFile();
                        _fileFormat.Export(pwInfo, sOut, new NullStatusLogger());

                        if (sOut != null)
                        {
                            sOut.Close();
                        }

                        writeTransaction.CommitWrite();
                    }
                    if (fileStorage is IOfflineSwitchable)
                    {
                        ((IOfflineSwitchable)fileStorage).IsOffline = App.Kp2a.OfflineMode;
                    }

                    Finish(true);
                }
                catch (Exception ex)
                {
                    Finish(false, ex.Message);
                }
            }
Example #37
0
        /* public override void Import(PwDatabase pwStorage, Stream sInput,
         *      IStatusLogger slLogger)
         * {
         *      StreamReader sr = new StreamReader(sInput, Encoding.UTF8);
         *      string strFileContents = sr.ReadToEnd();
         *      sr.Close();
         *
         *      CharStream csSource = new CharStream(strFileContents);
         *
         *      while(true)
         *      {
         *              if(ReadEntry(pwStorage, csSource) == false)
         *                      break;
         *      }
         * }
         *
         * private static bool ReadEntry(PwDatabase pwStorage, CharStream csSource)
         * {
         *      PwEntry pe = new PwEntry(true, true);
         *
         *      string strTitle = ReadCsvField(csSource);
         *      if(strTitle == null) return false; // No entry available
         *
         *      string strUser = ReadCsvField(csSource);
         *      if(strUser == null) throw new InvalidDataException();
         *
         *      string strPassword = ReadCsvField(csSource);
         *      if(strPassword == null) throw new InvalidDataException();
         *
         *      string strUrl = ReadCsvField(csSource);
         *      if(strUrl == null) throw new InvalidDataException();
         *
         *      string strNotes = ReadCsvField(csSource);
         *      if(strNotes == null) throw new InvalidDataException();
         *
         *      if((strTitle == "Account") && (strUser == "Login Name") &&
         *              (strPassword == "Password") && (strUrl == "Web Site") &&
         *              (strNotes == "Comments"))
         *      {
         *              return true; // Ignore header entry
         *      }
         *
         *      pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
         *              pwStorage.MemoryProtection.ProtectTitle, strTitle));
         *      pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
         *              pwStorage.MemoryProtection.ProtectUserName, strUser));
         *      pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
         *              pwStorage.MemoryProtection.ProtectPassword, strPassword));
         *      pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
         *              pwStorage.MemoryProtection.ProtectUrl, strUrl));
         *      pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
         *              pwStorage.MemoryProtection.ProtectNotes, strNotes));
         *
         *      pwStorage.RootGroup.AddEntry(pe, true);
         *      return true;
         * }
         *
         * private static string ReadCsvField(CharStream csSource)
         * {
         *      StringBuilder sb = new StringBuilder();
         *      bool bInField = false;
         *
         *      while(true)
         *      {
         *              char ch = csSource.ReadChar();
         *              if(ch == char.MinValue)
         *                      return null;
         *
         *              if((ch == '\"') && !bInField)
         *                      bInField = true;
         *              else if((ch == '\"') && bInField)
         *                      break;
         *              else if(ch == '\\')
         *              {
         *                      char chSub = csSource.ReadChar();
         *                      if(chSub == char.MinValue)
         *                              throw new InvalidDataException();
         *
         *                      sb.Append(chSub);
         *              }
         *              else if(bInField)
         *                      sb.Append(ch);
         *      }
         *
         *      return sb.ToString();
         * } */

        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            PwGroup pg = (pwExportInfo.DataGroup ?? ((pwExportInfo.ContextDatabase !=
                                                      null) ? pwExportInfo.ContextDatabase.RootGroup : null));

            StreamWriter sw = new StreamWriter(sOutput, StrUtil.Utf8);

            sw.Write("\"Account\",\"Login Name\",\"Password\",\"Web Site\",\"Comments\"\r\n");

            EntryHandler eh = delegate(PwEntry pe)
            {
                WriteCsvEntry(sw, pe);
                return(true);
            };

            if (pg != null)
            {
                pg.TraverseTree(TraversalMethod.PreOrder, null, eh);
            }

            sw.Close();
            return(true);
        }
        private static void ExportDatabaseFile(EcasAction a, EcasContext ctx)
        {
            string strPath = EcasUtil.GetParamString(a.Parameters, 0, true);
            // if(string.IsNullOrEmpty(strPath)) return; // Allow no-file exports
            string strFormat = EcasUtil.GetParamString(a.Parameters, 1, true);

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

            PwDatabase pd = Program.MainForm.ActiveDatabase;

            if ((pd == null) || !pd.IsOpen)
            {
                return;
            }

            PwExportInfo     pei = new PwExportInfo(pd.RootGroup, pd, true);
            IOConnectionInfo ioc = (!string.IsNullOrEmpty(strPath) ?
                                    IOConnectionInfo.FromPath(strPath) : null);

            ExportUtil.Export(pei, strFormat, ioc);
        }
Example #39
0
        // //////////////////////////////////////////////////////////////////
        // Export
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
			IStatusLogger slLogger)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!DOCTYPE NETSCAPE-Bookmark-file-1>");
            sb.AppendLine("<!-- This is an automatically generated file.");
            sb.AppendLine("     It will be read and overwritten.");
            sb.AppendLine("     DO NOT EDIT! -->");
            sb.AppendLine("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">");
            sb.AppendLine("<TITLE>Bookmarks</TITLE>");
            sb.AppendLine("<H1>Bookmarks</H1>");
            sb.AppendLine();
            sb.AppendLine("<DL><p>");

            ExportGroup(sb, pwExportInfo.DataGroup, 1, pwExportInfo.ContextDatabase);

            sb.AppendLine("</DL>");

            string strData = sb.ToString();
            strData = StrUtil.NormalizeNewLines(strData, false);

            byte[] pbData = StrUtil.Utf8.GetBytes(strData);
            sOutput.Write(pbData, 0, pbData.Length);
            sOutput.Close();
            return true;
        }
Example #40
0
        private static void ExportEntry(PwEntry pe, string strDir, PwExportInfo pxi)
        {
            PwDatabase pd  = ((pxi != null) ? pxi.ContextDatabase : null);
            SprContext ctx = new SprContext(pe, pd, SprCompileFlags.NonActive, false, false);

            KeyValuePair <string, string>?okvpCmd = null;
            string strUrl = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.UrlField), ctx);

            if (WinUtil.IsCommandLineUrl(strUrl))
            {
                strUrl = WinUtil.GetCommandLineFromUrl(strUrl);

                if (!NativeLib.IsUnix())                // LNKs only supported on Windows
                {
                    string strApp, strArgs;
                    StrUtil.SplitCommandLine(strUrl, out strApp, out strArgs);

                    if (!string.IsNullOrEmpty(strApp))
                    {
                        okvpCmd = new KeyValuePair <string, string>(strApp, strArgs);
                    }
                }
            }
            if (string.IsNullOrEmpty(strUrl))
            {
                return;
            }
            bool bLnk = okvpCmd.HasValue;

            string strTitleCmp = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.TitleField), ctx);

            if (string.IsNullOrEmpty(strTitleCmp))
            {
                strTitleCmp = KPRes.Entry;
            }
            string strTitle = Program.Config.Defaults.WinFavsFileNamePrefix + strTitleCmp;

            string strSuffix = Program.Config.Defaults.WinFavsFileNameSuffix +
                               (bLnk ? ".lnk" : ".url");

            strSuffix = UrlUtil.FilterFileName(strSuffix);

            string strFileBase = (UrlUtil.EnsureTerminatingSeparator(strDir,
                                                                     false) + UrlUtil.FilterFileName(strTitle));
            string strFile = strFileBase + strSuffix;
            int    iFind   = 2;

            while (File.Exists(strFile))
            {
                strFile = strFileBase + " (" + iFind.ToString() + ")" + strSuffix;
                ++iFind;
            }

            if (!Directory.Exists(strDir))
            {
                try { Directory.CreateDirectory(strDir); }
                catch (Exception exDir)
                {
                    throw new Exception(strDir + MessageService.NewParagraph + exDir.Message);
                }

                WaitForDirCommit(strDir, true);
            }

            try
            {
                if (bLnk)
                {
                    int    ccMaxDesc = NativeMethods.INFOTIPSIZE - 1 - LnkDescSuffix.Length;
                    string strDesc   = StrUtil.CompactString3Dots(strUrl, ccMaxDesc) +
                                       LnkDescSuffix;

                    ShellLinkEx sl = new ShellLinkEx(okvpCmd.Value.Key,
                                                     okvpCmd.Value.Value, strDesc);
                    sl.Save(strFile);
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine(@"[InternetShortcut]");
                    sb.AppendLine(@"URL=" + strUrl);                     // No additional line break
                    sb.AppendLine(@"[" + PwDefs.ShortProductName + @"]");
                    sb.AppendLine(IniTypeKey + @"=" + IniTypeValue);
                    // Terminating line break is important

                    File.WriteAllText(strFile, sb.ToString(), Encoding.Default);
                }
            }
            catch (Exception exWrite)
            {
                throw new Exception(strFile + MessageService.NewParagraph + exWrite.Message);
            }
        }
Example #41
0
        private static void ExportGroup(PwGroup pg, string strDir, IStatusLogger slLogger,
                                        uint uTotalEntries, ref uint uEntriesProcessed, PwExportInfo pxi)
        {
            foreach (PwEntry pe in pg.Entries)
            {
                ExportEntry(pe, strDir, pxi);

                ++uEntriesProcessed;
                if (slLogger != null)
                {
                    slLogger.SetProgress(((uEntriesProcessed * 50U) /
                                          uTotalEntries) + 50U);
                }
            }

            foreach (PwGroup pgSub in pg.Groups)
            {
                string strGroup = UrlUtil.FilterFileName(pgSub.Name);
                string strSub   = (UrlUtil.EnsureTerminatingSeparator(strDir, false) +
                                   (!string.IsNullOrEmpty(strGroup) ? strGroup : KPRes.Group));

                ExportGroup(pgSub, strSub, slLogger, uTotalEntries,
                            ref uEntriesProcessed, pxi);
            }
        }
Example #42
0
		public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
			IStatusLogger slLogger)
		{
			PwDatabase pd = pwExportInfo.ContextDatabase;
			PwGroup pgRoot = pwExportInfo.DataGroup;

			// Remove everything that requires KDBX 4 or higher;
			// see also KdbxFile.GetMinKdbxVersion

			KdfParameters pKdf = pd.KdfParameters;
			AesKdf kdfAes = new AesKdf();
			if(!kdfAes.Uuid.Equals(pKdf.KdfUuid))
				pd.KdfParameters = kdfAes.GetDefaultParameters();

			VariantDictionary vdPublic = pd.PublicCustomData;
			pd.PublicCustomData = new VariantDictionary();

			List<PwGroup> lCustomGK = new List<PwGroup>();
			List<StringDictionaryEx> lCustomGV = new List<StringDictionaryEx>();
			List<PwEntry> lCustomEK = new List<PwEntry>();
			List<StringDictionaryEx> lCustomEV = new List<StringDictionaryEx>();

			GroupHandler gh = delegate(PwGroup pg)
			{
				if(pg == null) { Debug.Assert(false); return true; }
				if(pg.CustomData.Count > 0)
				{
					lCustomGK.Add(pg);
					lCustomGV.Add(pg.CustomData);
					pg.CustomData = new StringDictionaryEx();
				}
				return true;
			};
			EntryHandler eh = delegate(PwEntry pe)
			{
				if(pe == null) { Debug.Assert(false); return true; }
				if(pe.CustomData.Count > 0)
				{
					lCustomEK.Add(pe);
					lCustomEV.Add(pe.CustomData);
					pe.CustomData = new StringDictionaryEx();
				}
				return true;
			};

			gh(pgRoot);
			pgRoot.TraverseTree(TraversalMethod.PreOrder, gh, eh);

			try
			{
				KdbxFile kdbx = new KdbxFile(pd);
				kdbx.ForceVersion = KdbxFile.FileVersion32_3;
				kdbx.Save(sOutput, pgRoot, KdbxFormat.Default, slLogger);
			}
			finally
			{
				// Restore

				pd.KdfParameters = pKdf;
				pd.PublicCustomData = vdPublic;

				for(int i = 0; i < lCustomGK.Count; ++i)
					lCustomGK[i].CustomData = lCustomGV[i];
				for(int i = 0; i < lCustomEK.Count; ++i)
					lCustomEK[i].CustomData = lCustomEV[i];
			}

			return true;
		}
Example #43
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
            IStatusLogger slLogger)
        {
            PwGroup pg = pwExportInfo.DataGroup;
            if(pg == null) { Debug.Assert(false); return true; }

            string strFavsRoot = Environment.GetFolderPath(
                Environment.SpecialFolder.Favorites);
            if(string.IsNullOrEmpty(strFavsRoot)) return false;

            uint uTotalGroups, uTotalEntries, uEntriesProcessed = 0;
            pwExportInfo.DataGroup.GetCounts(true, out uTotalGroups, out uTotalEntries);

            if(!m_bInRoot) // In folder
            {
                string strRootName = GetFolderName(false, pwExportInfo, pg);

                string strFavsSub = UrlUtil.EnsureTerminatingSeparator(
                    strFavsRoot, false) + strRootName;
                if(Directory.Exists(strFavsSub))
                {
                    Directory.Delete(strFavsSub, true);
                    WaitForDirCommit(strFavsSub, false);
                }

                ExportGroup(pwExportInfo.DataGroup, strFavsSub, slLogger,
                    uTotalEntries, ref uEntriesProcessed);
            }
            else // In root
            {
                DeletePreviousExport(strFavsRoot, slLogger);
                ExportGroup(pwExportInfo.DataGroup, strFavsRoot, slLogger,
                    uTotalEntries, ref uEntriesProcessed);
            }

            Debug.Assert(uEntriesProcessed == uTotalEntries);
            return true;
        }
        private static void PerformExport(PwDatabase pwDb, CommandLineArgs args)
        {
            FileFormatProvider prov = GetFormatProv(args);

            if (prov == null)
            {
                return;
            }

            if (!prov.SupportsExport)
            {
                KPScript.Program.WriteLineColored("E: No export support for this format!",
                                                  ConsoleColor.Red);
                return;
            }

            if (!prov.TryBeginExport())
            {
                KPScript.Program.WriteLineColored("E: Format initialization failed!",
                                                  ConsoleColor.Red);
                return;
            }

            FileStream fs;

            try
            {
                fs = new FileStream(args["outfile"], FileMode.Create, FileAccess.Write,
                                    FileShare.None);
            }
            catch (Exception exFs)
            {
                KPScript.Program.WriteLineColored("E: " + exFs.Message, ConsoleColor.Red);
                return;
            }

            PwGroup pg  = pwDb.RootGroup;
            string  str = args[EntryMod.ParamGroupPath];

            if (!string.IsNullOrEmpty(str))
            {
                pg = pg.FindCreateSubTree(str, new char[] { '/' }, false);
                if (pg == null)
                {
                    KPScript.Program.WriteLineColored(@"E: Group '" + str +
                                                      @"' not found!", ConsoleColor.Red);
                    return;
                }
            }

            PwExportInfo pwInfo = new PwExportInfo(pg, pwDb, true);

            str = args[ParamXslFileCL];
            if (!string.IsNullOrEmpty(str))
            {
                pwInfo.Parameters[ParamXslFile] = str;
            }

            if (prov.Export(pwInfo, fs, null))
            {
                KPScript.Program.WriteLineColored("OK: Export succeeded!", ConsoleColor.Green);
            }
            else
            {
                KPScript.Program.WriteLineColored("E: Export failed!", ConsoleColor.Red);
            }
        }
Example #45
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
                                    IStatusLogger slLogger)
        {
            PwDatabase pd     = pwExportInfo.ContextDatabase;
            PwGroup    pgRoot = pwExportInfo.DataGroup;

            // Remove everything that requires KDBX 4 or higher;
            // see also KdbxFile.GetMinKdbxVersion

            PwUuid puCipher = pd.DataCipherUuid;

            if (puCipher.Equals(ChaCha20Engine.ChaCha20Uuid))
            {
                pd.DataCipherUuid = StandardAesEngine.AesUuid;
            }

            KdfParameters pKdf   = pd.KdfParameters;
            AesKdf        kdfAes = new AesKdf();

            if (!pKdf.KdfUuid.Equals(kdfAes.Uuid))
            {
                pd.KdfParameters = kdfAes.GetDefaultParameters();
            }

            VariantDictionary vdPublic = pd.PublicCustomData;

            pd.PublicCustomData = new VariantDictionary();

            List <PwGroup>            lCustomGK = new List <PwGroup>();
            List <StringDictionaryEx> lCustomGV = new List <StringDictionaryEx>();
            List <PwEntry>            lCustomEK = new List <PwEntry>();
            List <StringDictionaryEx> lCustomEV = new List <StringDictionaryEx>();

            GroupHandler gh = delegate(PwGroup pg)
            {
                if (pg == null)
                {
                    Debug.Assert(false); return(true);
                }
                if (pg.CustomData.Count > 0)
                {
                    lCustomGK.Add(pg);
                    lCustomGV.Add(pg.CustomData);
                    pg.CustomData = new StringDictionaryEx();
                }
                return(true);
            };
            EntryHandler eh = delegate(PwEntry pe)
            {
                if (pe == null)
                {
                    Debug.Assert(false); return(true);
                }
                if (pe.CustomData.Count > 0)
                {
                    lCustomEK.Add(pe);
                    lCustomEV.Add(pe.CustomData);
                    pe.CustomData = new StringDictionaryEx();
                }
                return(true);
            };

            gh(pgRoot);
            pgRoot.TraverseTree(TraversalMethod.PreOrder, gh, eh);

            try
            {
                KdbxFile kdbx = new KdbxFile(pd);
                kdbx.ForceVersion = KdbxFile.FileVersion32_3_1;
                kdbx.Save(sOutput, pgRoot, KdbxFormat.Default, slLogger);
            }
            finally
            {
                // Restore

                pd.DataCipherUuid   = puCipher;
                pd.KdfParameters    = pKdf;
                pd.PublicCustomData = vdPublic;

                for (int i = 0; i < lCustomGK.Count; ++i)
                {
                    lCustomGK[i].CustomData = lCustomGV[i];
                }
                for (int i = 0; i < lCustomEK.Count; ++i)
                {
                    lCustomEK[i].CustomData = lCustomEV[i];
                }
            }

            return(true);
        }
Example #46
0
        public override bool Export(PwExportInfo pwExportInfo, Stream sOutput,
            IStatusLogger slLogger)
        {
            PwDatabase pd = (pwExportInfo.ContextDatabase ?? new PwDatabase());

            string strTempFile = Program.TempFilesPool.GetTempFileName(false);

            try
            {
                Kdb3File kdb = new Kdb3File(pd, slLogger);
                kdb.Save(strTempFile, pwExportInfo.DataGroup);

                byte[] pbKdb = File.ReadAllBytes(strTempFile);
                sOutput.Write(pbKdb, 0, pbKdb.Length);
                Array.Clear(pbKdb, 0, pbKdb.Length);
            }
            catch(Exception exKdb)
            {
                if(slLogger != null) slLogger.SetText(exKdb.Message, LogStatusType.Error);

                return false;
            }

            Program.TempFilesPool.Delete(strTempFile);
            return true;
        }
Example #47
0
		private static void ExportEntry(PwEntry pe, string strDir, PwExportInfo pxi)
		{
			PwDatabase pd = ((pxi != null) ? pxi.ContextDatabase : null);
			SprContext ctx = new SprContext(pe, pd, SprCompileFlags.NonActive, false, false);

			KeyValuePair<string, string>? okvpCmd = null;
			string strUrl = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.UrlField), ctx);
			if(WinUtil.IsCommandLineUrl(strUrl))
			{
				strUrl = WinUtil.GetCommandLineFromUrl(strUrl);

				if(!NativeLib.IsUnix()) // LNKs only supported on Windows
				{
					string strApp, strArgs;
					StrUtil.SplitCommandLine(strUrl, out strApp, out strArgs);

					if(!string.IsNullOrEmpty(strApp))
						okvpCmd = new KeyValuePair<string, string>(strApp, strArgs);
				}
			}
			if(string.IsNullOrEmpty(strUrl)) return;
			bool bLnk = okvpCmd.HasValue;

			string strTitleCmp = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.TitleField), ctx);
			if(string.IsNullOrEmpty(strTitleCmp)) strTitleCmp = KPRes.Entry;
			string strTitle = Program.Config.Defaults.WinFavsFileNamePrefix + strTitleCmp;

			string strSuffix = Program.Config.Defaults.WinFavsFileNameSuffix +
				(bLnk ? ".lnk" : ".url");
			strSuffix = UrlUtil.FilterFileName(strSuffix);

			string strFileBase = (UrlUtil.EnsureTerminatingSeparator(strDir,
				false) + UrlUtil.FilterFileName(strTitle));
			string strFile = strFileBase + strSuffix;
			int iFind = 2;
			while(File.Exists(strFile))
			{
				strFile = strFileBase + " (" + iFind.ToString() + ")" + strSuffix;
				++iFind;
			}

			if(!Directory.Exists(strDir))
			{
				try { Directory.CreateDirectory(strDir); }
				catch(Exception exDir)
				{
					throw new Exception(strDir + MessageService.NewParagraph + exDir.Message);
				}

				WaitForDirCommit(strDir, true);
			}

			try
			{
				if(bLnk)
				{
					int ccMaxDesc = NativeMethods.INFOTIPSIZE - 1 - LnkDescSuffix.Length;
					string strDesc = StrUtil.CompactString3Dots(strUrl, ccMaxDesc) +
						LnkDescSuffix;

					ShellLinkEx sl = new ShellLinkEx(okvpCmd.Value.Key,
						okvpCmd.Value.Value, strDesc);
					sl.Save(strFile);
				}
				else
				{
					StringBuilder sb = new StringBuilder();
					sb.AppendLine(@"[InternetShortcut]");
					sb.AppendLine(@"URL=" + strUrl); // No additional line break
					sb.AppendLine(@"[" + PwDefs.ShortProductName + @"]");
					sb.AppendLine(IniTypeKey + @"=" + IniTypeValue);
					// Terminating line break is important

					File.WriteAllText(strFile, sb.ToString(), Encoding.Default);
				}
			}
			catch(Exception exWrite)
			{
				throw new Exception(strFile + MessageService.NewParagraph + exWrite.Message);
			}
		}
Example #48
0
		private static void ExportGroup(PwGroup pg, string strDir, IStatusLogger slLogger,
			uint uTotalEntries, ref uint uEntriesProcessed, PwExportInfo pxi)
		{
			foreach(PwEntry pe in pg.Entries)
			{
				ExportEntry(pe, strDir, pxi);

				++uEntriesProcessed;
				if(slLogger != null)
					slLogger.SetProgress(((uEntriesProcessed * 50U) /
						uTotalEntries) + 50U);
			}

			foreach(PwGroup pgSub in pg.Groups)
			{
				string strGroup = UrlUtil.FilterFileName(pgSub.Name);
				string strSub = (UrlUtil.EnsureTerminatingSeparator(strDir, false) +
					(!string.IsNullOrEmpty(strGroup) ? strGroup : KPRes.Group));

				ExportGroup(pgSub, strSub, slLogger, uTotalEntries,
					ref uEntriesProcessed, pxi);
			}
		}