public static void Start(IWin32Window window, string service, bool prompt) { if (ElevateIfRequired(window, service, ServiceAccess.Start, "start")) { return; } if (prompt && !Prompt(window, service, "start", "", TaskDialogIcon.None)) { return; } try { using (var shandle = new ServiceHandle(service, ServiceAccess.Start)) shandle.Start(); } catch (Exception ex) { DialogResult r = MessageBox.Show(window, "Could not start the service \"" + service + "\":\n\n" + ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public TopshelfExitCode Run() { try { _log.InfoFormat("The {0} service is being started.", _settings.ServiceName); _serviceHandle.Start(this); _log.InfoFormat("The {0} service was started.", _settings.ServiceName); Thread.Sleep(100); _log.InfoFormat("The {0} service is being stopped.", _settings.ServiceName); _serviceHandle.Stop(this); } catch (Exception ex) { _log.Error("The service did not shut down gracefully", ex); } finally { _serviceHandle.Dispose(); _log.InfoFormat("The {0} service was stopped.", _settings.ServiceName); } return(TopshelfExitCode.Ok); }
protected override void OnStart(string[] args) { try { _log.Info("[Topshelf] Starting"); Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); _log.DebugFormat("[Topshelf] Current Directory: {0}", Directory.GetCurrentDirectory()); _log.DebugFormat("[Topshelf] Arguments: {0}", string.Join(",", args)); if (!_serviceHandle.Start(this)) { throw new TopshelfException("The service did not start successfully (returned false)."); } _log.Info("[Topshelf] Started"); } catch (Exception ex) { _log.Fatal("The service did not start successfully", ex); _log.Fatal(ex); ExitCode = (int)TopshelfExitCode.StartServiceFailed; throw; } }
private void RestartService(ServiceListViewItem serviceListViewItem) { try { using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect)) { using (ServiceHandle serviceHandle = scm.OpenService(serviceListViewItem.ServiceName, Advapi32.ServiceAccessRights.QueryStatus | Advapi32.ServiceAccessRights.Start | Advapi32.ServiceAccessRights.Stop)) { Advapi32.ServiceStatusProcess status = serviceHandle.QueryServiceStatus(); //Stop service (throws an exception if it is stopped) serviceHandle.Stop(); //Wait for stop serviceHandle.WaitForStatus(Advapi32.ServiceCurrentState.Stopped, TimeSpan.FromSeconds(10)); //Start service serviceHandle.Start(); } } } catch (System.TimeoutException) { MessageBox.Show(_resManager.GetString("timeout_exception_service_restart"), _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error); } catch (Exception ex) { MessageBox.Show(ex.Message, _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error); } }
public TopshelfExitCode Run() { var exitCode = TopshelfExitCode.AbnormalExit; try { exitCode = TopshelfExitCode.StartServiceFailed; _log.InfoFormat("The {0} service is being started.", _settings.ServiceName); _serviceHandle.Start(this); _log.InfoFormat("The {0} service was started.", _settings.ServiceName); Thread.Sleep(100); exitCode = TopshelfExitCode.StopServiceFailed; _log.InfoFormat("The {0} service is being stopped.", _settings.ServiceName); _serviceHandle.Stop(this); _log.InfoFormat("The {0} service was stopped.", _settings.ServiceName); exitCode = TopshelfExitCode.Ok; } catch (Exception ex) { _settings.ExceptionCallback?.Invoke(ex); _log.Error("The service threw an exception during testing.", ex); } finally { _serviceHandle.Dispose(); } return(exitCode); }
public override bool OnStart() { try { _log.Info("[Topshelf] Starting"); Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); _log.DebugFormat("[Topshelf] Current Directory: {0}", Directory.GetCurrentDirectory()); if (!_serviceHandle.Start(this)) { throw new TopshelfException("The service did not start successfully (returned false)."); } _log.Info("[Topshelf] Started"); return(true); } catch (Exception ex) { _log.Fatal("The service did not start successfully", ex); throw; } }
bool ServiceHandle.Start(HostControl hostControl) { _hostControl = hostControl; var control = new AppDomainHostControl(this); return(_service.Start(control)); }
void RestartService(object state) { try { _log.InfoFormat("Restarting service: {0}", _settings.ServiceName); var control = new AppDomainHostControl(this); _service.Stop(control); UnloadServiceAppDomain(); _log.DebugFormat("Service AppDomain unloaded: {0}", _settings.ServiceName); _service = CreateServiceInAppDomain(); _log.DebugFormat("Service created in new AppDomain: {0}", _settings.ServiceName); _service.Start(control); _log.InfoFormat("The service has been restarted: {0}", _settings.ServiceName); } catch (Exception ex) { _log.Error("Failed to restart service", ex); _hostControl.Stop(); } }
private void DoCreateService(ServiceControlManager serviceControlManager, ServiceDefinition serviceDefinition, bool startImmediately) { using (ServiceHandle svc = serviceControlManager.CreateService(serviceDefinition.ServiceName, serviceDefinition.DisplayName, serviceDefinition.BinaryPath, ServiceType.Win32OwnProcess, serviceDefinition.AutoStart ? ServiceStartType.AutoStart : ServiceStartType.StartOnDemand, serviceDefinition.ErrorSeverity, serviceDefinition.Credentials)) { string description = serviceDefinition.Description; if (!string.IsNullOrEmpty(description)) { svc.SetDescription(description); } ServiceFailureActions serviceFailureActions = serviceDefinition.FailureActions; if (serviceFailureActions != null) { svc.SetFailureActions(serviceFailureActions); svc.SetFailureActionFlag(serviceDefinition.FailureActionsOnNonCrashFailures); } if (serviceDefinition.AutoStart && serviceDefinition.DelayedAutoStart) { svc.SetDelayedAutoStartFlag(true); } if (startImmediately) { svc.Start(); } } }
public TopshelfExitCode Run() { hWnd = FindWindow(null, Console.Title); notifyIcon = new NotifyIcon(); notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath); notifyIcon.Visible = true; notifyIcon.MouseDoubleClick += icon_MouseDoubleClick; ShowWindow(hWnd, 0); isConsoleHiden = true; SetConsoleCtrlHandler(Handler, true); Console.WriteLine("Start services..."); if (!serviceHandle.Start(this)) { Console.WriteLine("Services failed to start."); } else { Console.WriteLine("Close the window to stop the services."); } Application.Run(); return(TopshelfExitCode.Ok); }
public void LoadService() { // Attempt to load the driver, then try again. ServiceHandle shandle; bool created = false; try { using (shandle = new ServiceHandle(_deviceName, ServiceAccess.Start)) { shandle.Start(); } } catch { using (ServiceManagerHandle scm = new ServiceManagerHandle(ScManagerAccess.CreateService)) { shandle = scm.CreateService( _deviceName, _deviceName, ServiceType.KernelDriver, Application.StartupPath + "\\kprocesshacker.sys" ); shandle.Start(); created = true; } } try { _fileHandle = new FileHandle( @"\Device\" + _deviceName, 0, FileAccess.GenericRead | FileAccess.GenericWrite ); } finally { if (created) { // The SCM will delete the service when it is stopped. shandle.Delete(); } shandle.Dispose(); } }
public TopshelfExitCode Run() { Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); AppDomain.CurrentDomain.UnhandledException += CatchUnhandledException; if (_environment.IsServiceInstalled(_settings.ServiceName)) { if (!_environment.IsServiceStopped(_settings.ServiceName)) { _log.ErrorFormat("The {0} service is running and must be stopped before running via the console", _settings.ServiceName); return(TopshelfExitCode.ServiceAlreadyRunning); } } bool started = false; try { _log.Debug("Starting up as a console application"); _exit = new ManualResetEvent(false); Console.CancelKeyPress += HandleCancelKeyPress; if (!_serviceHandle.Start(this)) { throw new TopshelfException("The service failed to start (return false)."); } started = true; _log.InfoFormat("The {0} service is now running, press Control+C to exit.", _settings.ServiceName); _exit.WaitOne(); } catch (Exception ex) { _log.Error("An exception occurred", ex); return(TopshelfExitCode.AbnormalExit); } finally { if (started) { StopService(); } _exit.Close(); (_exit as IDisposable).Dispose(); HostLogger.Shutdown(); } return(TopshelfExitCode.Ok); }
protected override void OnStart(string[] args) { try { _log.Info("[Topshelf] Starting"); _log.DebugFormat("[Topshelf] Arguments: {0}", string.Join(",", args)); _serviceHandle.Start(this); } catch (Exception ex) { _log.Fatal(ex); throw; } }
public TopshelfExitCode Run() { Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); AppDomain.CurrentDomain.UnhandledException += CatchUnhandledException; if (_environment.IsServiceInstalled(_settings.ServiceName)) { _log.ErrorFormat("The {0} service is installed as a service", _settings.ServiceName); return(TopshelfExitCode.ServiceAlreadyInstalled); } try { _log.Debug("Starting up as a console application"); _exit = new ManualResetEvent(false); Console.CancelKeyPress += HandleCancelKeyPress; _serviceHandle.Start(this); _log.InfoFormat("The {0} service is now running, press Control+C to exit.", _settings.ServiceName); _exit.WaitOne(); } catch (Exception ex) { _log.Error("An exception occurred", ex); return(TopshelfExitCode.AbnormalExit); } finally { StopService(); _exit.Close(); (_exit as IDisposable).Dispose(); HostLogger.Shutdown(); } return(TopshelfExitCode.Ok); }
private void StartService() { _logWriter.InfoFormat(Resources.StartingService, _settings.ServiceName); try { if (!_serviceHandle.Start(this)) { throw new TopshelfException(string.Format(Resources.ServiceDidntStartSuccessfully, _settings.ServiceName)); } } catch (Exception error) { _logWriter.Fatal(string.Format(Resources.StartServiceFailed, _settings.ServiceName), error); throw; } _logWriter.InfoFormat(Resources.ServiceStarted, _settings.ServiceName); }
private void StartService(ServiceListViewItem serviceListViewItem, bool inUserSession = false) { try { if (inUserSession) { //Write username where the service should start the process RegistryManagement.WriteSessionUsername(serviceListViewItem.ServiceName, WindowsIdentity.GetCurrent().Name); } using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect)) { using (ServiceHandle serviceHandle = scm.OpenService(serviceListViewItem.ServiceName, Advapi32.ServiceAccessRights.Start)) { serviceHandle.Start(); } } } catch (Exception ex) { MessageBox.Show(ex.Message, _resManager.GetString("error"), MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Creates a connection to KProcessHacker. /// </summary> /// <param name="deviceName">The name of the KProcessHacker service and device.</param> /// <param name="fileName">The file name of the KProcessHacker driver.</param> public KProcessHacker(string deviceName, string fileName) { _deviceName = deviceName; if (IntPtr.Size != 4) { throw new NotSupportedException("KProcessHacker does not support 64-bit Windows."); } try { _fileHandle = new FileHandle( @"\Device\" + deviceName, 0, FileAccess.GenericRead | FileAccess.GenericWrite ); } catch (WindowsException ex) { if ( ex.Status == NtStatus.NoSuchDevice || ex.Status == NtStatus.NoSuchFile || ex.Status == NtStatus.ObjectNameNotFound ) { // Attempt to load the driver, then try again. ServiceHandle shandle; bool created = false; try { using (shandle = new ServiceHandle("KProcessHacker", ServiceAccess.Start)) { shandle.Start(); } } catch { using (var scm = new ServiceManagerHandle(ScManagerAccess.CreateService)) { shandle = scm.CreateService( deviceName, deviceName, ServiceType.KernelDriver, fileName ); shandle.Start(); created = true; } } try { _fileHandle = new FileHandle( @"\Device\" + deviceName, 0, FileAccess.GenericRead | FileAccess.GenericWrite ); } finally { if (shandle != null) { if (created) { // The SCM will delete the service when it is stopped. shandle.Delete(); } shandle.Dispose(); } } } else { throw ex; } } _fileHandle.SetHandleFlags(Win32HandleFlags.ProtectFromClose, Win32HandleFlags.ProtectFromClose); byte[] bytes = _fileHandle.Read(4); fixed(byte *bytesPtr = bytes) _baseControlNumber = *(uint *)bytesPtr; try { _features = this.GetFeatures(); } catch { } }
public bool Start(HostControl hostControl) { return(_serviceHandle.Start(hostControl)); }
public static void Start(IWin32Window window, string service, bool prompt) { if (ElevateIfRequired(window, service, ServiceAccess.Start, "start")) return; if (prompt && !Prompt(window, service, "start", "", TaskDialogIcon.None)) return; try { using (var shandle = new ServiceHandle(service, ServiceAccess.Start)) shandle.Start(); } catch (Exception ex) { DialogResult r = MessageBox.Show(window, "Could not start the service \"" + service + "\":\n\n" + ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Installs the service. /// </summary> /// <param name="DisplayName">Service display name.</param> /// <param name="Description">Service description.</param> /// <param name="StartType">How the service should be started.</param> /// <param name="StartImmediately">If the service should be started immediately.</param> /// <param name="FailureActions">Service failure actions.</param> /// <param name="Credentials">Credentials to use when running service.</param> /// <returns> /// Return code: /// /// 0: Installed, not started. /// 1: Installed, started. /// 2: Updated, not started. /// 3: Updated, started. /// </returns> /// <exception cref="Exception">If service could not be installed.</exception> public int Install(string DisplayName, string Description, ServiceStartType StartType, bool StartImmediately, ServiceFailureActions FailureActions, Win32ServiceCredentials Credentials) { string Path = Assembly.GetExecutingAssembly().Location.Replace(".dll", ".exe"); try { using (ServiceControlManager mgr = ServiceControlManager.Connect(null, null, ServiceControlManagerAccessRights.All)) { if (mgr.TryOpenService(this.serviceName, ServiceControlAccessRights.All, out ServiceHandle existingService, out Win32Exception errorException)) { using (existingService) { existingService.ChangeConfig(DisplayName, Path, ServiceType.Win32OwnProcess, StartType, ErrorSeverity.Normal, Credentials); if (!string.IsNullOrEmpty(Description)) { existingService.SetDescription(Description); } if (FailureActions != null) { existingService.SetFailureActions(FailureActions); existingService.SetFailureActionFlag(true); } else { existingService.SetFailureActionFlag(false); } if (StartImmediately) { existingService.Start(throwIfAlreadyRunning: false); return(3); } else { return(2); } } } else { if (errorException.NativeErrorCode == Win32.ERROR_SERVICE_DOES_NOT_EXIST) { using (ServiceHandle svc = mgr.CreateService(this.serviceName, DisplayName, Path, ServiceType.Win32OwnProcess, StartType, ErrorSeverity.Normal, Credentials)) { if (!string.IsNullOrEmpty(Description)) { svc.SetDescription(Description); } if (FailureActions != null) { svc.SetFailureActions(FailureActions); svc.SetFailureActionFlag(true); } else { svc.SetFailureActionFlag(false); } if (StartImmediately) { svc.Start(); return(1); } else { return(0); } } } else { throw errorException; } } }
private void buttonOK_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; Application.DoEvents(); try { Assistant.SetDesktopWinStaAccess(); } catch { } try { bool omitUserAndType = false; if (_pid != -1) { omitUserAndType = true; } string mailslotName = "ProcessHackerAssistant" + Utils.CreateRandomString(8); string binPath = "\"" + Application.ExecutablePath + "\" -assistant " + (omitUserAndType ? string.Empty : ("-u \"" + this.comboUsername.Text + "\" -t " + this.comboType.SelectedItem.ToString().ToLowerInvariant() + " ")) + (this._pid != -1 ? ("-P " + this._pid.ToString() + " ") : string.Empty) + "-p \"" + this.textPassword.Text.Replace("\"", "\\\"") + "\" -s " + this.textSessionID.Text + " -c \"" + this.textCmdLine.Text.Replace("\"", "\\\"") + "\" -E " + mailslotName; if (Program.ElevationType == TokenElevationType.Limited) { var result = Program.StartProcessHackerAdminWait( "-e -type processhacker -action runas -obj \"" + binPath.Replace("\"", "\\\"") + "\" -mailslot " + mailslotName + " -hwnd " + this.Handle.ToString(), this.Handle, 5000); if (result == WaitResult.Object0) { this.Close(); } } else { string serviceName = Utils.CreateRandomString(8); using (ServiceManagerHandle manager = new ServiceManagerHandle(ScManagerAccess.CreateService)) using (ServiceHandle service = manager.CreateService( serviceName, serviceName + " (Process Hacker Assistant)", ServiceType.Win32OwnProcess, ServiceStartType.DemandStart, ServiceErrorControl.Ignore, binPath, string.Empty, "LocalSystem", null )) { // Create a mailslot so we can receive the error code for Assistant. using (MailslotHandle mhandle = MailslotHandle.Create(FileAccess.GenericRead, @"\Device\Mailslot\" + mailslotName, 0, 5000)) { try { service.Start(); } catch { } service.Delete(); Win32Error errorCode = (Win32Error)mhandle.Read(4).ToInt32(); if (errorCode != Win32Error.Success) { throw new WindowsException(errorCode); } } } this.Close(); } } catch (Exception ex) { PhUtils.ShowException("Unable to start the program", ex); } this.Cursor = Cursors.Default; }
public KProcessHacker(string deviceName, string fileName) { _deviceName = deviceName; if (IntPtr.Size != 4) throw new NotSupportedException("KProcessHacker does not support 64-bit Windows."); try { _fileHandle = new FileHandle( @"\Device\" + deviceName, 0, FileAccess.GenericRead | FileAccess.GenericWrite ); } catch (WindowsException ex) { if ( ex.Status == NtStatus.NoSuchDevice || ex.Status == NtStatus.NoSuchFile || ex.Status == NtStatus.ObjectNameNotFound ) { ServiceHandle shandle; bool created = false; try { using (shandle = new ServiceHandle("KProcessHacker", ServiceAccess.Start)) { shandle.Start(); } } catch { using (var scm = new ServiceManagerHandle(ScManagerAccess.CreateService)) { shandle = scm.CreateService( deviceName, deviceName, ServiceType.KernelDriver, fileName ); shandle.Start(); created = true; } } try { _fileHandle = new FileHandle( @"\Device\" + deviceName, 0, FileAccess.GenericRead | FileAccess.GenericWrite ); } finally { if (shandle != null) { if (created) { shandle.Delete(); } shandle.Dispose(); } } } else { throw ex; } } _fileHandle.SetHandleFlags(Win32HandleFlags.ProtectFromClose, Win32HandleFlags.ProtectFromClose); byte[] bytes = _fileHandle.Read(4); fixed (byte* bytesPtr = bytes) _baseControlNumber = *(uint*)bytesPtr; try { _features = this.GetFeatures(); } catch { } }
bool ServiceHandle.Start(HostControl hostControl) { return(_service.Start(_hostControl)); }