(******************************************************************************

Copyright (c) 2022+ Pepak (https://www.pepak.net)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Pepak nor the
      names of his contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL PEPAK BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************)

unit pkServices;
{$INCLUDE 'jedi.inc'}

interface

uses
  Windows, WinSvc,
  SysUtils, Classes,
  uCompatibility;

type
  TServiceState = (ssaUnknown, ssaRunning, ssaPaused, ssaStopped, ssaStartPending, ssaStopPending, ssaPausePending, ssaContinuePending);
  TServiceType = (styUnknown, styFileSystemDriver, styKernelDriver, styWin32OwnProcess, styWin32SharedProcess);
  TServiceStart = (sstUnknown, sstAuto, sstBoot, sstManual, sstSystem, sstDisabled);
  TServiceErrorControl = (secUnknown, secCritical, secSevere, secNormal, secIgnore);

  TServiceConfig = record
    ServiceType: TServiceType;
    Interactive: boolean;
    StartType: TServiceStart;
    ErrorControl: TServiceErrorControl;
    BinaryPathName: string;
    LoadOrderGroup: string;
    TagId: DWORD;
    Dependencies: string;
    ServiceStartName: string;
    DisplayName: string;
  end;

  TServiceCanStopProc = {$IFDEF UNICODE} reference to {$ENDIF} procedure(var CanStop: boolean) {$IFNDEF UNICODE} of object {$ENDIF} ;
  TServiceProc = {$IFDEF UNICODE} reference to {$ENDIF} procedure(const StopEvent: THandle) {$IFNDEF UNICODE} of object {$ENDIF} ;

  TServiceManager = class
  public
    class function Exists(const ServiceName: string): boolean;
    class function GetState(const ServiceName: string): TServiceState;
    class function GetList: TStringList;
    class function GetConfig(const ServiceName: string): TServiceConfig;
    class function GetCommandLine(const BinaryPathName: string; out Arguments: string): string;
    class function GetProcessID(const ServiceName: string): DWORD;
    class procedure Install(const ServiceName, DisplayName, CommandLine: string; const StartType: TServiceStart);
    class procedure Uninstall(const ServiceName: string);
    class procedure Start(const ServiceName: string);
    class procedure Stop(const ServiceName: string);
    class procedure Run(const ServiceProc: TServiceProc; const CanStopProc: TServiceCanStopProc = nil);
  end;

implementation

var
  ServiceIsRunning: boolean;
  RunningServiceProc: TServiceProc;
  RunningServiceStatusHandle: THandle;
  RunningServiceStatus: TServiceStatus;
  RunningServiceStopEvent: THandle;
  RunningServiceCanStopProc: TServiceCanStopProc;

procedure RunningServiceHandler(fdwControl: DWORD); stdcall;
var
  CanStop: boolean;
begin
  case fdwControl of
    SERVICE_CONTROL_INTERROGATE:
      begin
        SetServiceStatus(RunningServiceStatusHandle, RunningServiceStatus);
      end;
    SERVICE_CONTROL_STOP,
    SERVICE_CONTROL_SHUTDOWN:
      begin
        SetEvent(RunningServiceStopEvent);
        repeat
          RunningServiceStatus.dwCurrentState := SERVICE_STOP_PENDING;
          SetServiceStatus(RunningServiceStatusHandle, RunningServiceStatus);
          CanStop := True;
          if Assigned(RunningServiceCanStopProc) then
            RunningServiceCanStopProc(CanStop);
        until CanStop;
        RunningServiceStatus.dwCurrentState := SERVICE_STOPPED;
        SetServiceStatus(RunningServiceStatusHandle, RunningServiceStatus);
      end;
  end;
end;

procedure RunningServiceMain(dwArgC: DWORD; lpszArgV: PPChar); stdcall;
begin
  RunningServiceStopEvent := CreateEvent(nil, True, False, nil);
  try
    RunningServiceStatusHandle := RegisterServiceCtrlHandler('', @RunningServiceHandler);
    if RunningServiceStatusHandle = 0 then
      RaiseLastOSError;
    FillChar(RunningServiceStatus, Sizeof(RunningServiceStatus), 0);
    RunningServiceStatus.dwServiceType := SERVICE_WIN32_OWN_PROCESS;
    RunningServiceStatus.dwCurrentState := SERVICE_RUNNING;
    RunningServiceStatus.dwControlsAccepted := SERVICE_ACCEPT_STOP or SERVICE_ACCEPT_SHUTDOWN;
    RunningServiceStatus.dwWin32ExitCode := NO_ERROR;
    RunningServiceStatus.dwServiceSpecificExitCode := 0;
    RunningServiceStatus.dwCheckPoint := 0;
    RunningServiceStatus.dwWaitHint := 0;
    SetServiceStatus(RunningServiceStatusHandle, RunningServiceStatus);
    try
      if Assigned(RunningServiceProc) then
      begin
        RunningServiceProc(RunningServiceStopEvent);
      end;
    finally
      RunningServiceStatus.dwCurrentState := SERVICE_STOPPED;
      SetServiceStatus(RunningServiceStatusHandle, RunningServiceStatus);
    end;
  finally
    CloseHandle(RunningServiceStopEvent);
  end;
end;

class function TServiceManager.Exists(const ServiceName: string): boolean;
var
  ServiceManager, Service: SC_Handle;
begin
  ServiceManager := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
  if ServiceManager = 0 then
    RaiseLastOSError;
  try
    Service := OpenService(ServiceManager, PChar(ServiceName), SERVICE_QUERY_STATUS);
    if Service = 0 then
      Result := False
    else
      try
        Result := True;
      finally
        CloseServiceHandle(Service);
      end;
  finally
    CloseServiceHandle(ServiceManager);
  end;
end;

class function TServiceManager.GetCommandLine(const BinaryPathName: string; out Arguments: string): string;
var
  QuotePos, SpacePos: integer;
  PathExts: TStringList;
  PathExt, CurrentPathExt: string;
  PathExtPos: integer;
  FileName, PathPart: string;
  ExtIndex: integer;
begin
  Result := Trim(BinaryPathName);
  Arguments := '';
  if Result = '' then
    Exit;
  // If quoted, it's simple
  if Result[1] = '"' then
  begin
    Delete(Result, 1, 1);
    QuotePos := Pos('"', Result);
    if QuotePos > 0 then
    begin
      Arguments := Trim(Copy(Result, QuotePos + 1, MaxInt));
      SetLength(Result, QuotePos - 1);
    end;
    Exit;
  end;
  // If not quoted, need to find the first valid name
  PathExts := TStringList.Create;
  try
    PathExt := {$IFDEF DELPHI7_UP} SysUtils {$ELSE} uCompatibility {$ENDIF} .GetEnvironmentVariable('PATHEXT');
    while PathExt <> '' do
    begin
      PathExtPos := Pos(';', PathExt);
      if PathExtPos < 1 then
        PathExtPos := Length(PathExt) + 1;
      CurrentPathExt := Trim(Copy(PathExt, 1, PathExtPos - 1));
      if CurrentPathExt <> '' then
        PathExts.Add(CurrentPathExt);
      Delete(PathExt, 1, PathExtPos);
    end;
    if PathExts.Count = 0 then
    begin
      PathExts.Add('.EXE');
    end;
    for SpacePos := 1 to Length(Result) do
    begin
      if Result[SpacePos] <> ' ' then
        Continue;
      PathPart := Copy(Result, 1, SpacePos - 1);
      FileName := PathPart;
      ExtIndex := -1;
      repeat
        if FileExists(FileName) then
        begin
          Arguments := Trim(Copy(Result, SpacePos + 1, MaxInt));
          SetLength(Result, SpacePos - 1);
          Exit;
        end;
        Inc(ExtIndex);
        if ExtIndex >= PathExts.Count then
          Break;
        FileName := PathPart + PathExts[ExtIndex];
      until False;
    end;
  finally
    FreeAndNil(PathExts);
  end;
end;

class function TServiceManager.GetConfig(const ServiceName: string): TServiceConfig;
var
  ServiceManager, Service: SC_Handle;
  BytesNeeded: DWORD;
  Info: {$IFDEF DELPHIXE2_UP} LPQUERY_SERVICE_CONFIG {$ELSE} PQueryServiceConfig {$ENDIF} ;
  InfoSize: integer;
  OK: boolean;
begin
  ServiceManager := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
  if ServiceManager = 0 then
    RaiseLastOSError;
  try
    Service := OpenService(ServiceManager, PChar(ServiceName), SERVICE_QUERY_CONFIG);
    if Service = 0 then
      RaiseLastOSError;
    try
      InfoSize := 8192;
      GetMem(Info, InfoSize);
      try
        OK := QueryServiceConfig(Service, Info, InfoSize, BytesNeeded);
        if not OK then
        begin
          if GetLastError = ERROR_INSUFFICIENT_BUFFER then
          begin
            InfoSize := BytesNeeded;
            ReallocMem(Info, InfoSize);
            OK := QueryServiceConfig(Service, Info, InfoSize, BytesNeeded);
          end;
        end;
        if not OK then
          RaiseLastOSError;
        case (Info.dwServiceType and (not SERVICE_INTERACTIVE_PROCESS)) of
          SERVICE_FILE_SYSTEM_DRIVER:
            Result.ServiceType := styFileSystemDriver;
          SERVICE_KERNEL_DRIVER:
            Result.ServiceType := styKernelDriver;
          SERVICE_WIN32_OWN_PROCESS:
            Result.ServiceType := styWin32OwnProcess;
          SERVICE_WIN32_SHARE_PROCESS:
            Result.ServiceType := styWin32SharedProcess;
          else
            Result.ServiceType := styUnknown;
        end;
        Result.Interactive := (Info.dwServiceType and SERVICE_INTERACTIVE_PROCESS) <> 0;
        case Info.dwStartType of
          SERVICE_AUTO_START:
            Result.StartType := sstAuto;
          SERVICE_BOOT_START:
            Result.StartType := sstBoot;
          SERVICE_DEMAND_START:
            Result.StartType := sstManual;
          SERVICE_DISABLED:
            Result.StartType := sstDisabled;
          SERVICE_SYSTEM_START:
            Result.StartType := sstSystem;
          else
            Result.StartType := sstUnknown;
        end;
        case Info.dwErrorControl of
          SERVICE_ERROR_CRITICAL:
            Result.ErrorControl := secCritical;
          SERVICE_ERROR_IGNORE:
            Result.ErrorControl := secIgnore;
          SERVICE_ERROR_NORMAL:
            Result.ErrorControl := secNormal;
          SERVICE_ERROR_SEVERE:
            Result.ErrorControl := secSevere;
          else
            Result.ErrorControl := secUnknown;
        end;
        Result.BinaryPathName := string(Info.lpBinaryPathName);
        Result.LoadOrderGroup := string(Info.lpLoadOrderGroup);
        Result.TagId := Info.dwTagId;
        Result.Dependencies := string(Info.lpDependencies);
        Result.ServiceStartName := string(Info.lpServiceStartName);
        Result.DisplayName := string(Info.lpDisplayName);
      finally
        FreeMem(Info);
      end;
    finally
      CloseServiceHandle(Service);
    end;
  finally
    CloseServiceHandle(ServiceManager);
  end;
end;

class function TServiceManager.GetList: TStringList;
var
  ServiceManager: SC_Handle;
  ServiceStatusBuffer, CurrentService: PEnumServiceStatus;
  ServiceStatusBufferSize, BytesNeeded, ServiceCount: DWORD;
  ResumeHandle: DWORD;
  OK: boolean;
begin
  Result := TStringList.Create;
  try
    ServiceManager := OpenSCManager(nil, nil, SC_MANAGER_CONNECT or SC_MANAGER_ENUMERATE_SERVICE);
    if ServiceManager = 0 then
      RaiseLastOSError;
    try
      ResumeHandle := 0;
      ServiceStatusBufferSize := 65536;
      GetMem(ServiceStatusBuffer, ServiceStatusBufferSize);
      try
        repeat
          OK := EnumServicesStatus(ServiceManager, SERVICE_WIN32, SERVICE_ACTIVE or SERVICE_INACTIVE, ServiceStatusBuffer {$IFNDEF DELPHI27_UP} ^ {$ENDIF} , ServiceStatusBufferSize, BytesNeeded, ServiceCount, ResumeHandle);
          if not OK then
          begin
            if GetLastError = ERROR_MORE_DATA then
            begin
              ServiceStatusBufferSize := BytesNeeded;
              ReallocMem(ServiceStatusBuffer, ServiceStatusBufferSize);
              OK := EnumServicesStatus(ServiceManager, SERVICE_WIN32, SERVICE_ACTIVE or SERVICE_INACTIVE, ServiceStatusBuffer {$IFNDEF DELPHI27_UP} ^ {$ENDIF} , ServiceStatusBufferSize, BytesNeeded, ServiceCount, ResumeHandle);
            end;
          end;
          if not OK then
            RaiseLastOSError;
          CurrentService := ServiceStatusBuffer;
          while ServiceCount > 0 do
          begin
            Result.Add(CurrentService.lpServiceName);
            Inc(CurrentService);
            Dec(ServiceCount);
          end;
        until (not OK) or (ResumeHandle = 0);
      finally
        FreeMem(ServiceStatusBuffer);
      end;
    finally
      CloseServiceHandle(ServiceManager);
    end;
  except
    FreeAndNil(Result);
    Raise;
  end;
end;

{$IFNDEF UNICODE}
type
  SC_STATUS_TYPE = DWORD;
const
  SC_STATUS_PROCESS_INFO = 0;

function QueryServiceStatusEx(hService: SC_HANDLE; InfoLevel: SC_STATUS_TYPE; lpBuffer: PByte; cbBufSize: DWORD; var pcbBytesNeeded: DWORD): BOOL; stdcall; external 'advapi32.dll' name 'QueryServiceStatusEx';
{$ENDIF}

class function TServiceManager.GetProcessID(const ServiceName: string): DWORD;
type
  PServiceStatusProcess = ^TServiceStatusProcess;
  TServiceStatusProcess = record
    dwServiceType: DWORD;
    dwCurrentState: DWORD;
    dwControlsAccepted: DWORD;
    dwWin32ExitCode: DWORD;
    dwServiceSpecificExitCode: DWORD;
    dwCheckPoint: DWORD;
    dwWaitHint: DWORD;
    dwProcessId: DWORD;
    dwServiceFlags: DWORD;
  end;
var
  ServiceManager, Service: SC_Handle;
  ServiceStatus: PServiceStatusProcess;
  BytesNeeded: DWORD;
begin
  ServiceManager := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
  if ServiceManager = 0 then
    RaiseLastOSError;
  try
    Service := OpenService(ServiceManager, PChar(ServiceName), SERVICE_QUERY_STATUS);
    if Service = 0 then
      RaiseLastOSError;
    try
      BytesNeeded := 0;
      QueryServiceStatusEx(Service, SC_STATUS_PROCESS_INFO, nil, BytesNeeded, BytesNeeded);
      if BytesNeeded = 0 then
        RaiseLastOSError;
      GetMem(ServiceStatus, BytesNeeded);
      try
        if not QueryServiceStatusEx(Service, SC_STATUS_PROCESS_INFO, PByte(ServiceStatus), BytesNeeded, BytesNeeded) then
          RaiseLastOSError;
        Result := ServiceStatus^.dwProcessId;
      finally
        FreeMem(ServiceStatus);
      end;
    finally
      CloseServiceHandle(Service);
    end;
  finally
    CloseServiceHandle(ServiceManager);
  end;
end;

class function TServiceManager.GetState(const ServiceName: string): TServiceState;
const
  SERVICE_ERROR = $ffffffff;
  SERVICE_STOPPED = 1;
  SERVICE_START_PENDING = 2;
  SERVICE_STOP_PENDING = 3;
  SERVICE_RUNNING = 4;
  SERVICE_CONTINUE_PENDING = 5;
  SERVICE_PAUSE_PENDING = 6;
  SERVICE_PAUSED = 7;
var
  ServiceManager, Service: SC_Handle;
  ServiceStatus: SERVICE_STATUS;
begin
  Result := ssaUnknown;
  ServiceManager := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
  if ServiceManager = 0 then
    RaiseLastOSError;
  try
    Service := OpenService(ServiceManager, PChar(ServiceName), SERVICE_QUERY_STATUS);
    if Service = 0 then
      RaiseLastOSError;
    try
      if QueryServiceStatus(Service, ServiceStatus) then
      begin
        case ServiceStatus.dwCurrentState of
          1: Result := ssaStopped;
          2: Result := ssaStartPending;
          3: Result := ssaStopPending;
          4: Result := ssaRunning;
          5: Result := ssaContinuePending;
          6: Result := ssaPausePending;
          7: Result := ssaPaused;
        end;
      end;
    finally
      CloseServiceHandle(Service);
    end;
  finally
    CloseServiceHandle(ServiceManager);
  end;
end;

class procedure TServiceManager.Install(const ServiceName, DisplayName, CommandLine: string; const StartType: TServiceStart);
var
  ServiceManager, Service: SC_Handle;
  NativeStartType: DWORD;
begin
  case StartType of
    sstAuto:
      NativeStartType := SERVICE_AUTO_START;
    sstBoot:
      NativeStartType := SERVICE_BOOT_START;
    sstManual:
      NativeStartType := SERVICE_DEMAND_START;
    sstSystem:
      NativeStartType := SERVICE_SYSTEM_START;
    sstDisabled:
      NativeStartType := SERVICE_DISABLED;
    else
      NativeStartType := SERVICE_DEMAND_START;
  end;
  ServiceManager := OpenSCManager(nil, nil, SC_MANAGER_CONNECT or SC_MANAGER_CREATE_SERVICE);
  if ServiceManager = 0 then
    RaiseLastOSError;
  try
    Service := CreateService(ServiceManager, PChar(ServiceName), PChar(DisplayName), SC_MANAGER_CREATE_SERVICE , SERVICE_WIN32_OWN_PROCESS, NativeStartType, SERVICE_ERROR_NORMAL, PChar(CommandLine), nil, nil, nil, nil, nil);
    if Service = 0 then
      RaiseLastOSError;
    try
      // nothing to do
    finally
      CloseServiceHandle(Service);
    end;
  finally
    CloseServiceHandle(ServiceManager);
  end;
end;

class procedure TServiceManager.Run(const ServiceProc: TServiceProc; const CanStopProc: TServiceCanStopProc);
var
  ServiceTable: array[0..1] of TServiceTableEntry;
begin
  if ServiceIsRunning then
    raise Exception.Create('Cannot run multiple services');
  ServiceIsRunning := True;
  RunningServiceProc := ServiceProc;
  RunningServiceCanStopProc := CanStopProc;
  ServiceTable[0].lpServiceName := '';
  ServiceTable[0].lpServiceProc := @RunningServiceMain;
  ServiceTable[1].lpServiceName := nil;
  ServiceTable[1].lpServiceProc := nil;
  if not StartServiceCtrlDispatcher(ServiceTable[0]) then
    RaiseLastOSError;
end;

class procedure TServiceManager.Start(const ServiceName: string);
var
  ServiceManager, Service: SC_Handle;
  ArgVectors: PChar;
begin
  ServiceManager := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
  if ServiceManager = 0 then
    RaiseLastOSError;
  try
    Service := OpenService(ServiceManager, PChar(ServiceName), SERVICE_START);
    if Service = 0 then
      RaiseLastOSError;
    try
      ArgVectors := nil;
      if not StartService(Service, 0, ArgVectors) then
        RaiseLastOSError;
    finally
      CloseServiceHandle(Service);
    end;
  finally
    CloseServiceHandle(ServiceManager);
  end;
end;

class procedure TServiceManager.Stop(const ServiceName: string);
var
  ServiceManager, Service: SC_Handle;
  ServiceStatus: SERVICE_STATUS;
begin
  ServiceManager := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
  if ServiceManager = 0 then
    RaiseLastOSError;
  try
    Service := OpenService(ServiceManager, PChar(ServiceName), SERVICE_STOP);
    if Service = 0 then
      RaiseLastOSError;
    try
      if not ControlService(Service, SERVICE_CONTROL_STOP, ServiceStatus) then
        RaiseLastOSError;
    finally
      CloseServiceHandle(Service);
    end;
  finally
    CloseServiceHandle(ServiceManager);
  end;
end;

class procedure TServiceManager.Uninstall(const ServiceName: string);
var
  ServiceManager, Service: SC_Handle;
begin
  ServiceManager := OpenSCManager(nil, nil, SC_MANAGER_CONNECT or _DELETE);
  if ServiceManager = 0 then
    RaiseLastOSError;
  try
    Service := OpenService(ServiceManager, PChar(ServiceName), _DELETE);
    if Service = 0 then
      RaiseLastOSError;
    try
      if not DeleteService(Service) then
        RaiseLastOSError;
    finally
      CloseServiceHandle(Service);
    end;
  finally
    CloseServiceHandle(ServiceManager);
  end;
end;

initialization
  ServiceIsRunning := False;

end.
