Пример #1
0
        private void Query(String url)
        {
            try
            {
                //first: search for exact url
                Group = _db.SearchForExactUrl(url);
                if (!url.StartsWith("androidapp://"))
                {
                    //if no results, search for host (e.g. "accounts.google.com")
                    if (!Group.Entries.Any())
                    {
                        Group = _db.SearchForHost(url, false);
                    }
                    //if still no results, search for host, allowing subdomains ("www.google.com" in entry is ok for "accounts.google.com" in search (but not the other way around)
                    if (!Group.Entries.Any())
                    {
                        Group = _db.SearchForHost(url, true);
                    }
                }
                //if no results returned up to now, try to search through other fields as well:
                if (!Group.Entries.Any())
                {
                    Group = _db.SearchForText(url);
                }
                //search for host as text
                if (!Group.Entries.Any())
                {
                    Group = _db.SearchForText(UrlUtil.GetHost(url.Trim()));
                }
            } catch (Exception e)
            {
                Toast.MakeText(this, e.Message, ToastLength.Long).Show();
                SetResult(Result.Canceled);
                Finish();
                return;
            }

            //if there is exactly one match: open the entry
            if (Group.Entries.Count() == 1)
            {
                LaunchActivityForEntry(Group.Entries.Single(), 0);
                return;
            }

            //show results:
            if (Group == null || (!Group.Entries.Any()))
            {
                SetContentView(Resource.Layout.searchurlresults_empty);
            }

            SetGroupTitle();

            FragmentManager.FindFragmentById <GroupListFragment>(Resource.Id.list_fragment).ListAdapter = new PwGroupListAdapter(this, Group);

            View selectOtherEntry = FindViewById(Resource.Id.select_other_entry);

            var newTask = new SelectEntryForUrlTask(url);

            if (AppTask is SelectEntryTask currentSelectTask)
            {
                newTask.ShowUserNotifications = currentSelectTask.ShowUserNotifications;
            }

            selectOtherEntry.Click += (sender, e) => {
                GroupActivity.Launch(this, newTask);
            };


            View createUrlEntry = FindViewById(Resource.Id.add_url_entry);

            if (App.Kp2a.GetDb().CanWrite)
            {
                createUrlEntry.Visibility = ViewStates.Visible;
                createUrlEntry.Click     += (sender, e) =>
                {
                    GroupActivity.Launch(this, new CreateEntryThenCloseTask {
                        Url = url, ShowUserNotifications = (AppTask as SelectEntryTask)?.ShowUserNotifications ?? true
                    });
                    Toast.MakeText(this, GetString(Resource.String.select_group_then_add, new Java.Lang.Object[] { GetString(Resource.String.add_entry) }), ToastLength.Long).Show();
                };
            }
            else
            {
                createUrlEntry.Visibility = ViewStates.Gone;
            }

            Util.MoveBottomBarButtons(Resource.Id.select_other_entry, Resource.Id.add_url_entry, Resource.Id.bottom_bar, this);
        }
Пример #2
0
        private static string CompileInternal(string strText, SprContext ctx,
                                              uint uRecursionLevel)
        {
            if (strText == null)
            {
                Debug.Assert(false); return(string.Empty);
            }
            if (ctx == null)
            {
                Debug.Assert(false); ctx = new SprContext();
            }

            if (uRecursionLevel >= SprEngine.MaxRecursionDepth)
            {
                Debug.Assert(false);                 // Most likely a recursive reference
                return(string.Empty);                // Do not return strText (endless loop)
            }

            string   str = strText;
            MainForm mf  = Program.MainForm;

            bool bExt = ((ctx.Flags & (SprCompileFlags.ExtActive |
                                       SprCompileFlags.ExtNonActive)) != SprCompileFlags.None);

            if (bExt && (SprEngine.FilterCompilePre != null))
            {
                SprEventArgs args = new SprEventArgs(str, ctx.Clone());
                SprEngine.FilterCompilePre(null, args);
                str = args.Text;
            }

            if ((ctx.Flags & SprCompileFlags.Comments) != SprCompileFlags.None)
            {
                str = RemoveComments(str);
            }

            if ((ctx.Flags & SprCompileFlags.TextTransforms) != SprCompileFlags.None)
            {
                str = PerformTextTransforms(str, ctx, uRecursionLevel);
            }

            if ((ctx.Flags & SprCompileFlags.AppPaths) != SprCompileFlags.None)
            {
                str = AppLocator.FillPlaceholders(str, ctx);
            }

            if (ctx.Entry != null)
            {
                if ((ctx.Flags & SprCompileFlags.PickChars) != SprCompileFlags.None)
                {
                    str = ReplacePickPw(str, ctx, uRecursionLevel);
                }

                if ((ctx.Flags & SprCompileFlags.EntryStrings) != SprCompileFlags.None)
                {
                    str = FillEntryStrings(str, ctx, uRecursionLevel);
                }

                if ((ctx.Flags & SprCompileFlags.EntryStringsSpecial) != SprCompileFlags.None)
                {
                    // ctx.UrlRemoveSchemeOnce = true;
                    // str = SprEngine.FillIfExists(str, @"{URL:RMVSCM}",
                    //	ctx.Entry.Strings.GetSafe(PwDefs.UrlField), ctx, uRecursionLevel);
                    // Debug.Assert(!ctx.UrlRemoveSchemeOnce);

                    str = FillEntryStringsSpecial(str, ctx, uRecursionLevel);
                }

                if (((ctx.Flags & SprCompileFlags.PasswordEnc) != SprCompileFlags.None) &&
                    (str.IndexOf(@"{PASSWORD_ENC}", SprEngine.ScMethod) >= 0))
                {
                    string strPwCmp = SprEngine.FillIfExists(@"{PASSWORD}",
                                                             @"{PASSWORD}", ctx.Entry.Strings.GetSafe(PwDefs.PasswordField),
                                                             ctx.WithoutContentTransformations(), uRecursionLevel);

                    str = SprEngine.FillPlaceholder(str, @"{PASSWORD_ENC}",
                                                    StrUtil.EncryptString(strPwCmp), ctx);
                }

                PwGroup pg = ctx.Entry.ParentGroup;
                if (((ctx.Flags & SprCompileFlags.Group) != SprCompileFlags.None) &&
                    (pg != null))
                {
                    str = FillGroupPlh(str, @"{GROUP", pg, ctx, uRecursionLevel);
                }
            }

            if ((ctx.Flags & SprCompileFlags.Paths) != SprCompileFlags.None)
            {
                if (mf != null)
                {
                    PwGroup pgSel = mf.GetSelectedGroup();
                    if (pgSel != null)
                    {
                        str = FillGroupPlh(str, @"{GROUP_SEL", pgSel, ctx, uRecursionLevel);
                    }
                }

                str = SprEngine.FillIfExists(str, @"{APPDIR}", new ProtectedString(
                                                 false, UrlUtil.GetFileDirectory(m_strAppExePath, false, false)),
                                             ctx, uRecursionLevel);
            }

            if (ctx.Database != null)
            {
                if ((ctx.Flags & SprCompileFlags.Paths) != SprCompileFlags.None)
                {
                    // For backward compatibility only
                    str = SprEngine.FillIfExists(str, @"{DOCDIR}", new ProtectedString(
                                                     false, UrlUtil.GetFileDirectory(ctx.Database.IOConnectionInfo.Path,
                                                                                     false, false)), ctx, uRecursionLevel);

                    str = SprEngine.FillIfExists(str, @"{DB_PATH}", new ProtectedString(
                                                     false, ctx.Database.IOConnectionInfo.Path), ctx, uRecursionLevel);
                    str = SprEngine.FillIfExists(str, @"{DB_DIR}", new ProtectedString(
                                                     false, UrlUtil.GetFileDirectory(ctx.Database.IOConnectionInfo.Path,
                                                                                     false, false)), ctx, uRecursionLevel);
                    str = SprEngine.FillIfExists(str, @"{DB_NAME}", new ProtectedString(
                                                     false, UrlUtil.GetFileName(ctx.Database.IOConnectionInfo.Path)),
                                                 ctx, uRecursionLevel);
                    str = SprEngine.FillIfExists(str, @"{DB_BASENAME}", new ProtectedString(
                                                     false, UrlUtil.StripExtension(UrlUtil.GetFileName(
                                                                                       ctx.Database.IOConnectionInfo.Path))), ctx, uRecursionLevel);
                    str = SprEngine.FillIfExists(str, @"{DB_EXT}", new ProtectedString(
                                                     false, UrlUtil.GetExtension(ctx.Database.IOConnectionInfo.Path)),
                                                 ctx, uRecursionLevel);
                }
            }

            if ((ctx.Flags & SprCompileFlags.Paths) != SprCompileFlags.None)
            {
                str = SprEngine.FillIfExists(str, @"{ENV_DIRSEP}", new ProtectedString(
                                                 false, Path.DirectorySeparatorChar.ToString()), ctx, uRecursionLevel);

                string strPF86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
                if (string.IsNullOrEmpty(strPF86))
                {
                    strPF86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                }
                if (strPF86 != null)
                {
                    str = SprEngine.FillIfExists(str, @"{ENV_PROGRAMFILES_X86}",
                                                 new ProtectedString(false, strPF86), ctx, uRecursionLevel);
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            if ((ctx.Flags & SprCompileFlags.AutoType) != SprCompileFlags.None)
            {
                // Use Bksp instead of Del (in order to avoid Ctrl+Alt+Del);
                // https://sourceforge.net/p/keepass/discussion/329220/thread/4f1aa6b8/
                str = StrUtil.ReplaceCaseInsensitive(str, @"{CLEARFIELD}",
                                                     @"{HOME}+({END}){BKSP}{DELAY 50}");
            }

            if ((ctx.Flags & SprCompileFlags.DateTime) != SprCompileFlags.None)
            {
                DateTime dtNow = DateTime.Now;                 // Local time
                str = SprEngine.FillIfExists(str, @"{DT_YEAR}", new ProtectedString(
                                                 false, dtNow.Year.ToString("D4")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_MONTH}", new ProtectedString(
                                                 false, dtNow.Month.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_DAY}", new ProtectedString(
                                                 false, dtNow.Day.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_HOUR}", new ProtectedString(
                                                 false, dtNow.Hour.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_MINUTE}", new ProtectedString(
                                                 false, dtNow.Minute.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_SECOND}", new ProtectedString(
                                                 false, dtNow.Second.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_SIMPLE}", new ProtectedString(
                                                 false, dtNow.ToString("yyyyMMddHHmmss")), ctx, uRecursionLevel);

                dtNow = dtNow.ToUniversalTime();
                str   = SprEngine.FillIfExists(str, @"{DT_UTC_YEAR}", new ProtectedString(
                                                   false, dtNow.Year.ToString("D4")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_MONTH}", new ProtectedString(
                                                 false, dtNow.Month.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_DAY}", new ProtectedString(
                                                 false, dtNow.Day.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_HOUR}", new ProtectedString(
                                                 false, dtNow.Hour.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_MINUTE}", new ProtectedString(
                                                 false, dtNow.Minute.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_SECOND}", new ProtectedString(
                                                 false, dtNow.Second.ToString("D2")), ctx, uRecursionLevel);
                str = SprEngine.FillIfExists(str, @"{DT_UTC_SIMPLE}", new ProtectedString(
                                                 false, dtNow.ToString("yyyyMMddHHmmss")), ctx, uRecursionLevel);
            }

            if ((ctx.Flags & SprCompileFlags.References) != SprCompileFlags.None)
            {
                str = SprEngine.FillRefPlaceholders(str, ctx, uRecursionLevel);
            }

            if (((ctx.Flags & SprCompileFlags.EnvVars) != SprCompileFlags.None) &&
                (str.IndexOf('%') >= 0))
            {
                // Replace environment variables
                foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
                {
                    string strKey   = (de.Key as string);
                    string strValue = (de.Value as string);

                    if ((strKey != null) && (strValue != null))
                    {
                        str = SprEngine.FillIfExists(str, @"%" + strKey + @"%",
                                                     new ProtectedString(false, strValue), ctx, uRecursionLevel);
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
            }

            if ((ctx.Flags & SprCompileFlags.Env) != SprCompileFlags.None)
            {
                str = FillUriSpecial(str, ctx, @"{BASE", (ctx.Base ?? string.Empty),
                                     ctx.BaseIsEncoded, uRecursionLevel);
            }

            str = EntryUtil.FillPlaceholders(str, ctx, uRecursionLevel);

            if ((ctx.Flags & SprCompileFlags.PickChars) != SprCompileFlags.None)
            {
                str = ReplacePickChars(str, ctx, uRecursionLevel);
            }

            if (bExt && (SprEngine.FilterCompile != null))
            {
                SprEventArgs args = new SprEventArgs(str, ctx.Clone());
                SprEngine.FilterCompile(null, args);
                str = args.Text;
            }

            if (ctx.EncodeAsAutoTypeSequence)
            {
                str = StrUtil.NormalizeNewLines(str, false);
                str = str.Replace("\n", @"{ENTER}");
            }

            return(str);
        }
Пример #3
0
 private static void NavigateToIndexesList()
 {
     UrlUtil.Navigate("/indexes");
 }
Пример #4
0
        // log an error issue to job level timeline record
        private async Task LogWorkerProcessUnhandledException(Pipelines.AgentJobRequestMessage message, string errorMessage)
        {
            try
            {
                var systemConnection = message.Resources.Endpoints.SingleOrDefault(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection));
                ArgUtil.NotNull(systemConnection, nameof(systemConnection));

                var            jobServer           = HostContext.GetService <IJobServer>();
                VssCredentials jobServerCredential = VssUtil.GetVssCredential(systemConnection);
                Uri            jobServerUrl        = systemConnection.Url;

                // Make sure SystemConnection Url match Config Url base for OnPremises server
                if ((!message.Variables.ContainsKey(Constants.Variables.System.ServerType) && !UrlUtil.IsHosted(systemConnection.Url.AbsoluteUri)) ||
                    string.Equals(message.Variables[Constants.Variables.System.ServerType]?.Value, "OnPremises", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        Uri result    = null;
                        Uri configUri = new Uri(_agentSetting.ServerUrl);
                        if (Uri.TryCreate(new Uri(configUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)), jobServerUrl.PathAndQuery, out result))
                        {
                            //replace the schema and host portion of messageUri with the host from the
                            //server URI (which was set at config time)
                            jobServerUrl = result;
                        }
                    }
                    catch (InvalidOperationException ex)
                    {
                        //cannot parse the Uri - not a fatal error
                        Trace.Error(ex);
                    }
                    catch (UriFormatException ex)
                    {
                        //cannot parse the Uri - not a fatal error
                        Trace.Error(ex);
                    }
                }

                VssConnection jobConnection = VssUtil.CreateConnection(jobServerUrl, jobServerCredential);
                await jobServer.ConnectAsync(jobConnection);

                var timeline = await jobServer.GetTimelineAsync(message.Plan.ScopeIdentifier, message.Plan.PlanType, message.Plan.PlanId, message.Timeline.Id, CancellationToken.None);

                ArgUtil.NotNull(timeline, nameof(timeline));
                TimelineRecord jobRecord = timeline.Records.FirstOrDefault(x => x.Id == message.JobId && x.RecordType == "Job");
                ArgUtil.NotNull(jobRecord, nameof(jobRecord));
                jobRecord.ErrorCount++;
                jobRecord.Issues.Add(new Issue()
                {
                    Type = IssueType.Error, Message = errorMessage
                });
                await jobServer.UpdateTimelineRecordsAsync(message.Plan.ScopeIdentifier, message.Plan.PlanType, message.Plan.PlanId, message.Timeline.Id, new TimelineRecord[] { jobRecord }, CancellationToken.None);
            }
            catch (Exception ex)
            {
                Trace.Error("Fail to report unhandled exception from Agent.Worker process");
                Trace.Error(ex);
            }
        }
Пример #5
0
        internal static void GenerateSerializers(CommandLineArgs cl)
        {
            StringBuilder sb = new StringBuilder();
            int           t  = 0;

            AppendLine(sb, "// This is a generated file!", ref t);
            AppendLine(sb, "// Do not edit manually, changes will be overwritten.", ref t);
            AppendLine(sb);
            AppendLine(sb, "using System;", ref t);
            AppendLine(sb, "using System.Collections.Generic;", ref t);
            AppendLine(sb, "using System.Xml;", ref t);
            AppendLine(sb, "using System.Diagnostics;", ref t);
            AppendLine(sb);
            AppendLine(sb, "using KeePassLib.Interfaces;", ref t);
            AppendLine(sb);
            AppendLine(sb, "namespace KeePass.Util.XmlSerialization", ref t);
            AppendLine(sb, "{", ref t, 0, 1);
            AppendLine(sb, "public sealed partial class XmlSerializerEx : IXmlSerializerEx", ref t);
            AppendLine(sb, "{", ref t, 0, 1);
            AppendLine(sb, "private static char[] m_vEnumSeps = new char[] {", ref t, 0, 1);
            AppendLine(sb, "' ', '\\t', '\\r', '\\n', '|', ',', ';', ':'", ref t);
            AppendLine(sb, "};", ref t, -1, 0);

            Dictionary <string, XmlsTypeInfo> d =
                new Dictionary <string, XmlsTypeInfo>();

            d[typeof(AppConfigEx).FullName]   = new XmlsTypeInfo(typeof(AppConfigEx));
            d[typeof(KPTranslation).FullName] = new XmlsTypeInfo(typeof(KPTranslation));

            bool bTypeCreated = true;

            while (bTypeCreated)
            {
                bTypeCreated = false;
                foreach (KeyValuePair <string, XmlsTypeInfo> kvp in d)
                {
                    if (!kvp.Value.HasInfo)
                    {
                        d[kvp.Key]   = GenerateSerializer(kvp.Value.Type, d, t);
                        bTypeCreated = true;
                        break;                         // Iterator might be invalid
                    }
                }
            }

            foreach (KeyValuePair <string, XmlsTypeInfo> kvp in d)
            {
                AppendLine(sb);
                sb.Append(kvp.Value.ReadCode);
            }

            AppendLine(sb, "}", ref t, -1, 0);
            AppendLine(sb, "}", ref t, -1, 0);
            Debug.Assert(t == 0);

            string strFileData = StrUtil.NormalizeNewLines(sb.ToString(), true);

            string strFile = cl["out"];

            if (!string.IsNullOrEmpty(strFile))
            {
                strFile = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strFile);
                File.WriteAllText(strFile, strFileData, StrUtil.Utf8);
                MessageService.ShowInfo("Saved XmlSerializerEx to:", strFile);
            }
        }
Пример #6
0
        public FileTransactionEx(IOConnectionInfo iocBaseFile, bool bTransacted)
        {
            if (iocBaseFile == null)
            {
                throw new ArgumentNullException("iocBaseFile");
            }

            m_bTransacted = bTransacted;

            m_iocBase = iocBaseFile.CloneDeep();
            if (m_iocBase.IsLocalFile())
            {
                m_iocBase.Path = UrlUtil.GetShortestAbsolutePath(m_iocBase.Path);
            }

            string strPath = m_iocBase.Path;

            if (m_iocBase.IsLocalFile())
            {
                try
                {
                    if (File.Exists(strPath))
                    {
                        // Symbolic links are realized via reparse points;
                        // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365503.aspx
                        // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365680.aspx
                        // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365006.aspx
                        // Performing a file transaction on a symbolic link
                        // would delete/replace the symbolic link instead of
                        // writing to its target
                        FileAttributes fa = File.GetAttributes(strPath);
                        if ((long)(fa & FileAttributes.ReparsePoint) != 0)
                        {
                            m_bTransacted = false;
                        }
                    }
                    else
                    {
                        // If the base and the temporary file are in different
                        // folders and the base file doesn't exist (i.e. we can't
                        // backup the ACL), a transaction would cause the new file
                        // to have the default ACL of the temporary folder instead
                        // of the one of the base folder; therefore, we don't use
                        // a transaction when the base file doesn't exist (this
                        // also results in other applications monitoring the folder
                        // to see one file creation only)
                        m_bTransacted = false;
                    }
                }
                catch (Exception) { Debug.Assert(false); }
            }

#if !KeePassUAP
            // Prevent transactions for FTP URLs under .NET 4.0 in order to
            // avoid/workaround .NET bug 621450:
            // https://connect.microsoft.com/VisualStudio/feedback/details/621450/problem-renaming-file-on-ftp-server-using-ftpwebrequest-in-net-framework-4-0-vs2010-only
            if (strPath.StartsWith("ftp:", StrUtil.CaseIgnoreCmp) &&
                (Environment.Version.Major >= 4) && !NativeLib.IsUnix())
            {
                m_bTransacted = false;
            }
#endif

            foreach (KeyValuePair <string, bool> kvp in g_dEnabled)
            {
                if (strPath.StartsWith(kvp.Key, StrUtil.CaseIgnoreCmp))
                {
                    m_bTransacted = kvp.Value;
                    break;
                }
            }

            if (m_bTransacted)
            {
                m_iocTemp       = m_iocBase.CloneDeep();
                m_iocTemp.Path += StrTempSuffix;

                TxfPrepare();                 // Adjusts m_iocTemp
            }
            else
            {
                m_iocTemp = m_iocBase;
            }
        }
Пример #7
0
        private void OnClickKeyFileCreate(object sender, EventArgs e)
        {
            SaveFileDialogEx sfd = UIUtil.CreateSaveFileDialog(KPRes.KeyFileCreate,
                                                               UrlUtil.StripExtension(UrlUtil.GetFileName(m_ioInfo.Path)) + "." +
                                                               AppDefs.FileExtension.KeyFile, UIUtil.CreateFileTypeFilter("key",
                                                                                                                          KPRes.KeyFiles, true), 1, "key", AppDefs.FileDialogContext.KeyFile);

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                EntropyForm dlg = new EntropyForm();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    byte[] pbAdditionalEntropy = dlg.GeneratedEntropy;

                    try
                    {
                        KcpKeyFile.Create(sfd.FileName, pbAdditionalEntropy);

                        string str = sfd.FileName;
                        m_cmbKeyFile.Items.Add(str);
                        m_cmbKeyFile.SelectedIndex = m_cmbKeyFile.Items.Count - 1;
                    }
                    catch (Exception exKC)
                    {
                        MessageService.ShowWarning(exKC);
                    }
                }
                UIUtil.DestroyForm(dlg);
            }

            EnableUserControls();
        }
Пример #8
0
 /// <summary>Creates a WmfImage from a file.</summary>
 /// <param name="fileName">pah to the file</param>
 public WmfImageData(String fileName)
     : this(UrlUtil.ToURL(fileName))
 {
 }
Пример #9
0
        private static void GetConfigPaths()
        {
            if (m_strGlobalConfigFile == null)
            {
                Assembly asm = Assembly.GetExecutingAssembly();
                Debug.Assert(asm != null); if (asm == null)
                {
                    return;
                }

#if !KeePassLibSD
                string strFile = null;

                try { strFile = asm.Location; }
                catch (Exception) { }

                if (string.IsNullOrEmpty(strFile))
                {
                    strFile = UrlUtil.FileUrlToPath(asm.GetName().CodeBase);
                }
#else
                string strFile = UrlUtil.FileUrlToPath(asm.GetName().CodeBase);
#endif
                Debug.Assert(strFile != null); if (strFile == null)
                {
                    return;
                }

                if (string.IsNullOrEmpty(m_strBaseName))
                {
                    // Remove assembly extension
                    if (strFile.EndsWith(".exe", StrUtil.CaseIgnoreCmp))
                    {
                        strFile = strFile.Substring(0, strFile.Length - 4);
                    }
                    else if (strFile.EndsWith(".dll", StrUtil.CaseIgnoreCmp))
                    {
                        strFile = strFile.Substring(0, strFile.Length - 4);
                    }
                }
                else                 // Base name != null
                {
                    strFile = UrlUtil.GetFileDirectory(strFile, true, false) + m_strBaseName;
                }

                m_strGlobalConfigFile   = strFile + ".config.xml";
                m_strEnforcedConfigFile = strFile + ".config.enforced.xml";
            }

            if (m_strUserConfigFile == null)
            {
                string strBaseDirName = PwDefs.ShortProductName;
                if ((m_strBaseName != null) && (m_strBaseName.Length > 0))
                {
                    strBaseDirName = m_strBaseName;
                }

                string strUserDir;
                try
                {
                    strUserDir = Environment.GetFolderPath(
                        Environment.SpecialFolder.ApplicationData);
                }
                catch (Exception)
                {
                    strUserDir = UrlUtil.GetFileDirectory(UrlUtil.FileUrlToPath(
                                                              Assembly.GetExecutingAssembly().GetName().CodeBase), true, false);
                }
                strUserDir = UrlUtil.EnsureTerminatingSeparator(strUserDir, false);

                string strUserDirLocal;
                try
                {
                    strUserDirLocal = Environment.GetFolderPath(
                        Environment.SpecialFolder.LocalApplicationData);
                }
                catch (Exception) { strUserDirLocal = strUserDir; }
                strUserDirLocal = UrlUtil.EnsureTerminatingSeparator(strUserDirLocal, false);

                m_strCreateDir      = strUserDir + strBaseDirName;
                m_strCreateDirLocal = strUserDirLocal + strBaseDirName;
                m_strUserConfigFile = m_strCreateDir + Path.DirectorySeparatorChar +
                                      strBaseDirName + ".config.xml";
            }

            string strLocalOvr = Program.CommandLineArgs[
                AppDefs.CommandLineOptions.ConfigPathLocal];
            if (!string.IsNullOrEmpty(strLocalOvr))
            {
                string strWD = UrlUtil.EnsureTerminatingSeparator(
                    WinUtil.GetWorkingDirectory(), false);
                m_strUserConfigFile = UrlUtil.MakeAbsolutePath(strWD +
                                                               "Sentinel.txt", strLocalOvr);
            }

            Debug.Assert(!string.IsNullOrEmpty(m_strCreateDir));
        }
Пример #10
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            m_bInitializing = true;

            GlobalWindowManager.AddWindow(this);
            // if(m_bRedirectActivation) Program.MainForm.RedirectActivationPush(this);

            string strBannerTitle = (!string.IsNullOrEmpty(m_strCustomTitle) ?
                                     m_strCustomTitle : KPRes.EnterCompositeKey);
            string strBannerDesc = m_ioInfo.GetDisplayName();             // Compacted by banner

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_KGPG_Key2, strBannerTitle, strBannerDesc);
            this.Icon = AppIcons.Default;

            FontUtil.SetDefaultFont(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbKeyFile);
            FontUtil.AssignDefaultBold(m_cbUserAccount);

            UIUtil.ConfigureToolTip(m_ttRect);
            // m_ttRect.SetToolTip(m_cbHidePassword, KPRes.TogglePasswordAsterisks);
            m_ttRect.SetToolTip(m_btnOpenKeyFile, KPRes.KeyFileSelect);

            PwInputControlGroup.ConfigureHideButton(m_cbHidePassword, m_ttRect);

            string strStart = (!string.IsNullOrEmpty(m_strCustomTitle) ?
                               m_strCustomTitle : KPRes.OpenDatabase);
            string strNameEx = UrlUtil.GetFileName(m_ioInfo.Path);

            if (!string.IsNullOrEmpty(strNameEx))
            {
                this.Text = strStart + " - " + strNameEx;
            }
            else
            {
                this.Text = strStart;
            }

            // Must be set manually due to possible object override
            m_tbPassword.TextChanged += this.ProcessTextChangedPassword;

            // m_cmbKeyFile.OrderedImageList = m_lKeyFileImages;
            AddKeyFileSuggPriv(KPRes.NoKeyFileSpecifiedMeta, true);

            // Do not directly compare with Program.CommandLineArgs.FileName,
            // because this may be a relative path instead of an absolute one
            string strCmdLineFile = Program.CommandLineArgs.FileName;

            if ((strCmdLineFile != null) && (Program.MainForm != null))
            {
                strCmdLineFile = Program.MainForm.IocFromCommandLine().Path;
            }
            if ((strCmdLineFile != null) && strCmdLineFile.Equals(m_ioInfo.Path,
                                                                  StrUtil.CaseIgnoreCmp))
            {
                string str;

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.Password];
                if (str != null)
                {
                    m_cbPassword.Checked = true;
                    m_tbPassword.Text    = str;
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PasswordEncrypted];
                if (str != null)
                {
                    m_cbPassword.Checked = true;
                    m_tbPassword.Text    = StrUtil.DecryptString(str);
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PasswordStdIn];
                if (str != null)
                {
                    ProtectedString ps = KeyUtil.ReadPasswordStdIn(true);
                    if (ps != null)
                    {
                        m_cbPassword.Checked = true;
                        m_tbPassword.TextEx  = ps;
                    }
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.KeyFile];
                if (str != null)
                {
                    m_cbKeyFile.Checked = true;
                    AddKeyFileSuggPriv(str, true);
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PreSelect];
                if (str != null)
                {
                    m_cbKeyFile.Checked = true;
                    AddKeyFileSuggPriv(str, true);
                }
            }

            m_cbHidePassword.Checked = true;
            OnCheckedHidePassword(sender, e);

            Debug.Assert(m_cmbKeyFile.Text.Length != 0);

            m_btnExit.Enabled = m_bCanExit;
            m_btnExit.Visible = m_bCanExit;

            ulong uKpf = Program.Config.UI.KeyPromptFlags;

            UIUtil.ApplyKeyUIFlags(uKpf, m_cbPassword, m_cbKeyFile,
                                   m_cbUserAccount, m_cbHidePassword);

            if ((uKpf & (ulong)AceKeyUIFlags.DisableKeyFile) != 0)
            {
                UIUtil.SetEnabled(m_cmbKeyFile, m_cbKeyFile.Checked);
                UIUtil.SetEnabled(m_btnOpenKeyFile, m_cbKeyFile.Checked);
            }

            if (((uKpf & (ulong)AceKeyUIFlags.CheckPassword) != 0) ||
                ((uKpf & (ulong)AceKeyUIFlags.UncheckPassword) != 0))
            {
                m_bPwStatePreset = true;
            }
            if (((uKpf & (ulong)AceKeyUIFlags.CheckUserAccount) != 0) ||
                ((uKpf & (ulong)AceKeyUIFlags.UncheckUserAccount) != 0))
            {
                m_bUaStatePreset = true;
            }

            CustomizeForScreenReader();
            EnableUserControls();

            m_bInitializing = false;

            // E.g. command line options have higher priority
            m_bCanModKeyFile = (m_cmbKeyFile.SelectedIndex == 0);

            m_aKeyAssoc = Program.Config.Defaults.GetKeySources(m_ioInfo);
            if (m_aKeyAssoc != null)
            {
                if (m_aKeyAssoc.Password && !m_bPwStatePreset)
                {
                    m_cbPassword.Checked = true;
                }

                if (m_aKeyAssoc.KeyFilePath.Length > 0)
                {
                    AddKeyFileSuggPriv(m_aKeyAssoc.KeyFilePath, null);
                }

                if (m_aKeyAssoc.UserAccount && !m_bUaStatePreset)
                {
                    m_cbUserAccount.Checked = true;
                }
            }

            foreach (KeyProvider prov in Program.KeyProviderPool)
            {
                AddKeyFileSuggPriv(prov.Name, null);
            }

            // Local, but thread will continue to run anyway
            Thread th = new Thread(new ThreadStart(this.AsyncFormLoad));

            th.Start();
            // ThreadPool.QueueUserWorkItem(new WaitCallback(this.AsyncFormLoad));

            this.BringToFront();
            this.Activate();
            // UIUtil.SetFocus(m_tbPassword, this); // See OnFormShown
        }
            private CompositeKey OTPDB_RequestPassword(bool bSetNewPassword, out bool bCancel)
            {
                if (!bSetNewPassword)
                {
                    KeyPromptForm kpf   = new KeyPromptForm();
                    string        title = string.Format(PluginTranslate.OTP_OpenDB, string.IsNullOrEmpty(DB.Name) ? UrlUtil.GetFileName(DB.IOConnectionInfo.Path) : DB.Name);
                    kpf.InitEx(OTPDB.IOConnectionInfo, false, false, title);
                    bCancel = kpf.ShowDialog() != DialogResult.OK;
                    if (bCancel)
                    {
                        return(new CompositeKey());
                    }
                    return(kpf.CompositeKey);
                }
                KeyCreationForm kcf = new KeyCreationForm();

                kcf.InitEx(null, true);
                bCancel = kcf.ShowDialog() != DialogResult.OK;
                if (bCancel)
                {
                    return(OTPDB.MasterKey);
                }
                return(kcf.CompositeKey);
            }
Пример #12
0
        private static bool CompileAssembly(PlgxPluginInfo plgx,
                                            ref CompilerResults cr, string strCompilerVersion)
        {
            const string StrCoreRef = "System.Core";
            const string StrCoreDll = "System.Core.dll";
            bool         bHasCore = false, bCoreAdded = false;

            foreach (string strAsm in plgx.CompilerParameters.ReferencedAssemblies)
            {
                if (UrlUtil.AssemblyEquals(strAsm, StrCoreRef))
                {
                    bHasCore = true;
                    break;
                }
            }
            if ((strCompilerVersion != null) && strCompilerVersion.StartsWith(
                    "v", StrUtil.CaseIgnoreCmp))
            {
                ulong v = StrUtil.ParseVersion(strCompilerVersion.Substring(1));
                if (!bHasCore && (v >= 0x0003000500000000UL))
                {
                    plgx.CompilerParameters.ReferencedAssemblies.Add(StrCoreDll);
                    bCoreAdded = true;
                }
            }

            bool bResult = false;

            try
            {
                Dictionary <string, string> dictOpt = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(strCompilerVersion))
                {
                    dictOpt.Add("CompilerVersion", strCompilerVersion);
                }

                // Windows 98 only supports the parameterless constructor;
                // check must be separate from the instantiation method
                if (WinUtil.IsWindows9x)
                {
                    dictOpt.Clear();
                }

                CodeDomProvider cdp = null;
                if (plgx.ProjectType == PlgxProjectType.CSharp)
                {
                    cdp = ((dictOpt.Count == 0) ? new CSharpCodeProvider() :
                           CreateCscProvider(dictOpt));
                }
                // else if(plgx.ProjectType == PlgxProjectType.VisualBasic)
                //	cdp = ((dictOpt.Count == 0) ? new VBCodeProvider() :
                //		new VBCodeProvider(dictOpt));
                else
                {
                    throw new InvalidOperationException();
                }

                cr = cdp.CompileAssemblyFromFile(plgx.CompilerParameters,
                                                 plgx.SourceFiles.ToArray());

                bResult = ((cr.Errors == null) || !cr.Errors.HasErrors);
            }
            catch (Exception) { }

            if (bCoreAdded)
            {
                plgx.CompilerParameters.ReferencedAssemblies.Remove(StrCoreDll);
            }

            // cr = null; // Keep previous results for output
            return(bResult);
        }
Пример #13
0
        private static string Compile(string strTmpRoot, PlgxPluginInfo plgx,
                                      string strBuildPre, string strBuildPost)
        {
            if (strTmpRoot == null)
            {
                Debug.Assert(false); return(null);
            }

            RunBuildCommand(strBuildPre, UrlUtil.EnsureTerminatingSeparator(
                                strTmpRoot, false), null);

            PlgxCsprojLoader.LoadDefault(strTmpRoot, plgx);

            List <string> vCustomRefs = new List <string>();

            foreach (string strIncRefAsm in plgx.IncludedReferencedAssemblies)
            {
                string strSrcAsm = plgx.GetAbsPath(UrlUtil.ConvertSeparators(
                                                       strIncRefAsm));
                string strCached = PlgxCache.AddCacheFile(strSrcAsm, plgx);
                if (string.IsNullOrEmpty(strCached))
                {
                    throw new InvalidOperationException();
                }
                vCustomRefs.Add(strCached);
            }

            CompilerParameters cp = plgx.CompilerParameters;

            cp.OutputAssembly = UrlUtil.EnsureTerminatingSeparator(strTmpRoot, false) +
                                UrlUtil.GetFileName(PlgxCache.GetCacheFile(plgx, false, false));
            cp.GenerateExecutable      = false;
            cp.GenerateInMemory        = false;
            cp.IncludeDebugInformation = false;
            cp.TreatWarningsAsErrors   = false;
            cp.ReferencedAssemblies.Add(WinUtil.GetExecutable());
            foreach (string strCustomRef in vCustomRefs)
            {
                cp.ReferencedAssemblies.Add(strCustomRef);
            }

            CompileEmbeddedRes(plgx);
            PrepareSourceFiles(plgx);

            string[] vCompilers;
            Version  vClr = Environment.Version;
            int      iClrMajor = vClr.Major, iClrMinor = vClr.Minor;

            if ((iClrMajor >= 5) || ((iClrMajor == 4) && (iClrMinor >= 5)))
            {
                vCompilers = new string[] {
                    null,
                    "v4.5",
                    "v4",                     // Suggested in CodeDomProvider.CreateProvider doc
                    "v4.0",                   // Suggested in community content of the above
                    "v4.0.30319",             // Deduced from file system
                    "v3.5"
                };
            }
            else if (iClrMajor == 4)            // 4.0
            {
                vCompilers = new string[] {
                    null,
                    "v4",                     // Suggested in CodeDomProvider.CreateProvider doc
                    "v4.0",                   // Suggested in community content of the above
                    "v4.0.30319",             // Deduced from file system
                    "v4.5",
                    "v3.5"
                };
            }
            else             // <= 3.5
            {
                vCompilers = new string[] {
                    null,
                    "v3.5",
                    "v4",                     // Suggested in CodeDomProvider.CreateProvider doc
                    "v4.0",                   // Suggested in community content of the above
                    "v4.0.30319",             // Deduced from file system
                    "v4.5"
                };
            }

            CompilerResults cr        = null;
            bool            bCompiled = false;

            for (int iCmp = 0; iCmp < vCompilers.Length; ++iCmp)
            {
                if (CompileAssembly(plgx, ref cr, vCompilers[iCmp]))
                {
                    bCompiled = true;
                    break;
                }
            }

            if (!bCompiled)
            {
                if (Program.CommandLineArgs[
                        AppDefs.CommandLineOptions.SavePluginCompileRes] != null)
                {
                    SaveCompilerResults(plgx, cr);
                }

                throw new InvalidOperationException();
            }

            Program.TempFilesPool.Add(cr.PathToAssembly);

            Debug.Assert(cr.PathToAssembly == cp.OutputAssembly);
            string strCacheAsm = PlgxCache.AddCacheAssembly(cr.PathToAssembly, plgx);

            RunBuildCommand(strBuildPost, UrlUtil.EnsureTerminatingSeparator(
                                strTmpRoot, false), UrlUtil.GetFileDirectory(strCacheAsm, true, false));

            return(strCacheAsm);
        }
Пример #14
0
        private static void ExtractFile(byte[] pbData, string strTmpRoot,
                                        PlgxPluginInfo plgx)
        {
            MemoryStream ms = new MemoryStream(pbData, false);
            BinaryReader br = new BinaryReader(ms);

            string strPath = null;

            byte[] pbContent = null;

            while (true)
            {
                KeyValuePair <ushort, byte[]> kvp = ReadObject(br);

                if (kvp.Key == PlgxfEOF)
                {
                    break;
                }
                else if (kvp.Key == PlgxfPath)
                {
                    strPath = StrUtil.Utf8.GetString(kvp.Value);
                }
                else if (kvp.Key == PlgxfData)
                {
                    pbContent = kvp.Value;
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            br.Close();
            ms.Close();

            if (!string.IsNullOrEmpty(strPath) && (pbContent != null))
            {
                string strTmpFile = UrlUtil.EnsureTerminatingSeparator(strTmpRoot,
                                                                       false) + UrlUtil.ConvertSeparators(strPath);

                string strTmpDir = UrlUtil.GetFileDirectory(strTmpFile, false, true);
                if (!Directory.Exists(strTmpDir))
                {
                    Directory.CreateDirectory(strTmpDir);
                }

                byte[] pbDecompressed = MemUtil.Decompress(pbContent);
                File.WriteAllBytes(strTmpFile, pbDecompressed);

                // Although the temporary directory will be deleted recursively
                // anyway, add the extracted file here manually, in order to
                // minimize left-over files in case the recursive deletion fails
                // due to locked / in-use files
                Program.TempFilesPool.Add(strTmpFile);

                if (plgx.LogStream != null)
                {
                    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                    byte[] pbMD5 = md5.ComputeHash(pbDecompressed);
                    plgx.LogStream.Write(MemUtil.ByteArrayToHexString(pbMD5));
                    plgx.LogStream.WriteLine(" " + strPath);
                }
            }
            else
            {
                Debug.Assert(false);
            }
        }
Пример #15
0
        private static void MainPriv(string[] args)
        {
#if DEBUG
            // Program.DesignMode should not be queried before executing
            // Main (e.g. by a static Control) when running the program
            // normally
            Debug.Assert(!m_bDesignModeQueried);
#endif
            m_bDesignMode = false;             // Designer doesn't call Main method

            m_cmdLineArgs = new CommandLineArgs(args);

            // Before loading the configuration
            string strWaDisable = m_cmdLineArgs[
                AppDefs.CommandLineOptions.WorkaroundDisable];
            if (!string.IsNullOrEmpty(strWaDisable))
            {
                MonoWorkarounds.SetEnabled(strWaDisable, false);
            }

            try
            {
                DpiUtil.ConfigureProcess();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.DoEvents();                 // Required
            }
            catch (Exception) { Debug.Assert(MonoWorkarounds.IsRequired(106)); }

#if DEBUG
            string strInitialWorkDir = WinUtil.GetWorkingDirectory();
#endif

            if (!CommonInit())
            {
                CommonTerminate(); return;
            }

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

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

            /* if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadRegister] != null)
             * {
             *      string strPreLoadPath = WinUtil.GetExecutable().Trim();
             *      if(strPreLoadPath.StartsWith("\"") == false)
             *              strPreLoadPath = "\"" + strPreLoadPath + "\"";
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, strPreLoadPath,
             *              @"--" + AppDefs.CommandLineOptions.PreLoad, true);
             *      MainCleanUp();
             *      return;
             * }
             * if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadUnregister] != null)
             * {
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, string.Empty,
             *              string.Empty, false);
             *      MainCleanUp();
             *      return;
             * } */
            if ((m_cmdLineArgs[AppDefs.CommandLineOptions.Help] != null) ||
                (m_cmdLineArgs[AppDefs.CommandLineOptions.HelpLong] != null))
            {
                AppHelp.ShowHelp(AppDefs.HelpTopics.CommandLine, null);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetUrlOverride];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigClearUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = string.Empty;
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigGetUrlOverride] != null)
            {
                try
                {
                    string strFileOut = UrlUtil.EnsureTerminatingSeparator(
                        UrlUtil.GetTempPath(), false) + "KeePass_UrlOverride.tmp";
                    string strContent = ("[KeePass]\r\nKeeURLOverride=" +
                                         Program.Config.Integration.UrlOverride + "\r\n");
                    File.WriteAllText(strFileOut, strContent);
                }
                catch (Exception) { Debug.Assert(false); }
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetLanguageFile] != null)
            {
                Program.Config.Application.LanguageFile = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetLanguageFile];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreate] != null)
            {
                PlgxPlugin.CreateFromCommandLine();
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreateInfo] != null)
            {
                PlgxPlugin.CreateInfoFile(m_cmdLineArgs.FileName);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ShowAssemblyInfo] != null)
            {
                MessageService.ShowInfo(Assembly.GetExecutingAssembly().ToString());
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXmlSerializerEx] != null)
            {
                XmlSerializerEx.GenerateSerializers(m_cmdLineArgs);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXspFile] != null)
            {
                XspArchive.CreateFile(m_cmdLineArgs.FileName, m_cmdLineArgs["d"]);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.Version] != null)
            {
                Console.WriteLine(PwDefs.ShortProductName + " " + PwDefs.VersionString);
                Console.WriteLine(PwDefs.Copyright);
                MainCleanUp();
                return;
            }
#if DEBUG
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.TestGfx] != null)
            {
                List <Image> lImg = new List <Image>();
                lImg.Add(Properties.Resources.B16x16_Browser);
                lImg.Add(Properties.Resources.B48x48_Keyboard_Layout);
                ImageArchive aHighRes = new ImageArchive();
                aHighRes.Load(Properties.Resources.Images_Client_HighRes);
                lImg.Add(aHighRes.GetForObject("C12_IRKickFlash"));
                if (File.Exists("Test.png"))
                {
                    lImg.Add(Image.FromFile("Test.png"));
                }
                Image img = GfxUtil.ScaleTest(lImg.ToArray());
                img.Save("GfxScaleTest.png", ImageFormat.Png);
                return;
            }
#endif
            // #if (DEBUG && !KeePassLibSD)
            // if(m_cmdLineArgs[AppDefs.CommandLineOptions.MakePopularPasswordTable] != null)
            // {
            //	PopularPasswords.MakeList();
            //	MainCleanUp();
            //	return;
            // }
            // #endif

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

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

                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.LockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Lock);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.UnlockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Unlock);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent] != null)
            {
                string strName = m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent];
                if (!string.IsNullOrEmpty(strName))
                {
                    string[] vFlt = KeyUtil.MakeCtxIndependent(args);

                    IpcParamEx ipEvent = new IpcParamEx(IpcUtilEx.CmdIpcEvent, strName,
                                                        CommandLineArgs.SafeSerialize(vFlt), null, null, null);
                    IpcUtilEx.SendGlobalMessage(ipEvent);
                }

                MainCleanUp();
                return;
            }

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

            Mutex mGlobalNotify = TryGlobalInstanceNotify(AppDefs.MutexNameGlobal);

            AutoType.InitStatic();

            CustomMessageFilterEx cmfx = new CustomMessageFilterEx();
            Application.AddMessageFilter(cmfx);

#if DEBUG
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null)
            {
                throw new Exception(AppDefs.CommandLineOptions.DebugThrowException);
            }

            m_formMain = new MainForm();
            Application.Run(m_formMain);
#else
            try
            {
                if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null)
                {
                    throw new Exception(AppDefs.CommandLineOptions.DebugThrowException);
                }

                m_formMain = new MainForm();
                Application.Run(m_formMain);
            }
            catch (Exception exPrg) { ShowFatal(exPrg); }
#endif

            Application.RemoveMessageFilter(cmfx);

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

            MainCleanUp();

#if DEBUG
            string strEndWorkDir = WinUtil.GetWorkingDirectory();
            Debug.Assert(strEndWorkDir.Equals(strInitialWorkDir, StrUtil.CaseIgnoreCmp));
#endif

            if (mGlobalNotify != null)
            {
                GC.KeepAlive(mGlobalNotify);
            }
            // if(mSingleLock != null) { GC.KeepAlive(mSingleLock); }
        }
Пример #16
0
        /// <summary>
        /// Rename/move a file. For local file system and WebDAV, the
        /// specified file is moved, i.e. the file destination can be
        /// in a different directory/path. In contrast, for FTP the
        /// file is renamed, i.e. its destination must be in the same
        /// directory/path.
        /// </summary>
        /// <param name="iocFrom">Source file path.</param>
        /// <param name="iocTo">Target file path.</param>
        public static void RenameFile(IOConnectionInfo iocFrom, IOConnectionInfo iocTo)
        {
            RaiseIOAccessPreEvent(iocFrom, iocTo, IOAccessType.Move);

            if (iocFrom.IsLocalFile())
            {
                File.Move(iocFrom.Path, iocTo.Path); return;
            }

#if !KeePassLibSD
            WebRequest req = CreateWebRequest(iocFrom);
            if (req != null)
            {
                if (IsHttpWebRequest(req))
                {
#if KeePassUAP
                    throw new NotSupportedException();
#else
                    req.Method = "MOVE";
                    req.Headers.Set("Destination", iocTo.Path);                     // Full URL supported
#endif
                }
                else if (IsFtpWebRequest(req))
                {
#if KeePassUAP
                    throw new NotSupportedException();
#else
                    req.Method = WebRequestMethods.Ftp.Rename;
                    string strTo = UrlUtil.GetFileName(iocTo.Path);

                    // We're affected by .NET bug 621450:
                    // https://connect.microsoft.com/VisualStudio/feedback/details/621450/problem-renaming-file-on-ftp-server-using-ftpwebrequest-in-net-framework-4-0-vs2010-only
                    // Prepending "./", "%2E/" or "Dummy/../" doesn't work.

                    ((FtpWebRequest)req).RenameTo = strTo;
#endif
                }
                else if (IsFileWebRequest(req))
                {
                    File.Move(UrlUtil.FileUrlToPath(iocFrom.Path),
                              UrlUtil.FileUrlToPath(iocTo.Path));
                    return;
                }
                else
                {
#if KeePassUAP
                    throw new NotSupportedException();
#else
                    req.Method = WrmMoveFile;
                    req.Headers.Set(WrhMoveFileTo, iocTo.Path);
#endif
                }

#if !KeePassUAP // Unreachable code
                DisposeResponse(req.GetResponse(), true);
#endif
            }
#endif

            // using(Stream sIn = IOConnection.OpenRead(iocFrom))
            // {
            //	using(Stream sOut = IOConnection.OpenWrite(iocTo))
            //	{
            //		MemUtil.CopyStream(sIn, sOut);
            //		sOut.Close();
            //	}
            //
            //	sIn.Close();
            // }
            // DeleteFile(iocFrom);
        }
Пример #17
0
        private void CommitWriteTransaction()
        {
            if (g_bExtraSafe)
            {
                if (!IOConnection.FileExists(m_iocTemp))
                {
                    throw new FileNotFoundException(m_iocTemp.Path +
                                                    MessageService.NewLine + KLRes.FileSaveFailed);
                }
            }

            bool bMadeUnhidden = UrlUtil.UnhideFile(m_iocBase.Path);

#if !KeePassUAP
            // 'All' includes 'Audit' (SACL), which requires SeSecurityPrivilege,
            // which we usually don't have and therefore get an exception;
            // trying to set 'Owner' or 'Group' can result in an
            // UnauthorizedAccessException; thus we restore 'Access' (DACL) only
            const AccessControlSections acs = AccessControlSections.Access;

            bool   bEfsEncrypted = false;
            byte[] pbSec         = null;
#endif
            DateTime?otCreation = null;

            bool bBaseExists = IOConnection.FileExists(m_iocBase);
            if (bBaseExists && m_iocBase.IsLocalFile())
            {
                // FileAttributes faBase = FileAttributes.Normal;
                try
                {
#if !KeePassUAP
                    FileAttributes faBase = File.GetAttributes(m_iocBase.Path);
                    bEfsEncrypted = ((long)(faBase & FileAttributes.Encrypted) != 0);
                    try { if (bEfsEncrypted)
                          {
                              File.Decrypt(m_iocBase.Path);
                          }
                    }                                                                           // For TxF
                    catch (Exception) { Debug.Assert(false); }
#endif
                    otCreation = File.GetCreationTimeUtc(m_iocBase.Path);
#if !KeePassUAP
                    // May throw with Mono
                    FileSecurity sec = File.GetAccessControl(m_iocBase.Path, acs);
                    if (sec != null)
                    {
                        pbSec = sec.GetSecurityDescriptorBinaryForm();
                    }
#endif
                }
                catch (Exception) { Debug.Assert(NativeLib.IsUnix()); }

                // if((long)(faBase & FileAttributes.ReadOnly) != 0)
                //	throw new UnauthorizedAccessException();
            }

            if (!TxfMove())
            {
                if (bBaseExists)
                {
                    IOConnection.DeleteFile(m_iocBase);
                }
                IOConnection.RenameFile(m_iocTemp, m_iocBase);
            }
            else
            {
                Debug.Assert(pbSec != null);
            }                                                 // TxF success => NTFS => has ACL

            try
            {
                // If File.GetCreationTimeUtc fails, it may return a
                // date with year 1601, and Unix times start in 1970,
                // so testing for 1971 should ensure validity;
                // https://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc.aspx
                if (otCreation.HasValue && (otCreation.Value.Year >= 1971))
                {
                    File.SetCreationTimeUtc(m_iocBase.Path, otCreation.Value);
                }

#if !KeePassUAP
                if (bEfsEncrypted)
                {
                    try { File.Encrypt(m_iocBase.Path); }
                    catch (Exception) { Debug.Assert(false); }
                }

                // File.SetAccessControl(m_iocBase.Path, secPrev);
                // Directly calling File.SetAccessControl with the previous
                // FileSecurity object does not work; the binary form
                // indirection is required;
                // https://sourceforge.net/p/keepass/bugs/1738/
                // https://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol.aspx
                if ((pbSec != null) && (pbSec.Length != 0))
                {
                    FileSecurity sec = new FileSecurity();
                    sec.SetSecurityDescriptorBinaryForm(pbSec, acs);

                    File.SetAccessControl(m_iocBase.Path, sec);
                }
#endif
            }
            catch (Exception) { Debug.Assert(false); }

            if (bMadeUnhidden)
            {
                UrlUtil.HideFile(m_iocBase.Path, true);
            }
        }
Пример #18
0
        /// <exception cref="CouchbaseBootstrapException">Condition.</exception>
        public override void LoadConfig()
        {
            Lock.EnterWriteLock();
            try
            {
                Log.Info("o3-Creating the Servers list using rev#{0}", BucketConfig.Rev);
                var clientBucketConfig = ClientConfig.BucketConfigs[BucketConfig.Name];
                var searchUris         = new ConcurrentBag <FailureCountingUri>();
                var queryUris          = new ConcurrentBag <FailureCountingUri>();
                var analyticsUris      = new ConcurrentBag <FailureCountingUri>();
                var servers            = new Dictionary <IPAddress, IServer>();
                var nodes = BucketConfig.GetNodes();
                foreach (var adapter in nodes)
                {
                    var endpoint = adapter.GetIPEndPoint(clientBucketConfig.UseSsl);
                    try
                    {
                        IServer server;
                        if (adapter.IsSearchNode)
                        {
                            var uri = UrlUtil.GetFailureCountinSearchBaseUri(adapter, clientBucketConfig);
                            searchUris.Add(uri);
                        }
                        if (adapter.IsQueryNode)
                        {
                            var uri = UrlUtil.GetFailureCountingBaseUri(adapter, clientBucketConfig);
                            queryUris.Add(uri);
                        }
                        if (adapter.IsAnalyticsNode)
                        {
                            var uri = UrlUtil.GetFailureCountingAnalyticsUri(adapter, clientBucketConfig);
                            analyticsUris.Add(uri);
                        }
                        if (adapter.IsDataNode) //a data node so create a connection pool
                        {
                            var uri = UrlUtil.GetBaseUri(adapter, clientBucketConfig);
                            var poolConfiguration = ClientConfig.BucketConfigs[BucketConfig.Name].ClonePoolConfiguration(uri);
                            var connectionPool    = ConnectionPoolFactory(poolConfiguration.Clone(uri), endpoint);
                            connectionPool.SaslMechanism = SaslFactory(BucketConfig.Name, BucketConfig.Password, connectionPool, Transcoder);
                            connectionPool.Initialize();

                            var newIoService = IOServiceFactory(connectionPool);
                            server = new Core.Server(newIoService, adapter, ClientConfig, BucketConfig, Transcoder, QueryCache);

                            SupportsEnhancedDurability     = newIoService.SupportsEnhancedDurability;
                            SupportsSubdocXAttributes      = newIoService.SupportsSubdocXAttributes;
                            SupportsEnhancedAuthentication = newIoService.SupportsEnhancedAuthentication;
                            SupportsKvErrorMap             = newIoService.SupportsKvErrorMap;
                        }
                        else
                        {
                            server = new Core.Server(null, adapter, ClientConfig, BucketConfig, Transcoder, QueryCache);
                        }
                        servers.Add(endpoint.Address, server);
                    }
                    catch (Exception e)
                    {
                        Log.Error("Could not add server {0}. Exception: {1}", endpoint, e);
                    }
                }

                UpdateServices(servers);

                //for caching uri's
                Interlocked.Exchange(ref QueryUris, queryUris);
                Interlocked.Exchange(ref SearchUris, searchUris);
                Interlocked.Exchange(ref AnalyticsUris, analyticsUris);

                var old = Interlocked.Exchange(ref Servers, servers);
                var vBucketKeyMapper = new VBucketKeyMapper(Servers, BucketConfig.VBucketServerMap, BucketConfig.Rev, BucketConfig.Name);
                Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper);
                if (old != null)
                {
                    foreach (var server in old.Values)
                    {
                        server.Dispose();
                    }
                    old.Clear();
                }
            }
            finally
            {
                Lock.ExitWriteLock();
            }
        }
Пример #19
0
 /// <summary>
 /// Open an
 /// <see cref="System.IO.Stream"/>
 /// to a style sheet URI.
 /// </summary>
 /// <param name="uri">the URI</param>
 /// <returns>
 /// the
 /// <see cref="System.IO.Stream"/>
 /// </returns>
 /// <exception cref="System.IO.IOException">Signals that an I/O exception has occurred.</exception>
 public virtual Stream RetrieveStyleSheet(String uri)
 {
     return(UrlUtil.OpenStream(uriResolver.ResolveAgainstBaseUri(uri)));
 }
Пример #20
0
        /// <summary>
        /// Loads the most updated configuration creating any resources as needed.
        /// </summary>
        /// <param name="bucketConfig">The latest <see cref="IBucketConfig"/>
        /// that will drive the recreation if the configuration context.</param>
        /// <param name="force">True to force the reconfiguration.</param>
        public override void LoadConfig(IBucketConfig bucketConfig, bool force = false)
        {
            try
            {
                Lock.EnterWriteLock();
                var nodes = bucketConfig.GetNodes();
                if (BucketConfig == null || !nodes.AreEqual(_bucketConfig.GetNodes()) || !Servers.Any() || force)
                {
                    Log.Info("o1-Creating the Servers {0} list using rev#{1}", nodes.Count, bucketConfig.Rev);

                    var searchUris         = new ConcurrentBag <FailureCountingUri>();
                    var queryUris          = new ConcurrentBag <FailureCountingUri>();
                    var analyticsUris      = new ConcurrentBag <FailureCountingUri>();
                    var clientBucketConfig = ClientConfig.BucketConfigs[bucketConfig.Name];
                    var servers            = new Dictionary <IPAddress, IServer>();
                    foreach (var adapter in nodes)
                    {
                        var endpoint = adapter.GetIPEndPoint(clientBucketConfig.UseSsl);
                        try
                        {
                            Log.Info("Creating node {0} for rev#{1}", endpoint, bucketConfig.Rev);
                            IServer server;
                            if (adapter.IsSearchNode)
                            {
                                var uri = UrlUtil.GetFailureCountinSearchBaseUri(adapter, clientBucketConfig);
                                searchUris.Add(uri);
                            }
                            if (adapter.IsQueryNode)
                            {
                                var uri = UrlUtil.GetFailureCountingBaseUri(adapter, clientBucketConfig);
                                queryUris.Add(uri);
                            }
                            if (adapter.IsAnalyticsNode)
                            {
                                var uri = UrlUtil.GetFailureCountingAnalyticsUri(adapter, clientBucketConfig);
                                analyticsUris.Add(uri);
                            }
                            if (adapter.IsDataNode) //a data node so create a connection pool
                            {
                                var uri = UrlUtil.GetBaseUri(adapter, clientBucketConfig);
                                var poolConfiguration = ClientConfig.BucketConfigs[BucketConfig.Name].ClonePoolConfiguration(uri);
                                var connectionPool    = ConnectionPoolFactory(poolConfiguration.Clone(uri), endpoint);
                                connectionPool.SaslMechanism = SaslFactory(BucketConfig.Name, BucketConfig.Password, connectionPool, Transcoder);
                                connectionPool.Initialize();

                                var ioService = IOServiceFactory(connectionPool);
                                server = new Core.Server(ioService, adapter, ClientConfig, bucketConfig, Transcoder, QueryCache);

                                SupportsEnhancedDurability     = ioService.SupportsEnhancedDurability;
                                SupportsSubdocXAttributes      = ioService.SupportsSubdocXAttributes;
                                SupportsEnhancedAuthentication = ioService.SupportsEnhancedAuthentication;
                                SupportsKvErrorMap             = ioService.SupportsKvErrorMap;
                            }
                            else
                            {
                                server = new Core.Server(null, adapter, ClientConfig, bucketConfig, Transcoder, QueryCache);
                            }
                            servers.Add(endpoint.Address, server);
                        }
                        catch (Exception e)
                        {
                            Log.Error("Could not add server {0} for rev#{1}. Exception: {2}", endpoint, bucketConfig.Rev, e);
                        }
                    }

                    UpdateServices(servers);

                    //for caching uri's
                    Interlocked.Exchange(ref QueryUris, queryUris);
                    Interlocked.Exchange(ref SearchUris, searchUris);
                    Interlocked.Exchange(ref AnalyticsUris, analyticsUris);

                    var old = Interlocked.Exchange(ref Servers, servers);
                    Log.Info("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev);
                    var vBucketKeyMapper = new VBucketKeyMapper(Servers, bucketConfig.VBucketServerMap, bucketConfig.Rev, bucketConfig.Name);
                    Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper);
                    Interlocked.Exchange(ref _bucketConfig, bucketConfig);

                    if (old != null)
                    {
                        foreach (var server in old.Values)
                        {
                            Log.Info("Disposing node {0} from rev#{1}", server.EndPoint, server.Revision);
                            server.Dispose();
                        }
                        old.Clear();
                    }
                }
                else
                {
                    if (BucketConfig == null || !BucketConfig.IsVBucketServerMapEqual(bucketConfig) || force)
                    {
                        Log.Info("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev);
                        var vBucketKeyMapper = new VBucketKeyMapper(Servers, bucketConfig.VBucketServerMap,
                                                                    bucketConfig.Rev, bucketConfig.Name);
                        Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper);
                        Interlocked.Exchange(ref _bucketConfig, bucketConfig);
                    }
                    //only the revision changed so update to it
                    if (bucketConfig.Rev > BucketConfig.Rev)
                    {
                        Log.Info("Only the revision changed from using rev#{0} to rev#{1}", BucketConfig.Rev, bucketConfig.Rev);
                        BucketConfig.Rev = bucketConfig.Rev;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            finally
            {
                Lock.ExitWriteLock();
            }
        }
Пример #21
0
        // Multiple calls of this method are wrapped in
        // GetSequencesForWindowBegin and GetSequencesForWindowEnd
        private static List <string> GetSequencesForWindow(PwEntry pwe,
                                                           IntPtr hWnd, string strWindow, PwDatabase pdContext, int iEventID)
        {
            List <string> l = new List <string>();

            if (pwe == null)
            {
                Debug.Assert(false); return(l);
            }
            if (strWindow == null)
            {
                Debug.Assert(false); return(l);
            }                                                                    // May be empty

            if (!pwe.GetAutoTypeEnabled())
            {
                return(l);
            }

            SprContext sprCtx = new SprContext(pwe, pdContext,
                                               SprCompileFlags.NonActive);

            RaiseSequenceQueryEvent(AutoType.SequenceQueryPre, iEventID,
                                    hWnd, strWindow, pwe, pdContext, l);

            // Specifically defined sequences must match before the title,
            // in order to allow selecting the first item as default one
            foreach (AutoTypeAssociation a in pwe.AutoType.Associations)
            {
                string strWndSpec = a.WindowName;
                if (strWndSpec == null)
                {
                    Debug.Assert(false); continue;
                }

                strWndSpec = SprEngine.Compile(strWndSpec.Trim(), sprCtx);

                if (MatchWindows(strWndSpec, strWindow))
                {
                    string strSeq = a.Sequence;
                    if (string.IsNullOrEmpty(strSeq))
                    {
                        strSeq = pwe.GetAutoTypeSequence();
                    }
                    AddSequence(l, strSeq);
                }
            }

            RaiseSequenceQueryEvent(AutoType.SequenceQuery, iEventID,
                                    hWnd, strWindow, pwe, pdContext, l);

            if (Program.Config.Integration.AutoTypeMatchByTitle)
            {
                string strTitle = SprEngine.Compile(pwe.Strings.ReadSafe(
                                                        PwDefs.TitleField).Trim(), sprCtx);
                if ((strTitle.Length > 0) && (strWindow.IndexOf(strTitle,
                                                                StrUtil.CaseIgnoreCmp) >= 0))
                {
                    AddSequence(l, pwe.GetAutoTypeSequence());
                }
            }

            string strCmpUrl = null;             // To cache compiled URL

            if (Program.Config.Integration.AutoTypeMatchByUrlInTitle)
            {
                strCmpUrl = SprEngine.Compile(pwe.Strings.ReadSafe(
                                                  PwDefs.UrlField).Trim(), sprCtx);
                if ((strCmpUrl.Length > 0) && (strWindow.IndexOf(strCmpUrl,
                                                                 StrUtil.CaseIgnoreCmp) >= 0))
                {
                    AddSequence(l, pwe.GetAutoTypeSequence());
                }
            }

            if (Program.Config.Integration.AutoTypeMatchByUrlHostInTitle)
            {
                if (strCmpUrl == null)
                {
                    strCmpUrl = SprEngine.Compile(pwe.Strings.ReadSafe(
                                                      PwDefs.UrlField).Trim(), sprCtx);
                }

                string strCleanUrl = StrUtil.RemovePlaceholders(strCmpUrl);
                string strHost     = UrlUtil.GetHost(strCleanUrl);

                if (strHost.StartsWith("www.", StrUtil.CaseIgnoreCmp) &&
                    (strCleanUrl.StartsWith("http:", StrUtil.CaseIgnoreCmp) ||
                     strCleanUrl.StartsWith("https:", StrUtil.CaseIgnoreCmp)))
                {
                    strHost = strHost.Substring(4);
                }

                if ((strHost.Length > 0) && (strWindow.IndexOf(strHost,
                                                               StrUtil.CaseIgnoreCmp) >= 0))
                {
                    AddSequence(l, pwe.GetAutoTypeSequence());
                }
            }

            if (Program.Config.Integration.AutoTypeMatchByTagInTitle)
            {
                foreach (string strTag in pwe.Tags)
                {
                    if (string.IsNullOrEmpty(strTag))
                    {
                        Debug.Assert(false); continue;
                    }

                    if (strWindow.IndexOf(strTag, StrUtil.CaseIgnoreCmp) >= 0)
                    {
                        AddSequence(l, pwe.GetAutoTypeSequence());
                        break;
                    }
                }
            }

            RaiseSequenceQueryEvent(AutoType.SequenceQueryPost, iEventID,
                                    hWnd, strWindow, pwe, pdContext, l);

            return(l);
        }
Пример #22
0
        public async Task GetSourceAsync(
            IExecutionContext executionContext,
            ServiceEndpoint endpoint,
            CancellationToken cancellationToken)
        {
            Trace.Entering();
            // Validate args.
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            ArgUtil.NotNull(endpoint, nameof(endpoint));

            executionContext.Output($"Syncing repository: {endpoint.Name} ({RepositoryType})");
            Uri repositoryUrl = endpoint.Url;

            if (!repositoryUrl.IsAbsoluteUri)
            {
                throw new InvalidOperationException("Repository url need to be an absolute uri.");
            }

            string targetPath    = GetEndpointData(endpoint, Constants.EndpointData.SourcesDirectory);
            string sourceBranch  = GetEndpointData(endpoint, Constants.EndpointData.SourceBranch);
            string sourceVersion = GetEndpointData(endpoint, Constants.EndpointData.SourceVersion);

            bool clean = false;

            if (endpoint.Data.ContainsKey(WellKnownEndpointData.Clean))
            {
                clean = StringUtil.ConvertToBoolean(endpoint.Data[WellKnownEndpointData.Clean]);
            }

            bool checkoutSubmodules = false;

            if (endpoint.Data.ContainsKey(WellKnownEndpointData.CheckoutSubmodules))
            {
                checkoutSubmodules = StringUtil.ConvertToBoolean(endpoint.Data[WellKnownEndpointData.CheckoutSubmodules]);
            }

            bool checkoutNestedSubmodules = false;

            if (endpoint.Data.ContainsKey(WellKnownEndpointData.CheckoutNestedSubmodules))
            {
                checkoutNestedSubmodules = StringUtil.ConvertToBoolean(endpoint.Data[WellKnownEndpointData.CheckoutNestedSubmodules]);
            }

            int fetchDepth = 0;

            if (endpoint.Data.ContainsKey("fetchDepth") &&
                (!int.TryParse(endpoint.Data["fetchDepth"], out fetchDepth) || fetchDepth < 0))
            {
                fetchDepth = 0;
            }
            // prefer feature variable over endpoint data
            fetchDepth = executionContext.Variables.GetInt(Constants.Variables.Features.GitShallowDepth) ?? fetchDepth;

            bool gitLfsSupport = false;

            if (endpoint.Data.ContainsKey("GitLfsSupport"))
            {
                gitLfsSupport = StringUtil.ConvertToBoolean(endpoint.Data["GitLfsSupport"]);
            }
            // prefer feature variable over endpoint data
            gitLfsSupport = executionContext.Variables.GetBoolean(Constants.Variables.Features.GitLfsSupport) ?? gitLfsSupport;

            bool exposeCred = executionContext.Variables.GetBoolean(Constants.Variables.System.EnableAccessToken) ?? false;

            Trace.Info($"Repository url={repositoryUrl}");
            Trace.Info($"targetPath={targetPath}");
            Trace.Info($"sourceBranch={sourceBranch}");
            Trace.Info($"sourceVersion={sourceVersion}");
            Trace.Info($"clean={clean}");
            Trace.Info($"checkoutSubmodules={checkoutSubmodules}");
            Trace.Info($"checkoutNestedSubmodules={checkoutNestedSubmodules}");
            Trace.Info($"exposeCred={exposeCred}");
            Trace.Info($"fetchDepth={fetchDepth}");
            Trace.Info($"gitLfsSupport={gitLfsSupport}");

            // Determine which git will be use
            // On windows, we prefer the built-in portable git within the agent's externals folder, set system.prefergitfrompath=true can change the behavior,
            // agent will find git.exe from %PATH%
            // On Linux, we will always use git find in %PATH% regardless of system.prefergitfrompath
            bool preferGitFromPath = executionContext.Variables.GetBoolean(Constants.Variables.System.PreferGitFromPath) ?? false;

#if !OS_WINDOWS
            // On linux/OSX, we will always find git from %PATH%
            preferGitFromPath = true;
#endif

            // Determine do we need to provide creds to git operation
            _selfManageGitCreds = executionContext.Variables.GetBoolean(Constants.Variables.System.SelfManageGitCreds) ?? false;
            if (_selfManageGitCreds)
            {
                // Customer choose to own git creds by themselves.
                executionContext.Output(StringUtil.Loc("SelfManageGitCreds"));
            }

            // Initialize git command manager
            _gitCommandManager = HostContext.GetService <IGitCommandManager>();
            await _gitCommandManager.LoadGitExecutionInfo(executionContext, useBuiltInGit : !preferGitFromPath);

            // Make sure the build machine met all requirements for the git repository
            // For now, the requirement we have is git version greater than 2.9  and git-lfs version greater than 2.1 for on-prem tfsgit
            RequirementCheck(executionContext, endpoint);

            // retrieve credential from endpoint.
            string username = string.Empty;
            string password = string.Empty;
            if (!_selfManageGitCreds && endpoint.Authorization != null)
            {
                switch (endpoint.Authorization.Scheme)
                {
                case EndpointAuthorizationSchemes.OAuth:
                    username = EndpointAuthorizationSchemes.OAuth;
                    if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.AccessToken, out password))
                    {
                        password = string.Empty;
                    }
                    break;

                case EndpointAuthorizationSchemes.UsernamePassword:
                    if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Username, out username))
                    {
                        // leave the username as empty, the username might in the url, like: http://[email protected]
                        username = string.Empty;
                    }
                    if (!endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.Password, out password))
                    {
                        // we have username, but no password
                        password = string.Empty;
                    }
                    break;

                default:
                    executionContext.Warning($"Unsupport endpoint authorization schemes: {endpoint.Authorization.Scheme}");
                    break;
                }
            }

            // prepare credentail embedded urls
            _repositoryUrlWithCred = UrlUtil.GetCredentialEmbeddedUrl(repositoryUrl, username, password);
            var agentProxy = HostContext.GetService <IVstsAgentWebProxy>();
            if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.IsBypassed(repositoryUrl))
            {
                _proxyUrlWithCred = UrlUtil.GetCredentialEmbeddedUrl(new Uri(executionContext.Variables.Agent_ProxyUrl), executionContext.Variables.Agent_ProxyUsername, executionContext.Variables.Agent_ProxyPassword);

                // uri.absoluteuri will not contains port info if the scheme is http/https and the port is 80/443
                // however, git.exe always require you provide port info, if nothing passed in, it will use 1080 as default
                // as result, we need prefer the uri.originalstring when it's different than uri.absoluteuri.
                if (string.Equals(_proxyUrlWithCred.AbsoluteUri, _proxyUrlWithCred.OriginalString, StringComparison.OrdinalIgnoreCase))
                {
                    _proxyUrlWithCredString = _proxyUrlWithCred.AbsoluteUri;
                }
                else
                {
                    _proxyUrlWithCredString = _proxyUrlWithCred.OriginalString;
                }
            }

            if (gitLfsSupport)
            {
                // Construct git-lfs url
                UriBuilder gitLfsUrl = new UriBuilder(_repositoryUrlWithCred);
                if (gitLfsUrl.Path.EndsWith(".git"))
                {
                    gitLfsUrl.Path = gitLfsUrl.Path + "/info/lfs";
                }
                else
                {
                    gitLfsUrl.Path = gitLfsUrl.Path + ".git/info/lfs";
                }

                _gitLfsUrlWithCred = gitLfsUrl.Uri;
            }

            // Check the current contents of the root folder to see if there is already a repo
            // If there is a repo, see if it matches the one we are expecting to be there based on the remote fetch url
            // if the repo is not what we expect, remove the folder
            if (!await IsRepositoryOriginUrlMatch(executionContext, targetPath, repositoryUrl))
            {
                // Delete source folder
                IOUtil.DeleteDirectory(targetPath, cancellationToken);
            }
            else
            {
                // delete the index.lock file left by previous canceled build or any operation cause git.exe crash last time.
                string lockFile = Path.Combine(targetPath, ".git\\index.lock");
                if (File.Exists(lockFile))
                {
                    try
                    {
                        File.Delete(lockFile);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug($"Unable to delete the index.lock file: {lockFile}");
                        executionContext.Debug(ex.ToString());
                    }
                }

                // When repo.clean is selected for a git repo, execute git clean -fdx and git reset --hard HEAD on the current repo.
                // This will help us save the time to reclone the entire repo.
                // If any git commands exit with non-zero return code or any exception happened during git.exe invoke, fall back to delete the repo folder.
                if (clean)
                {
                    Boolean softCleanSucceed = true;

                    // git clean -fdx
                    int exitCode_clean = await _gitCommandManager.GitClean(executionContext, targetPath);

                    if (exitCode_clean != 0)
                    {
                        executionContext.Debug($"'git clean -fdx' failed with exit code {exitCode_clean}, this normally caused by:\n    1) Path too long\n    2) Permission issue\n    3) File in use\nFor futher investigation, manually run 'git clean -fdx' on repo root: {targetPath} after each build.");
                        softCleanSucceed = false;
                    }

                    // git reset --hard HEAD
                    if (softCleanSucceed)
                    {
                        int exitCode_reset = await _gitCommandManager.GitReset(executionContext, targetPath);

                        if (exitCode_reset != 0)
                        {
                            executionContext.Debug($"'git reset --hard HEAD' failed with exit code {exitCode_reset}\nFor futher investigation, manually run 'git reset --hard HEAD' on repo root: {targetPath} after each build.");
                            softCleanSucceed = false;
                        }
                    }

                    // git clean -fdx and git reset --hard HEAD for each submodule
                    if (checkoutSubmodules)
                    {
                        if (softCleanSucceed)
                        {
                            int exitCode_submoduleclean = await _gitCommandManager.GitSubmoduleClean(executionContext, targetPath);

                            if (exitCode_submoduleclean != 0)
                            {
                                executionContext.Debug($"'git submodule foreach git clean -fdx' failed with exit code {exitCode_submoduleclean}\nFor futher investigation, manually run 'git submodule foreach git clean -fdx' on repo root: {targetPath} after each build.");
                                softCleanSucceed = false;
                            }
                        }

                        if (softCleanSucceed)
                        {
                            int exitCode_submodulereset = await _gitCommandManager.GitSubmoduleReset(executionContext, targetPath);

                            if (exitCode_submodulereset != 0)
                            {
                                executionContext.Debug($"'git submodule foreach git reset --hard HEAD' failed with exit code {exitCode_submodulereset}\nFor futher investigation, manually run 'git submodule foreach git reset --hard HEAD' on repo root: {targetPath} after each build.");
                                softCleanSucceed = false;
                            }
                        }
                    }

                    if (!softCleanSucceed)
                    {
                        //fall back
                        executionContext.Warning("Unable to run \"git clean -fdx\" and \"git reset --hard HEAD\" successfully, delete source folder instead.");
                        IOUtil.DeleteDirectory(targetPath, cancellationToken);
                    }
                }
            }

            // if the folder is missing, create it
            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath);
            }

            // if the folder contains a .git folder, it means the folder contains a git repo that matches the remote url and in a clean state.
            // we will run git fetch to update the repo.
            if (!Directory.Exists(Path.Combine(targetPath, ".git")))
            {
                // init git repository
                int exitCode_init = await _gitCommandManager.GitInit(executionContext, targetPath);

                if (exitCode_init != 0)
                {
                    throw new InvalidOperationException($"Unable to use git.exe init repository under {targetPath}, 'git init' failed with exit code: {exitCode_init}");
                }

                int exitCode_addremote = await _gitCommandManager.GitRemoteAdd(executionContext, targetPath, "origin", repositoryUrl.AbsoluteUri);

                if (exitCode_addremote != 0)
                {
                    throw new InvalidOperationException($"Unable to use git.exe add remote 'origin', 'git remote add' failed with exit code: {exitCode_addremote}");
                }
            }

            cancellationToken.ThrowIfCancellationRequested();
            executionContext.Progress(0, "Starting fetch...");

            // disable git auto gc
            int exitCode_disableGC = await _gitCommandManager.GitDisableAutoGC(executionContext, targetPath);

            if (exitCode_disableGC != 0)
            {
                executionContext.Warning("Unable turn off git auto garbage collection, git fetch operation may trigger auto garbage collection which will affect the performance of fetching.");
            }

            // always remove any possible left extraheader setting from git config.
            if (await _gitCommandManager.GitConfigExist(executionContext, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader"))
            {
                executionContext.Debug("Remove any extraheader setting from git config.");
                await RemoveGitConfig(executionContext, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader", string.Empty);
            }

            // always remove any possible left proxy setting from git config, the proxy setting may contains credential
            if (await _gitCommandManager.GitConfigExist(executionContext, targetPath, $"http.proxy"))
            {
                executionContext.Debug("Remove any proxy setting from git config.");
                await RemoveGitConfig(executionContext, targetPath, $"http.proxy", string.Empty);
            }

            List <string> additionalFetchArgs    = new List <string>();
            List <string> additionalLfsFetchArgs = new List <string>();
            if (!_selfManageGitCreds)
            {
                // v2.9 git support provide auth header as cmdline arg.
                // as long 2.9 git exist, VSTS repo, TFS repo and Github repo will use this to handle auth challenge.
                if (GitUseAuthHeaderCmdlineArg)
                {
                    additionalFetchArgs.Add($"-c http.extraheader=\"AUTHORIZATION: {GenerateAuthHeader(username, password)}\"");
                }
                else
                {
                    // Otherwise, inject credential into fetch/push url
                    // inject credential into fetch url
                    executionContext.Debug("Inject credential into git remote url.");
                    ArgUtil.NotNull(_repositoryUrlWithCred, nameof(_repositoryUrlWithCred));

                    // inject credential into fetch url
                    executionContext.Debug("Inject credential into git remote fetch url.");
                    int exitCode_seturl = await _gitCommandManager.GitRemoteSetUrl(executionContext, targetPath, "origin", _repositoryUrlWithCred.AbsoluteUri);

                    if (exitCode_seturl != 0)
                    {
                        throw new InvalidOperationException($"Unable to use git.exe inject credential to git remote fetch url, 'git remote set-url' failed with exit code: {exitCode_seturl}");
                    }

                    // inject credential into push url
                    executionContext.Debug("Inject credential into git remote push url.");
                    exitCode_seturl = await _gitCommandManager.GitRemoteSetPushUrl(executionContext, targetPath, "origin", _repositoryUrlWithCred.AbsoluteUri);

                    if (exitCode_seturl != 0)
                    {
                        throw new InvalidOperationException($"Unable to use git.exe inject credential to git remote push url, 'git remote set-url --push' failed with exit code: {exitCode_seturl}");
                    }
                }

                // Prepare proxy config for fetch.
                if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.IsBypassed(repositoryUrl))
                {
                    executionContext.Debug($"Config proxy server '{executionContext.Variables.Agent_ProxyUrl}' for git fetch.");
                    ArgUtil.NotNullOrEmpty(_proxyUrlWithCredString, nameof(_proxyUrlWithCredString));
                    additionalFetchArgs.Add($"-c http.proxy=\"{_proxyUrlWithCredString}\"");
                    additionalLfsFetchArgs.Add($"-c http.proxy=\"{_proxyUrlWithCredString}\"");
                }

                // Prepare gitlfs url for fetch and checkout
                if (gitLfsSupport)
                {
                    // Initialize git lfs by execute 'git lfs install'
                    executionContext.Debug("Setup the local Git hooks for Git LFS.");
                    int exitCode_lfsInstall = await _gitCommandManager.GitLFSInstall(executionContext, targetPath);

                    if (exitCode_lfsInstall != 0)
                    {
                        throw new InvalidOperationException($"Git-lfs installation failed with exit code: {exitCode_lfsInstall}");
                    }

                    if (GitLfsUseAuthHeaderCmdlineArg)
                    {
                        additionalLfsFetchArgs.Add($"-c http.extraheader=\"AUTHORIZATION: {GenerateAuthHeader(username, password)}\"");
                    }
                    else
                    {
                        // Inject credential into lfs fetch/push url
                        executionContext.Debug("Inject credential into git-lfs remote url.");
                        ArgUtil.NotNull(_gitLfsUrlWithCred, nameof(_gitLfsUrlWithCred));

                        // inject credential into fetch url
                        executionContext.Debug("Inject credential into git-lfs remote fetch url.");
                        _configModifications["remote.origin.lfsurl"] = _gitLfsUrlWithCred.AbsoluteUri;
                        int exitCode_configlfsurl = await _gitCommandManager.GitConfig(executionContext, targetPath, "remote.origin.lfsurl", _gitLfsUrlWithCred.AbsoluteUri);

                        if (exitCode_configlfsurl != 0)
                        {
                            throw new InvalidOperationException($"Git config failed with exit code: {exitCode_configlfsurl}");
                        }

                        // inject credential into push url
                        executionContext.Debug("Inject credential into git-lfs remote push url.");
                        _configModifications["remote.origin.lfspushurl"] = _gitLfsUrlWithCred.AbsoluteUri;
                        int exitCode_configlfspushurl = await _gitCommandManager.GitConfig(executionContext, targetPath, "remote.origin.lfspushurl", _gitLfsUrlWithCred.AbsoluteUri);

                        if (exitCode_configlfspushurl != 0)
                        {
                            throw new InvalidOperationException($"Git config failed with exit code: {exitCode_configlfspushurl}");
                        }
                    }
                }
            }

            // If this is a build for a pull request, then include
            // the pull request reference as an additional ref.
            List <string> additionalFetchSpecs = new List <string>();
            if (IsPullRequest(sourceBranch))
            {
                additionalFetchSpecs.Add("+refs/heads/*:refs/remotes/origin/*");
                additionalFetchSpecs.Add(StringUtil.Format("+{0}:{1}", sourceBranch, GetRemoteRefName(sourceBranch)));
            }

            int exitCode_fetch = await _gitCommandManager.GitFetch(executionContext, targetPath, "origin", fetchDepth, additionalFetchSpecs, string.Join(" ", additionalFetchArgs), cancellationToken);

            if (exitCode_fetch != 0)
            {
                throw new InvalidOperationException($"Git fetch failed with exit code: {exitCode_fetch}");
            }

            // Checkout
            // sourceToBuild is used for checkout
            // if sourceBranch is a PR branch or sourceVersion is null, make sure branch name is a remote branch. we need checkout to detached head.
            // (change refs/heads to refs/remotes/origin, refs/pull to refs/remotes/pull, or leave it as it when the branch name doesn't contain refs/...)
            // if sourceVersion provide, just use that for checkout, since when you checkout a commit, it will end up in detached head.
            cancellationToken.ThrowIfCancellationRequested();
            executionContext.Progress(80, "Starting checkout...");
            string sourcesToBuild;
            if (IsPullRequest(sourceBranch) || string.IsNullOrEmpty(sourceVersion))
            {
                sourcesToBuild = GetRemoteRefName(sourceBranch);
            }
            else
            {
                sourcesToBuild = sourceVersion;
            }

            // fetch lfs object upfront, this will avoid fetch lfs object during checkout which cause checkout taking forever
            // since checkout will fetch lfs object 1 at a time, while git lfs fetch will fetch lfs object in parallel.
            if (gitLfsSupport)
            {
                int exitCode_lfsFetch = await _gitCommandManager.GitLFSFetch(executionContext, targetPath, "origin", sourcesToBuild, string.Join(" ", additionalLfsFetchArgs), cancellationToken);

                if (exitCode_lfsFetch != 0)
                {
                    // git lfs fetch failed, get lfs log, the log is critical for debug.
                    int exitCode_lfsLogs = await _gitCommandManager.GitLFSLogs(executionContext, targetPath);

                    throw new InvalidOperationException($"Git lfs fetch failed with exit code: {exitCode_lfsFetch}. Git lfs logs returned with exit code: {exitCode_lfsLogs}.");
                }
            }

            // Finally, checkout the sourcesToBuild (if we didn't find a valid git object this will throw)
            int exitCode_checkout = await _gitCommandManager.GitCheckout(executionContext, targetPath, sourcesToBuild, cancellationToken);

            if (exitCode_checkout != 0)
            {
                // local repository is shallow repository, checkout may fail due to lack of commits history.
                // this will happen when the checkout commit is older than tip -> fetchDepth
                if (fetchDepth > 0)
                {
                    executionContext.Warning(StringUtil.Loc("ShallowCheckoutFail", fetchDepth, sourcesToBuild));
                }

                throw new InvalidOperationException($"Git checkout failed with exit code: {exitCode_checkout}");
            }

            // Submodule update
            if (checkoutSubmodules)
            {
                cancellationToken.ThrowIfCancellationRequested();
                executionContext.Progress(90, "Updating submodules...");

                int exitCode_submoduleSync = await _gitCommandManager.GitSubmoduleSync(executionContext, targetPath, checkoutNestedSubmodules, cancellationToken);

                if (exitCode_submoduleSync != 0)
                {
                    throw new InvalidOperationException($"Git submodule sync failed with exit code: {exitCode_submoduleSync}");
                }

                List <string> additionalSubmoduleUpdateArgs = new List <string>();
                if (!_selfManageGitCreds)
                {
                    if (GitUseAuthHeaderCmdlineArg)
                    {
                        string authorityUrl = repositoryUrl.AbsoluteUri.Replace(repositoryUrl.PathAndQuery, string.Empty);
                        additionalSubmoduleUpdateArgs.Add($"-c http.{authorityUrl}.extraheader=\"AUTHORIZATION: {GenerateAuthHeader(username, password)}\"");
                    }

                    // Prepare proxy config for submodule update.
                    if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.IsBypassed(repositoryUrl))
                    {
                        executionContext.Debug($"Config proxy server '{executionContext.Variables.Agent_ProxyUrl}' for git submodule update.");
                        ArgUtil.NotNullOrEmpty(_proxyUrlWithCredString, nameof(_proxyUrlWithCredString));
                        additionalSubmoduleUpdateArgs.Add($"-c http.proxy=\"{_proxyUrlWithCredString}\"");
                    }
                }

                int exitCode_submoduleUpdate = await _gitCommandManager.GitSubmoduleUpdate(executionContext, targetPath, string.Join(" ", additionalSubmoduleUpdateArgs), checkoutNestedSubmodules, cancellationToken);

                if (exitCode_submoduleUpdate != 0)
                {
                    throw new InvalidOperationException($"Git submodule update failed with exit code: {exitCode_submoduleUpdate}");
                }
            }

            // handle expose creds, related to 'Allow Scripts to Access OAuth Token' option
            if (!_selfManageGitCreds)
            {
                if (GitUseAuthHeaderCmdlineArg && exposeCred)
                {
                    string configKey   = $"http.{repositoryUrl.AbsoluteUri}.extraheader";
                    string configValue = $"\"AUTHORIZATION: {GenerateAuthHeader(username, password)}\"";
                    _configModifications[configKey] = configValue.Trim('\"');
                    int exitCode_config = await _gitCommandManager.GitConfig(executionContext, targetPath, configKey, configValue);

                    if (exitCode_config != 0)
                    {
                        throw new InvalidOperationException($"Git config failed with exit code: {exitCode_config}");
                    }
                }

                if (!GitUseAuthHeaderCmdlineArg && !exposeCred)
                {
                    // remove cached credential from origin's fetch/push url.
                    await RemoveCachedCredential(executionContext, targetPath, repositoryUrl, "origin");
                }

                if (exposeCred)
                {
                    // save proxy setting to git config.
                    if (!string.IsNullOrEmpty(executionContext.Variables.Agent_ProxyUrl) && !agentProxy.IsBypassed(repositoryUrl))
                    {
                        executionContext.Debug($"Save proxy config for proxy server '{executionContext.Variables.Agent_ProxyUrl}' into git config.");
                        ArgUtil.NotNullOrEmpty(_proxyUrlWithCredString, nameof(_proxyUrlWithCredString));

                        string proxyConfigKey   = "http.proxy";
                        string proxyConfigValue = $"\"{_proxyUrlWithCredString}\"";
                        _configModifications[proxyConfigKey] = proxyConfigValue.Trim('\"');

                        int exitCode_proxyconfig = await _gitCommandManager.GitConfig(executionContext, targetPath, proxyConfigKey, proxyConfigValue);

                        if (exitCode_proxyconfig != 0)
                        {
                            throw new InvalidOperationException($"Git config failed with exit code: {exitCode_proxyconfig}");
                        }
                    }
                }

                if (gitLfsSupport)
                {
                    if (GitLfsUseAuthHeaderCmdlineArg && exposeCred)
                    {
                        string configKey   = $"http.{repositoryUrl.AbsoluteUri}.extraheader";
                        string configValue = $"\"AUTHORIZATION: {GenerateAuthHeader(username, password)}\"";
                        _configModifications[configKey] = configValue.Trim('\"');
                        int exitCode_config = await _gitCommandManager.GitConfig(executionContext, targetPath, configKey, configValue);

                        if (exitCode_config != 0)
                        {
                            throw new InvalidOperationException($"Git config failed with exit code: {exitCode_config}");
                        }
                    }

                    if (!GitLfsUseAuthHeaderCmdlineArg && !exposeCred)
                    {
                        // remove cached credential from origin's lfs fetch/push url.
                        executionContext.Debug("Remove git-lfs fetch and push url setting from git config.");
                        await RemoveGitConfig(executionContext, targetPath, "remote.origin.lfsurl", _gitLfsUrlWithCred.AbsoluteUri);

                        _configModifications.Remove("remote.origin.lfsurl");
                        await RemoveGitConfig(executionContext, targetPath, "remote.origin.lfspushurl", _gitLfsUrlWithCred.AbsoluteUri);

                        _configModifications.Remove("remote.origin.lfspushurl");
                    }
                }
            }
        }
Пример #23
0
        public static void qunfa_shoudong_gengfa(CmsForm cmsForm, string content1)
        {
            try
            {
                SendItem sendItem = new SendItem();
                sendItem.from            = "手工添加";
                sendItem.create_date_str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string content = cmsForm.webBrowser_send_content.Document.Body.InnerHtml;

                //ContentItem contentItem = UrlUtil.parseContent(this,content);
                //sendItem.num_iid = contentItem.num_iid;
                if (!string.IsNullOrEmpty(content))
                {
                    content       = UrlUtil.copyImgContent(cmsForm, content, sendItem.create_date_str);
                    sendItem.memo = CommonUtil.toText(content);
                    string follow_path = cmsForm.appBean.follow_path + @"\" + sendItem.create_date_str;
                    if (!Directory.Exists(follow_path))
                    {
                        Directory.CreateDirectory(follow_path);
                    }

                    UtilFile.write(string.Concat(follow_path, "\\content_wenan.html"), UrlUtil.parseContentWenan(cmsForm, content), Encoding.GetEncoding("GB2312"));

                    UtilFile.write(string.Concat(follow_path, "\\content_img.html"), UrlUtil.parseImg(cmsForm, content), Encoding.GetEncoding("GB2312"));


                    UtilFile.write(string.Concat(follow_path, "\\content.html"), content, Encoding.GetEncoding("GB2312"));
                    ((IHTMLDocument2)cmsForm.webBrowser_send_content.Document.DomDocument).body.innerHTML = "";
                    LogUtil.log_call(cmsForm, "添加跟发成功!");
                    string out_log = "";
                    cmsForm.sendSqlUtil.insert(sendItem, out out_log);
                    FollowUtil.load_call(cmsForm);
                }
                else
                {
                    LogUtil.log_call(cmsForm, "跟发内容不能为空!");
                }
            }
            catch (Exception exception)
            {
                //MessageBox.Show("[messageForThread]出错:" + exception.ToString());
            }
        }
Пример #24
0
        public void ToUrl_Test(string schema, string ipAddress, int port, string expected)
        {
            var actual = UrlUtil.ToUrl(schema, ipAddress, port);

            Assert.Equal(expected, actual);
        }
Пример #25
0
 public string GetFilenameWithoutPathAndExt(IOConnectionInfo ioc)
 {
     return(UrlUtil.StripExtension(
                UrlUtil.GetFileName(ioc.Path)));
 }
Пример #26
0
        public void GetUrlAddress_Test(string url, string expected)
        {
            var actual = UrlUtil.GetUrlAddress(url);

            Assert.Equal(expected, actual);
        }
Пример #27
0
        private static string FillUriSpecial(string strText, SprContext ctx,
                                             string strPlhInit, string strData, bool bDataIsEncoded,
                                             uint uRecursionLevel)
        {
            Debug.Assert(strPlhInit.StartsWith(@"{") && !strPlhInit.EndsWith(@"}"));
            Debug.Assert(strData != null);

            string[] vPlhs = new string[] {
                strPlhInit + @"}",
                strPlhInit + @":RMVSCM}",
                strPlhInit + @":SCM}",
                strPlhInit + @":HOST}",
                strPlhInit + @":PORT}",
                strPlhInit + @":PATH}",
                strPlhInit + @":QUERY}",
                strPlhInit + @":USERINFO}",
                strPlhInit + @":USERNAME}",
                strPlhInit + @":PASSWORD}"
            };

            string str        = strText;
            string strDataCmp = null;
            Uri    uri        = null;

            for (int i = 0; i < vPlhs.Length; ++i)
            {
                string strPlh = vPlhs[i];
                if (str.IndexOf(strPlh, SprEngine.ScMethod) < 0)
                {
                    continue;
                }

                if (strDataCmp == null)
                {
                    SprContext ctxData = (bDataIsEncoded ?
                                          ctx.WithoutContentTransformations() : ctx);
                    strDataCmp = SprEngine.CompileInternal(strData, ctxData,
                                                           uRecursionLevel + 1);
                }

                string strRep = null;
                if (i == 0)
                {
                    strRep = strDataCmp;
                }
                else if (i == 1)
                {
                    strRep = UrlUtil.RemoveScheme(strDataCmp);
                }
                else
                {
                    try
                    {
                        if (uri == null)
                        {
                            uri = new Uri(strDataCmp);
                        }

                        int t;
                        switch (i)
                        {
                        case 2: strRep = uri.Scheme; break;

                        case 3: strRep = uri.Host; break;

                        case 4:
                            strRep = uri.Port.ToString(
                                NumberFormatInfo.InvariantInfo);
                            break;

                        case 5: strRep = uri.AbsolutePath; break;

                        case 6: strRep = uri.Query; break;

                        case 7: strRep = uri.UserInfo; break;

                        case 8:
                            strRep = uri.UserInfo;
                            t      = strRep.IndexOf(':');
                            if (t >= 0)
                            {
                                strRep = strRep.Substring(0, t);
                            }
                            break;

                        case 9:
                            strRep = uri.UserInfo;
                            t      = strRep.IndexOf(':');
                            if (t < 0)
                            {
                                strRep = string.Empty;
                            }
                            else
                            {
                                strRep = strRep.Substring(t + 1);
                            }
                            break;

                        default: Debug.Assert(false); break;
                        }
                    }
                    catch (Exception) { }                    // Invalid URI
                }
                if (strRep == null)
                {
                    strRep = string.Empty;                                // No assert
                }
                str = StrUtil.ReplaceCaseInsensitive(str, strPlh, strRep);
            }

            return(str);
        }
Пример #28
0
        public void GetBaseUrl_Test(string url, string expected)
        {
            var actual = UrlUtil.GetBaseUrl(url);

            Assert.Equal(expected, actual);
        }
Пример #29
0
 private static void NavigateToIndexQuery(string indexName)
 {
     UrlUtil.Navigate("/query/" + indexName);
 }
        /// <summary>
        /// Loads the most updated configuration creating any resources as needed.
        /// </summary>
        /// <param name="bucketConfig">The latest <see cref="IBucketConfig"/>
        /// that will drive the recreation if the configuration context.</param>
        /// <param name="force">True to force the reconfiguration.</param>
        public override void LoadConfig(IBucketConfig bucketConfig, bool force = false)
        {
            try
            {
                Lock.EnterWriteLock();
                var nodes = bucketConfig.GetNodes();
                if (BucketConfig == null || !nodes.AreEqual(BucketConfig.GetNodes()) || !Servers.Any() || force)
                {
                    Log.Info("o1-Creating the Servers {0} list using rev#{1}", nodes.Count, bucketConfig.Rev);

                    var searchUris         = new ConcurrentBag <FailureCountingUri>();
                    var queryUris          = new ConcurrentBag <FailureCountingUri>();
                    var analyticsUris      = new ConcurrentBag <FailureCountingUri>();
                    var clientBucketConfig = ClientConfig.BucketConfigs[bucketConfig.Name];
                    var servers            = new Dictionary <IPEndPoint, IServer>();
                    foreach (var adapter in nodes)
                    {
                        var endpoint = adapter.GetIPEndPoint(clientBucketConfig.UseSsl);
                        try
                        {
                            //The node does not have to be created or swapped out so reuse the existing mode
                            if (Servers.TryGetValue(endpoint, out IServer cachedServer))
                            {
                                //The services list may have changed even though the
                                //connections can be reused so use the latest settings
                                cachedServer.LoadNodeAdapter(adapter, bucketConfig.Rev);

                                Log.Info("Reusing node {0} for rev#{1}", endpoint, bucketConfig.Rev);
                                servers.Add(endpoint, cachedServer);
                            }
                            else
                            {
                                Log.Info("Creating node {0} for rev#{1}", endpoint, bucketConfig.Rev);

                                IServer server;
                                if (adapter.IsDataNode) //a data node so create a connection pool
                                {
                                    var uri = UrlUtil.GetBaseUri(adapter, clientBucketConfig);
                                    var poolConfiguration = ClientConfig.BucketConfigs[BucketConfig.Name]
                                                            .ClonePoolConfiguration(uri);

                                    var ioService = CreateIOService(poolConfiguration, endpoint);

                                    server = new Core.Server(ioService, adapter, Transcoder, QueryCache, this);

                                    SupportsEnhancedDurability     = ioService.SupportsEnhancedDurability;
                                    SupportsSubdocXAttributes      = ioService.SupportsSubdocXAttributes;
                                    SupportsEnhancedAuthentication = ioService.SupportsEnhancedAuthentication;
                                    SupportsKvErrorMap             = ioService.SupportsKvErrorMap;
                                }
                                else
                                {
                                    server = new Core.Server(null, adapter, Transcoder, QueryCache, this);
                                }

                                servers.Add(endpoint, server);
                            }

                            if (adapter.IsSearchNode)
                            {
                                var uri = UrlUtil.GetFailureCountinSearchBaseUri(adapter, clientBucketConfig);
                                searchUris.Add(uri);
                            }
                            if (adapter.IsQueryNode)
                            {
                                var uri = UrlUtil.GetFailureCountingBaseUri(adapter, clientBucketConfig);
                                queryUris.Add(uri);
                            }
                            if (adapter.IsAnalyticsNode)
                            {
                                var uri = UrlUtil.GetFailureCountingAnalyticsUri(adapter, clientBucketConfig);
                                analyticsUris.Add(uri);
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Error("Could not add server {0} for rev#{1}. Exception: {2}", endpoint, bucketConfig.Rev, e);
                        }
                    }

                    UpdateServices(servers);

                    //for caching uri's
                    Interlocked.Exchange(ref QueryUris, queryUris);
                    Interlocked.Exchange(ref SearchUris, searchUris);
                    Interlocked.Exchange(ref AnalyticsUris, analyticsUris);

                    SwapServers(servers);

                    Log.Info("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev);
                    var vBucketKeyMapper = new VBucketKeyMapper(Servers,
                                                                bucketConfig.GetBucketServerMap(clientBucketConfig.UseSsl),
                                                                bucketConfig.Rev,
                                                                bucketConfig.Name);

                    Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper);
                    Interlocked.Exchange(ref _bucketConfig, bucketConfig);
                }
                else
                {
                    if (BucketConfig == null || !BucketConfig.IsVBucketServerMapEqual(bucketConfig) || force)
                    {
                        Log.Info("Creating the KeyMapper list using rev#{0}", bucketConfig.Rev);
                        var vBucketKeyMapper = new VBucketKeyMapper(Servers,
                                                                    bucketConfig.GetBucketServerMap(ClientConfig.BucketConfigs[bucketConfig.Name].UseSsl),
                                                                    bucketConfig.Rev,
                                                                    bucketConfig.Name);

                        Interlocked.Exchange(ref KeyMapper, vBucketKeyMapper);
                        Interlocked.Exchange(ref _bucketConfig, bucketConfig);
                    }
                    //only the revision changed so update to it
                    if (bucketConfig.Rev > BucketConfig.Rev)
                    {
                        Log.Info("Only the revision changed from using rev#{0} to rev#{1}", BucketConfig.Rev, bucketConfig.Rev);
                        BucketConfig.Rev = bucketConfig.Rev;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            finally
            {
                Lock.ExitWriteLock();
            }
        }