void StartService() { if (_serviceHandle != null) { _log.Debug("Attempted to start service, but it is already started"); return; } if (!_serviceAvailability.CanStart()) { _log.Debug("Attempted to start service, but it is unavailable"); return; } _log.Debug("Starting supervised service"); var arguments = new CommandScriptStepArguments { _serviceBuilderFactory }; var script = new CommandScript { new CommandScriptStep <CreateServiceCommand>(arguments), new CommandScriptStep <StartServiceCommand>(arguments), }; bool started = Execute(script); if (started) { _serviceHandle = arguments.Get <ServiceHandle>(); } }
public static void Delete(IWin32Window window, string service, bool prompt) { if (ElevateIfRequired(window, service, (ServiceAccess)StandardRights.Delete, "delete")) { return; } if (prompt && !Prompt(window, service, "delete", "Deleting a service can prevent the system from starting or functioning properly. " + "Are you sure you want to continue?", TaskDialogIcon.Warning)) { return; } try { using (var shandle = new ServiceHandle(service, (ServiceAccess)StandardRights.Delete)) shandle.Delete(); } catch (Exception ex) { DialogResult r = MessageBox.Show(window, "Could not delete the service \"" + service + "\":\n\n" + ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void CloseSocketTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 target.CloseSocket(); Assert.Inconclusive("无法验证不返回值的方法。"); }
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 RehabServiceHandle(HostSettings settings, ServiceBuilderFactory serviceBuilderFactory) { _settings = settings; _serviceBuilderFactory = serviceBuilderFactory; _service = CreateServiceInAppDomain(); }
public static void Stop(IWin32Window window, string service, bool prompt) { if (ElevateIfRequired(window, service, ServiceAccess.Stop, "stop")) { return; } if (prompt && !Prompt(window, service, "stop", "", TaskDialogIcon.None)) { return; } try { using (var shandle = new ServiceHandle(service, ServiceAccess.Stop)) shandle.Control(ServiceControl.Stop); } catch (Exception ex) { DialogResult r = MessageBox.Show(window, "Could not stop the service \"" + service + "\":\n\n" + ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
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(); } }
void RestartService() { _log.Debug("Restarting supervised service"); var createArguments = new CommandScriptStepArguments { _serviceBuilderFactory, }; var unloadArguments = new CommandScriptStepArguments { _serviceHandle, }; var script = new CommandScript { new CommandScriptStep <CreateServiceCommand>(createArguments), new CommandScriptStep <StopServiceCommand>(unloadArguments), new CommandScriptStep <StartServiceCommand>(createArguments), new CommandScriptStep <UnloadServiceCommand>(unloadArguments), }; bool restarted = Execute(script); if (restarted) { _serviceHandle = createArguments.Get <ServiceHandle>(); } }
void StartService() { if (_serviceHandle != null) { _log.Debug("Attempted to start service, but it is already started"); return; } string reason; if (!CanStartService(out reason)) { _log.DebugFormat("Attempted to start service, but it is not available: {0}", reason); return; } _log.Debug("Starting supervised service"); var arguments = new CommandScriptStepArguments { _serviceBuilderFactory }; var script = new CommandScript { new CommandScriptStep <CreateServiceCommand>(arguments), new CommandScriptStep <StartServiceCommand>(arguments), }; bool started = Execute(script); if (started) { _serviceHandle = arguments.Get <ServiceHandle>(); } }
public ConsoleRunHost(HostSettings settings, HostEnvironment environment, ServiceHandle serviceHandle) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (environment == null) { throw new ArgumentNullException(nameof(environment)); } _settings = settings; _environment = environment; _serviceHandle = serviceHandle; #if !NETCORE if (settings.CanSessionChanged) { SystemEvents.SessionSwitch += OnSessionChanged; } if (settings.CanHandlePowerEvent) { SystemEvents.PowerModeChanged += OnPowerModeChanged; } #endif }
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 static void DumpServices(MemoryFileSystem mfs) { using (var services = mfs.RootObject.GetChild("Services")) { foreach (var service in Windows.GetServices().Values) { using (var serviceChild = services.CreateChild(service.ServiceName)) { BinaryWriter bw = new BinaryWriter(serviceChild.GetWriteStream()); bw.Write("Name", service.ServiceName); bw.Write("DisplayName", service.DisplayName); bw.Write("Type", (int)service.ServiceStatusProcess.ServiceType); bw.Write("State", (int)service.ServiceStatusProcess.CurrentState); bw.Write("ProcessId", service.ServiceStatusProcess.ProcessID); bw.Write("ControlsAccepted", (int)service.ServiceStatusProcess.ControlsAccepted); bw.Write("Flags", (int)service.ServiceStatusProcess.ServiceFlags); try { QueryServiceConfig config; using (var shandle = new ServiceHandle(service.ServiceName, ServiceAccess.QueryConfig)) { config = shandle.GetConfig(); bw.Write("StartType", (int)config.StartType); bw.Write("ErrorControl", (int)config.ErrorControl); bw.Write("BinaryPath", FileUtils.GetFileName(config.BinaryPathName)); bw.Write("Group", config.LoadOrderGroup); bw.Write("UserName", config.ServiceStartName); bw.Write("Description", shandle.GetDescription()); } if (config.ServiceType == ServiceType.Win32ShareProcess) { try { using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( "SYSTEM\\CurrentControlSet\\Services\\" + service.ServiceName + "\\Parameters")) { bw.Write( "ServiceDll", Environment.ExpandEnvironmentVariables((string)key.GetValue("ServiceDll")) ); } } catch { } } } catch { } bw.Close(); } } } }
public WinformsRunHost(HostEnvironment environment, HostSettings settings, ServiceHandle serviceHandle, bool autostart) { _settings = settings; _Autostart = autostart; _environment = environment; _serviceHandle = serviceHandle; }
public static extern bool QueryServiceConfig ( ServiceHandle serviceHandle, IntPtr buffer, uint bufferSize, ref uint bytesNeeded );
public void ClientAddressTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 string actual; actual = target.ClientAddress; Assert.Inconclusive("验证此测试方法的正确性。"); }
public void IsOnlineTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 bool actual; actual = target.IsOnline; Assert.Inconclusive("验证此测试方法的正确性。"); }
public void LastMessageBlockTimeTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 long actual; actual = target.LastMessageBlockTime; Assert.Inconclusive("验证此测试方法的正确性。"); }
public void MessageBlockNumbersTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 long actual; actual = target.MessageBlockNumbers; Assert.Inconclusive("验证此测试方法的正确性。"); }
public void RemoteOnlyIPTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 string actual; actual = target.RemoteOnlyIP; Assert.Inconclusive("验证此测试方法的正确性。"); }
public void FirstTimeTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 long actual; actual = target.FirstTime; Assert.Inconclusive("验证此测试方法的正确性。"); }
public void Dispose() { if (ServiceHandle != null) { ServiceHandle.Dispose(); ServiceHandle = null; } }
public void SendToTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 MessageBlock sendMessageBlock = MessageBlock.Zero; // TODO: 初始化为适当的值 target.SendTo(sendMessageBlock); Assert.Inconclusive("无法验证不返回值的方法。"); }
public static extern bool QueryServiceStatusEx ( ServiceHandle serviceHandle, uint infoLevel, IntPtr buffer, uint bufferSize, out uint bytesNeeded );
public void RemotePortTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 int actual; actual = target.RemotePort; Assert.Inconclusive("验证此测试方法的正确性。"); }
public ServiceHandleProxy(HostSettings settings, HostControl hostControl, ServiceBuilderFactory serviceBuilderFactory) { _settings = settings; _hostControl = new HostControlProxy(hostControl); _serviceBuilderFactory = serviceBuilderFactory; _service = CreateServiceInAppDomain(); }
Host CreateHost(ServiceHandle serviceHandle) { if (environment.IsRunningAsAService) { return(environment.CreateServiceHost(settings, serviceHandle)); } return(new CustomConsoleHost(settings, environment, serviceHandle)); }
static bool StopService(Options opt) { bool bResult = false; try { bool IsWindows = System.Runtime.InteropServices.RuntimeInformation .IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows); if (IsWindows == true) { ServiceControlManager mgr = ServiceControlManager.Connect(Win32ServiceInterop.Wrapper, null, null, ServiceControlManagerAccessRights.All); if ((mgr != null) && (mgr.IsInvalid != true)) { ServiceHandle h = mgr.OpenService(ServiceName, ServiceControlAccessRights.All); if (h != null) { ServiceStatusProcess status = new ServiceStatusProcess(); uint reason = (uint)StopReasonMinorReasonFlags.SERVICE_STOP_REASON_MINOR_MAINTENANCE | (uint)StopReasonMajorReasonFlags.SERVICE_STOP_REASON_MAJOR_NONE | (uint)StopReasonFlags.SERVICE_STOP_REASON_FLAG_UNPLANNED; ServiceStatusParam param = new ServiceStatusParam(reason, status); int s = Marshal.SizeOf <ServiceStatusParam>(); var lpParam = Marshal.AllocHGlobal(s); Marshal.StructureToPtr(param, lpParam, fDeleteOld: false); if (Win32ServiceInterop.ControlServiceExW(h, (uint)ServiceControlCommandFlags.SERVICE_CONTROL_STOP, (uint)ServiceControlCommandReasonFlags.SERVICE_CONTROL_STATUS_REASON_INFO, lpParam) == true) { bResult = true; } else { opt.LogError("Stop feature: can't stop Service: " + ServiceName + " ErrorCode: " + Marshal.GetLastWin32Error().ToString()); } } else { opt.LogError("Stop feature: can't open Service: " + ServiceName); } } else { opt.LogError("Stop feature: can't open ServiceManager"); } } else { opt.LogError("Stop feature: this service is not available on the current platform"); } } catch (Exception ex) { opt.LogError("Stop feature: exception: " + ex.Message); } return(bResult); }
private Host CreateHost(ServiceHandle serviceHandle) { if (this._Environment.IsRunningAsAService) { //RunBuilder._log.Debug("Running as a service, creating service host."); return(this._Environment.CreateServiceHost(this._Settings, serviceHandle)); } //RunBuilder._log.Debug("Running as a console application, creating the console host."); return(new WinformsRunHost(this._Environment, this._Settings, serviceHandle, _Autostart)); }
public void SocketHandlerManagerTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 ServiceHandleManager expected = ServiceHandleManager.Zero; // TODO: 初始化为适当的值 ServiceHandleManager actual; target.SocketHandlerManager = expected; actual = target.SocketHandlerManager; Assert.AreEqual( expected, actual ); Assert.Inconclusive( "验证此测试方法的正确性。" ); }
public void ValueTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 IntPtr expected = new IntPtr(); // TODO: 初始化为适当的值 IntPtr actual; target.Handle = expected; actual = target.Handle; Assert.AreEqual( expected, actual ); Assert.Inconclusive( "验证此测试方法的正确性。" ); }
private Host CreateHost(ServiceHandle serviceHandle) { if (Environment.IsRunningAsAService) { _log.Debug("Running as a service, creating service host."); return(Environment.CreateServiceHost(Settings, serviceHandle)); } _log.Debug("Running as an application, creating the application host."); return(new ApplicationHost(Settings, serviceHandle)); }
public void InitClientHandlerTest1() { ClientSocketManager target = new ClientSocketManager(); // TODO: 初始化为适当的值 Listener listener = null; // TODO: 初始化为适当的值 ServiceHandle serviceHandle = null; // TODO: 初始化为适当的值 ReceiveQueue receiveBuffer = null; // TODO: 初始化为适当的值 target.InitClientHandler(listener, serviceHandle, receiveBuffer); Assert.Inconclusive("无法验证不返回值的方法。"); }
public WindowsServiceHost(HostEnvironment environment, HostSettings settings, ServiceHandle serviceHandle) { if (settings == null) throw new ArgumentNullException("settings"); if (serviceHandle == null) throw new ArgumentNullException("serviceHandle"); _settings = settings; _serviceHandle = serviceHandle; _environment = environment; }
public void Create(ServiceBuilderFactory serviceBuilderFactory, HostSettings settings, HostLoggerConfigurator loggerConfigurator) { AppDomain.CurrentDomain.UnhandledException += CatchUnhandledException; HostLogger.UseLogger(loggerConfigurator); ServiceBuilder serviceBuilder = serviceBuilderFactory(settings); _serviceHandle = serviceBuilder.Build(settings); }
public ConsoleRunHost(HostSettings settings, HostEnvironment environment, ServiceHandle serviceHandle) { if (settings == null) throw new ArgumentNullException("settings"); if (environment == null) throw new ArgumentNullException("environment"); _settings = settings; _environment = environment; _serviceHandle = serviceHandle; }
public Host CreateServiceHost(HostSettings settings, ServiceHandle serviceHandle) { if (MonoHelper.RunningUnderMonoService) { return new WindowsServiceHost(this, settings, serviceHandle, configurator); } else { // TODO: Implement a service host which execs mono-service under the hood. throw new NotImplementedException(); } }
public WindowsServiceHost(HostEnvironment environment, HostSettings settings, ServiceHandle serviceHandle) { if (settings == null) throw new ArgumentNullException("settings"); if (serviceHandle == null) throw new ArgumentNullException("serviceHandle"); _settings = settings; _serviceHandle = serviceHandle; _environment = environment; CanPauseAndContinue = settings.CanPauseAndContinue; CanShutdown = settings.CanShutdown; }
public ConsoleRunHost(HostSettings settings, HostEnvironment environment, ServiceHandle serviceHandle) { if (settings == null) throw new ArgumentNullException("settings"); if (environment == null) throw new ArgumentNullException("environment"); _settings = settings; _environment = environment; _serviceHandle = serviceHandle; if (settings.CanSessionChanged) { SystemEvents.SessionSwitch += OnSessionChanged; } }
public WindowsServiceHost(HostEnvironment environment, HostSettings settings, ServiceHandle serviceHandle, HostConfigurator configurator) { if (settings == null) throw new ArgumentNullException("settings"); if (serviceHandle == null) throw new ArgumentNullException("serviceHandle"); _settings = settings; _serviceHandle = serviceHandle; _environment = environment; _configurator = configurator; CanPauseAndContinue = settings.CanPauseAndContinue; CanShutdown = settings.CanShutdown; CanHandleSessionChangeEvent = settings.CanSessionChanged; ServiceName = _settings.ServiceName; }
public LinuxServiceHost(HostSettings settings, ServiceHandle serviceHandle) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (serviceHandle == null) { throw new ArgumentNullException(nameof(serviceHandle)); } _settings = settings; _serviceHandle = serviceHandle; _logWriter = HostLogger.Get<LinuxServiceHost>(); _stopSignal = new ManualResetEvent(false); _signalListener = new LinuxSignalListener(); _signalListener.Subscribe(Signum.SIGINT, SetStopSignal); _signalListener.Subscribe(Signum.SIGTERM, SetStopSignal); }
public static void Pause(IWin32Window window, string service, bool prompt) { if (ElevateIfRequired(window, service, ServiceAccess.PauseContinue, "pause")) return; if (prompt && !Prompt(window, service, "pause", "", TaskDialogIcon.None)) return; try { using (var shandle = new ServiceHandle(service, ServiceAccess.PauseContinue)) shandle.Control(ServiceControl.Pause); } catch (Exception ex) { DialogResult r = MessageBox.Show(window, "Could not pause the service \"" + service + "\":\n\n" + ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static void Delete(IWin32Window window, string service, bool prompt) { if (ElevateIfRequired(window, service, (ServiceAccess)StandardRights.Delete, "delete")) return; if (prompt && !Prompt(window, service, "delete", "Deleting a service can prevent the system from starting or functioning properly. " + "Are you sure you want to continue?", TaskDialogIcon.Warning)) return; try { using (var shandle = new ServiceHandle(service, (ServiceAccess)StandardRights.Delete)) shandle.Delete(); } catch (Exception ex) { DialogResult r = MessageBox.Show(window, "Could not delete the service \"" + service + "\":\n\n" + ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
void RestartService() { _log.Debug("Restarting supervised service"); var createArguments = new CommandScriptStepArguments { _serviceBuilderFactory, }; var unloadArguments = new CommandScriptStepArguments { _serviceHandle, }; var script = new CommandScript { new CommandScriptStep<CreateServiceCommand>(createArguments), new CommandScriptStep<StopServiceCommand>(unloadArguments), new CommandScriptStep<StartServiceCommand>(createArguments), new CommandScriptStep<UnloadServiceCommand>(unloadArguments), }; bool restarted = Execute(script); if (restarted) { _serviceHandle = createArguments.Get<ServiceHandle>(); } }
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 { } }
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 Host CreateServiceHost(HostSettings settings, ServiceHandle serviceHandle) { return new LinuxServiceHost(settings, serviceHandle); }
public WinformsRunHost(HostEnvironment environment, HostSettings settings, ServiceHandle serviceHandle) { _environment = environment; _settings = settings; _serviceHandle = serviceHandle; }
private void UpdateInformation() { checkChangePassword.Checked = false; if (listServices.SelectedItems.Count == 0) { buttonApply.Enabled = false; buttonStart.Enabled = false; buttonStop.Enabled = false; buttonDependents.Enabled = false; buttonDependencies.Enabled = false; buttonPermissions.Enabled = false; comboType.Enabled = false; comboStartType.Enabled = false; comboErrorControl.Enabled = false; _oldConfig = new QueryServiceConfig(); this.ClearControls(); } else { try { buttonApply.Enabled = true; buttonStart.Enabled = true; buttonStop.Enabled = true; buttonDependents.Enabled = true; buttonDependencies.Enabled = true; buttonPermissions.Enabled = true; comboType.Enabled = true; comboStartType.Enabled = true; comboErrorControl.Enabled = true; try { using (var shandle = new ServiceHandle(listServices.SelectedItems[0].Name, ServiceAccess.QueryConfig)) _provider.UpdateServiceConfig(listServices.SelectedItems[0].Name, shandle.GetConfig()); } catch { } ServiceItem item = _provider.Dictionary[listServices.SelectedItems[0].Name]; _oldConfig = item.Config; _oldConfig.BinaryPathName = FileUtils.GetFileName(_oldConfig.BinaryPathName); buttonStart.Enabled = true; buttonStop.Enabled = true; if (item.Status.ServiceStatusProcess.CurrentState == ServiceState.Running) buttonStart.Enabled = false; else if (item.Status.ServiceStatusProcess.CurrentState == ServiceState.Stopped) buttonStop.Enabled = false; if ((item.Status.ServiceStatusProcess.ControlsAccepted & ServiceAccept.Stop) == 0) buttonStop.Enabled = false; labelServiceName.Text = item.Status.ServiceName; labelServiceDisplayName.Text = item.Status.DisplayName; comboType.SelectedItem = item.Config.ServiceType.ToString(); if (item.Config.ServiceType == (ProcessHacker.Native.Api.ServiceType.Win32OwnProcess | ProcessHacker.Native.Api.ServiceType.InteractiveProcess)) comboType.SelectedItem = "Win32OwnProcess, InteractiveProcess"; else if (item.Config.ServiceType == (ProcessHacker.Native.Api.ServiceType.Win32ShareProcess | ProcessHacker.Native.Api.ServiceType.InteractiveProcess)) comboType.SelectedItem = "Win32ShareProcess, InteractiveProcess"; comboStartType.SelectedItem = item.Config.StartType.ToString(); comboErrorControl.SelectedItem = item.Config.ErrorControl.ToString(); textServiceBinaryPath.Text = FileUtils.GetFileName(item.Config.BinaryPathName); textUserAccount.Text = item.Config.ServiceStartName; textLoadOrderGroup.Text = item.Config.LoadOrderGroup; try { using (var shandle = new ServiceHandle(item.Status.ServiceName, ServiceAccess.QueryConfig)) textDescription.Text = shandle.GetDescription(); } catch { textDescription.Text = string.Empty; } textServiceDll.Text = string.Empty; if (item.Config.ServiceType == ProcessHacker.Native.Api.ServiceType.Win32ShareProcess) { try { using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( "SYSTEM\\CurrentControlSet\\Services\\" + item.Status.ServiceName + "\\Parameters")) textServiceDll.Text = Environment.ExpandEnvironmentVariables((string)key.GetValue("ServiceDll")); } catch { } } try { using (ServiceController controller = new ServiceController( listServices.SelectedItems[0].Name)) { if (controller.DependentServices.Length == 0) buttonDependents.Enabled = false; if (controller.ServicesDependedOn.Length == 0) buttonDependencies.Enabled = false; } } catch { buttonDependents.Enabled = false; buttonDependencies.Enabled = false; } } catch (Exception ex) { labelServiceName.Text = ex.Message; _oldConfig = new QueryServiceConfig(); this.ClearControls(); } } }
void StartService() { if (_serviceHandle != null) { _log.Debug("Attempted to start service, but it is already started"); return; } string reason; if (!CanStartService(out reason)) { _log.DebugFormat("Attempted to start service, but it is not available: {0}", reason); return; } _log.Debug("Starting supervised service"); var arguments = new CommandScriptStepArguments {_serviceBuilderFactory}; var script = new CommandScript { new CommandScriptStep<CreateServiceCommand>(arguments), new CommandScriptStep<StartServiceCommand>(arguments), }; bool started = Execute(script); if (started) { _serviceHandle = arguments.Get<ServiceHandle>(); } }
/// <summary> /// /// </summary> /// <param name="clientHandler"></param> public SocketConnectEventArgs( ServiceHandle clientHandler ) { m_ClientHandler = clientHandler; }
public Host CreateServiceHost(HostSettings settings, ServiceHandle serviceHandle) { return new WindowsServiceHost(this, settings, serviceHandle, this._hostConfigurator); }
void StopService() { _log.Debug("Stopping supervised service"); var unloadArguments = new CommandScriptStepArguments { _serviceHandle, }; var script = new CommandScript { new CommandScriptStep<StopServiceCommand>(unloadArguments), new CommandScriptStep<UnloadServiceCommand>(unloadArguments), }; bool stopped = Execute(script); if (stopped) { _serviceHandle = null; } }
public Host CreateServiceHost(HostSettings settings, ServiceHandle serviceHandle) { return _environment.CreateServiceHost(settings, serviceHandle); }
public static void Run(IDictionary<string, string> args) { try { ThemingScope.Activate(); } catch { } if (!args.ContainsKey("-type")) throw new Exception("-type switch required."); string type = args["-type"].ToLower(); if (!args.ContainsKey("-obj")) throw new Exception("-obj switch required."); string obj = args["-obj"]; if (!args.ContainsKey("-action")) throw new Exception("-action switch required."); string action = args["-action"].ToLower(); WindowFromHandle window = new WindowFromHandle(IntPtr.Zero); if (args.ContainsKey("-hwnd")) window = new WindowFromHandle(new IntPtr(int.Parse(args["-hwnd"]))); try { switch (type) { case "processhacker": { switch (action) { case "runas": { using (var manager = new ServiceManagerHandle(ScManagerAccess.CreateService)) { Random r = new Random((int)(DateTime.Now.ToFileTime() & 0xffffffff)); string serviceName = ""; for (int i = 0; i < 8; i++) serviceName += (char)('A' + r.Next(25)); using (var service = manager.CreateService( serviceName, serviceName + " (Process Hacker Assistant)", ServiceType.Win32OwnProcess, ServiceStartType.DemandStart, ServiceErrorControl.Ignore, obj, "", "LocalSystem", null)) { // Create a mailslot so we can receive the error code for Assistant. using (var mhandle = MailslotHandle.Create( FileAccess.GenericRead, @"\Device\Mailslot\" + args["-mailslot"], 0, 5000) ) { try { service.Start(); } catch { } service.Delete(); Win32Error errorCode = (Win32Error)mhandle.Read(4).ToInt32(); if (errorCode != Win32Error.Success) throw new WindowsException(errorCode); } } } } break; default: throw new Exception("Unknown action '" + action + "'"); } } break; case "process": { var processes = Windows.GetProcesses(); string[] pidStrings = obj.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); int[] pids = new int[pidStrings.Length]; string[] names = new string[pidStrings.Length]; for (int i = 0; i < pidStrings.Length; i++) { pids[i] = int.Parse(pidStrings[i]); names[i] = processes[pids[i]].Name; } switch (action) { case "terminate": ProcessActions.Terminate(window, pids, names, true); break; case "suspend": ProcessActions.Suspend(window, pids, names, true); break; case "resume": ProcessActions.Resume(window, pids, names, true); break; case "reduceworkingset": ProcessActions.ReduceWorkingSet(window, pids, names, false); break; default: throw new Exception("Unknown action '" + action + "'"); } } break; case "thread": { foreach (string tid in obj.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { switch (action) { case "terminate": { try { using (var thandle = new ThreadHandle(int.Parse(tid), ThreadAccess.Terminate)) thandle.Terminate(); } catch (Exception ex) { DialogResult result = MessageBox.Show(window, "Could not terminate thread with ID " + tid + ":\n\n" + ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); if (result == DialogResult.Cancel) return; } } break; case "suspend": { try { using (var thandle = new ThreadHandle(int.Parse(tid), ThreadAccess.SuspendResume)) thandle.Suspend(); } catch (Exception ex) { DialogResult result = MessageBox.Show(window, "Could not suspend thread with ID " + tid + ":\n\n" + ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); if (result == DialogResult.Cancel) return; } } break; case "resume": { try { using (var thandle = new ThreadHandle(int.Parse(tid), ThreadAccess.SuspendResume)) thandle.Resume(); } catch (Exception ex) { DialogResult result = MessageBox.Show(window, "Could not resume thread with ID " + tid + ":\n\n" + ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); if (result == DialogResult.Cancel) return; } } break; default: throw new Exception("Unknown action '" + action + "'"); } } } break; case "service": { switch (action) { case "start": { ServiceActions.Start(window, obj, false); } break; case "continue": { ServiceActions.Continue(window, obj, false); } break; case "pause": { ServiceActions.Pause(window, obj, false); } break; case "stop": { ServiceActions.Stop(window, obj, false); } break; case "delete": { ServiceActions.Delete(window, obj, true); } break; case "config": { using (ServiceHandle service = new ServiceHandle(obj, ServiceAccess.ChangeConfig)) { ServiceType serviceType; if (args["-servicetype"] == "Win32OwnProcess, InteractiveProcess") serviceType = ServiceType.Win32OwnProcess | ServiceType.InteractiveProcess; else if (args["-servicetype"] == "Win32ShareProcess, InteractiveProcess") serviceType = ServiceType.Win32ShareProcess | ServiceType.InteractiveProcess; else serviceType = (ServiceType)Enum.Parse(typeof(ServiceType), args["-servicetype"]); var startType = (ServiceStartType) Enum.Parse(typeof(ServiceStartType), args["-servicestarttype"]); var errorControl = (ServiceErrorControl) Enum.Parse(typeof(ServiceErrorControl), args["-serviceerrorcontrol"]); string binaryPath = null; string loadOrderGroup = null; string userAccount = null; string password = null; if (args.ContainsKey("-servicebinarypath")) binaryPath = args["-servicebinarypath"]; if (args.ContainsKey("-serviceloadordergroup")) loadOrderGroup = args["-serviceloadordergroup"]; if (args.ContainsKey("-serviceuseraccount")) userAccount = args["-serviceuseraccount"]; if (args.ContainsKey("-servicepassword")) password = args["-servicepassword"]; if (!Win32.ChangeServiceConfig(service, serviceType, startType, errorControl, binaryPath, loadOrderGroup, IntPtr.Zero, null, userAccount, password, null)) Win32.ThrowLastError(); } } break; default: throw new Exception("Unknown action '" + action + "'"); } } break; case "session": { int sessionId = int.Parse(obj); switch (action) { case "disconnect": { SessionActions.Disconnect(window, sessionId, false); } break; case "logoff": { SessionActions.Logoff(window, sessionId, false); } break; default: throw new Exception("Unknown action '" + action + "'"); } } break; default: throw new Exception("Unknown object type '" + type + "'"); } } catch (Exception ex) { MessageBox.Show(window, ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private static bool ElevateIfRequired(IWin32Window window, string service, ServiceAccess access, string action) { if (Properties.Settings.Default.ElevationLevel == (int)ElevationLevel.Never) return false; if (OSVersion.HasUac && Program.ElevationType == TokenElevationType.Limited) { try { using (var shandle = new ServiceHandle(service, access)) { } } catch (WindowsException ex) { DialogResult result; if (Properties.Settings.Default.ElevationLevel == (int)ElevationLevel.Elevate) { result = DialogResult.Yes; } else { TaskDialog td = new TaskDialog(); td.WindowTitle = "Process Hacker"; td.MainIcon = TaskDialogIcon.Warning; td.MainInstruction = "Do you want to elevate the action?"; td.Content = "The action cannot be performed in the current security context. " + "Do you want Process Hacker to prompt for the appropriate credentials and elevate the action?"; td.ExpandedInformation = "Error: " + ex.Message + " (0x" + ex.ErrorCode.ToString("x") + ")"; td.ExpandFooterArea = true; td.Buttons = new TaskDialogButton[] { new TaskDialogButton((int)DialogResult.Yes, "Elevate\nPrompt for credentials and elevate the action."), new TaskDialogButton((int)DialogResult.No, "Continue\nAttempt to perform the action without elevation.") }; td.CommonButtons = TaskDialogCommonButtons.Cancel; td.UseCommandLinks = true; td.Callback = (taskDialog, args, userData) => { if (args.Notification == TaskDialogNotification.Created) { taskDialog.SetButtonElevationRequiredState((int)DialogResult.Yes, true); } return false; }; result = (DialogResult)td.Show(window); } if (result == DialogResult.Yes) { Program.StartProcessHackerAdmin("-e -type service -action " + action + " -obj \"" + service + "\" -hwnd " + window.Handle.ToString(), null, window.Handle); return true; } else if (result == DialogResult.No) { return false; } else if (result == DialogResult.Cancel) { return true; } } } return false; }
public Host CreateServiceHost(HostSettings settings, ServiceHandle serviceHandle) { return new WindowsServiceHost(this, settings, serviceHandle); }
private static bool ProcessCommandLine(Dictionary<string, string> pArgs) { if (pArgs.ContainsKey("-assistant")) { Assistant.Main(pArgs); return true; } if (pArgs.ContainsKey("-e")) { try { ExtendedCmd.Run(pArgs); } catch (Exception ex) { PhUtils.ShowException("Unable to complete the operation", ex); } return true; } if (pArgs.ContainsKey("-installkph")) { try { using (ServiceManagerHandle scm = new ServiceManagerHandle(ScManagerAccess.CreateService)) { using (ServiceHandle shandle = scm.CreateService( "KProcessHacker2", "KProcessHacker2", ServiceType.KernelDriver, ServiceStartType.SystemStart, ServiceErrorControl.Ignore, Application.StartupPath + "\\kprocesshacker.sys", null, null, null )) { shandle.Start(); } } } catch (WindowsException ex) { // Need to pass status back. Environment.Exit((int)ex.ErrorCode); } return true; } if (pArgs.ContainsKey("-uninstallkph")) { try { using (ServiceHandle shandle = new ServiceHandle("KProcessHacker2", ServiceAccess.Stop | (ServiceAccess)StandardRights.Delete)) { try { shandle.Control(ServiceControl.Stop); } catch { } shandle.Delete(); } } catch (WindowsException ex) { // Need to pass status back. Environment.Exit((int)ex.ErrorCode); } return true; } if (pArgs.ContainsKey("-ip")) InspectPid = int.Parse(pArgs["-ip"]); if (pArgs.ContainsKey("-pw")) { int pid = int.Parse(pArgs["-pw"]); PrimaryProviderThread = new ProviderThread(Settings.Instance.RefreshInterval); SecondaryProviderThread = new ProviderThread(Settings.Instance.RefreshInterval); ProcessProvider = new ProcessSystemProvider(); ServiceProvider = new ServiceProvider(); PrimaryProviderThread.Add(ProcessProvider); PrimaryProviderThread.Add(ServiceProvider); ProcessProvider.Boost(); ServiceProvider.Boost(); ProcessProvider.Enabled = true; ServiceProvider.Enabled = true; Win32.LoadLibrary(Settings.Instance.DbgHelpPath); if (!ProcessProvider.Dictionary.ContainsKey(pid)) { PhUtils.ShowError("The process (PID " + pid.ToString() + ") does not exist."); Environment.Exit(0); return true; } ProcessWindow pw = new ProcessWindow(ProcessProvider.Dictionary[pid]); Application.Run(pw); PrimaryProviderThread.Dispose(); ProcessProvider.Dispose(); ServiceProvider.Dispose(); Environment.Exit(0); return true; } if (pArgs.ContainsKey("-pt")) { int pid = int.Parse(pArgs["-pt"]); try { using (var phandle = new ProcessHandle(pid, Program.MinProcessQueryRights)) Application.Run(new TokenWindow(phandle)); } catch (Exception ex) { PhUtils.ShowException("Unable to show token properties", ex); } return true; } if (pArgs.ContainsKey("-o")) { OptionsWindow options = new OptionsWindow(true) { StartPosition = FormStartPosition.CenterScreen }; IWin32Window window; if (pArgs.ContainsKey("-hwnd")) window = new WindowFromHandle(new IntPtr(int.Parse(pArgs["-hwnd"]))); else window = new WindowFromHandle(IntPtr.Zero); if (pArgs.ContainsKey("-rect")) { Rectangle rect = Utils.GetRectangle(pArgs["-rect"]); options.Location = new Point(rect.X + 20, rect.Y + 20); options.StartPosition = FormStartPosition.Manual; } options.SelectedTab = options.TabPages["tabAdvanced"]; options.ShowDialog(window); return true; } if (pArgs.ContainsKey(string.Empty)) if (pArgs[string.Empty].Replace("\"", string.Empty).Trim().EndsWith("taskmgr.exe", StringComparison.OrdinalIgnoreCase)) StartVisible = true; if (pArgs.ContainsKey("-m")) StartHidden = true; if (pArgs.ContainsKey("-v")) StartVisible = true; if (pArgs.ContainsKey("-a")) { try { Unhook(); } catch { } try { NProcessHacker.KphHookInit(); } catch { } } if (pArgs.ContainsKey("-t")) { if (pArgs["-t"] == "0") SelectTab = "Processes"; else if (pArgs["-t"] == "1") SelectTab = "Services"; else if (pArgs["-t"] == "2") SelectTab = "Network"; } return false; }
public void RemotePortTest() { ServiceHandle target = new ServiceHandle(); // TODO: 初始化为适当的值 int actual; actual = target.RemotePort; Assert.Inconclusive( "验证此测试方法的正确性。" ); }
private void buttonApply_Click(object sender, EventArgs e) { try { string serviceName = listServices.SelectedItems[0].Name; ProcessHacker.Native.Api.ServiceType type; if (comboType.SelectedItem.ToString() == "Win32OwnProcess, InteractiveProcess") type = ProcessHacker.Native.Api.ServiceType.Win32OwnProcess | ProcessHacker.Native.Api.ServiceType.InteractiveProcess; else if (comboType.SelectedItem.ToString() == "Win32ShareProcess, InteractiveProcess") type = ProcessHacker.Native.Api.ServiceType.Win32ShareProcess | ProcessHacker.Native.Api.ServiceType.InteractiveProcess; else type = (ProcessHacker.Native.Api.ServiceType) Enum.Parse(typeof(ProcessHacker.Native.Api.ServiceType), comboType.SelectedItem.ToString()); string binaryPath = textServiceBinaryPath.Text; string loadOrderGroup = textLoadOrderGroup.Text; string userAccount = textUserAccount.Text; string password = textPassword.Text; var startType = (ServiceStartType) Enum.Parse(typeof(ServiceStartType), comboStartType.SelectedItem.ToString()); var errorControl = (ServiceErrorControl) Enum.Parse(typeof(ServiceErrorControl), comboErrorControl.SelectedItem.ToString()); // Only change the items which the user modified. if (binaryPath == _oldConfig.BinaryPathName) binaryPath = null; if (loadOrderGroup == _oldConfig.LoadOrderGroup) loadOrderGroup = null; if (userAccount == _oldConfig.ServiceStartName) userAccount = null; if (!checkChangePassword.Checked) password = null; if (type == ProcessHacker.Native.Api.ServiceType.KernelDriver || type == ProcessHacker.Native.Api.ServiceType.FileSystemDriver) userAccount = null; if (Program.ElevationType == TokenElevationType.Full) { using (var shandle = new ServiceHandle(serviceName, ServiceAccess.ChangeConfig)) { if (!Win32.ChangeServiceConfig(shandle.Handle, type, startType, errorControl, binaryPath, loadOrderGroup, IntPtr.Zero, null, userAccount, password, null)) Win32.Throw(); } } else { string args = "-e -type service -action config -obj \"" + serviceName + "\" -hwnd " + this.Handle.ToString(); args += " -servicetype \"" + comboType.SelectedItem.ToString() + "\""; args += " -servicestarttype \"" + comboStartType.SelectedItem.ToString() + "\""; args += " -serviceerrorcontrol \"" + comboErrorControl.SelectedItem.ToString() + "\""; if (binaryPath != null) args += " -servicebinarypath \"" + binaryPath.Replace("\"", "\\\"") + "\""; if (loadOrderGroup != null) args += " -serviceloadordergroup \"" + loadOrderGroup.Replace("\"", "\\\"") + "\""; if (userAccount != null) args += " -serviceuseraccount \"" + userAccount.Replace("\"", "\\\"") + "\""; if (password != null) args += " -servicepassword \"" + password.Replace("\"", "\\\"") + "\""; var result = Program.StartProcessHackerAdminWait(args, this.Handle, 2000); if (result == WaitResult.Timeout || result == WaitResult.Abandoned) return; } using (var shandle = new ServiceHandle(serviceName, ServiceAccess.QueryConfig)) _provider.UpdateServiceConfig(serviceName, shandle.GetConfig()); if (listServices.Items.Count == 1) this.Close(); } catch (Exception ex) { PhUtils.ShowException("Unable to change service configuration", ex); } }