Ejemplo n.º 1
0
		public static bool Export(PwExportInfo pwExportInfo, IStatusLogger slLogger)
		{
			if(pwExportInfo == null) throw new ArgumentNullException("pwExportInfo");
			if(pwExportInfo.DataGroup == null) throw new ArgumentException();

			if(!AppPolicy.Try(AppPolicyId.Export)) return false;

			ExchangeDataForm dlg = new ExchangeDataForm();
			dlg.InitEx(true, pwExportInfo.ContextDatabase, pwExportInfo.DataGroup);

			if(dlg.ShowDialog() == DialogResult.OK)
			{
				FileFormatProvider ffp = dlg.ResultFormat;
				if(ffp == null) { Debug.Assert(false); return false; }
				if(ffp.RequiresFile)
				{
					if(dlg.ResultFiles.Length != 1) { Debug.Assert(false); return false; }
					if(dlg.ResultFiles[0] == null) { Debug.Assert(false); return false; }
					if(dlg.ResultFiles[0].Length == 0) { Debug.Assert(false); return false; }
				}

				Application.DoEvents(); // Redraw parent window

				IOConnectionInfo iocOutput = (ffp.RequiresFile ? IOConnectionInfo.FromPath(
					dlg.ResultFiles[0]) : null);

				try
				{
					return Export(pwExportInfo, dlg.ResultFormat, iocOutput, slLogger);
				}
				catch(Exception ex) { MessageService.ShowWarning(ex); }
			}

			return false;
		}
Ejemplo n.º 2
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			StreamReader sr = new StreamReader(sInput, StrUtil.Utf8);
			string strDoc = sr.ReadToEnd();
			sr.Close();

			XmlDocument doc = new XmlDocument();
			doc.LoadXml(strDoc);

			XmlElement xmlRoot = doc.DocumentElement;
			Debug.Assert(xmlRoot.Name == ElemRoot);

			PwGroup pgRoot = pwStorage.RootGroup;

			foreach(XmlNode xmlChild in xmlRoot.ChildNodes)
			{
				if(xmlChild.Name == ElemGroup)
					ImportGroup(xmlChild, pgRoot, pwStorage, false);
				else if(xmlChild.Name == ElemRecycleBin)
					ImportGroup(xmlChild, pgRoot, pwStorage, true);
				else if(xmlChild.Name == ElemEntry)
					ImportEntry(xmlChild, pgRoot, pwStorage);
				else { Debug.Assert(false); }
			}
		}
Ejemplo n.º 3
0
        public static void Export(PwExportInfo pwExportInfo, IStatusLogger slLogger)
        {
            if(pwExportInfo == null) throw new ArgumentNullException("pwExportInfo");
            if(pwExportInfo.DataGroup == null) throw new ArgumentException();

            if(!AppPolicy.Try(AppPolicyId.Export)) return;

            ExchangeDataForm dlg = new ExchangeDataForm();
            dlg.InitEx(true, pwExportInfo.ContextDatabase, pwExportInfo.DataGroup);

            if(dlg.ShowDialog() == DialogResult.OK)
            {
                if(dlg.ResultFormat == null) { Debug.Assert(false); return; }
                if(dlg.ResultFiles.Length != 1) { Debug.Assert(false); return; }
                if(dlg.ResultFiles[0] == null) { Debug.Assert(false); return; }
                if(dlg.ResultFiles[0].Length == 0) { Debug.Assert(false); return; }

                Application.DoEvents(); // Redraw parent window

                try
                {
                    PerformExport(pwExportInfo, dlg.ResultFormat, dlg.ResultFiles[0],
                        slLogger);
                }
                catch(Exception ex)
                {
                    MessageService.ShowWarning(ex);
                }
            }
        }
Ejemplo n.º 4
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;
        }
Ejemplo n.º 5
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.Load(sInput);

			XmlNode xmlRoot = xmlDoc.DocumentElement;
			Debug.Assert(xmlRoot.Name == ElemRoot);

			Stack<PwGroup> vGroups = new Stack<PwGroup>();
			vGroups.Push(pwStorage.RootGroup);

			int nNodeCount = xmlRoot.ChildNodes.Count;
			for(int i = 0; i < nNodeCount; ++i)
			{
				XmlNode xmlChild = xmlRoot.ChildNodes[i];

				if(xmlChild.Name == ElemGroup)
					ReadGroup(xmlChild, vGroups, pwStorage);
				else { Debug.Assert(false); }

				if(slLogger != null)
					slLogger.SetProgress((uint)(((i + 1) * 100) / nNodeCount));
			}
		}
Ejemplo n.º 6
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;
		}
Ejemplo n.º 7
0
		/// <summary>
		/// Default constructor.
		/// </summary>
		/// <param name="pwDataStore">The <c>PwDatabase</c> instance that the class
		/// will load file data into or use to create a KDB file. Must not be <c>null</c>.</param>
		/// <exception cref="System.ArgumentNullException">Thrown if the database
		/// reference is <c>null</c>.</exception>
		public KdbFile(PwDatabase pwDataStore, IStatusLogger slLogger)
		{
			Debug.Assert(pwDataStore != null);
			if(pwDataStore == null) throw new ArgumentNullException("pwDataStore");
			m_pwDatabase = pwDataStore;

			m_slLogger = slLogger;
		}
Ejemplo n.º 8
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			XmlSerializer xs = new XmlSerializer(typeof(HspFolder));
			HspFolder hspRoot = (HspFolder)xs.Deserialize(sInput);

			AddFolder(pwStorage.RootGroup, hspRoot, false);
		}
Ejemplo n.º 9
0
		// public void Save(string strFile, PwGroup pgDataSource, KdbxFormat format,
		//	IStatusLogger slLogger)
		// {
		//	bool bMadeUnhidden = UrlUtil.UnhideFile(strFile);
		//
		//	IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile);
		//	this.Save(IOConnection.OpenWrite(ioc), pgDataSource, format, slLogger);
		//
		//	if(bMadeUnhidden) UrlUtil.HideFile(strFile, true); // Hide again
		// }

		/// <summary>
		/// Save the contents of the current <c>PwDatabase</c> to a KDBX file.
		/// </summary>
		/// <param name="sSaveTo">Stream to write the KDBX file into.</param>
		/// <param name="pgDataSource">Group containing all groups and
		/// entries to write. If <c>null</c>, the complete database will
		/// be written.</param>
		/// <param name="format">Format of the file to create.</param>
		/// <param name="slLogger">Logger that recieves status information.</param>
		public void Save(Stream sSaveTo, PwGroup pgDataSource, KdbxFormat format,
			IStatusLogger slLogger)
		{
			Debug.Assert(sSaveTo != null);
			if(sSaveTo == null) throw new ArgumentNullException("sSaveTo");

			m_format = format;
			m_slLogger = slLogger;

			HashingStreamEx hashedStream = new HashingStreamEx(sSaveTo, true, null);

			UTF8Encoding encNoBom = StrUtil.Utf8;
			CryptoRandom cr = CryptoRandom.Instance;

			try
			{
				m_pbMasterSeed = cr.GetRandomBytes(32);
				m_pbTransformSeed = cr.GetRandomBytes(32);
				m_pbEncryptionIV = cr.GetRandomBytes(16);

				m_pbProtectedStreamKey = cr.GetRandomBytes(32);
				m_craInnerRandomStream = CrsAlgorithm.Salsa20;
				m_randomStream = new CryptoRandomStream(m_craInnerRandomStream,
					m_pbProtectedStreamKey);

				m_pbStreamStartBytes = cr.GetRandomBytes(32);

				Stream writerStream;
				if(m_format == KdbxFormat.Default)
				{
					WriteHeader(hashedStream); // Also flushes the stream

					Stream sEncrypted = AttachStreamEncryptor(hashedStream);
					if((sEncrypted == null) || (sEncrypted == hashedStream))
						throw new SecurityException(KLRes.CryptoStreamFailed);

					sEncrypted.Write(m_pbStreamStartBytes, 0, m_pbStreamStartBytes.Length);

					Stream sHashed = new HashedBlockStream(sEncrypted, true);

					if(m_pwDatabase.Compression == PwCompressionAlgorithm.GZip)
						writerStream = new GZipStream(sHashed, CompressionMode.Compress);
					else
						writerStream = sHashed;
				}
				else if(m_format == KdbxFormat.PlainXml)
					writerStream = hashedStream;
				else { Debug.Assert(false); throw new FormatException("KdbFormat"); }

				m_xmlWriter = new XmlTextWriter(writerStream, encNoBom);
				WriteDocument(pgDataSource);

				m_xmlWriter.Flush();
				m_xmlWriter.Close();
				writerStream.Close();
			}
			finally { CommonCleanUpWrite(sSaveTo, hashedStream); }
		}
Ejemplo n.º 10
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			XPathDocument xpDoc = new XPathDocument(sInput);
			XPathNavigator xpNav = xpDoc.CreateNavigator();

			ImportLogins(xpNav, pwStorage);
			ImportMemos(xpNav, pwStorage);
		}
Ejemplo n.º 11
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			StreamReader sr = new StreamReader(sInput, Encoding.Default);
			string strDoc = sr.ReadToEnd();
			sr.Close();

			ImportFileString(strDoc, pwStorage);
		}
Ejemplo n.º 12
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			StreamReader sr = new StreamReader(sInput, Encoding.Default);
			string strDoc = sr.ReadToEnd();
			sr.Close();

			int nIndex = strDoc.IndexOf('<');
			while(nIndex >= 0)
			{
				int nAttrib = strDoc.LastIndexOf("=\"", nIndex);
				int nElem = strDoc.LastIndexOf('>', nIndex);
				
				if(nAttrib > nElem)
				{
					strDoc = strDoc.Remove(nIndex, 1);
					strDoc = strDoc.Insert(nIndex, @"&lt;");
				}
				nIndex = strDoc.IndexOf('<', nIndex + 1);
			}

			nIndex = strDoc.IndexOf('>');
			while(nIndex >= 0)
			{
				if(nIndex <= 3)
					throw new FormatException("Invalid header!");

				char chPrev = strDoc[nIndex - 1];
				string strPrev4 = strDoc.Substring(nIndex - 3, 4);

				if((chPrev != '/') && (chPrev != '\"') && (strPrev4 != @"xml>") &&
					(strPrev4 != @"ies>"))
				{
					strDoc = strDoc.Remove(nIndex, 1);
					strDoc = strDoc.Insert(nIndex, @"&gt;");
				}
				nIndex = strDoc.IndexOf('>', nIndex + 1);
			}

			MemoryStream msXml = new MemoryStream(Encoding.UTF8.GetBytes(strDoc), false);

			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.Load(msXml);
			msXml.Close();

			XmlNode xmlRoot = xmlDoc.DocumentElement;
			if(xmlRoot.Name != ElemRoot)
				throw new FormatException("Invalid root element!");

			foreach(XmlNode xmlChild in xmlRoot.ChildNodes)
			{
				if(xmlChild.Name == ElemEntries)
					ImportEntries(xmlChild, pwStorage);
				else { Debug.Assert(false); }
			}
		}
Ejemplo n.º 13
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			KdbxFile kdbx = new KdbxFile(pwStorage);
			// CappedByteStream s = new CappedByteStream(sInput, 64);

			kdbx.RepairMode = true;

			try { kdbx.Load(sInput, KdbxFormat.Default, slLogger); }
			catch(Exception) { }
		}
Ejemplo n.º 14
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			BinaryReader br = new BinaryReader(sInput);
			byte[] pbData = br.ReadBytes((int)sInput.Length);
			br.Close();

			ImportCsvForm csv = new ImportCsvForm();
			csv.InitEx(pwStorage, pbData);
			csv.ShowDialog();
		}
Ejemplo n.º 15
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			StreamReader sr = new StreamReader(sInput, Encoding.Default);
			string strData = sr.ReadToEnd();
			sr.Close();

			strData = strData.Replace("\r", string.Empty);
			string[] vLines = strData.Split(new char[] { '\n' });

			PwGroup pg = pwStorage.RootGroup;
			Dictionary<string, string> dItems = new Dictionary<string, string>();
			bool bInNotes = false;

			foreach(string strLine in vLines)
			{
				if(strLine.StartsWith(StrGroupStart) && strLine.EndsWith(StrGroupEnd))
				{
					AddEntry(pg, dItems, ref bInNotes);
					dItems.Clear();

					pg = new PwGroup(true, true);
					pg.Name = strLine.Substring(StrGroupStart.Length, strLine.Length -
						StrGroupStart.Length - StrGroupEnd.Length);

					pwStorage.RootGroup.AddGroup(pg, true);
				}
				else if(strLine.StartsWith(StrEntryStart) && strLine.EndsWith(StrEntryEnd))
				{
					AddEntry(pg, dItems, ref bInNotes);
					dItems.Clear();
				}
				else if(strLine == StrNotesBegin) bInNotes = true;
				else if(bInNotes)
				{
					if(dItems.ContainsKey(PwDefs.NotesField))
						dItems[PwDefs.NotesField] += MessageService.NewLine + strLine;
					else dItems[PwDefs.NotesField] = strLine;
				}
				else
				{
					int nSplitPos = strLine.IndexOf(StrFieldSplit);
					if(nSplitPos < 0) { Debug.Assert(false); }
					else
					{
						AddField(dItems, strLine.Substring(0, nSplitPos),
							strLine.Substring(nSplitPos + StrFieldSplit.Length));
					}
				}
			}

			AddEntry(pg, dItems, ref bInNotes);
		}
Ejemplo n.º 16
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			StreamReader sr = new StreamReader(sInput, Encoding.Unicode);
			string strData = sr.ReadToEnd();
			sr.Close();

			string[] vLines = strData.Split(new char[]{ '\r', '\n' });

			foreach(string strLine in vLines)
			{
				if(strLine.Length == 0) continue;

				string[] vParts = strLine.Split(new char[]{ 'µ' });

				PwEntry pe = new PwEntry(true, true);
				PwGroup pgContainer = pwStorage.RootGroup;

				string strNotes = string.Empty;
				for(int i = 0; i < vParts.Length; ++i)
				{
					switch(i)
					{
						case 0: // Empty field
							break;
						case 1:
							pgContainer = pwStorage.RootGroup.FindCreateSubTree(
								vParts[i], new char[]{ '.' });
							break;
						case 2: pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
							pwStorage.MemoryProtection.ProtectTitle, vParts[i]));
							break;
						case 3: pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
							pwStorage.MemoryProtection.ProtectUserName, vParts[i]));
							break;
						case 4: pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
							pwStorage.MemoryProtection.ProtectPassword, vParts[i]));
							break;
						case 5: strNotes += vParts[i].Replace("\\n", "\n");
							break;
						default:
							strNotes += @"µ" + vParts[i].Replace("\\n", "\n");
							break;
					}
				}

				pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectNotes, strNotes));

				pgContainer.AddEntry(pe, true);
			}
		}
Ejemplo n.º 17
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			StreamReader sr = new StreamReader(sInput, Encoding.Default);
			string strData = sr.ReadToEnd();
			sr.Close();

			// Normalize 2.70 files
			strData = strData.Replace("<td class=\"c1\" nowrap>", m_strStartTd);
			strData = strData.Replace("<td class=\"c2\" nowrap>", m_strStartTd);
			strData = strData.Replace("<td class=\"c3\" nowrap>", m_strStartTd);
			strData = strData.Replace("<td class=\"c4\" nowrap>", m_strStartTd);
			strData = strData.Replace("<td class=\"c5\" nowrap>", m_strStartTd);
			strData = strData.Replace("<td class=\"c6\" nowrap>", m_strStartTd);

			// Additionally support old versions
			string[] vRepl = new string[5] {
				// 2.60
				"<td nowrap align=\"center\" bgcolor=\"#[0-9a-fA-F]{6}\"><font color=\"#[0-9a-fA-F]{6}\" face=\"[^\"]*\">",

				// 2.50 and 2.60
				"<td nowrap align=\"(center|right)\" bgcolor=\"#[0-9a-fA-F]{6}\"><font color=\"#[0-9a-fA-F]{6}\"\\s*>",
				"<td nowrap bgcolor=\"#[0-9a-fA-F]{6}\"><font color=\"#[0-9a-fA-F]{6}\"\\s*>",
				"<td nowrap align=\"(center|right)\" bgcolor=\"#[0-9a-fA-F]{6}\"><b>",
				"<td nowrap bgcolor=\"#[0-9a-fA-F]{6}\"><b>"
			};
			foreach(string strRepl in vRepl)
				strData = Regex.Replace(strData, strRepl, m_strStartTd);
			strData = strData.Replace("</font></td>\r\n", m_strEndTd + "\r\n");

			int nOffset = 0;

			PwEntry peHeader;
			if(!ReadEntry(out peHeader, strData, ref nOffset, pwStorage))
			{
				Debug.Assert(false);
				return;
			}

			while((nOffset >= 0) && (nOffset < strData.Length))
			{
				PwEntry pe;
				if(!ReadEntry(out pe, strData, ref nOffset, pwStorage))
				{
					Debug.Assert(false);
					break;
				}
				if(pe == null) break;

				pwStorage.RootGroup.AddEntry(pe, true);
			}
		}
Ejemplo n.º 18
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			MemoryStream ms = new MemoryStream();
			MemUtil.CopyStream(sInput, ms);
			byte[] pbData = ms.ToArray();
			ms.Close();
			sInput.Close();

			CsvImportForm dlg = new CsvImportForm();
			dlg.InitEx(pwStorage, pbData);
			UIUtil.ShowDialogAndDestroy(dlg);
		}
Ejemplo n.º 19
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
            IStatusLogger slLogger)
        {
            StreamReader sr = new StreamReader(sInput, Encoding.UTF8);
            string strDoc = sr.ReadToEnd();
            sr.Close();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strDoc);

            ProcessEntries(pwStorage, pwStorage.RootGroup,
                doc.DocumentElement.ChildNodes);
        }
Ejemplo n.º 20
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);
		}
Ejemplo n.º 21
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;
		}
Ejemplo n.º 22
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
            IStatusLogger slLogger)
        {
            StreamReader sr = new StreamReader(sInput, Encoding.Default);
            string strData = sr.ReadToEnd();
            sr.Close();

            string[] vLines = strData.Split(new char[] { '\r', '\n' });

            foreach(string strLine in vLines)
            {
                if(strLine.Length > 5) ProcessCsvLine(strLine, pwStorage);
            }
        }
Ejemplo n.º 23
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
        {
            StreamReader sr = new StreamReader(sInput, Encoding.UTF8);
            string strContent = sr.ReadToEnd();
            sr.Close();

            if(strContent.IndexOf(@"<!DOCTYPE NETSCAPE-Bookmark-file-1>") < 0)
                throw new FormatException("Invalid DOCTYPE!");

            strContent = strContent.Replace(@"<!DOCTYPE NETSCAPE-Bookmark-file-1>", string.Empty);
            strContent = strContent.Replace(@"<HR>", string.Empty);
            strContent = strContent.Replace(@"<p>", string.Empty);
            strContent = strContent.Replace(@"<DD>", string.Empty);
            strContent = strContent.Replace(@"<DL>", string.Empty);
            strContent = strContent.Replace(@"</DL>", string.Empty);
            strContent = strContent.Replace(@"<DT>", string.Empty);

            int nOffset = strContent.IndexOf('&');
            while(nOffset >= 0)
            {
                string str4 = strContent.Substring(nOffset, 4);
                string str5 = strContent.Substring(nOffset, 5);
                string str6 = strContent.Substring(nOffset, 6);

                if((str6 != @"&nbsp;") && (str5 != @"&amp;") && (str4 != @"&lt;") &&
                    (str4 != @"&gt;") && (str5 != @"&#39;") && (str6 != @"&quot;"))
                {
                    strContent = strContent.Remove(nOffset, 1);
                    strContent = strContent.Insert(nOffset, @"&amp;");
                }
                else nOffset = strContent.IndexOf('&', nOffset + 1);
            }

            strContent = "<RootSentinel>" + strContent + "</META></RootSentinel>";

            byte[] pbFixedData = StrUtil.Utf8.GetBytes(strContent);
            MemoryStream msFixed = new MemoryStream(pbFixedData, false);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(msFixed);
            msFixed.Close();

            XmlNode xmlRoot = xmlDoc.DocumentElement;
            foreach(XmlNode xmlChild in xmlRoot)
            {
                if(xmlChild.Name == "META")
                    ImportLinksFlat(xmlChild, pwStorage);
            }
        }
Ejemplo n.º 24
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.Load(sInput);

			XmlNode xmlRoot = xmlDoc.DocumentElement;

			foreach(XmlNode xmlChild in xmlRoot.ChildNodes)
			{
				if(xmlChild.Name == ElemGroup)
					ReadGroup(xmlChild, pwStorage.RootGroup, pwStorage);
				else { Debug.Assert(false); }
			}
		}
Ejemplo n.º 25
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			string strTempFile = Program.TempFilesPool.GetTempFileName();

			BinaryReader br = new BinaryReader(sInput);
			byte[] pb = br.ReadBytes((int)sInput.Length);
			br.Close();
			File.WriteAllBytes(strTempFile, pb);

			Kdb3File kdb3 = new Kdb3File(pwStorage, slLogger);
			kdb3.Load(strTempFile);

			Program.TempFilesPool.Delete(strTempFile);
		}
Ejemplo n.º 26
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;
			}
		}
Ejemplo n.º 27
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
            IStatusLogger slLogger)
        {
            StreamReader sr = new StreamReader(sInput, Encoding.UTF8);
            string strContent = sr.ReadToEnd();
            sr.Close();

            if(strContent.Length == 0) return;

            CharStream cs = new CharStream(strContent);

            JsonObject jRoot = new JsonObject(cs);
            AddObject(pwStorage.RootGroup, jRoot, pwStorage, false);
            Debug.Assert(cs.PeekChar(true) == char.MinValue);
        }
Ejemplo n.º 28
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			string str = PwMemory2008Xml104.Preprocess(sInput);
			MemoryStream ms = new MemoryStream(StrUtil.Utf8.GetBytes(str), false);

			XmlSerializer xs = new XmlSerializer(typeof(Priv_PwMem2008XmlFile));
			Priv_PwMem2008XmlFile f = (Priv_PwMem2008XmlFile)xs.Deserialize(ms);
			ms.Close();

			if((f == null) || (f.Cells == null)) return;

			Dictionary<string, PwGroup> vGroups = new Dictionary<string, PwGroup>();

			for(int iLine = 2; iLine < f.Cells.Length; ++iLine)
			{
				string[] vCells = f.Cells[iLine];
				if((vCells == null) || (vCells.Length != 6)) continue;
				if((vCells[1] == null) || (vCells[2] == null) ||
					(vCells[3] == null) || (vCells[4] == null)) continue;

				string strGroup = vCells[4];
				PwGroup pg;
				if(strGroup == ".") pg = pwStorage.RootGroup;
				else if(vGroups.ContainsKey(strGroup)) pg = vGroups[strGroup];
				else
				{
					pg = new PwGroup(true, true);
					pg.Name = strGroup;
					pwStorage.RootGroup.AddGroup(pg, true);

					vGroups[strGroup] = pg;
				}

				PwEntry pe = new PwEntry(true, true);
				pg.AddEntry(pe, true);

				if(vCells[1] != ".")
					pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
						pwStorage.MemoryProtection.ProtectTitle, vCells[1]));
				if(vCells[2] != ".")
					pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
						pwStorage.MemoryProtection.ProtectUserName, vCells[2]));
				if(vCells[3] != ".")
					pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
						pwStorage.MemoryProtection.ProtectPassword, vCells[3]));
			}
		}
Ejemplo n.º 29
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.Load(sInput);

			XmlNode xmlRoot = xmlDoc.DocumentElement;

			foreach(XmlNode xmlChild in xmlRoot.ChildNodes)
			{
				if(xmlChild.Name == ElemHeader) { } // Unsupported
				else if(xmlChild.Name == ElemContainer)
					ReadContainer(xmlChild, pwStorage);
				else { Debug.Assert(false); }
			}
		}
Ejemplo n.º 30
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
        {
            StreamReader sr = new StreamReader(sInput, Encoding.Default, true);
            string strData = sr.ReadToEnd();
            sr.Close();

            string[] vLines = strData.Split(new char[] { '\r', '\n' },
                StringSplitOptions.RemoveEmptyEntries);

            Dictionary<string, PwGroup> dictGroups = new Dictionary<string, PwGroup>();
            foreach(string strLine in vLines)
            {
                ProcessCsvLine(strLine, pwStorage, dictGroups);
            }
        }
Ejemplo n.º 31
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));
        }
Ejemplo n.º 32
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, Encoding.Default);
            string       strData = sr.ReadToEnd();

            sr.Close();

            string[] vLines = strData.Split(new char[] { '\r', '\n' });

            foreach (string strLine in vLines)
            {
                if (strLine.Length > 5)
                {
                    ProcessCsvLine(strLine, pwStorage);
                }
            }
        }
Ejemplo n.º 33
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 override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            JsonObject jo;

            using (StreamReader sr = new StreamReader(sInput, StrUtil.Utf8, true))
            {
                string strJson = sr.ReadToEnd();
                if (string.IsNullOrEmpty(strJson))
                {
                    return;
                }

                jo = new JsonObject(new CharStream(strJson));
            }

            Dictionary <string, List <string> > dTags =
                new Dictionary <string, List <string> >();
            List <PwEntry> lCreatedEntries = new List <PwEntry>();

            AddObject(pwStorage.RootGroup, jo, pwStorage, false, dTags,
                      lCreatedEntries);

            // Tags support (old versions)
            foreach (PwEntry pe in lCreatedEntries)
            {
                string strUri = pe.Strings.ReadSafe(PwDefs.UrlField);
                if (strUri.Length == 0)
                {
                    continue;
                }

                foreach (KeyValuePair <string, List <string> > kvp in dTags)
                {
                    foreach (string strTagUri in kvp.Value)
                    {
                        if (strUri.Equals(strTagUri, StrUtil.CaseIgnoreCmp))
                        {
                            pe.AddTag(kvp.Key);
                        }
                    }
                }
            }
        }
Ejemplo n.º 35
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);
        }
Ejemplo n.º 36
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);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Exports a wlan connection information from the database to a .xml profil.
        /// </summary>
        /// <param name="pwStorage">The database in which the key lies</param>
        /// <param name="entry">The entry which we want to export</param>
        /// <param name="soutput">Where to print to the xml structure (via serialization)</param>
        /// <param name="slLogger">Where we log to (can be null)</param>
        /// <param name="totalProcents">If we parsed completely, how many (additional) procents of the
        /// total progress did we finish? (Senseless if slLogger = null)</param>
        /// <param name="minProcents">How many procents of the total progress were already finished</param>
        /// <remarks>Note that minProcents + totalProcents has to be less than or equal to 100.
        /// <para>Note furthermore that nothing is written to soutput if an error occured</para></remarks>
        /// <returns>Whether the export was successfull.</returns>
        public bool Export(PwDatabase pwStorage, PwEntry entry, Stream sOutput,
                           IStatusLogger slLogger = null, double totalProcents = 60,
                           double minProcents     = 20)
        {
            WlanProfile profile = new WlanProfile();

            profile.LoadFrom(pwStorage, entry);

            if (!profile.IsValid)
            {
                return(false);
            }

            XmlSerializer xml = new XmlSerializer(typeof(WlanProfile));

            xml.Serialize(sOutput, profile);

            return(true);
        }
Ejemplo n.º 38
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);
        }
Ejemplo n.º 39
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, Encoding.Default);
            string       strData = sr.ReadToEnd();

            sr.Close();

            const string strNormalized = "<td class=\"c0\" nowrap>";

            strData = strData.Replace("<td class=\"c1\" nowrap>", strNormalized);
            strData = strData.Replace("<td class=\"c2\" nowrap>", strNormalized);
            strData = strData.Replace("<td class=\"c3\" nowrap>", strNormalized);
            strData = strData.Replace("<td class=\"c4\" nowrap>", strNormalized);
            strData = strData.Replace("<td class=\"c5\" nowrap>", strNormalized);
            strData = strData.Replace("<td class=\"c6\" nowrap>", strNormalized);

            int nOffset = 0;

            PwEntry peHeader;

            if (ReadEntry(out peHeader, strData, ref nOffset, pwStorage) == false)
            {
                Debug.Assert(false);
                return;
            }

            while ((nOffset >= 0) && (nOffset < strData.Length))
            {
                PwEntry pe;
                if (ReadEntry(out pe, strData, ref nOffset, pwStorage) == false)
                {
                    Debug.Assert(false);
                    break;
                }
                if (pe == null)
                {
                    break;
                }

                pwStorage.RootGroup.AddEntry(pe, true);
            }
        }
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            if (MessageService.AskYesNo(KPRes.ImportMustRead + MessageService.NewParagraph +
                                        KPRes.ImportMustReadQuestion) == false)
            {
                AppHelp.ShowHelp(AppDefs.HelpTopics.ImportExport,
                                 AppDefs.HelpTopics.ImportExportSteganos);
                return;
            }

            PwEntry pePrev = new PwEntry(true, true);

            for (int i = 0; i < 20; ++i)
            {
                Thread.Sleep(500);
                Application.DoEvents();
            }

            try
            {
                while (true)
                {
                    PwEntry pe = ImportEntry(pwStorage);

                    if (ImportUtil.EntryEquals(pe, pePrev))
                    {
                        if (pe.ParentGroup != null)                        // Remove duplicate
                        {
                            pe.ParentGroup.Entries.Remove(pe);
                        }
                        break;
                    }

                    ImportUtil.GuiSendKeysPrc(@"{DOWN}");
                    pePrev = pe;
                }

                MessageService.ShowInfo(KPRes.ImportFinished);
            }
            catch (Exception exImp) { MessageService.ShowWarning(exImp); }
        }
Ejemplo n.º 41
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;
        }
Ejemplo n.º 42
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, Encoding.Unicode, true);
            string       strData = sr.ReadToEnd();

            sr.Close();

            strData = strData.Replace(@"<WBR>", string.Empty);
            strData = strData.Replace(@"&shy;", string.Empty);

            using (WebBrowser wb = new WebBrowser())
            {
                wb.Visible = false;
                wb.ScriptErrorsSuppressed = true;

                UIUtil.SetWebBrowserDocument(wb, strData);
                ImportPriv(pwStorage, wb.Document.Body);
            }
        }
Ejemplo n.º 43
0
        public FaviconDialog(IPluginHost host)
        {
            // KeePass plugin host
            pluginHost = host;

            // Set up BackgroundWorker
            bgWorker = new BackgroundWorker();

            // BackgroundWorker Events
            bgWorker.DoWork             += BgWorker_DoWork;
            bgWorker.RunWorkerCompleted += BgWorker_RunWorkerCompleted;

            // Status Progress Form
            Form fStatusDialog;

            logger = StatusUtil.CreateStatusDialog(pluginHost.MainWindow, out fStatusDialog, "Yet Another Favicon Downloader", "Downloading favicons...", true, false);

            // Block UI
            pluginHost.MainWindow.UIBlockInteraction(true);
        }
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr         = new StreamReader(sInput, Encoding.UTF8);
            string       strContent = sr.ReadToEnd();

            sr.Close();

            if (strContent.Length == 0)
            {
                return;
            }

            CharStream cs = new CharStream(strContent);

            JsonObject jRoot = new JsonObject(cs);

            AddObject(pwStorage.RootGroup, jRoot, pwStorage, false);
            Debug.Assert(cs.PeekChar(true) == char.MinValue);
        }
Ejemplo n.º 45
0
        public static async Task ProcessSignonsAsync(
            IEnumerable <Signon> signons,
            ImportDialog form,
            PwDatabase db,
            IStatusLogger logger)
        {
            logger.SetText("Processing signons", LogStatusType.Info);

            List <Task> tasks    = signons.Select(signon => AddEntryAsync(signon, form, db, logger)).ToList();
            int         total    = tasks.Count;
            var         progress = 0;

            while (tasks.Count > 0)
            {
                Task completedTask = Task.Factory.ContinueWhenAny(tasks.ToArray(), task => tasks.Remove(task));
                await completedTask.ConfigureAwait(false);

                ++progress;
                logger.SetProgress((uint)(100 * (double)progress / total));
            }
        }
Ejemplo n.º 46
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);
        }
Ejemplo n.º 47
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(sInput);

            XmlNode xmlRoot = xmlDoc.DocumentElement;

            foreach (XmlNode xmlChild in xmlRoot.ChildNodes)
            {
                if (xmlChild.Name == ElemGroup)
                {
                    ReadGroup(xmlChild, pwStorage.RootGroup, pwStorage);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
        }
Ejemplo n.º 48
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);
            }
Ejemplo n.º 49
0
        internal static void ShowLoadError(string strPath, Exception ex,
                                           IStatusLogger slStatus)
        {
            if (string.IsNullOrEmpty(strPath))
            {
                Debug.Assert(false); return;
            }

            if (slStatus != null)
            {
                slStatus.SetText(KPRes.PluginLoadFailed, LogStatusType.Info);
            }

            bool bShowExcp = (Program.CommandLineArgs[
                                  AppDefs.CommandLineOptions.Debug] != null);

            string strMsg = KPRes.PluginIncompatible + MessageService.NewLine +
                            strPath + MessageService.NewParagraph + KPRes.PluginUpdateHint;
            string strExcp = ((ex != null) ? StrUtil.FormatException(ex).Trim() : null);

            VistaTaskDialog vtd = new VistaTaskDialog();

            vtd.Content             = strMsg;
            vtd.ExpandedByDefault   = ((strExcp != null) && bShowExcp);
            vtd.ExpandedInformation = strExcp;
            vtd.WindowTitle         = PwDefs.ShortProductName;
            vtd.SetIcon(VtdIcon.Warning);

            if (!vtd.ShowDialog())
            {
                if (!bShowExcp)
                {
                    MessageService.ShowWarning(strMsg);
                }
                else
                {
                    MessageService.ShowWarningExcp(strPath, ex);
                }
            }
        }
Ejemplo n.º 50
0
        public override void Import(PwDatabase pwStorage, Stream sInput, IStatusLogger slLogger)
        {
            var form = new OptionForm();

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

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

            var pfp     = new PfpConvert();
            var protect = Util.GetMemoryProtection(pwStorage.MemoryProtection);

            protect.Add("PIN");
            protect.Add("PUK");
            protect.Add("CVV");

            var entries = pfp.Load(sInput, form.MasterPassword);
            var pw      = pfp.GetPasswordGetter(form.MasterPassword);

            var i = 0;

            foreach (var baseentry in entries)
            {
                if (!(baseentry is PassEntry entry))
                {
                    continue;
                }

                slLogger.SetText($"Importing {entry.name}@{entry.site}...", LogStatusType.Info);

                var pwEntry = Util.GetKeepassEntry(entry, pw, protect);

                pwStorage.RootGroup.AddEntry(pwEntry, true);
                i++;
            }

            slLogger.SetText($"Imported {i} entries.", LogStatusType.Info);
        }
Ejemplo n.º 51
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            byte[] pb = MemUtil.Read(sInput);

            if (ImportOld(pwStorage, pb))
            {
                return;
            }

            XmlDocument d = XmlUtilEx.CreateXmlDocument();

            using (MemoryStream ms = new MemoryStream(pb, false))
            {
                using (StreamReader sr = new StreamReader(ms, StrUtil.Utf8, true))
                {
                    d.Load(sr);
                }
            }

            XmlNode xmlRoot = d.DocumentElement;

            Debug.Assert(xmlRoot.Name == "data");

            foreach (XmlNode xmlChild in xmlRoot.ChildNodes)
            {
                if (xmlChild.Name == ElemGroup)
                {
                    ReadGroup(xmlChild, pwStorage.RootGroup, pwStorage);
                }
                else if (xmlChild.Name == ElemEntry)
                {
                    ReadEntry(xmlChild, pwStorage.RootGroup, pwStorage);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
        }
Ejemplo n.º 52
0
        public override void Import(PwDatabase pwStorage, Stream sInput, IStatusLogger slLogger)
        {
            var entries   = new List <Entry>();
            var name      = GetName(sInput);
            var rootGroup = CreateGroup(pwStorage, name);

            using (var reader = new StreamReader(sInput, System.Text.Encoding.UTF8))
            {
                while (!reader.EndOfStream)
                {
                    var entry = Entry.Read(reader);
                    entries.Add(entry);
                }
            }

            for (int i = 0; i < entries.Count; i++)
            {
                var entry = entries[i];
                slLogger.SetText(string.Format("{0} ({1} of {2})", entry.Name, i + 1, entries.Count), LogStatusType.Info);
                AddEntry(pwStorage, rootGroup, entry);
            }
        }
Ejemplo n.º 53
0
 public static void Load(string strFilePath, IStatusLogger slStatus)
 {
     try { LoadPriv(strFilePath, slStatus, true, true, true, null); }
     catch (PlgxException exPlgx)
     {
         MessageService.ShowWarning(strFilePath + MessageService.NewParagraph +
                                    KPRes.PluginLoadFailed + MessageService.NewParagraph +
                                    exPlgx.Message);
     }
     catch (Exception exLoad)
     {
         if (Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null)
         {
             MessageService.ShowWarningExcp(strFilePath, exLoad);
         }
         else
         {
             MessageService.ShowWarning(KPRes.PluginIncompatible +
                                        MessageService.NewLine + strFilePath, KPRes.PluginUpdateHint);
         }
     }
 }
Ejemplo n.º 54
0
			DownloadInfoFiles(List<string> lUrls, IStatusLogger sl)
		{
			List<UpdateDownloadInfo> lDl = new List<UpdateDownloadInfo>();
			foreach(string strUrl in lUrls)
			{
				if(string.IsNullOrEmpty(strUrl)) { Debug.Assert(false); continue; }

				UpdateDownloadInfo dl = new UpdateDownloadInfo(strUrl);
				lDl.Add(dl);

				ThreadPool.QueueUserWorkItem(new WaitCallback(
					UpdateCheckEx.DownloadInfoFile), dl);
			}

			while(true)
			{
				bool bReady = true;
				foreach(UpdateDownloadInfo dl in lDl)
				{
					lock(dl.SyncObj) { bReady &= dl.Ready; }
				}

				if(bReady) break;
				Thread.Sleep(40);

				if(sl != null)
				{
					if(!sl.ContinueWork()) return null;
				}
			}

			Dictionary<string, List<UpdateComponentInfo>> dict =
				new Dictionary<string, List<UpdateComponentInfo>>();
			foreach(UpdateDownloadInfo dl in lDl)
			{
				dict[dl.Url.ToLower()] = dl.ComponentInfo;
			}
			return dict;
		}
Ejemplo n.º 55
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr     = new StreamReader(sInput, StrUtil.Utf8);
            string       strDoc = sr.ReadToEnd();

            sr.Close();

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(strDoc);

            XmlElement xmlRoot = doc.DocumentElement;

            Debug.Assert(xmlRoot.Name == ElemRoot);

            PwGroup pgRoot = pwStorage.RootGroup;

            foreach (XmlNode xmlChild in xmlRoot.ChildNodes)
            {
                if (xmlChild.Name == ElemGroup)
                {
                    ImportGroup(xmlChild, pgRoot, pwStorage, false);
                }
                else if (xmlChild.Name == ElemRecycleBin)
                {
                    ImportGroup(xmlChild, pgRoot, pwStorage, true);
                }
                else if (xmlChild.Name == ElemEntry)
                {
                    ImportEntry(xmlChild, pgRoot, pwStorage);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
        }
Ejemplo n.º 56
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);
        }
Ejemplo n.º 57
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)
		{
			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;
		}
Ejemplo n.º 58
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            string strAll;

            using (StreamReader sr = new StreamReader(sInput, Encoding.UTF8, true))
            {
                strAll = sr.ReadToEnd();
            }

            // Fix new-line sequences and normalize to '\n'
            strAll = strAll.Replace("\r\r\n", "\r\n");
            strAll = StrUtil.NormalizeNewLines(strAll, false);

            string[] vBlocks = strAll.Split(new string[] { "\n\n---\n\n" },
                                            StringSplitOptions.None);
            PwGroup pg = pwStorage.RootGroup;

            foreach (string strBlock in vBlocks)
            {
                ImportBlock(pwStorage, ref pg, strBlock);
            }
        }
Ejemplo n.º 59
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            StreamReader sr      = new StreamReader(sInput, StrUtil.Utf8, true);
            string       strData = sr.ReadToEnd();

            sr.Close();

            // The Chrome extension of LastPass 4.1.35 encodes some
            // special characters as XML entities; the web version and
            // the Firefox extension do not do this
            strData = strData.Replace(@"&lt;", @"<");
            strData = strData.Replace(@"&gt;", @">");
            strData = strData.Replace(@"&amp;", @"&");

            CsvOptions opt = new CsvOptions();

            opt.BackslashIsEscape = false;

            CsvStreamReaderEx csr = new CsvStreamReaderEx(strData, opt);

            ImportCsv(csr, pwStorage);
        }
        public override void Import(PwDatabase pwStorage, System.IO.Stream sInput, IStatusLogger slLogger)
        {
            var document = new XmlDocument();

            document.Load(sInput);

            var root     = document.DocumentElement;
            var products = root.SelectNodes("Product_Key");

            if (products == null || products.Count == 0)
            {
                return;
            }

            var msdnGroup = pwStorage.RootGroup.FindCreateGroup("Microsoft Product Keys", true);

            for (int i = 0; i < products.Count; i++)
            {
                var product = new Product(products[i]);
                slLogger.SetText(string.Format("{0} ({1} of {2})", product.Name, i + 1, products.Count), LogStatusType.Info);
                AddProduct(pwStorage, msdnGroup, product);
            }
        }