Ejemplo n.º 1
0
        private static void GenerateKfb(StringBuilder sb, PwDatabase pd,
                                        string strDbFile, string strKeyFile,
                                        GFunc <string, string> h, GFunc <string, string> ne, GFunc <string, string> ltrPath,
                                        string strFillInit, string strFillInitEx, string strFillEnd, string strFill)
        {
            string strContent;

            using (Stream s = IOConnection.OpenRead(IOConnectionInfo.FromPath(
                                                        strKeyFile)))
            {
                using (StreamReader sr = new StreamReader(s, StrUtil.Utf8, true))
                {
                    strContent = sr.ReadToEnd();
                }
            }

            // Internet Explorer 11 does not support the 'tab-size' CSS property
            strContent = strContent.Replace("\t", "    ");

            string strNlCode = (new PwUuid(true)).ToHexString();

            strContent = StrUtil.NormalizeNewLines(strContent, false);
            strContent = strContent.Replace("\n", strNlCode);             // Prevent <br />

            strContent = StrUtil.StringToHtml(strContent, false);

            strContent = strContent.Replace(strNlCode, MessageService.NewLine);

            sb.AppendLine("<p><strong>" + h(KPRes.KeyFile) + ":</strong></p>");
            sb.AppendLine(strFillInitEx + ne(h(ltrPath(strKeyFile))) + strFillEnd);

            sb.AppendLine("<br />");
            sb.AppendLine("<p><strong>" + h(KPRes.DatabaseFile) + ":</strong></p>");
            sb.AppendLine(strFillInitEx + ne(h(ltrPath(strDbFile))) + strFillEnd);

            sb.AppendLine("<br />");
            sb.AppendLine("<p><strong>" + h(KPRes.KeyFileContent) + ":</strong></p>");
            sb.AppendLine(strFillInit);
            sb.Append("<pre>");
            sb.Append(strContent);
            sb.AppendLine("</pre>");
            sb.AppendLine(strFillEnd);

            sb.AppendLine("<br />");
            sb.AppendLine("<h3>" + h(KPRes.InstrAndGenInfo) + "</h3>");

            sb.AppendLine("<ul class=\"withspc\">");
            sb.AppendLine("<li>" + h(KPRes.KeyFileFromBackup) + ":");
            sb.AppendLine("<ul class=\"withspc\">");
            sb.AppendLine("<li><p>" + Beautify(h(KPRes.KeyFileFromBackupF2)) + "</p></li>");
            sb.AppendLine("<li><p>" + h(KPRes.KeyFileFromBackupT) + "</p></li>");
            sb.AppendLine("</ul></li>");
            sb.AppendLine("<li>" + h(KPRes.LatestVersionWeb) + ": <a href=\"" +
                          h(PwDefs.HomepageUrl) + "\" target=\"_blank\">" +
                          h(PwDefs.HomepageUrl) + "</a>.</li>");
            sb.AppendLine("</ul>");
        }
Ejemplo n.º 2
0
        private static string GenerateDoc(PwDatabase pd, bool bEmSheet, bool bKeyFile)
        {
            string strDbFile = pd.IOConnectionInfo.Path;

            KcpKeyFile kf         = (pd.MasterKey.GetUserKey(typeof(KcpKeyFile)) as KcpKeyFile);
            string     strKeyFile = ((kf != null) ? kf.Path : string.Empty);

            if (bKeyFile)
            {
                if (strKeyFile.Length == 0)
                {
                    Debug.Assert(false); return(string.Empty);
                }

                if (!KfxFile.CanLoad(strKeyFile))
                {
                    throw new FormatException(strKeyFile + MessageService.NewParagraph +
                                              KPRes.KeyFileNoXml + MessageService.NewParagraph +
                                              KPRes.KeyFilePrintReqXml + MessageService.NewParagraph +
                                              KPRes.KeyFileGenHint);
                }
            }

            string strName = UrlUtil.StripExtension(UrlUtil.GetFileName(bEmSheet ?
                                                                        strDbFile : strKeyFile));

            if (strName.Length == 0)
            {
                strName = (bEmSheet ? KPRes.Database : KPRes.KeyFile);
            }

            string strDocKind = (bEmSheet ? KPRes.EmergencySheet : KPRes.KeyFileBackup);

            bool   bRtl        = Program.Translation.Properties.RightToLeft;
            string strLogLeft  = (bRtl ? "right" : "left");
            string strLogRight = (bRtl ? "left" : "right");

            GFunc <string, string> h  = new GFunc <string, string>(StrUtil.StringToHtml);
            GFunc <string, string> ne = delegate(string str)
            {
                if (string.IsNullOrEmpty(str))
                {
                    return("&nbsp;");
                }
                return(str);
            };
            GFunc <string, string> ltrPath = delegate(string str)
            {
                return(bRtl ? StrUtil.EnsureLtrPath(str) : str);
            };

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!DOCTYPE html>");

            sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"");
            string strLang = Program.Translation.Properties.Iso6391Code;

            if (string.IsNullOrEmpty(strLang))
            {
                strLang = "en";
            }
            strLang = h(strLang);
            sb.Append(" xml:lang=\"" + strLang + "\" lang=\"" + strLang + "\"");
            if (bRtl)
            {
                sb.Append(" dir=\"rtl\"");
            }
            sb.AppendLine(">");

            sb.AppendLine("<head>");
            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
            sb.AppendLine("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />");
            sb.AppendLine("<meta http-equiv=\"expires\" content=\"0\" />");
            sb.AppendLine("<meta http-equiv=\"cache-control\" content=\"no-cache\" />");
            sb.AppendLine("<meta http-equiv=\"pragma\" content=\"no-cache\" />");

            sb.Append("<title>");
            sb.Append(h(strName + " - " + strDocKind));
            sb.AppendLine("</title>");

            sb.AppendLine("<style type=\"text/css\">");
            sb.AppendLine("/* <![CDATA[ */");

            string strFont = "\"Arial\", \"Tahoma\", \"Verdana\", sans-serif;";

            // https://sourceforge.net/p/keepass/discussion/329220/thread/f98dece5/
            if (Program.Translation.IsFor("fa"))
            {
                strFont = "\"Tahoma\", \"Arial\", \"Verdana\", sans-serif;";
            }

            sb.AppendLine("body {");
            sb.AppendLine("\tcolor: #000000;");
            sb.AppendLine("\tbackground-color: #FFFFFF;");
            sb.AppendLine("\tfont-family: " + strFont);
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("h3, p {");
            sb.AppendLine("\tmargin: 0.5em 0em 0.5em 0em;");
            sb.AppendLine("}");

            sb.AppendLine("ol, ul {");
            sb.AppendLine("\tmargin-bottom: 0em;");
            sb.AppendLine("}");

            sb.AppendLine("h1, h2, h3 {");
            sb.AppendLine("\tfont-family: \"Verdana\", \"Arial\", \"Tahoma\", sans-serif;");
            sb.AppendLine("}");
            sb.AppendLine("h1, h2 {");
            sb.AppendLine("\tmargin: 0pt 0pt 0pt 0pt;");
            sb.AppendLine("\ttext-align: center;");
            sb.AppendLine("}");
            sb.AppendLine("h1 {");
            sb.AppendLine("\tpadding: 3pt 0pt 0pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h2 {");
            sb.AppendLine("\tpadding: 1pt 0pt 3pt 0pt;");
            sb.AppendLine("}");
            // sb.AppendLine("h3 {");
            // sb.AppendLine("\tpadding: 3pt 3pt 3pt 3pt;");
            // sb.AppendLine("\tcolor: #000000;");
            // sb.AppendLine("\tbackground-color: #EEEEEE;");
            // sb.AppendLine("\tbackground-image: -webkit-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -moz-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -ms-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: linear-gradient(to bottom, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("}");

            sb.AppendLine("a {");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("}");
            sb.AppendLine("a:hover, a:active {");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("\ttext-decoration: underline;");
            sb.AppendLine("}");

            sb.AppendLine("img {");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("}");

            sb.AppendLine(".withspc > li + li {");
            sb.AppendLine("\tmargin-top: 0.5em;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tbackground-color: #EEEEEE;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            // border-collapse is incompatible with border-radius
            // sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\t-webkit-border-radius: 5px;");
            sb.AppendLine("\t-moz-border-radius: 5px;");
            sb.AppendLine("\tborder-radius: 5px;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader tr td {");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\tpadding: 0px 15px 0px 15px;");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("}");

            sb.AppendLine("table.fillinline {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\ttable-layout: fixed;");
            sb.AppendLine("\tempty-cells: show;");
            sb.AppendLine("}");
            sb.AppendLine("table.fillinline tr td {");
            sb.AppendLine("\tpadding: 4pt 4pt 4pt 4pt;");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("\tword-break: break-all;");
            sb.AppendLine("\toverflow-wrap: break-word;");
            sb.AppendLine("\tword-wrap: break-word;");
            sb.AppendLine("}");
            sb.AppendLine("table.fillinline tr td img {");
            sb.AppendLine("\tdisplay: block;");             // Inline results in additional space at the bottom
            sb.AppendLine("\tmargin: 0px " + (bRtl ? "auto 0px 0px;" : "0px 0px auto;"));
            sb.AppendLine("}");
            // sb.AppendLine("span.fillinlinesym {");
            // sb.AppendLine("\tdisplay: inline-block;");
            // sb.AppendLine("\ttransform: scale(1.75, 1.75) translate(-0.5pt, -0.5pt);");
            // sb.AppendLine("}");

            sb.AppendLine("table.fillinline tr td pre {");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\twhite-space: pre-wrap;");
            sb.AppendLine("\toverflow: auto;");
            sb.AppendLine("\toverflow-wrap: break-word;");
            sb.AppendLine("\tword-wrap: break-word;");
            sb.AppendLine("\tword-break: break-all;");
            sb.AppendLine("}");

            // sb.AppendLine("@media print {");
            // sb.AppendLine(".scronly {");
            // sb.AppendLine("\tdisplay: none;");
            // sb.AppendLine("}");
            // sb.AppendLine("}");

            sb.AppendLine("@media print {");
            sb.AppendLine(".ems_break_before {");
            sb.AppendLine("\tpage-break-before: always;");      // CSS 2
            sb.AppendLine("\tbreak-before: page;");             // CSS 3
            sb.AppendLine("}");
            sb.AppendLine("}");

            // Add the temporary content identifier
            // (always, as the sheet should be printed, not saved)
            sb.AppendLine("." + Program.TempFilesPool.TempContentTag + " {");
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("/* ]]> */");
            sb.AppendLine("</style>");
            sb.AppendLine("</head><body>");

            ImageArchive ia = new ImageArchive();

            ia.Load(Properties.Resources.Images_App_HighRes);

            sb.AppendLine("<table class=\"docheader\"><tr>");
            sb.AppendLine("<td style=\"text-align: " + strLogLeft + ";\">");
            Debug.Assert(Properties.Resources.B16x16_KeePass != null);             // Name ref.
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KeePass")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(PwDefs.ShortProductName) + "\" /></td>");
            sb.AppendLine("<td style=\"text-align: center;\">");
            sb.AppendLine("<h1>" + h(PwDefs.ShortProductName) + "</h1>");
            sb.AppendLine("<h2>" + h(strDocKind) + "</h2>");
            sb.AppendLine("</td>");
            sb.AppendLine("<td style=\"text-align: " + strLogRight + ";\">");
            Debug.Assert(Properties.Resources.B16x16_KOrganizer != null);             // Name ref.
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KOrganizer")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(strDocKind) + "\" /></td>");
            sb.AppendLine("</tr></table>");

            sb.AppendLine("<p style=\"text-align: " + strLogRight + ";\">" +
                          h(TimeUtil.ToDisplayStringDateOnly(DateTime.Now)) + "</p>");

            const string strFillInit    = "<table class=\"fillinline\"><tr><td>";
            const string strFillInitLtr = "<table class=\"fillinline\"><tr><td dir=\"ltr\">";
            const string strFillEnd     = "</td></tr></table>";
            string       strFillSym     = "<img src=\"" + GfxUtil.ImageToDataUri(
                Properties.Resources.B48x35_WritingHand) +
                                          "\" style=\"width: 1.3714em; height: 1em;" +
                                          (bRtl ? " transform: scaleX(-1);" : string.Empty) +
                                          "\" alt=\"&#x270D;\" />";
            string strFill = strFillInit + ne(string.Empty) +
                             // "</td><td style=\"text-align: right;\"><span class=\"fillinlinesym\">&#x270D;</span>" +
                             // "</td><td style=\"text-align: " + strLogRight + ";\">" +
                             "</td><td>" +
                             strFillSym + strFillEnd;

            string strFillInitEx = (bRtl ? strFillInitLtr : strFillInit);

            if (bEmSheet)
            {
                GenerateEms(sb, pd, strDbFile,
                            h, ne, ltrPath, strFillInit, strFillInitEx, strFillEnd, strFill);
            }
            if (bEmSheet && bKeyFile)
            {
                sb.AppendLine("<table class=\"docheader ems_break_before\"><tr>");
                sb.AppendLine("<td style=\"text-align: center;\">");
                sb.AppendLine("<h2>" + h(KPRes.KeyFileBackup) + "</h2>");
                sb.AppendLine("</td></tr></table><br />");
            }
            if (bKeyFile)
            {
                GenerateKfb(sb, pd, strDbFile, strKeyFile,
                            h, ne, ltrPath, strFillInit, strFillInitEx, strFillEnd, strFill);
            }

            sb.AppendLine("</body></html>");

            string strDoc = sb.ToString();

#if DEBUG
            XmlUtilEx.ValidateXml(strDoc, true);
#endif
            return(strDoc);
        }
Ejemplo n.º 3
0
        private static void GenerateEms(StringBuilder sb, PwDatabase pd, string strDbFile,
                                        GFunc <string, string> h, GFunc <string, string> ne, GFunc <string, string> ltrPath,
                                        string strFillInit, string strFillInitEx, string strFillEnd, string strFill)
        {
            sb.AppendLine("<p><strong>" + h(KPRes.DatabaseFile) + ":</strong></p>");
            sb.AppendLine(strFillInitEx + ne(h(ltrPath(strDbFile))) + strFillEnd);

            // if(pd.Name.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Name) + ":</strong> " +
            //		h(pd.Name) + "</p>");
            // if(pd.Description.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Description) + ":</strong> " +
            //		h(pd.Description));

            sb.AppendLine("<p>" + h(KPRes.BackupDatabase) + " " +
                          h(KPRes.BackupLocation) + "</p>");
            sb.AppendLine(strFill);

            CompositeKey ck = pd.MasterKey;

            if (ck.UserKeyCount > 0)
            {
                sb.AppendLine("<br />");
                sb.AppendLine("<h3>" + h(KPRes.MasterKey) + "</h3>");
                sb.AppendLine("<p>" + h(KPRes.MasterKeyComponents) + "</p>");
                sb.AppendLine("<ul>");

                foreach (IUserKey k in ck.UserKeys)
                {
                    KcpPassword    p  = (k as KcpPassword);
                    KcpKeyFile     kf = (k as KcpKeyFile);
                    KcpUserAccount a  = (k as KcpUserAccount);
                    KcpCustomKey   c  = (k as KcpCustomKey);

                    if (p != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.MasterPassword) +
                                      ":</strong></p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (kf != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyFile) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInitEx + ne(h(ltrPath(kf.Path))) + strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.BackupFile) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill);

                        sb.AppendLine("</li>");
                    }
                    else if (a != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.WindowsUserAccount) +
                                      ":</strong></p>");
                        sb.Append(strFillInitEx);
                        try
                        {
                            sb.Append(ne(h(ltrPath(Environment.UserDomainName +
                                                   "\\" + Environment.UserName))));
                        }
                        catch (Exception) { Debug.Assert(false); sb.Append(ne(string.Empty)); }
                        sb.AppendLine(strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.WindowsUserAccountBackup) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (c != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyProvider) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInitEx + ne(h(ltrPath(c.Name))) + strFillEnd);

                        sb.AppendLine("</li>");
                    }
                    else
                    {
                        Debug.Assert(false);
                        sb.AppendLine("<li><p><strong>" + h(KPRes.Unknown) + ".</strong></p></li>");
                    }
                }

                sb.AppendLine("</ul>");
            }

            sb.AppendLine("<br />");
            sb.AppendLine("<h3>" + h(KPRes.InstrAndGenInfo) + "</h3>");

            sb.AppendLine("<ul class=\"withspc\">");

            sb.AppendLine("<li>" + h(KPRes.EmergencySheetInfo) + "</li>");
            // sb.AppendLine("<form class=\"scronly\" action=\"#\" onsubmit=\"javascript:window.print();\">");
            // sb.AppendLine("<input type=\"submit\" value=\"&#x1F5B6; " +
            //	h(KPRes.Print) + "\" />");
            // sb.AppendLine("</form></li>");

            sb.AppendLine("<li>" + h(KPRes.DataLoss) + "</li>");
            sb.AppendLine("<li>" + h(KPRes.LatestVersionWeb) + ": <a href=\"" +
                          h(PwDefs.HomepageUrl) + "\" target=\"_blank\">" +
                          h(PwDefs.HomepageUrl) + "</a>.</li>");
            sb.AppendLine("</ul>");
        }
Ejemplo n.º 4
0
        /* private static bool SetDataUwp(byte[] pbToCopy, string strFormat)
         * {
         *      if(pbToCopy == null) { Debug.Assert(false); return false; }
         *      if(pbToCopy.Length == 0) return false; // Use Windows API
         *      if(string.IsNullOrEmpty(strFormat)) { Debug.Assert(false); return false; }
         *
         *      try
         *      {
         *              GFunc<Type, object, bool> f = delegate(Type tDP, object oDP)
         *              {
         *                      MethodInfo mi = tDP.GetMethod("SetData", BindingFlags.Public |
         *                              BindingFlags.Instance);
         *                      if(mi == null) { Debug.Assert(false); return false; }
         *                      mi.Invoke(oDP, new object[] { strFormat, pbToCopy });
         *
         *                      return true;
         *              };
         *
         *              return SetDataUwp(f);
         *      }
         *      catch(Exception) { Debug.Assert(false); }
         *
         *      return false;
         * } */

        private static bool SetDataUwp(GFunc <Type, object, bool> fSetData)
        {
            if (fSetData == null)
            {
                Debug.Assert(false); return(false);
            }
            if (!WinUtil.IsAtLeastWindows10)
            {
                return(false);
            }
            if (!Program.Config.Security.ClipboardNoPersist)
            {
                return(false);
            }

            const string       strDT    = "Windows.ApplicationModel.DataTransfer";
            const string       strC     = strDT + ".Clipboard";
            const string       strCCO   = strDT + ".ClipboardContentOptions";
            const string       strDP    = strDT + ".DataPackage";
            const BindingFlags bfStatic = (BindingFlags.Public | BindingFlags.Static);
            const BindingFlags bfInst   = (BindingFlags.Public | BindingFlags.Instance);

            Type tC = NativeLib.GetUwpType(strC);

            if (tC == null)
            {
                Debug.Assert(Environment.Version.Major < 4); return(false);
            }

            MethodInfo miH = tC.GetMethod("IsHistoryEnabled", bfStatic);

            if (miH == null)
            {
                return(false);                        // >= Windows 10 1809 only
            }
            bool bHistory = (bool)miH.Invoke(null, null);

            MethodInfo miR = tC.GetMethod("IsRoamingEnabled", bfStatic);

            if (miR == null)
            {
                return(false);                        // >= Windows 10 1809 only
            }
            bool bRoaming = (bool)miR.Invoke(null, null);

            if (!bHistory && !bRoaming)
            {
                return(false);
            }

            Type tCCO = NativeLib.GetUwpType(strCCO);

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

            object oCCO = Activator.CreateInstance(tCCO);

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

            PropertyInfo piH = tCCO.GetProperty("IsAllowedInHistory", bfInst);

            if (piH == null)
            {
                Debug.Assert(false); return(false);
            }
            piH.SetValue(oCCO, false, null);

            PropertyInfo piR = tCCO.GetProperty("IsRoamable", bfInst);

            if (piR == null)
            {
                Debug.Assert(false); return(false);
            }
            piR.SetValue(oCCO, false, null);

            Type tDP = NativeLib.GetUwpType(strDP);

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

            object oDP = Activator.CreateInstance(tDP);

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

            AttachIgnoreFormatUwp(tDP, oDP);
            if (!fSetData(tDP, oDP))
            {
                return(false);
            }

            MethodInfo miSet = tC.GetMethod("SetContentWithOptions", bfStatic);

            if (miSet == null)
            {
                Debug.Assert(false); return(false);
            }
            if (!InvokeAndRetry(delegate()
            {
                return((bool)miSet.Invoke(null, new object[] { oDP, oCCO }));
            }))
            {
                return(false);
            }

            MethodInfo miFlush = tC.GetMethod("Flush", bfStatic);

            if (miFlush != null)
            {
                // The Flush method gives up too fast
                InvokeAndRetry(delegate()
                {
                    miFlush.Invoke(null, null);                     // May throw exception
                    return(true);
                });
            }
            else
            {
                Debug.Assert(false);
            }

            return(true);
        }
Ejemplo n.º 5
0
        private void DpiScale()
        {
            AceMeta aceMeta = this.Meta;             // m_meta might be null
            double  dCfgX = aceMeta.DpiFactorX, dCfgY = aceMeta.DpiFactorY;
            double  dScrX = DpiUtil.FactorX, dScrY = DpiUtil.FactorY;

            if ((dScrX == dCfgX) && (dScrY == dCfgY))
            {
                return;
            }

            // When this method returns, all positions and sizes are in pixels
            // for the current screen DPI
            aceMeta.DpiFactorX = dScrX;
            aceMeta.DpiFactorY = dScrY;

            // Backward compatibility; configuration files created by KeePass
            // 2.37 and earlier do not contain DpiFactor* values, they default
            // to 0.0 and all positions and sizes are in pixels for the current
            // screen DPI; so, do not perform any DPI scaling in this case
            if ((dCfgX == 0.0) || (dCfgY == 0.0))
            {
                return;
            }

            double           sX = dScrX / dCfgX, sY = dScrY / dCfgY;
            GFunc <int, int> fX = delegate(int x)
            {
                return((int)Math.Round((double)x * sX));
            };
            GFunc <int, int> fY = delegate(int y)
            {
                return((int)Math.Round((double)y * sY));
            };
            GFunc <string, string> fWsr = delegate(string strRect)
            {
                return(UIUtil.ScaleWindowScreenRect(strRect, sX, sY));
            };
            GFunc <string, string> fVX = delegate(string strArray)
            {
                if (string.IsNullOrEmpty(strArray))
                {
                    return(strArray);
                }

                try
                {
                    int[] v = StrUtil.DeserializeIntArray(strArray);
                    if (v == null)
                    {
                        Debug.Assert(false); return(strArray);
                    }

                    for (int i = 0; i < v.Length; ++i)
                    {
                        v[i] = (int)Math.Round((double)v[i] * sX);
                    }

                    return(StrUtil.SerializeIntArray(v));
                }
                catch (Exception) { Debug.Assert(false); }

                return(strArray);
            };
            Action <AceFont> fFont = delegate(AceFont f)
            {
                if (f == null)
                {
                    Debug.Assert(false); return;
                }

                if (f.GraphicsUnit == GraphicsUnit.Pixel)
                {
                    f.Size = (float)(f.Size * sY);
                }
            };

            AceMainWindow mw = this.MainWindow;
            AceUI         ui = this.UI;

            if (mw.X != AppDefs.InvalidWindowValue)
            {
                mw.X = fX(mw.X);
            }
            if (mw.Y != AppDefs.InvalidWindowValue)
            {
                mw.Y = fY(mw.Y);
            }
            if (mw.Width != AppDefs.InvalidWindowValue)
            {
                mw.Width = fX(mw.Width);
            }
            if (mw.Height != AppDefs.InvalidWindowValue)
            {
                mw.Height = fY(mw.Height);
            }

            foreach (AceColumn c in mw.EntryListColumns)
            {
                if (c.Width >= 0)
                {
                    c.Width = fX(c.Width);
                }
            }

            ui.DataViewerRect          = fWsr(ui.DataViewerRect);
            ui.DataEditorRect          = fWsr(ui.DataEditorRect);
            ui.CharPickerRect          = fWsr(ui.CharPickerRect);
            ui.AutoTypeCtxRect         = fWsr(ui.AutoTypeCtxRect);
            ui.AutoTypeCtxColumnWidths = fVX(ui.AutoTypeCtxColumnWidths);

            fFont(ui.StandardFont);
            fFont(ui.PasswordFont);
            fFont(ui.DataEditorFont);
        }
Ejemplo n.º 6
0
        private string GenerateHtmlDocument(bool bTemporary)
        {
            PwGroup pgDataSource = m_pgDataSource.CloneDeep();             // Sorting, ...

            int    nSortEntries     = m_cmbSortEntries.SelectedIndex;
            string strSortFieldName = null;

            if (nSortEntries == 0)
            {
            }                                     // No sort
            else if (nSortEntries == 1)
            {
                strSortFieldName = PwDefs.TitleField;
            }
            else if (nSortEntries == 2)
            {
                strSortFieldName = PwDefs.UserNameField;
            }
            else if (nSortEntries == 3)
            {
                strSortFieldName = PwDefs.PasswordField;
            }
            else if (nSortEntries == 4)
            {
                strSortFieldName = PwDefs.UrlField;
            }
            else if (nSortEntries == 5)
            {
                strSortFieldName = PwDefs.NotesField;
            }
            else
            {
                Debug.Assert(false);
            }
            if (strSortFieldName != null)
            {
                SortGroupEntriesRecursive(pgDataSource, strSortFieldName);
            }

            bool bGroup = m_cbGroups.Checked;
            bool bTitle = m_cbTitle.Checked, bUserName = m_cbUser.Checked;
            bool bPassword = m_cbPassword.Checked, bUrl = m_cbUrl.Checked;
            bool bNotes = m_cbNotes.Checked;
            bool bCreation = m_cbCreation.Checked, bLastMod = m_cbLastMod.Checked;
            // bool bLastAcc = m_cbLastAccess.Checked;
            bool bExpire        = m_cbExpire.Checked;
            bool bAutoType      = m_cbAutoType.Checked;
            bool bTags          = m_cbTags.Checked;
            bool bCustomStrings = m_cbCustomStrings.Checked;
            bool bUuid          = m_cbUuid.Checked;

            PfOptions p = new PfOptions();

            p.MonoPasswords = m_cbMonospaceForPasswords.Checked;
            if (m_rbMonospace.Checked)
            {
                p.MonoPasswords = false;                                   // Monospace anyway
            }
            p.SmallMono = m_cbSmallMono.Checked;
            p.SprMode   = m_cmbSpr.SelectedIndex;
            p.Rtl       = (this.RightToLeft == RightToLeft.Yes);
            p.Database  = m_pdContext;
            if (m_cbIcon.Checked)
            {
                p.ClientIcons = m_ilClientIcons;
            }

            if (m_rbSerif.Checked)
            {
                p.FontInit = "<span class=\"fserif\">";
                p.FontExit = "</span>";
            }
            else if (m_rbSansSerif.Checked)
            {
                p.FontInit = string.Empty;
                p.FontExit = string.Empty;
            }
            else if (m_rbMonospace.Checked)
            {
                p.FontInit = (p.SmallMono ? "<code><small>" : "<code>");
                p.FontExit = (p.SmallMono ? "</small></code>" : "</code>");
            }
            else
            {
                Debug.Assert(false);
            }

            GFunc <string, string> h = new GFunc <string, string>(StrUtil.StringToHtml);
            GFunc <string, string> c = delegate(string strRaw)
            {
                return(CompileText(strRaw, p, true, false));
            };
            GFunc <string, string> cs = delegate(string strRaw)
            {
                return(CompileText(strRaw, p, true, true));
            };

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!DOCTYPE html>");

            sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"");
            string strLang = Program.Translation.Properties.Iso6391Code;

            if (string.IsNullOrEmpty(strLang))
            {
                strLang = "en";
            }
            strLang = h(strLang);
            sb.Append(" xml:lang=\"" + strLang + "\" lang=\"" + strLang + "\"");
            if (p.Rtl)
            {
                sb.Append(" dir=\"rtl\"");
            }
            sb.AppendLine(">");

            sb.AppendLine("<head>");
            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
            sb.AppendLine("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />");
            sb.AppendLine("<meta http-equiv=\"expires\" content=\"0\" />");
            sb.AppendLine("<meta http-equiv=\"cache-control\" content=\"no-cache\" />");
            sb.AppendLine("<meta http-equiv=\"pragma\" content=\"no-cache\" />");

            sb.Append("<title>");
            sb.Append(h(pgDataSource.Name));
            sb.AppendLine("</title>");

            sb.AppendLine("<style type=\"text/css\">");
            sb.AppendLine("/* <![CDATA[ */");

            sb.AppendLine("body {");
            sb.AppendLine("\tcolor: #000000;");
            sb.AppendLine("\tbackground-color: #FFFFFF;");
            sb.AppendLine("\tfont-family: \"Tahoma\", \"MS Sans Serif\", \"Sans Serif\", \"Verdana\", sans-serif;");
            sb.AppendLine("\tfont-size: 10pt;");
            sb.AppendLine("}");

            sb.AppendLine("h2 {");
            sb.AppendLine("\tcolor: #000000;");
            sb.AppendLine("\tbackground-color: #D0D0D0;");
            sb.AppendLine("\tpadding-left: 2pt;");
            sb.AppendLine("\tpadding-right: 2pt;");             // RTL support
            sb.AppendLine("}");
            sb.AppendLine("h3 {");
            sb.AppendLine("\tcolor: #000000;");
            sb.AppendLine("\tbackground-color: #D0D0D0;");
            sb.AppendLine("\tpadding-left: 2pt;");
            sb.AppendLine("\tpadding-right: 2pt;");             // RTL support
            sb.AppendLine("}");

            sb.AppendLine("table, th, td {");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("}");

            sb.AppendLine("table {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\ttable-layout: fixed;");
            sb.AppendLine("\tempty-cells: show;");
            sb.AppendLine("}");

            sb.AppendLine("th, td {");
            sb.AppendLine("\ttext-align: " + (p.Rtl ? "right;" : "left;"));
            sb.AppendLine("\tvertical-align: top;");
            sb.AppendLine("}");

            sb.AppendLine("th {");
            sb.AppendLine("\tfont-weight: bold;");
            sb.AppendLine("}");

            sb.AppendLine("a {");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("}");
            sb.AppendLine("a:hover, a:active {");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("\ttext-decoration: underline;");
            sb.AppendLine("}");

            sb.AppendLine(".field_name {");
            sb.AppendLine("\t-webkit-hyphens: auto;");
            sb.AppendLine("\t-moz-hyphens: auto;");
            sb.AppendLine("\t-ms-hyphens: auto;");
            sb.AppendLine("\thyphens: auto;");
            sb.AppendLine("}");
            sb.AppendLine(".field_data {");
            // sb.AppendLine("\tword-break: break-all;");
            sb.AppendLine("\toverflow-wrap: break-word;");
            sb.AppendLine("\tword-wrap: break-word;");
            sb.AppendLine("}");

            sb.AppendLine(".fserif {");
            sb.AppendLine("\tfont-family: \"Times New Roman\", serif;");
            sb.AppendLine("}");

            sb.AppendLine(".icon_cli {");
            sb.AppendLine("\tdisplay: inline-block;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("\twidth: 1.1em;");
            sb.AppendLine("\theight: 1.1em;");
            sb.AppendLine("\tvertical-align: top;");
            sb.AppendLine("}");

            if (bTemporary)
            {
                // Add the temporary content identifier
                sb.AppendLine("." + Program.TempFilesPool.TempContentTag + " {");
                sb.AppendLine("\tfont-size: 10pt;");
                sb.AppendLine("}");
            }

            sb.AppendLine("/* ]]> */");
            sb.AppendLine("</style>");
            sb.AppendLine("</head><body>");

            sb.AppendLine("<h2>" + h(pgDataSource.Name) + "</h2>");
            WriteGroupNotes(sb, pgDataSource);

            EntryHandler ehInit = delegate(PwEntry pe)
            {
                p.Entry = pe;

                if (p.SprMode != 0)
                {
                    p.SprContext = new SprContext(pe, p.Database,
                                                  SprCompileFlags.NonActive, false, false);
                }
                else
                {
                    Debug.Assert(p.SprContext == null);
                }

                Application.DoEvents();
                return(true);
            };

            EntryHandler eh           = null;
            string       strTableInit = "<table>";
            PwGroup      pgLast       = null;

            if (m_rbTabular.Checked)
            {
                int nEquiCols = 0;
                if (bGroup)
                {
                    ++nEquiCols;
                }
                if (bTitle)
                {
                    ++nEquiCols;
                }
                if (bUserName)
                {
                    ++nEquiCols;
                }
                if (bPassword)
                {
                    ++nEquiCols;
                }
                if (bUrl)
                {
                    ++nEquiCols;
                }
                if (bNotes)
                {
                    nEquiCols += 2;
                }
                if (bCreation)
                {
                    ++nEquiCols;
                }
                // if(bLastAcc) ++nEquiCols;
                if (bLastMod)
                {
                    ++nEquiCols;
                }
                if (bExpire)
                {
                    ++nEquiCols;
                }
                if (bTags)
                {
                    ++nEquiCols;
                }
                if (bUuid)
                {
                    ++nEquiCols;
                }
                if (nEquiCols == 0)
                {
                    nEquiCols = 1;
                }

                string strColWidth = (100.0f / (float)nEquiCols).ToString(
                    "F2", NumberFormatInfo.InvariantInfo);
                string strColWidth2 = (200.0f / (float)nEquiCols).ToString(
                    "F2", NumberFormatInfo.InvariantInfo);

                string strHTdInit = "<th class=\"field_name\" style=\"width: " +
                                    strColWidth + "%;\">";
                string strHTdInit2 = "<th class=\"field_name\" style=\"width: " +
                                     strColWidth2 + "%;\">";
                string strHTdExit    = "</th>";
                string strDataTdInit = "<td class=\"field_data\">";
                string strDataTdExit = "</td>";

                p.CellInit = strDataTdInit + p.FontInit;
                p.CellExit = p.FontExit + strDataTdExit;

                StringBuilder sbH = new StringBuilder();
                sbH.AppendLine();
                sbH.Append("<tr>");
                if (bGroup)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Group) + strHTdExit);
                }
                if (bTitle)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Title) + strHTdExit);
                }
                if (bUserName)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.UserName) + strHTdExit);
                }
                if (bPassword)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Password) + strHTdExit);
                }
                if (bUrl)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Url) + strHTdExit);
                }
                if (bNotes)
                {
                    sbH.AppendLine(strHTdInit2 + h(KPRes.Notes) + strHTdExit);
                }
                if (bCreation)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.CreationTime) + strHTdExit);
                }
                // if(bLastAcc) sbH.AppendLine(strHTdInit + h(KPRes.LastAccessTime) + strHTdExit);
                if (bLastMod)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.LastModificationTime) + strHTdExit);
                }
                if (bExpire)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.ExpiryTime) + strHTdExit);
                }
                if (bTags)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Tags) + strHTdExit);
                }
                if (bUuid)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Uuid) + strHTdExit);
                }
                sbH.Append("</tr>");                 // No terminating \r\n

                strTableInit += sbH.ToString();
                sb.AppendLine(strTableInit);

                eh = delegate(PwEntry pe)
                {
                    ehInit(pe);

                    sb.AppendLine("<tr>");

                    WriteTabularIf(bGroup, sb, c(pe.ParentGroup.Name), p);
                    WriteTabularIf(bTitle, sb, pe, PwDefs.TitleField, p);
                    WriteTabularIf(bUserName, sb, pe, PwDefs.UserNameField, p);

                    if (bPassword)
                    {
                        if (p.MonoPasswords)
                        {
                            sb.Append(strDataTdInit + (p.SmallMono ?
                                                       "<code><small>" : "<code>"));
                        }
                        else
                        {
                            sb.Append(p.CellInit);
                        }

                        string strInner = cs(pe.Strings.ReadSafe(PwDefs.PasswordField));
                        if (strInner.Length == 0)
                        {
                            strInner = "&nbsp;";
                        }
                        sb.Append(strInner);

                        if (p.MonoPasswords)
                        {
                            sb.AppendLine((p.SmallMono ? "</small></code>" :
                                           "</code>") + strDataTdExit);
                        }
                        else
                        {
                            sb.AppendLine(p.CellExit);
                        }
                    }

                    // WriteTabularIf(bUrl, sb, pe, PwDefs.UrlField, p);
                    WriteTabularIf(bUrl, sb, MakeUrlLink(pe.Strings.ReadSafe(
                                                             PwDefs.UrlField), p), p);

                    WriteTabularIf(bNotes, sb, pe, PwDefs.NotesField, p);

                    WriteTabularIf(bCreation, sb, h(TimeUtil.ToDisplayString(
                                                        pe.CreationTime)), p);
                    // WriteTabularIf(bLastAcc, sb, h(TimeUtil.ToDisplayString(
                    //	pe.LastAccessTime)), p);
                    WriteTabularIf(bLastMod, sb, h(TimeUtil.ToDisplayString(
                                                       pe.LastModificationTime)), p);
                    WriteTabularIf(bExpire, sb, h(pe.Expires ? TimeUtil.ToDisplayString(
                                                      pe.ExpiryTime) : KPRes.NeverExpires), p);

                    WriteTabularIf(bTags, sb, h(StrUtil.TagsToString(pe.Tags, true)), p);

                    WriteTabularIf(bUuid, sb, pe.Uuid.ToHexString(), p);

                    sb.AppendLine("</tr>");
                    return(true);
                };
            }
            else if (m_rbDetails.Checked)
            {
                sb.AppendLine(strTableInit);

                if (pgDataSource.Entries.UCount == 0)
                {
                    sb.AppendLine(@"<tr><td>&nbsp;</td></tr>");
                }

                eh = delegate(PwEntry pe)
                {
                    ehInit(pe);

                    if ((pgLast != null) && (pgLast == pe.ParentGroup))
                    {
                        sb.AppendLine("<tr><td colspan=\"2\"><hr /></td></tr>");
                    }

                    if (bGroup)
                    {
                        WriteDetailsLine(sb, KPRes.Group, pe.ParentGroup.Name, p);
                    }
                    if (bTitle)
                    {
                        PfOptions pSub = p.CloneShallow();
                        pSub.FontInit = MakeIconImg(pe.IconId, pe.CustomIconUuid, pe,
                                                    p) + pSub.FontInit + "<b>";
                        pSub.FontExit = "</b>" + pSub.FontExit;

                        WriteDetailsLine(sb, KPRes.Title, pe.Strings.ReadSafe(
                                             PwDefs.TitleField), pSub);
                    }
                    if (bUserName)
                    {
                        WriteDetailsLine(sb, KPRes.UserName, pe.Strings.ReadSafe(
                                             PwDefs.UserNameField), p);
                    }
                    if (bPassword)
                    {
                        WriteDetailsLine(sb, KPRes.Password, pe.Strings.ReadSafe(
                                             PwDefs.PasswordField), p);
                    }
                    if (bUrl)
                    {
                        WriteDetailsLine(sb, KPRes.Url, pe.Strings.ReadSafe(
                                             PwDefs.UrlField), p);
                    }
                    if (bNotes)
                    {
                        WriteDetailsLine(sb, KPRes.Notes, pe.Strings.ReadSafe(
                                             PwDefs.NotesField), p);
                    }
                    if (bCreation)
                    {
                        WriteDetailsLine(sb, KPRes.CreationTime, TimeUtil.ToDisplayString(
                                             pe.CreationTime), p);
                    }
                    // if(bLastAcc) WriteDetailsLine(sb, KPRes.LastAccessTime, TimeUtil.ToDisplayString(
                    //	pe.LastAccessTime), p);
                    if (bLastMod)
                    {
                        WriteDetailsLine(sb, KPRes.LastModificationTime, TimeUtil.ToDisplayString(
                                             pe.LastModificationTime), p);
                    }
                    if (bExpire)
                    {
                        WriteDetailsLine(sb, KPRes.ExpiryTime, (pe.Expires ? TimeUtil.ToDisplayString(
                                                                    pe.ExpiryTime) : KPRes.NeverExpires), p);
                    }

                    if (bAutoType)
                    {
                        foreach (AutoTypeAssociation a in pe.AutoType.Associations)
                        {
                            WriteDetailsLine(sb, KPRes.AutoType, a.WindowName +
                                             ": " + a.Sequence, p);
                        }
                    }

                    if (bTags)
                    {
                        WriteDetailsLine(sb, KPRes.Tags, StrUtil.TagsToString(
                                             pe.Tags, true), p);
                    }
                    if (bUuid)
                    {
                        WriteDetailsLine(sb, KPRes.Uuid, pe.Uuid.ToHexString(), p);
                    }

                    foreach (KeyValuePair <string, ProtectedString> kvp in pe.Strings)
                    {
                        if (bCustomStrings && !PwDefs.IsStandardField(kvp.Key))
                        {
                            WriteDetailsLine(sb, kvp, p);
                        }
                    }

                    pgLast = pe.ParentGroup;
                    return(true);
                };
            }
            else
            {
                Debug.Assert(false);
            }

            GroupHandler gh = delegate(PwGroup pg)
            {
                if (pg.Entries.UCount == 0)
                {
                    return(true);
                }

                sb.Append("</table><br /><br /><h3>");                 // "</table><br /><hr /><h3>"
                // sb.Append(MakeIconImg(pg.IconId, pg.CustomIconUuid, pg, p));
                sb.Append(h(pg.GetFullPath(" - ", false)));
                sb.AppendLine("</h3>");
                WriteGroupNotes(sb, pg);
                sb.AppendLine(strTableInit);

                return(true);
            };

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

            if (m_rbTabular.Checked)
            {
                sb.AppendLine("</table>");
            }
            else if (m_rbDetails.Checked)
            {
                sb.AppendLine("</table><br />");
            }

            sb.AppendLine("</body></html>");

            string strDoc = sb.ToString();

#if DEBUG
            XmlUtilEx.ValidateXml(strDoc, true);
#endif
            return(strDoc);
        }
Ejemplo n.º 7
0
        internal static void UpdateImages(ListView lv,
                                          GFunc <ListViewItem, string> fItemToName)
        {
            if (lv == null)
            {
                Debug.Assert(false); return;
            }

            Size sz = GetSizeOrSmall(null);

            ImageList ilToDispose = lv.SmallImageList;

            lv.BeginUpdate();

            List <Image> lImages = new List <Image>();

            foreach (ListViewItem lvi in lv.Items)
            {
                if (lvi == null)
                {
                    Debug.Assert(false); continue;
                }

                string strName;
                if (fItemToName != null)
                {
                    strName = fItemToName(lvi);
                }
                else
                {
                    strName = lvi.Text;
                }

                Image img = GetImageForName(strName, sz);
                if (img == null)
                {
                    Debug.Assert(false); continue;
                }

                int iImage = -1;
                for (int i = 0; i < lImages.Count; ++i)
                {
                    if (object.ReferenceEquals(lImages[i], img))
                    {
                        iImage = i;
                        break;
                    }
                }
                if (iImage < 0)
                {
                    iImage = lImages.Count;
                    lImages.Add(img);
                }

                lvi.ImageIndex = iImage;
            }

            if (lImages.Count != 0)
            {
                ImageList il = UIUtil.BuildImageListUnscaled(lImages,
                                                             sz.Width, sz.Height);
#if DEBUG
                il.Tag = FiImageListTag;
#endif
                lv.SmallImageList = il;
            }
            else if (ilToDispose != null)
            {
                lv.SmallImageList = null;                 // Release previous ImageList
            }
            lv.EndUpdate();
            if (ilToDispose != null)
            {
                Debug.Assert((ilToDispose.Tag as string) == FiImageListTag);
                ilToDispose.Dispose();
            }
        }
Ejemplo n.º 8
0
        private bool TxfIsUnusable()
        {
            try
            {
                string strReleaseId = (Registry.GetValue(
                                           "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
                                           "ReleaseId", string.Empty) as string);

                // Due to a bug in Microsoft's 'cldflt.sys' driver, a TxF transaction
                // results in a Blue Screen of Death on Windows 10 1903/1909;
                // https://www.windowslatest.com/2019/10/20/windows-10-update-issues-bsod-broken-apps-and-defender-atp/
                // https://sourceforge.net/p/keepass/discussion/329221/thread/924b94ea48/
                // This bug is fixed by the Windows update 4530684;
                // https://support.microsoft.com/en-us/help/4530684/windows-10-update-kb4530684
                // if(strReleaseId == "1903") return true;
                // if(strReleaseId == "1909") return true;

                if (strReleaseId != "1809")
                {
                    return(false);
                }

                // On Windows 10 1809, OneDrive crashes if the file is
                // in a OneDrive folder;
                // https://sourceforge.net/p/keepass/discussion/329220/thread/672ffecc65/
                // https://sourceforge.net/p/keepass/discussion/329221/thread/514786c23a/

                string strFile = m_iocBase.Path;

                GFunc <string, string, bool> fMatch = delegate(string strRoot, string strSfx)
                {
                    if (string.IsNullOrEmpty(strRoot))
                    {
                        return(false);
                    }
                    string strPfx = UrlUtil.EnsureTerminatingSeparator(
                        strRoot, false) + strSfx;
                    return(strFile.StartsWith(strPfx, StrUtil.CaseIgnoreCmp));
                };
                GFunc <string, string, bool> fMatchEnv = delegate(string strEnv, string strSfx)
                {
                    return(fMatch(Environment.GetEnvironmentVariable(strEnv), strSfx));
                };

                string strKnown = NativeMethods.GetKnownFolderPath(
                    NativeMethods.FOLDERID_SkyDrive);
                if (fMatch(strKnown, string.Empty))
                {
                    return(true);
                }

                if (fMatchEnv("USERPROFILE", "OneDrive\\"))
                {
                    return(true);
                }
                if (fMatchEnv("OneDrive", string.Empty))
                {
                    return(true);
                }
                if (fMatchEnv("OneDriveCommercial", string.Empty))
                {
                    return(true);
                }
                if (fMatchEnv("OneDriveConsumer", string.Empty))
                {
                    return(true);
                }

                using (RegistryKey kAccs = Registry.CurrentUser.OpenSubKey(
                           "Software\\Microsoft\\OneDrive\\Accounts", false))
                {
                    string[] vAccs = (((kAccs != null) ? kAccs.GetSubKeyNames() :
                                       null) ?? new string[0]);

                    foreach (string strAcc in vAccs)
                    {
                        if (string.IsNullOrEmpty(strAcc))
                        {
                            Debug.Assert(false); continue;
                        }

                        using (RegistryKey kTenants = kAccs.OpenSubKey(
                                   strAcc + "\\Tenants", false))
                        {
                            string[] vTenants = (((kTenants != null) ?
                                                  kTenants.GetSubKeyNames() : null) ?? new string[0]);

                            foreach (string strT in vTenants)
                            {
                                if (string.IsNullOrEmpty(strT))
                                {
                                    Debug.Assert(false); continue;
                                }

                                using (RegistryKey kT = kTenants.OpenSubKey(strT, false))
                                {
                                    string[] vPaths = (((kT != null) ?
                                                        kT.GetValueNames() : null) ?? new string[0]);

                                    foreach (string strPath in vPaths)
                                    {
                                        if ((strPath == null) || (strPath.Length < 4) ||
                                            (strPath[1] != ':'))
                                        {
                                            Debug.Assert(false);
                                            continue;
                                        }

                                        if (fMatch(strPath, string.Empty))
                                        {
                                            return(true);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception) { Debug.Assert(false); }

            return(false);
        }
Ejemplo n.º 9
0
        // https://sourceforge.net/p/keepass/discussion/329220/thread/672ffecc65/
        // https://sourceforge.net/p/keepass/discussion/329221/thread/514786c23a/
        private bool IsOneDriveWorkaroundRequired()
        {
            if (NativeLib.IsUnix())
            {
                return(false);
            }

            try
            {
                string strReleaseId = (Registry.GetValue(
                                           "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
                                           "ReleaseId", string.Empty) as string);
                if (strReleaseId != "1809")
                {
                    return(false);
                }

                string strFile = m_iocBase.Path;

                GFunc <string, string, bool> fMatch = delegate(string strRoot, string strSfx)
                {
                    if (string.IsNullOrEmpty(strRoot))
                    {
                        return(false);
                    }
                    string strPfx = UrlUtil.EnsureTerminatingSeparator(
                        strRoot, false) + strSfx;
                    return(strFile.StartsWith(strPfx, StrUtil.CaseIgnoreCmp));
                };
                GFunc <string, string, bool> fMatchEnv = delegate(string strEnv, string strSfx)
                {
                    return(fMatch(Environment.GetEnvironmentVariable(strEnv), strSfx));
                };

                string strKnown = NativeMethods.GetKnownFolderPath(
                    NativeMethods.FOLDERID_SkyDrive);
                if (fMatch(strKnown, string.Empty))
                {
                    return(true);
                }

                if (fMatchEnv("USERPROFILE", "OneDrive\\"))
                {
                    return(true);
                }
                if (fMatchEnv("OneDrive", string.Empty))
                {
                    return(true);
                }
                if (fMatchEnv("OneDriveCommercial", string.Empty))
                {
                    return(true);
                }
                if (fMatchEnv("OneDriveConsumer", string.Empty))
                {
                    return(true);
                }

                using (RegistryKey kAccs = Registry.CurrentUser.OpenSubKey(
                           "Software\\Microsoft\\OneDrive\\Accounts", false))
                {
                    string[] vAccs = (((kAccs != null) ? kAccs.GetSubKeyNames() :
                                       null) ?? new string[0]);

                    foreach (string strAcc in vAccs)
                    {
                        if (string.IsNullOrEmpty(strAcc))
                        {
                            Debug.Assert(false); continue;
                        }

                        using (RegistryKey kTenants = kAccs.OpenSubKey(
                                   strAcc + "\\Tenants", false))
                        {
                            string[] vTenants = (((kTenants != null) ?
                                                  kTenants.GetSubKeyNames() : null) ?? new string[0]);

                            foreach (string strT in vTenants)
                            {
                                if (string.IsNullOrEmpty(strT))
                                {
                                    Debug.Assert(false); continue;
                                }

                                using (RegistryKey kT = kTenants.OpenSubKey(strT, false))
                                {
                                    string[] vPaths = (((kT != null) ?
                                                        kT.GetValueNames() : null) ?? new string[0]);

                                    foreach (string strPath in vPaths)
                                    {
                                        if ((strPath == null) || (strPath.Length < 4) ||
                                            (strPath[1] != ':'))
                                        {
                                            Debug.Assert(false);
                                            continue;
                                        }

                                        if (fMatch(strPath, string.Empty))
                                        {
                                            return(true);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception) { Debug.Assert(false); }

            return(false);
        }
Ejemplo n.º 10
0
        private static string GenerateHtml(PwDatabase pd, string strName)
        {
            bool   bRtl        = Program.Translation.Properties.RightToLeft;
            string strLogLeft  = (bRtl ? "right" : "left");
            string strLogRight = (bRtl ? "left" : "right");

            GFunc <string, string> h  = new GFunc <string, string>(StrUtil.StringToHtml);
            GFunc <string, string> ne = delegate(string str)
            {
                if (string.IsNullOrEmpty(str))
                {
                    return("&nbsp;");
                }
                return(str);
            };
            GFunc <string, string> ltrPath = delegate(string str)
            {
                return(bRtl ? StrUtil.EnsureLtrPath(str) : str);
            };

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
            sb.AppendLine("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");

            sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"");
            string strLang = Program.Translation.Properties.Iso6391Code;

            if (string.IsNullOrEmpty(strLang))
            {
                strLang = "en";
            }
            strLang = h(strLang);
            sb.Append(" lang=\"" + strLang + "\" xml:lang=\"" + strLang + "\"");
            if (bRtl)
            {
                sb.Append(" dir=\"rtl\"");
            }
            sb.AppendLine(">");

            sb.AppendLine("<head>");
            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
            sb.Append("<title>");
            sb.Append(h(strName + " - " + KPRes.EmergencySheet));
            sb.AppendLine("</title>");
            sb.AppendLine("<meta http-equiv=\"expires\" content=\"0\" />");
            sb.AppendLine("<meta http-equiv=\"cache-control\" content=\"no-cache\" />");
            sb.AppendLine("<meta http-equiv=\"pragma\" content=\"no-cache\" />");

            sb.AppendLine("<style type=\"text/css\">");
            sb.AppendLine("/* <![CDATA[ */");

            string strFont = "\"Arial\", \"Tahoma\", \"Verdana\", sans-serif;";

            // https://sourceforge.net/p/keepass/discussion/329220/thread/f98dece5/
            if (Program.Translation.IsFor("fa"))
            {
                strFont = "\"Tahoma\", \"Arial\", \"Verdana\", sans-serif;";
            }

            sb.AppendLine("body, p, div, h1, h2, h3, h4, h5, h6, ol, ul, li, td, th, dd, dt, a {");
            sb.AppendLine("\tfont-family: " + strFont);
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("body, p, div, table {");
            sb.AppendLine("\tcolor: #000000;");
            sb.AppendLine("\tbackground-color: #FFFFFF;");
            sb.AppendLine("}");

            sb.AppendLine("p, h3 {");
            sb.AppendLine("\tmargin: 0.5em 0em 0.5em 0em;");
            sb.AppendLine("}");

            sb.AppendLine("ol, ul {");
            sb.AppendLine("\tmargin-bottom: 0em;");
            sb.AppendLine("}");

            sb.AppendLine("h1, h2, h3 {");
            sb.AppendLine("\tfont-family: \"Verdana\", \"Arial\", \"Tahoma\", sans-serif;");
            sb.AppendLine("}");
            sb.AppendLine("h1, h2 {");
            sb.AppendLine("\ttext-align: center;");
            sb.AppendLine("\tmargin: 0pt 0pt 0pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h1 {");
            sb.AppendLine("\tfont-size: 2em;");
            sb.AppendLine("\tpadding: 3pt 0pt 0pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h2 {");
            sb.AppendLine("\tfont-size: 1.5em;");
            sb.AppendLine("\tpadding: 1pt 0pt 3pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h3 {");
            sb.AppendLine("\tfont-size: 1.2em;");
            // sb.AppendLine("\tpadding: 3pt 3pt 3pt 3pt;");
            // sb.AppendLine("\tcolor: #000000;");
            // sb.AppendLine("\tbackground-color: #EEEEEE;");
            // sb.AppendLine("\tbackground-image: -webkit-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -moz-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -ms-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: linear-gradient(to bottom, #E2E2E2, #FAFAFA);");
            sb.AppendLine("}");
            sb.AppendLine("h4 { font-size: 1em; }");
            sb.AppendLine("h5 { font-size: 0.89em; }");
            sb.AppendLine("h6 { font-size: 0.6em; }");

            sb.AppendLine("a:visited {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("}");
            sb.AppendLine("a:active {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("}");
            sb.AppendLine("a:link {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("}");
            sb.AppendLine("a:hover {");
            sb.AppendLine("\ttext-decoration: underline;");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("}");

            sb.AppendLine("img {");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("}");

            sb.AppendLine(".withspc > li + li {");
            sb.AppendLine("\tmargin-top: 0.5em;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tbackground-color: #EEEEEE;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            // border-collapse is incompatible with border-radius
            // sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\t-webkit-border-radius: 5px;");
            sb.AppendLine("\t-moz-border-radius: 5px;");
            sb.AppendLine("\tborder-radius: 5px;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader tr td {");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("\tpadding: 0px 15px 0px 15px;");
            sb.AppendLine("}");

            sb.AppendLine("table.fillinline {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\tempty-cells: show;");
            sb.AppendLine("}");
            sb.AppendLine("table.fillinline tr td {");
            sb.AppendLine("\tpadding: 4pt 4pt 4pt 4pt;");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("\tword-break: break-all;");
            sb.AppendLine("\toverflow-wrap: break-word;");
            sb.AppendLine("\tword-wrap: break-word;");
            sb.AppendLine("}");
            // sb.AppendLine("span.fillinlinesym {");
            // sb.AppendLine("\tdisplay: inline-block;");
            // sb.AppendLine("\ttransform: scale(1.75, 1.75) translate(-0.5pt, -0.5pt);");
            // sb.AppendLine("}");

            // sb.AppendLine("@media print {");
            // sb.AppendLine(".scronly {");
            // sb.AppendLine("\tdisplay: none;");
            // sb.AppendLine("}");
            // sb.AppendLine("}");

            // Add the temporary content identifier
            sb.AppendLine("." + Program.TempFilesPool.TempContentTag + " {");
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("/* ]]> */");
            sb.AppendLine("</style>");
            sb.AppendLine("</head><body>");

            ImageArchive ia = new ImageArchive();

            ia.Load(Properties.Resources.Images_App_HighRes);

            sb.AppendLine("<table class=\"docheader\" cellspacing=\"0\" cellpadding=\"0\"><tr>");
            sb.AppendLine("<td style=\"text-align: " + strLogLeft + ";\">");
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KeePass")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(PwDefs.ShortProductName) + "\" /></td>");
            sb.AppendLine("<td style=\"text-align: center;\">");
            sb.AppendLine("<h1>" + h(PwDefs.ShortProductName) + "</h1>");
            sb.AppendLine("<h2>" + h(KPRes.EmergencySheet) + "</h2>");
            sb.AppendLine("</td>");
            sb.AppendLine("<td style=\"text-align: " + strLogRight + ";\">");
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KOrganizer")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(KPRes.EmergencySheet) + "\" /></td>");
            sb.AppendLine("</tr></table>");

            sb.AppendLine("<p style=\"text-align: " + strLogRight + ";\">" +
                          h(TimeUtil.ToDisplayStringDateOnly(DateTime.Now)) + "</p>");

            const string strFillInit    = "<table class=\"fillinline\"><tr><td>";
            const string strFillInitLtr = "<table class=\"fillinline\"><tr><td dir=\"ltr\">";
            const string strFillEnd     = "</td></tr></table>";
            string       strFillSym     = "<img src=\"" + GfxUtil.ImageToDataUri(
                Properties.Resources.B48x35_WritingHand) +
                                          "\" style=\"width: 1.3714em; height: 1em;" +
                                          (bRtl ? " transform: scaleX(-1);" : string.Empty) +
                                          "\" alt=\"&#x270D;\" />";
            string strFill = strFillInit + ne(string.Empty) +
                             // "</td><td style=\"text-align: right;\"><span class=\"fillinlinesym\">&#x270D;</span>" +
                             "</td><td style=\"text-align: " + strLogRight + ";\">" +
                             strFillSym + strFillEnd;

            string strFillInitEx = (bRtl ? strFillInitLtr : strFillInit);

            IOConnectionInfo ioc = pd.IOConnectionInfo;

            sb.AppendLine("<p><strong>" + h(KPRes.DatabaseFile) + ":</strong></p>");
            sb.AppendLine(strFillInitEx + ne(h(ltrPath(ioc.Path))) + strFillEnd);

            // if(pd.Name.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Name) + ":</strong> " +
            //		h(pd.Name) + "</p>");
            // if(pd.Description.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Description) + ":</strong> " +
            //		h(pd.Description));

            sb.AppendLine("<p>" + h(KPRes.BackupDatabase) + " " +
                          h(KPRes.BackupLocation) + "</p>");
            sb.AppendLine(strFill);

            CompositeKey ck = pd.MasterKey;

            if (ck.UserKeyCount > 0)
            {
                sb.AppendLine("<br />");
                sb.AppendLine("<h3>" + h(KPRes.MasterKey) + "</h3>");
                sb.AppendLine("<p>" + h(KPRes.MasterKeyComponents) + "</p>");
                sb.AppendLine("<ul>");

                foreach (IUserKey k in ck.UserKeys)
                {
                    KcpPassword    p  = (k as KcpPassword);
                    KcpKeyFile     kf = (k as KcpKeyFile);
                    KcpUserAccount a  = (k as KcpUserAccount);
                    KcpCustomKey   c  = (k as KcpCustomKey);

                    if (p != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.MasterPassword) +
                                      ":</strong></p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (kf != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyFile) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInitEx + ne(h(ltrPath(kf.Path))) + strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.BackupFile) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill);

                        sb.AppendLine("</li>");
                    }
                    else if (a != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.WindowsUserAccount) +
                                      ":</strong></p>");
                        sb.Append(strFillInitEx);
                        try
                        {
                            sb.Append(ne(h(ltrPath(Environment.UserDomainName +
                                                   "\\" + Environment.UserName))));
                        }
                        catch (Exception) { Debug.Assert(false); sb.Append(ne(string.Empty)); }
                        sb.AppendLine(strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.WindowsUserAccountBackup) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (c != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyProvider) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInitEx + ne(h(ltrPath(c.Name))) + strFillEnd);

                        sb.AppendLine("</li>");
                    }
                    else
                    {
                        Debug.Assert(false);
                        sb.AppendLine("<li><p><strong>" + h(KPRes.Unknown) + ".</strong></p></li>");
                    }
                }

                sb.AppendLine("</ul>");
            }

            sb.AppendLine("<br />");
            sb.AppendLine("<h3>" + h(KPRes.InstrAndGenInfo) + "</h3>");

            sb.AppendLine("<ul class=\"withspc\">");

            sb.AppendLine("<li>" + h(KPRes.EmergencySheetInfo) + "</li>");
            // sb.AppendLine("<form class=\"scronly\" action=\"#\" onsubmit=\"javascript:window.print();\">");
            // sb.AppendLine("<input type=\"submit\" value=\"&#x1F5B6; " +
            //	h(KPRes.Print) + "\" />");
            // sb.AppendLine("</form></li>");

            sb.AppendLine("<li>" + h(KPRes.DataLoss) + "</li>");
            sb.AppendLine("<li>" + h(KPRes.LatestVersionWeb) + ": <a href=\"" +
                          h(PwDefs.HomepageUrl) + "\" target=\"_blank\">" +
                          h(PwDefs.HomepageUrl) + "</a>.</li>");
            sb.AppendLine("</ul>");

            sb.AppendLine("</body></html>");
            return(sb.ToString());
        }
Ejemplo n.º 11
0
        private static void OnMenuExecute(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = (sender as ToolStripMenuItem);

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

            PwEntry peTemplate = (tsmi.Tag as PwEntry);

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

            MainForm mf = Program.MainForm;

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

            PwDatabase pd = mf.ActiveDatabase;

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

            // Ensure that the correct database is still active
            if (pd != mf.DocumentManager.FindContainerOf(peTemplate))
            {
                return;
            }

            GFunc <PwEntry> fNewEntry = delegate()
            {
                PwEntry pe = peTemplate.Duplicate();
                pe.History.Clear();
                return(pe);
            };

            Action <PwEntry> fAddPre = delegate(PwEntry pe)
            {
                if (EntryTemplates.EntryCreating != null)
                {
                    EntryTemplates.EntryCreating(null, new TemplateEntryEventArgs(
                                                     peTemplate.CloneDeep(), pe));
                }
            };

            Action <PwEntry> fAddPost = delegate(PwEntry pe)
            {
                if (EntryTemplates.EntryCreated != null)
                {
                    EntryTemplates.EntryCreated(null, new TemplateEntryEventArgs(
                                                    peTemplate.CloneDeep(), pe));
                }
            };

            mf.AddEntryEx(null, fNewEntry, fAddPre, fAddPost);
        }
Ejemplo n.º 12
0
        private List <ToolStripItem> ConstructMenuItems()
        {
            List <ToolStripItem> l          = new List <ToolStripItem>();
            List <char>          lAvailKeys = new List <char>(PwCharSet.MenuAccels);
            ProtectedString      ps         = GetPassword();

            GFunc <string, Image, EventHandler, object, ToolStripMenuItem> fAdd =
                delegate(string strText, Image img, EventHandler ehClick,
                         object oTag)
            {
                string str = StrUtil.EncodeMenuText(strText ?? string.Empty);
                str = StrUtil.AddAccelerator(str, lAvailKeys);

                ToolStripMenuItem tsmi = new ToolStripMenuItem(str);
                if (img != null)
                {
                    tsmi.Image = img;
                }
                if (ehClick != null)
                {
                    tsmi.Click += ehClick;
                }
                if (oTag != null)
                {
                    tsmi.Tag = oTag;
                }

                l.Add(tsmi);
                return(tsmi);
            };

            fAdd(KPRes.PwGenOpen, Properties.Resources.B16x16_Key_New,
                 this.OnGenOpen, null);

            l.Add(new ToolStripSeparator());

            ToolStripMenuItem tsmiDerive = fAdd(GenDeriveFromPrevious,
                                                Properties.Resources.B16x16_CompFile, this.OnGenDeriveFromPrevious, null);

            if (IsMultipleValues(ps))
            {
                tsmiDerive.Enabled = false;
            }

            fAdd(GenAuto, Properties.Resources.B16x16_FileNew, this.OnGenAuto, null);

            bool bHideBuiltIn = ((Program.Config.UI.UIFlags &
                                  (ulong)AceUIFlags.HideBuiltInPwGenPrfInEntryDlg) != 0);
            bool bFirst = true;

            foreach (PwProfile prf in PwGeneratorUtil.GetAllProfiles(true))
            {
                if (prf == null)
                {
                    Debug.Assert(false); continue;
                }

                if (bHideBuiltIn && PwGeneratorUtil.IsBuiltInProfile(prf.Name))
                {
                    continue;
                }

                if (bFirst)
                {
                    l.Add(new ToolStripSeparator());
                    bFirst = false;
                }

                fAdd(prf.Name, Properties.Resources.B16x16_KOrganizer,
                     this.OnGenProfile, prf);
            }

            return(l);
        }
Ejemplo n.º 13
0
        /* private static void BlockPrintScreen(Form f, bool bBlock)
         * {
         *      if(f == null) { Debug.Assert(false); return; }
         *
         *      try
         *      {
         *              if(bBlock)
         *              {
         *                      NativeMethods.RegisterHotKey(f.Handle, NativeMethods.IDHOT_SNAPDESKTOP,
         *                              0, NativeMethods.VK_SNAPSHOT);
         *                      NativeMethods.RegisterHotKey(f.Handle, NativeMethods.IDHOT_SNAPWINDOW,
         *                              NativeMethods.MOD_ALT, NativeMethods.VK_SNAPSHOT);
         *              }
         *              else
         *              {
         *                      NativeMethods.UnregisterHotKey(f.Handle, NativeMethods.IDHOT_SNAPWINDOW);
         *                      NativeMethods.UnregisterHotKey(f.Handle, NativeMethods.IDHOT_SNAPDESKTOP);
         *              }
         *      }
         *      catch(Exception) { Debug.Assert(false); }
         * } */

        internal static DialogResult ShowDialog <TForm, TResult>(bool bProtect,
                                                                 GFunc <TForm> fnConstruct, GFunc <TForm, TResult> fnResultBuilder,
                                                                 out TResult r)
            where TForm : Form
            where TResult : class
        {
            if (fnConstruct == null)
            {
                Debug.Assert(false); throw new ArgumentNullException("fnConstruct");
            }
            if (fnResultBuilder == null)
            {
                Debug.Assert(false); throw new ArgumentNullException("fnResultBuilder");
            }

            r = null;

            if (!bProtect)
            {
                TForm tf = fnConstruct();
                if (tf == null)
                {
                    Debug.Assert(false); return(DialogResult.None);
                }

                try
                {
                    DialogResult drDirect = tf.ShowDialog();
                    r = fnResultBuilder(tf);                     // Always
                    return(drDirect);
                }
                finally { UIUtil.DestroyForm(tf); }
            }

            UIFormConstructor fnUifC = delegate(object objParam)
            {
                return(fnConstruct());
            };

            UIFormResultBuilder fnUifRB = delegate(Form f)
            {
                TForm tf = (f as TForm);
                if (tf == null)
                {
                    Debug.Assert(false); return(null);
                }

                return(fnResultBuilder(tf));
            };

            ProtectedDialog dlg = new ProtectedDialog(fnUifC, fnUifRB);

            object       objResult;
            DialogResult dr = dlg.ShowDialog(out objResult, null);

            r = (objResult as TResult);
            return(dr);
        }
Ejemplo n.º 14
0
        private IEnumerable <PwEntryDatabase> FindMatchingEntries(string url, string realm)
        {
            var listResult = new List <PwEntryDatabase>();
            var hostUri    = new Uri(url);

            var formHost       = hostUri.Host;
            var searchHost     = hostUri.Host;
            var origSearchHost = hostUri.Host;

            List <PwDatabase> listDatabases = new List <PwDatabase>();

            var configOpt = new ConfigOpt(_host.CustomConfig);

            if (configOpt.SearchInAllOpenedDatabases)
            {
                foreach (PwDocument doc in _host.MainWindow.DocumentManager.Documents)
                {
                    if (doc.Database.IsOpen)
                    {
                        listDatabases.Add(doc.Database);
                    }
                }
            }
            else
            {
                listDatabases.Add(_host.Database);
            }

            var parms      = MakeSearchParameters(configOpt.HideExpired);
            var searchUrls = configOpt.SearchUrls;
            int listCount  = 0;

            foreach (PwDatabase db in listDatabases)
            {
                searchHost = origSearchHost;
                //get all possible entries for given host-name
                while (listResult.Count == listCount && (origSearchHost == searchHost || searchHost.IndexOf(".") != -1))
                {
                    parms.SearchString = string.Format("^{0}$|/{0}/?", searchHost);
                    var listEntries = new PwObjectList <PwEntry>();
                    db.RootGroup.SearchEntries(parms, listEntries);
                    listResult.AddRange(listEntries.Select(x => new PwEntryDatabase(x, db)));
                    if (searchUrls)
                    {
                        AddURLCandidates(db, listResult, parms.RespectEntrySearchingDisabled);
                    }
                    searchHost = searchHost.Substring(searchHost.IndexOf(".") + 1);

                    //searchHost contains no dot --> prevent possible infinite loop
                    if (searchHost == origSearchHost)
                    {
                        break;
                    }
                }
                listCount = listResult.Count;
            }

            var filter = new GFunc <PwEntry, bool>((PwEntry e) =>
            {
                var title    = e.Strings.ReadSafe(PwDefs.TitleField);
                var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField);
                var c        = _ext.GetEntryConfig(e);
                if (c != null)
                {
                    if (c.Allow.Contains(formHost))
                    {
                        return(true);
                    }
                    if (c.Deny.Contains(formHost))
                    {
                        return(false);
                    }
                    if (!string.IsNullOrEmpty(realm) && c.Realm != realm)
                    {
                        return(false);
                    }
                }

                if (IsValidUrl(entryUrl, formHost))
                {
                    return(true);
                }

                if (IsValidUrl(title, formHost))
                {
                    return(true);
                }

                if (searchUrls)
                {
                    foreach (var sf in e.Strings.Where(s => s.Key.StartsWith("URL", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        var sfv = e.Strings.ReadSafe(sf.Key);

                        if (sf.Key.IndexOf("regex", StringComparison.OrdinalIgnoreCase) >= 0 &&
                            System.Text.RegularExpressions.Regex.IsMatch(formHost, sfv))
                        {
                            return(true);
                        }

                        if (IsValidUrl(sfv, formHost))
                        {
                            return(true);
                        }
                    }
                }

                return(formHost.Contains(title) || (!string.IsNullOrEmpty(entryUrl) && formHost.Contains(entryUrl)));
            });

            var filterSchemes = new GFunc <PwEntry, bool>((PwEntry e) =>
            {
                var title    = e.Strings.ReadSafe(PwDefs.TitleField);
                var entryUrl = e.Strings.ReadSafe(PwDefs.UrlField);
                Uri entryUri;
                Uri titleUri;

                if (entryUrl != null && Uri.TryCreate(entryUrl, UriKind.Absolute, out entryUri) && entryUri.Scheme == hostUri.Scheme)
                {
                    return(true);
                }

                if (Uri.TryCreate(title, UriKind.Absolute, out titleUri) && titleUri.Scheme == hostUri.Scheme)
                {
                    return(true);
                }

                return(false);
            });

            var result = listResult.Where(e => filter(e.entry));

            if (configOpt.MatchSchemes)
            {
                result = result.Where(e => filterSchemes(e.entry));
            }

            if (configOpt.HideExpired)
            {
                result = result.Where(x => !(x.entry.Expires && x.entry.ExpiryTime <= DateTime.UtcNow));
            }

            return(result);
        }
Ejemplo n.º 15
0
        internal Response GetLoginsHandler(Request req)
        {
            if (!req.TryDecrypt())
            {
                return(new ErrorResponse(req, ErrorType.CannotDecryptMessage));
            }

            var msg       = req.Message;
            var id        = msg.GetString("id");
            var url       = msg.GetString("url");
            var submitUrl = msg.GetString("submitUrl");

            Uri hostUri;
            Uri submitUri = null;

            if (!string.IsNullOrEmpty(url))
            {
                hostUri = new Uri(url);
            }
            else
            {
                return(new ErrorResponse(req, ErrorType.NoUrlProvided));
            }

            if (!string.IsNullOrEmpty(submitUrl))
            {
                submitUri = new Uri(submitUrl);
            }

            var resp = req.GetResponse();

            resp.Message.Add("id", id);

            var items = FindMatchingEntries(url, null);

            if (items.ToList().Count > 0)
            {
                var filter = new GFunc <PwEntry, bool>((PwEntry e) =>
                {
                    var c = _ext.GetEntryConfig(e);

                    return(c == null || (!c.Allow.Contains(hostUri.Authority)) || (submitUri != null && submitUri.Authority != null && !c.Allow.Contains(submitUri.Authority)));
                });

                var configOpt     = new ConfigOpt(_host.CustomConfig);
                var needPrompting = items.Where(e => filter(e.entry)).ToList();

                if (needPrompting.Count > 0 && !configOpt.AlwaysAllowAccess)
                {
                    var win = _host.MainWindow;

                    using (var f = new AccessControlForm())
                    {
                        win.Invoke((MethodInvoker) delegate
                        {
                            f.Icon          = win.Icon;
                            f.Plugin        = _ext;
                            f.StartPosition = win.Visible ? FormStartPosition.CenterParent : FormStartPosition.CenterScreen;
                            f.Entries       = needPrompting.Select(e => e.entry).ToList();
                            f.Host          = submitUri != null ? submitUri.Authority : hostUri.Authority;
                            f.Load         += delegate { f.Activate(); };
                            f.ShowDialog(win);
                            if (f.Remember && (f.Allowed || f.Denied))
                            {
                                foreach (var e in needPrompting)
                                {
                                    var c   = _ext.GetEntryConfig(e.entry) ?? new EntryConfig();
                                    var set = f.Allowed ? c.Allow : c.Deny;
                                    set.Add(hostUri.Authority);
                                    if (submitUri != null && submitUri.Authority != null && submitUri.Authority != hostUri.Authority)
                                    {
                                        set.Add(submitUri.Authority);
                                    }
                                    _ext.SetEntryConfig(e.entry, c);
                                }
                            }
                            if (!f.Allowed)
                            {
                                items = items.Except(needPrompting);
                            }
                        });
                    }
                }

                var uri = submitUri != null ? submitUri : hostUri;

                foreach (var entryDatabase in items)
                {
                    string entryUrl = string.Copy(entryDatabase.entry.Strings.ReadSafe(PwDefs.UrlField));
                    if (string.IsNullOrEmpty(entryUrl))
                    {
                        entryUrl = entryDatabase.entry.Strings.ReadSafe(PwDefs.TitleField);
                    }

                    entryUrl = entryUrl.ToLower();

                    entryDatabase.entry.UsageCount = (ulong)LevenshteinDistance(uri.ToString().ToLower(), entryUrl);
                }

                var itemsList = items.ToList();

                if (configOpt.SpecificMatchingOnly)
                {
                    itemsList = (from e in itemsList
                                 orderby e.entry.UsageCount ascending
                                 select e).ToList();

                    ulong lowestDistance = itemsList.Count > 0 ?
                                           itemsList[0].entry.UsageCount :
                                           0;

                    itemsList = (from e in itemsList
                                 where e.entry.UsageCount == lowestDistance
                                 orderby e.entry.UsageCount
                                 select e).ToList();
                }

                if (configOpt.SortResultByUsername)
                {
                    var items2 = from e in itemsList orderby e.entry.UsageCount ascending, _ext.GetUserPass(e)[0] ascending select e;
                    itemsList = items2.ToList();
                }
                else
                {
                    var items2 = from e in itemsList orderby e.entry.UsageCount ascending, e.entry.Strings.ReadSafe(PwDefs.TitleField) ascending select e;
                    itemsList = items2.ToList();
                }

                var entries = new JArray(itemsList.Select(item =>
                {
                    var up        = _ext.GetUserPass(item);
                    JArray fldArr = null;
                    var fields    = GetFields(configOpt, item);
                    if (fields != null)
                    {
                        fldArr = new JArray(fields.Select(f => new JObject {
                            { f.Key, f.Value }
                        }));
                    }
                    var jobj = new JObject {
                        { "name", item.entry.Strings.ReadSafe(PwDefs.TitleField) },
                        { "login", up[0] },
                        { "password", up[1] },
                        { "uuid", item.entry.Uuid.ToHexString() },
                        { "stringFields", fldArr },
                    };

                    CheckTotp(item, jobj);

                    return(jobj);
                }));

                resp.Message.Add("count", itemsList.Count);
                resp.Message.Add("entries", entries);

                if (itemsList.Count > 0)
                {
                    var names = (from e in itemsList select e.entry.Strings.ReadSafe(PwDefs.TitleField)).Distinct();
                    var n     = String.Join("\n    ", names);

                    if (configOpt.ReceiveCredentialNotification)
                    {
                        _ext.ShowNotification(String.Format("{0}: {1} is receiving credentials for:\n    {2}", req.GetString("id"), hostUri.Host, n));
                    }
                }

                return(resp);
            }

            resp.Message.Add("count", 0);
            resp.Message.Add("entries", new JArray());

            return(resp);
        }
Ejemplo n.º 16
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            if (m_dStrings == null)
            {
                Debug.Assert(false); throw new InvalidOperationException();
            }

            GlobalWindowManager.AddWindow(this);

            string strTitle, strDesc;

            if (m_strInitName == null)
            {
                strTitle = KPRes.AddStringField;
                strDesc  = KPRes.AddStringFieldDesc;
            }
            else
            {
                strTitle = KPRes.EditStringField;
                strDesc  = KPRes.EditStringFieldDesc;
            }

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_Font, strTitle, strDesc);
            this.Icon = AppIcons.Default;

            UIUtil.ConfigureToolTip(m_ttRect);

            UIUtil.EnableAutoCompletion(m_cmbName, true);

            UIUtil.PrepareStandardMultilineControl(m_rtbValue, true, true);
            m_ctxValue.Attach(m_rtbValue, this);

            GFunc <PwEntry> fGetContextEntry = delegate()
            {
                return(PwEntry.CreateVirtual(((m_pdContext != null) ? m_pdContext.RootGroup :
                                              null) ?? new PwGroup(true, true), m_dStrings));
            };

            m_pgm = new PwGeneratorMenu(m_btnGenPw, m_ttRect, m_rtbValue,
                                        fGetContextEntry, m_pdContext, (m_mvec != null));

            if (m_strInitName != null)
            {
                m_cmbName.Text = m_strInitName;
            }
            if (m_psInitValue != null)
            {
                m_rtbValue.Text = StrUtil.NormalizeNewLines(
                    m_psInitValue.ReadString(), true);
                UIUtil.SetChecked(m_cbProtect, m_psInitValue.IsProtected);
            }

            ValidateStringNameUI();
            PopulateNamesComboBox();

            if (m_mvec != null)
            {
                m_cmbName.Enabled = false;
                MultipleValuesEx.ConfigureText(m_rtbValue, true);

                bool bMultiProt;
                m_mvec.MultiStringProt.TryGetValue(m_cmbName.Text, out bMultiProt);
                if (bMultiProt)
                {
                    MultipleValuesEx.ConfigureState(m_cbProtect, true);
                }
            }

            if (m_bReadOnly)
            {
                m_cmbName.Enabled   = false;
                m_rtbValue.ReadOnly = true;
                m_cbProtect.Enabled = false;
                m_btnGenPw.Enabled  = false;
                // m_btnOK.Enabled = false; // See ValidateStringNameUI
            }

            // UIUtil.SetFocus(..., this); // See PopulateNamesComboBox
        }