1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
|
/*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2024 Dominik Reichl <dominik.reichl@t-online.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using KeePass.Resources;
using KeePassLib;
using KeePassLib.Collections;
using KeePassLib.Cryptography.KeyDerivation;
using KeePassLib.Delegates;
using KeePassLib.Interfaces;
using KeePassLib.Keys;
using KeePassLib.Resources;
using KeePassLib.Security;
using KeePassLib.Utility;
namespace KeePass.DataExchange
{
/// <summary>
/// Serialization to KeePass KDB files.
/// </summary>
public sealed class KdbFile
{
private readonly PwDatabase m_pwDatabase;
private readonly IStatusLogger m_slLogger;
private const string KdbPrefix = "KDB: ";
private const string AutoTypePrefix = "Auto-Type";
private const string AutoTypeWindowPrefix = "Auto-Type-Window";
private const string UrlOverridePrefix = "Url-Override:";
public static bool IsLibraryInstalled()
{
Exception ex;
return IsLibraryInstalled(out ex);
}
public static bool IsLibraryInstalled(out Exception ex)
{
try
{
KdbManager mgr = new KdbManager();
mgr.Dispose();
}
catch(Exception exMgr)
{
ex = exMgr;
return false;
}
ex = null;
return true;
}
/// <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;
}
private static KdbErrorCode SetDatabaseKey(KdbManager mgr, CompositeKey pwKey)
{
string strPassword = null;
if(pwKey.ContainsType(typeof(KcpPassword)))
{
KcpPassword p = (pwKey.GetUserKey(typeof(KcpPassword)) as KcpPassword);
ProtectedString ps = ((p != null) ? p.Password : null);
if(ps == null)
throw new Exception(KPRes.OptionReqOn + @" '" +
KPRes.MasterPasswordRmbWhileOpen + @"'.");
strPassword = ps.ReadString();
}
string strKeyFile = null;
if(pwKey.ContainsType(typeof(KcpKeyFile)))
strKeyFile = (pwKey.GetUserKey(typeof(KcpKeyFile)) as KcpKeyFile).Path;
KdbErrorCode e;
if(!string.IsNullOrEmpty(strKeyFile))
e = mgr.SetMasterKey(strKeyFile, true, strPassword, IntPtr.Zero, false);
else if(strPassword != null)
e = mgr.SetMasterKey(strPassword, false, null, IntPtr.Zero, false);
else if(pwKey.ContainsType(typeof(KcpUserAccount)))
throw new Exception(KPRes.KdbWUA);
else throw new Exception(KLRes.InvalidCompositeKey);
return e;
}
/// <summary>
/// Loads a KDB file and stores all loaded entries in the current
/// PwDatabase instance.
/// </summary>
/// <param name="strFilePath">Relative or absolute path to the file to open.</param>
public void Load(string strFilePath)
{
Debug.Assert(strFilePath != null);
if(strFilePath == null) throw new ArgumentNullException("strFilePath");
using(KdbManager mgr = new KdbManager())
{
KdbErrorCode e;
e = KdbFile.SetDatabaseKey(mgr, m_pwDatabase.MasterKey);
if(e != KdbErrorCode.Success)
throw new Exception(KLRes.InvalidCompositeKey);
e = mgr.OpenDatabase(strFilePath, IntPtr.Zero);
if(e != KdbErrorCode.Success)
throw new Exception(KLRes.FileLoadFailed);
// Copy properties
m_pwDatabase.KdfParameters = (new AesKdf()).GetDefaultParameters();
m_pwDatabase.KdfParameters.SetUInt64(AesKdf.ParamRounds,
mgr.KeyTransformationRounds);
// Read groups and entries
Dictionary<UInt32, PwGroup> dictGroups = ReadGroups(mgr);
ReadEntries(mgr, dictGroups);
}
}
private Dictionary<UInt32, PwGroup> ReadGroups(KdbManager mgr)
{
uint uGroupCount = mgr.GroupCount;
Dictionary<UInt32, PwGroup> dictGroups = new Dictionary<UInt32, PwGroup>();
Stack<PwGroup> vGroupStack = new Stack<PwGroup>();
vGroupStack.Push(m_pwDatabase.RootGroup);
DateTime dtNeverExpire = KdbManager.GetNeverExpireTime();
for(uint uGroup = 0; uGroup < uGroupCount; ++uGroup)
{
KdbGroup g = mgr.GetGroup(uGroup);
PwGroup pg = new PwGroup(true, false);
pg.Name = g.Name;
pg.IconId = (g.ImageId < (uint)PwIcon.Count) ? (PwIcon)g.ImageId : PwIcon.Folder;
pg.CreationTime = g.CreationTime.ToDateTime();
pg.LastModificationTime = g.LastModificationTime.ToDateTime();
pg.LastAccessTime = g.LastAccessTime.ToDateTime();
pg.ExpiryTime = g.ExpirationTime.ToDateTime();
pg.Expires = (pg.ExpiryTime != dtNeverExpire);
pg.IsExpanded = ((g.Flags & (uint)KdbGroupFlags.Expanded) != 0);
while(g.Level < (vGroupStack.Count - 1))
vGroupStack.Pop();
vGroupStack.Peek().AddGroup(pg, true);
dictGroups[g.GroupId] = pg;
if(g.Level == (uint)(vGroupStack.Count - 1))
vGroupStack.Push(pg);
}
return dictGroups;
}
private void ReadEntries(KdbManager mgr, Dictionary<UInt32, PwGroup> dictGroups)
{
DateTime dtNeverExpire = KdbManager.GetNeverExpireTime();
uint uEntryCount = mgr.EntryCount;
for(uint uEntry = 0; uEntry < uEntryCount; ++uEntry)
{
KdbEntry e = mgr.GetEntry(uEntry);
PwGroup pgContainer;
if(!dictGroups.TryGetValue(e.GroupId, out pgContainer))
{
Debug.Assert(false);
continue;
}
PwEntry pe = new PwEntry(false, false);
pe.SetUuid(new PwUuid(e.Uuid.ToByteArray()), false);
pgContainer.AddEntry(pe, true, true);
pe.IconId = (e.ImageId < (uint)PwIcon.Count) ? (PwIcon)e.ImageId : PwIcon.Key;
pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
m_pwDatabase.MemoryProtection.ProtectTitle, e.Title));
pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
m_pwDatabase.MemoryProtection.ProtectUserName, e.UserName));
pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
m_pwDatabase.MemoryProtection.ProtectPassword, e.Password));
pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
m_pwDatabase.MemoryProtection.ProtectUrl, e.Url));
string strNotes = e.Additional;
ImportAutoType(ref strNotes, pe);
ImportUrlOverride(ref strNotes, pe);
pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
m_pwDatabase.MemoryProtection.ProtectNotes, strNotes));
pe.CreationTime = e.CreationTime.ToDateTime();
pe.LastModificationTime = e.LastModificationTime.ToDateTime();
pe.LastAccessTime = e.LastAccessTime.ToDateTime();
pe.ExpiryTime = e.ExpirationTime.ToDateTime();
pe.Expires = (pe.ExpiryTime != dtNeverExpire);
if((e.BinaryDataLength > 0) && (e.BinaryData != IntPtr.Zero))
{
byte[] pbData = KdbManager.ReadBinary(e.BinaryData, e.BinaryDataLength);
Debug.Assert(pbData.Length == e.BinaryDataLength);
string strDesc = e.BinaryDescription;
if(string.IsNullOrEmpty(strDesc)) strDesc = "Attachment";
pe.Binaries.Set(strDesc, new ProtectedBinary(false, pbData));
}
if(m_slLogger != null)
{
if(!m_slLogger.SetProgress((100 * uEntry) / uEntryCount))
throw new Exception(KPRes.Cancel);
}
}
}
/// <summary>
/// Save the contents of the current <c>PwDatabase</c> to a KDB file.
/// </summary>
/// <param name="strSaveToFile">Location to save the KDB file to.</param>
public void Save(string strSaveToFile, PwGroup pgDataSource)
{
Debug.Assert(strSaveToFile != null);
if(strSaveToFile == null) throw new ArgumentNullException("strSaveToFile");
using(KdbManager mgr = new KdbManager())
{
KdbErrorCode e = KdbFile.SetDatabaseKey(mgr, m_pwDatabase.MasterKey);
if(e != KdbErrorCode.Success)
{
Debug.Assert(false);
throw new Exception(KLRes.InvalidCompositeKey);
}
if(m_slLogger != null)
{
if(m_pwDatabase.MasterKey.ContainsType(typeof(KcpUserAccount)))
m_slLogger.SetText(KPRes.KdbWUA, LogStatusType.Warning);
if(m_pwDatabase.Name.Length != 0)
m_slLogger.SetText(KdbPrefix + KPRes.FormatNoDatabaseName, LogStatusType.Warning);
if(m_pwDatabase.Description.Length != 0)
m_slLogger.SetText(KdbPrefix + KPRes.FormatNoDatabaseDesc, LogStatusType.Warning);
}
// Set properties
AesKdf kdf = new AesKdf();
if(!kdf.Uuid.Equals(m_pwDatabase.KdfParameters.KdfUuid))
mgr.KeyTransformationRounds = (uint)PwDefs.DefaultKeyEncryptionRounds;
else
{
ulong uRounds = m_pwDatabase.KdfParameters.GetUInt64(
AesKdf.ParamRounds, PwDefs.DefaultKeyEncryptionRounds);
uRounds = Math.Min(uRounds, 0xFFFFFFFEUL);
mgr.KeyTransformationRounds = (uint)uRounds;
}
PwGroup pgRoot = (pgDataSource ?? m_pwDatabase.RootGroup);
// Write groups and entries
Dictionary<PwGroup, UInt32> dictGroups = WriteGroups(mgr, pgRoot);
WriteEntries(mgr, dictGroups, pgRoot);
e = mgr.SaveDatabase(strSaveToFile);
if(e != KdbErrorCode.Success)
throw new Exception(KLRes.FileSaveFailed);
}
}
private static Dictionary<PwGroup, UInt32> WriteGroups(KdbManager mgr,
PwGroup pgRoot)
{
Dictionary<PwGroup, UInt32> dictGroups = new Dictionary<PwGroup, UInt32>();
uint uGroupIndex = 1;
DateTime dtNeverExpire = KdbManager.GetNeverExpireTime();
GroupHandler gh = delegate(PwGroup pg)
{
WriteGroup(pg, pgRoot, ref uGroupIndex, dictGroups, dtNeverExpire,
mgr, false);
return true;
};
pgRoot.TraverseTree(TraversalMethod.PreOrder, gh, null);
Debug.Assert(dictGroups.Count == (int)(uGroupIndex - 1));
EnsureParentGroupsExported(pgRoot, ref uGroupIndex, dictGroups,
dtNeverExpire, mgr);
return dictGroups;
}
private static void WriteGroup(PwGroup pg, PwGroup pgRoot, ref uint uGroupIndex,
Dictionary<PwGroup, UInt32> dictGroups, DateTime dtNeverExpire,
KdbManager mgr, bool bForceLevel0)
{
if(pg == pgRoot) return;
KdbGroup grp = new KdbGroup();
grp.GroupId = uGroupIndex;
dictGroups[pg] = grp.GroupId;
grp.ImageId = (uint)pg.IconId;
grp.Name = pg.Name;
grp.CreationTime.Set(pg.CreationTime);
grp.LastModificationTime.Set(pg.LastModificationTime);
grp.LastAccessTime.Set(pg.LastAccessTime);
if(pg.Expires)
grp.ExpirationTime.Set(pg.ExpiryTime);
else grp.ExpirationTime.Set(dtNeverExpire);
grp.Level = (bForceLevel0 ? (ushort)0 : (ushort)(pg.GetDepth() - 1));
if(pg.IsExpanded) grp.Flags |= (uint)KdbGroupFlags.Expanded;
if(!mgr.AddGroup(ref grp))
{
Debug.Assert(false);
throw new InvalidOperationException();
}
++uGroupIndex;
}
private static void EnsureParentGroupsExported(PwGroup pgRoot, ref uint uGroupIndex,
Dictionary<PwGroup, UInt32> dictGroups, DateTime dtNeverExpires,
KdbManager mgr)
{
bool bHasAtLeastOneGroup = (dictGroups.Count > 0);
uint uLocalIndex = uGroupIndex; // Local copy, can't use ref in delegate
EntryHandler eh = delegate(PwEntry pe)
{
PwGroup pg = pe.ParentGroup;
if(pg == null) { Debug.Assert(false); return true; }
if(bHasAtLeastOneGroup && (pg == pgRoot)) return true;
if(dictGroups.ContainsKey(pg)) return true;
WriteGroup(pg, pgRoot, ref uLocalIndex, dictGroups, dtNeverExpires,
mgr, true);
return true;
};
pgRoot.TraverseTree(TraversalMethod.PreOrder, null, eh);
uGroupIndex = uLocalIndex;
}
private void WriteEntries(KdbManager mgr, Dictionary<PwGroup, UInt32> dictGroups,
PwGroup pgRoot)
{
bool bWarnedOnce = false;
uint uGroupCount, uEntryCount, uEntriesSaved = 0;
pgRoot.GetCounts(true, out uGroupCount, out uEntryCount);
DateTime dtNeverExpire = KdbManager.GetNeverExpireTime();
EntryHandler eh = delegate(PwEntry pe)
{
KdbEntry e = new KdbEntry();
e.Uuid.Set(pe.Uuid.UuidBytes);
if(pe.ParentGroup != pgRoot)
e.GroupId = dictGroups[pe.ParentGroup];
else
{
e.GroupId = 1;
if((m_slLogger != null) && !bWarnedOnce)
{
m_slLogger.SetText(KdbPrefix +
KPRes.FormatNoRootEntries, LogStatusType.Warning);
bWarnedOnce = true;
}
if(dictGroups.Count == 0)
throw new Exception(KPRes.FormatNoSubGroupsInRoot);
}
e.ImageId = (uint)pe.IconId;
e.Title = pe.Strings.ReadSafe(PwDefs.TitleField);
e.UserName = pe.Strings.ReadSafe(PwDefs.UserNameField);
e.Password = pe.Strings.ReadSafe(PwDefs.PasswordField);
e.Url = pe.Strings.ReadSafe(PwDefs.UrlField);
string strNotes = pe.Strings.ReadSafe(PwDefs.NotesField);
ExportCustomStrings(pe, ref strNotes);
ExportAutoType(pe, ref strNotes);
ExportUrlOverride(pe, ref strNotes);
e.Additional = strNotes;
e.PasswordLength = (uint)e.Password.Length;
Debug.Assert(TimeUtil.PwTimeLength == 7);
e.CreationTime.Set(pe.CreationTime);
e.LastModificationTime.Set(pe.LastModificationTime);
e.LastAccessTime.Set(pe.LastAccessTime);
if(pe.Expires) e.ExpirationTime.Set(pe.ExpiryTime);
else e.ExpirationTime.Set(dtNeverExpire);
IntPtr hBinaryData = IntPtr.Zero;
if(pe.Binaries.UCount != 0)
{
foreach(KeyValuePair<string, ProtectedBinary> kvp in pe.Binaries)
{
e.BinaryDescription = kvp.Key;
byte[] pbAttached = kvp.Value.ReadData();
e.BinaryDataLength = (uint)pbAttached.Length;
if(e.BinaryDataLength > 0)
{
hBinaryData = Marshal.AllocHGlobal((int)e.BinaryDataLength);
Marshal.Copy(pbAttached, 0, hBinaryData, (int)e.BinaryDataLength);
e.BinaryData = hBinaryData;
}
break; // In KDB, an entry may have at most one attachment
}
if((pe.Binaries.UCount > 1) && (m_slLogger != null))
m_slLogger.SetText(KdbPrefix + KPRes.FormatOnlyOneAttachment + "\r\n\r\n" +
KPRes.Entry + ":\r\n" + KPRes.Title + ": " + e.Title + "\r\n" +
KPRes.UserName + ": " + e.UserName, LogStatusType.Warning);
}
bool bResult = mgr.AddEntry(ref e);
Marshal.FreeHGlobal(hBinaryData);
hBinaryData = IntPtr.Zero;
if(!bResult)
{
Debug.Assert(false);
throw new InvalidOperationException();
}
++uEntriesSaved;
if(m_slLogger != null)
if(!m_slLogger.SetProgress((100 * uEntriesSaved) / uEntryCount))
return false;
return true;
};
if(!pgRoot.TraverseTree(TraversalMethod.PreOrder, null, eh))
throw new InvalidOperationException();
}
/* private static void ImportAutoType(ref string strNotes, PwEntry peStorage)
{
string str = strNotes;
char[] vTrim = new char[] { '\r', '\n', '\t', ' ' };
int nFirstAutoType = str.IndexOf(AutoTypePrefix, StringComparison.OrdinalIgnoreCase);
if(nFirstAutoType < 0) nFirstAutoType = int.MaxValue;
int nFirstAutoTypeWindow = str.IndexOf(AutoTypeWindowPrefix, StringComparison.OrdinalIgnoreCase);
if((nFirstAutoTypeWindow >= 0) && (nFirstAutoTypeWindow < nFirstAutoType))
{
int nWindowEnd = str.IndexOf('\n', nFirstAutoTypeWindow);
if(nWindowEnd < 0) nWindowEnd = str.Length - 1;
string strWindow = str.Substring(nFirstAutoTypeWindow + AutoTypeWindowPrefix.Length,
nWindowEnd - nFirstAutoTypeWindow - AutoTypeWindowPrefix.Length + 1);
strWindow = strWindow.Trim(vTrim);
str = str.Remove(nFirstAutoTypeWindow, nWindowEnd - nFirstAutoTypeWindow + 1);
peStorage.AutoType.Set(strWindow, string.Empty);
}
while(true)
{
int nAutoTypeStart = str.IndexOf(AutoTypePrefix, 0,
StringComparison.OrdinalIgnoreCase);
if(nAutoTypeStart < 0) break;
int nAutoTypeEnd = str.IndexOf('\n', nAutoTypeStart);
if(nAutoTypeEnd < 0) nAutoTypeEnd = str.Length - 1;
string strAutoType = str.Substring(nAutoTypeStart + AutoTypePrefix.Length,
nAutoTypeEnd - nAutoTypeStart - AutoTypePrefix.Length + 1);
strAutoType = strAutoType.Trim(vTrim);
str = str.Remove(nAutoTypeStart, nAutoTypeEnd - nAutoTypeStart + 1);
int nWindowStart = str.IndexOf(AutoTypeWindowPrefix, 0,
StringComparison.OrdinalIgnoreCase);
if((nWindowStart < 0) || (nWindowStart >= nAutoTypeStart))
{
peStorage.AutoType.DefaultSequence = strAutoType;
continue;
}
int nWindowEnd = str.IndexOf('\n', nWindowStart);
if(nWindowEnd < 0) nWindowEnd = str.Length - 1;
string strWindow = str.Substring(nWindowStart + AutoTypeWindowPrefix.Length,
nWindowEnd - nWindowStart - AutoTypeWindowPrefix.Length + 1);
strWindow = strWindow.Trim(vTrim);
str = str.Remove(nWindowStart, nWindowEnd - nWindowStart + 1);
peStorage.AutoType.Set(strWindow, strAutoType);
}
strNotes = str;
} */
private static void ImportAutoType(ref string strNotes, PwEntry peStorage)
{
if(string.IsNullOrEmpty(strNotes)) return;
string str = strNotes.Replace("\r", string.Empty);
string[] vLines = str.Split('\n');
string strOvr = FindPrefixedLine(vLines, AutoTypePrefix + ":");
if((strOvr != null) && (strOvr.Length > (AutoTypePrefix.Length + 1)))
{
strOvr = strOvr.Substring(AutoTypePrefix.Length + 1).Trim();
peStorage.AutoType.DefaultSequence = ConvertAutoTypeSequence(
strOvr, true);
}
StringBuilder sb = new StringBuilder();
foreach(string strLine in vLines)
{
bool bProcessed = false;
for(int iIdx = 0; iIdx < 32; ++iIdx)
{
string s = ((iIdx == 0) ? string.Empty : ("-" +
iIdx.ToString(NumberFormatInfo.InvariantInfo)));
string strWndPrefix = (AutoTypeWindowPrefix + s + ":");
string strSeqPrefix = (AutoTypePrefix + s + ":");
if(strLine.StartsWith(strWndPrefix, StrUtil.CaseIgnoreCmp) &&
(strLine.Length > strWndPrefix.Length))
{
string strWindow = strLine.Substring(strWndPrefix.Length).Trim();
string strSeq = FindPrefixedLine(vLines, strSeqPrefix);
if((strSeq != null) && (strSeq.Length > strSeqPrefix.Length))
peStorage.AutoType.Add(new AutoTypeAssociation(
strWindow, ConvertAutoTypeSequence(strSeq.Substring(
strSeqPrefix.Length), true)));
else // Window, but no sequence
peStorage.AutoType.Add(new AutoTypeAssociation(
strWindow, string.Empty));
bProcessed = true;
break;
}
else if(strLine.StartsWith(strSeqPrefix, StrUtil.CaseIgnoreCmp))
{
bProcessed = true;
break;
}
}
if(!bProcessed)
{
sb.Append(strLine);
sb.Append(MessageService.NewLine);
}
}
strNotes = sb.ToString();
// peStorage.AutoType.Sort();
}
private static string FindPrefixedLine(string[] vLines, string strPrefix)
{
foreach(string str in vLines)
{
if(str.StartsWith(strPrefix, StrUtil.CaseIgnoreCmp))
return str;
}
return null;
}
private static Dictionary<string, string> g_dSeq1xTo2x = null;
private static Dictionary<string, string> g_dSeq1xTo2xBiDir = null;
private static string ConvertAutoTypeSequence(string strSeq, bool b1xTo2x)
{
if(string.IsNullOrEmpty(strSeq)) return string.Empty;
if(g_dSeq1xTo2x == null)
{
g_dSeq1xTo2x = new Dictionary<string, string>();
// m_dSeq1xTo2x[@"{SPACE}"] = " ";
// m_dSeq1xTo2x[@"{CLEARFIELD}"] = @"{HOME}+({END}){DEL}";
g_dSeq1xTo2xBiDir = new Dictionary<string, string>
{
{ @"{AT}", @"@" },
{ @"{PLUS}", @"{+}" },
{ @"{PERCENT}", @"{%}" },
{ @"{CARET}", @"{^}" },
{ @"{TILDE}", @"{~}" },
{ @"{LEFTBRACE}", @"{{}" },
{ @"{RIGHTBRACE}", @"{}}" },
{ @"{LEFTPAREN}", @"{(}" },
{ @"{RIGHTPAREN}", @"{)}" },
{ @"(+{END})", @"+({END})" }
};
}
string str = strSeq.Trim();
if(b1xTo2x)
{
foreach(KeyValuePair<string, string> kvp in g_dSeq1xTo2x)
str = StrUtil.ReplaceCaseInsensitive(str, kvp.Key, kvp.Value);
}
foreach(KeyValuePair<string, string> kvp in g_dSeq1xTo2xBiDir)
{
if(b1xTo2x) str = StrUtil.ReplaceCaseInsensitive(str, kvp.Key, kvp.Value);
else str = StrUtil.ReplaceCaseInsensitive(str, kvp.Value, kvp.Key);
}
if(!b1xTo2x) str = CapitalizePlaceholders(str);
return str;
}
private static string CapitalizePlaceholders(string strSeq)
{
string str = strSeq;
int iOffset = 0;
while(true)
{
int iStart = str.IndexOf('{', iOffset);
if(iStart < 0) break;
int iEnd = str.IndexOf('}', iStart);
if(iEnd < 0) break; // No assert (user data)
string strPlaceholder = str.Substring(iStart, iEnd - iStart + 1);
if(!strPlaceholder.StartsWith("{S:", StrUtil.CaseIgnoreCmp))
str = str.Replace(strPlaceholder, strPlaceholder.ToUpperInvariant());
iOffset = iStart + 1;
}
return str;
}
private static void ExportCustomStrings(PwEntry peSource, ref string strNotes)
{
bool bSep = false;
foreach(KeyValuePair<string, ProtectedString> kvp in peSource.Strings)
{
if(PwDefs.IsStandardField(kvp.Key)) continue;
if(!bSep)
{
if(strNotes.Length > 0) strNotes += MessageService.NewParagraph;
bSep = true;
}
strNotes += kvp.Key + ": " + kvp.Value.ReadString() +
MessageService.NewLine;
}
}
private static void ExportAutoType(PwEntry peSource, ref string strNotes)
{
StringBuilder sbAppend = new StringBuilder();
bool bSeparator = false;
uint uIndex = 0;
if((peSource.AutoType.DefaultSequence.Length > 0) &&
(peSource.AutoType.AssociationsCount == 0)) // Avoid broken indices
{
if(strNotes.Length > 0)
sbAppend.Append(MessageService.NewParagraph);
sbAppend.Append(AutoTypePrefix);
sbAppend.Append(@": ");
sbAppend.Append(ConvertAutoTypeSeqExp(peSource.AutoType.DefaultSequence,
peSource));
sbAppend.Append(MessageService.NewLine);
bSeparator = true;
++uIndex;
}
foreach(AutoTypeAssociation a in peSource.AutoType.Associations)
{
if(!bSeparator)
{
if(strNotes.Length > 0)
sbAppend.Append(MessageService.NewParagraph);
bSeparator = true;
}
string strSuffix = ((uIndex > 0) ? ("-" + uIndex.ToString(
NumberFormatInfo.InvariantInfo)) : string.Empty);
sbAppend.Append(AutoTypePrefix + strSuffix);
sbAppend.Append(@": ");
sbAppend.Append(ConvertAutoTypeSeqExp(a.Sequence, peSource));
sbAppend.Append(MessageService.NewLine);
sbAppend.Append(AutoTypeWindowPrefix + strSuffix);
sbAppend.Append(@": ");
sbAppend.Append(a.WindowName);
sbAppend.Append(MessageService.NewLine);
++uIndex;
}
strNotes = strNotes.TrimEnd(new char[] { '\r', '\n', '\t', ' ' });
strNotes += sbAppend.ToString();
}
private static string ConvertAutoTypeSeqExp(string strSeq, PwEntry pe)
{
string strExp = strSeq;
if(string.IsNullOrEmpty(strExp)) strExp = pe.GetAutoTypeSequence();
return ConvertAutoTypeSequence(strExp, false);
}
private static void ImportUrlOverride(ref string strNotes, PwEntry peStorage)
{
string str = strNotes;
char[] vTrim = new char[] { '\r', '\n', '\t', ' ' };
int nUrlStart = str.IndexOf(UrlOverridePrefix, 0,
StringComparison.OrdinalIgnoreCase);
if(nUrlStart < 0) return;
int nUrlEnd = str.IndexOf('\n', nUrlStart);
if(nUrlEnd < 0) nUrlEnd = str.Length - 1;
string strUrl = str.Substring(nUrlStart + UrlOverridePrefix.Length,
nUrlEnd - nUrlStart - UrlOverridePrefix.Length + 1);
strUrl = strUrl.Trim(vTrim);
peStorage.OverrideUrl = strUrl;
str = str.Remove(nUrlStart, nUrlEnd - nUrlStart + 1);
strNotes = str;
}
private static void ExportUrlOverride(PwEntry peSource, ref string strNotes)
{
if(peSource.OverrideUrl.Length > 0)
{
StringBuilder sbAppend = new StringBuilder();
sbAppend.Append(MessageService.NewParagraph);
sbAppend.Append(UrlOverridePrefix);
sbAppend.Append(@" ");
sbAppend.Append(peSource.OverrideUrl);
sbAppend.Append(MessageService.NewLine);
strNotes = strNotes.TrimEnd(new char[] { '\r', '\n', '\t', ' ' });
strNotes += sbAppend.ToString();
}
}
}
}
|