-
Notifications
You must be signed in to change notification settings - Fork 3
/
Windows.ServiceManager.pas
1283 lines (1077 loc) · 34.9 KB
/
Windows.ServiceManager.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit Windows.ServiceManager;
{ --------------------------------------------------------------------------- }
{ }
{ Written with }
{ - Delphi XE3 Pro }
{ - Refactored with 11.2 }
{ }
{ Created Nov 24, 2012 by Darian Miller }
{ - Some refactoring etc by Tommi Prami }
{ }
{ Based on answer by Ritsaert Hornstra on May 6, 2011 to question: }
{ - http://stackoverflow.com/questions/5913279/detect-windows-service-state }
{ - https://stackoverflow.com/users/246383/ritsaert-hornstra (Thanks man) }
{ }
{ --------------------------------------------------------------------------- }
interface
uses
Winapi.Windows, Winapi.Winsvc, System.Generics.Collections, System.SysUtils, Windows.ServiceManager.Types;
type
// Forward declaration of Service manager class
TServiceManager = class;
{ Gives information of and controls a single Service. Can be accessed via @link(TServiceManager). }
TServiceInfo = class(TObject)
private
FBinaryPathName: string;
FCommandLine: string;
FConfigQueried: Boolean;
FDisplayName: string;
FFileName: string;
FIndex: Integer;
FInteractive: Boolean;
FLive: Boolean;
FOwnProcess: Boolean;
FPath: string;
FServiceHandle: SC_HANDLE;
FServiceHandleAccess: DWORD;
FServiceManager: TServiceManager;
FServiceName: string;
FServiceStatus: TServiceStatus;
FStartType: TServiceStartup;
FUserName: string;
function DependenciesToList(const AQServicesStatus: PEnumServiceStatus; const AServiceInfoCount: Integer): TArray<TServiceInfo>;
function GetBinaryPathname: string;
function GetCommandLine: string;
function GetFileName: string;
function GetHandle(const AAccess: DWORD): Boolean;
function GetInteractive: Boolean;
function GetOwnProcess: Boolean;
function GetPath: string;
function GetServiceAccepts: TServiceAccepts;
function GetServiceStartType(const AServiceConfig: QUERY_SERVICE_CONFIG; var AStartType: TServiceStartup): Boolean;
function GetStartType: TServiceStartup;
function GetState: TServiceState;
function HandleOK: Boolean;
function Query: Boolean;
function QueryConfig: Boolean;
function WaitFor(const AState: DWORD): Boolean;
function WaitForPendingServiceState(const AServiceState: TServiceState): Boolean;
procedure CleanupHandle;
procedure ParseBinaryPath;
procedure RefreshIfNeeded;
procedure SetStartType(const AValue: TServiceStartup);
procedure SetState(const AServiceState: TServiceState);
protected
function InitializeByName(const AServiceName: string): Boolean;
public
constructor Create(const AParentServiceManager: TServiceManager);
destructor Destroy; override;
{ Get array of services that depent on this service }
function Dependents: TArray<TServiceInfo>;
{ Action: Pause a running service. }
function Pause(const AWait: Boolean = True): Boolean;
{ Action: Continue a paused service. }
function Continue(const AWait: Boolean = True): Boolean;
{ Action: Stop a running service. }
function Stop(const AWait: Boolean = True): Boolean;
{ Action: Start a not running service.
You can use the @link(State) property to change the state from ssStopped to ssRunning }
function Start(const AWait: Boolean = True): Boolean;
{ Name of this service. }
property Name: string read FServiceName;
{ Display name of this service }
property DisplayName: string read FDisplayName;
{ The current state of the service. You can set the service only to the non-transitional states.
You can restart the service by first setting the State to first ssStopped and second ssRunning. }
property State: TServiceState read GetState write SetState;
{ Are various properties using live information or historic information. }
property Live: Boolean read FLive write FLive;
{ When service is running, does it run as a separate process (own process) or combined with
other services under svchost. }
property OwnProcess: Boolean read GetOwnProcess;
{ Is the service capable of interacting with the desktop.
Possible: The logon must the Local System Account. }
property Interactive: Boolean read GetInteractive;
{ How is this service started. See @link(TServiceStartup) for a description of startup types.
If you want to set this property, the manager must be activeted with AllowLocking set to True. }
property StartType: TServiceStartup read GetStartType write SetStartType;
{ Path to the binary that implements the service. }
property BinaryPathName: string read GetBinaryPathName;
property Path: string read GetPath;
property FileName: string read GetFileName;
property CommandLine: string read GetCommandLine;
{ See what controls the service accepts. }
property ServiceAccepts: TServiceAccepts read GetServiceAccepts;
{ Index in ServiceManagers list }
property Index: Integer read FIndex write FIndex;
{ }
property UserName: string read FUserName;
end;
{ A service manager allows the services of a particular machine to be explored and modified. }
TServiceManager = class(TObject)
strict private
FAllowLocking: Boolean;
FGetServiceListOnActive: Boolean;
FLastErrorCode: Integer;
FLastErrorMessage: string;
FLastSystemErrorCode: DWord;
FLastSystemErrorMessage: string;
FLockHandle: SC_LOCK;
FHostName: string;
FManagerHandle: SC_HANDLE;
FRaiseExceptions: Boolean;
FServicesByName: TDictionary<string, TServiceInfo>;
FServicesList: TObjectList<TServiceInfo>;
function CheckOS: Boolean;
function GetActive: Boolean;
function GetService(const AIndex: Integer): TServiceInfo;
function GetServiceCount: Integer;
function InitializeSingleService(const AServiceName: string): TServiceInfo;
procedure AddServiceInfoToLists(const AServiceInfo: TServiceInfo);
procedure CleanupServices;
procedure EnumerateAndAddServices(const AServices: PEnumServiceStatus; const AByesNeeded: DWORD);
procedure ServiceToLists(const AServiceEnumStatus: ENUM_SERVICE_STATUS);
procedure SetActive(const ASetToActive: Boolean);
procedure SetAllowLocking(const AValue: Boolean);
procedure SetHostName(const AHostName: string);
private
function GetError: Boolean;
function GetErrorMessage: string;
protected
{ using classic protected visibility to give TServiceInfo access to TServiceManager services that nare not public }
function GetManagerHandle: SC_HANDLE;
function Lock: Boolean;
function Unlock: Boolean;
procedure HandleError(const AErrorCode: Integer; const AForceException: Boolean = False);
procedure ResetLastError;
procedure SortArray(var AServiceInfoArray: TArray<TServiceInfo>);
public
constructor Create(const AHostName: string = ''; const AGetServiceListOnActive: Boolean = True;
const ARaiseExceptions: Boolean = True; const AAllowLocking: Boolean = False);
destructor Destroy; override;
// Begin- and EndLockingProcess, so can easily do propcess between try..finally, which need locking
procedure BeginLockingProcess(const AActivateServiceManager: Boolean = True);
procedure EndLockingProcess;
//
function Open: Boolean;
function Close: Boolean;
{ Requeries the states, names etc of all services on the given @link(HostName).
Works only while active. }
function RebuildServicesList: Boolean;
{ Find services by name (case insensitive). Works only while active. If no service can be found
an exception will be raised. }
function ServiceByName(const AServiceName: string; const AAllowUnkown: Boolean = False): TServiceInfo;
{ Get array of services, sorted by display name, Serrvice manager owns objects, so handle with care. }
function GetServicesByDisplayName: TArray<TServiceInfo>;
{ Delete a service... }
// procedure DeleteService(Index: Integer);
{ Get the number of services. This number is refreshed when the @link(Active) is
set to True or @link(RebuildServicesList) is called. Works only while active. }
property ServiceCount: Integer read GetServiceCount;
{ Find a servce by index in the services list. This list is refreshed when the @link(Active) is
set to True or @link(RebuildServicesList) is called. Works only while active. Valid Index
values are 0..@link(ServiceCount) - 1. }
property Services[const AIndex: Integer]: TServiceInfo read GetService;
{ Activate / deactivate the service manager. In active state can you access the individual
service, check RaiseExceptions property and open and close methods, thiose will affect on how this property
works }
property Active: Boolean read GetActive write SetActive;
{ The machine name for which you want the services list. }
property HostName: string read FHostName write SetHostName;
{ Allow locking... Is needed only when changing several properties in TServiceInfo.
Property can only be set while inactive. }
property AllowLocking: Boolean read FAllowLocking write SetAllowLocking;
{ Raise Exceptions, if all functions should return False if it fails, then more info at Last*Error* properties}
property RaiseExceptions: Boolean read FRaiseExceptions write FRaiseExceptions;
// Error properties, check HandleError()
property Error: Boolean read GetError;
property ErrorMessage: string read GetErrorMessage;
property LastErrorCode: Integer read FLastErrorCode;
property LastSystemErrorCode: DWord read FLastSystemErrorCode;
property LastSystemErrorMessage: string read FLastSystemErrorMessage;
property LastErrorMessage: string read FLastErrorMessage;
property GetServiceListOnActive: Boolean read FGetServiceListOnActive write FGetServiceListOnActive;
end;
function ServiceStateToString(const AServiceState: TServiceState): string;
implementation
uses
System.Generics.Defaults, System.SysConst, Windows.ServiceManager.Consts;
function ServiceStateToString(const AServiceState: TServiceState): string;
begin
// TODO: Should make this easier to localize, if needed.
case AServiceState of
ssStopped: Result := 'Stopped';
ssStartPending: Result := 'Starting...';
ssStopPending: Result := 'Stopping...';
ssRunning: Result := 'Running';
ssContinuePending: Result := 'Continuing...';
ssPausePending: Result := 'Pausing...';
ssPaused: Result := 'Paused';
end;
end;
{ TServiceManager }
function TServiceManager.RebuildServicesList: Boolean;
var
LServices: PEnumServiceStatus;
LBytesNeeded: DWORD;
LServicesReturned: DWORD;
LResumeHandle: DWORD;
begin
Result := False;
if not Active then
begin
HandleError(SERVICELIST_NOT_ACTIVE);
Exit;
end;
// Cleanup
ResetLastError;
CleanupServices;
LServicesReturned := 0;
LResumeHandle := 0;
LServices := nil;
// Get the amount of memory needed...
if EnumServicesStatus(FManagerHandle, SERVICE_WIN32, SERVICE_STATE_ALL, LServices, 0, LBytesNeeded, LServicesReturned,
LResumeHandle) then
Exit;
if GetLastError <> ERROR_MORE_DATA then
begin
HandleError(LAST_OS_ERROR);
Exit;
end;
GetMem(LServices, LBytesNeeded); // will raise EOutOfMemory if fails
try
EnumerateAndAddServices(LServices, LBytesNeeded);
finally
FreeMem(LServices);
end;
Result := True;
end;
procedure TServiceManager.ResetLastError;
begin
FLastErrorCode := 0;
FLastSystemErrorCode := 0;
FLastErrorMessage := '';
FLastSystemErrorMessage := '';
end;
procedure TServiceManager.AddServiceInfoToLists(const AServiceInfo: TServiceInfo);
begin
AServiceInfo.FIndex := FServicesList.Add(AServiceInfo);
FServicesByName.Add(AServiceInfo.FServiceName.ToLower, AServiceInfo);
end;
procedure TServiceManager.BeginLockingProcess(const AActivateServiceManager: Boolean = True);
begin
AllowLocking := True;
if not Active and AActivateServiceManager then
Active := True;
end;
function TServiceManager.CheckOS: Boolean;
var
LVersionInfo: TOSVersionInfo;
begin
Result := False;
// Check that we are NT, 2000, XP or above...
LVersionInfo.dwOSVersionInfoSize := SizeOf(LVersionInfo);
if not GetVersionEx(LVersionInfo) then
begin
HandleError(LAST_OS_ERROR);
Exit;
end;
if LVersionInfo.dwPlatformId <> VER_PLATFORM_WIN32_NT then
begin
HandleError(OS_NOT_CUPPOORTED);
Exit;
end;
Result := True;
end;
procedure TServiceManager.CleanupServices;
begin
FServicesList.Clear;
FServicesByName.Clear;
end;
function TServiceManager.Close: Boolean;
begin
if not Active then
Exit(True);
Result := False;
ResetLastError;
CleanupServices;
if Assigned(FLockHandle) then
if not Unlock then
Exit;
CloseServiceHandle(FManagerHandle);
FManagerHandle := 0;
Result := not GetActive;
end;
constructor TServiceManager.Create(const AHostName: string = ''; const AGetServiceListOnActive: Boolean = True;
const ARaiseExceptions: Boolean = True; const AAllowLocking: Boolean = False);
begin
inherited Create;
FServicesList := TObjectList<TServiceInfo>.Create(True);
FServicesByName := TDictionary<string, TServiceInfo>.Create;
ResetLastError;
FManagerHandle := 0;
FHostName := AHostName;
FRaiseExceptions := ARaiseExceptions;
FGetServiceListOnActive := AGetServiceListOnActive;
FAllowLocking := AAllowLocking;
end;
destructor TServiceManager.Destroy;
begin
Active := False;
FServicesList.Free;
FServicesByName.Free;
inherited Destroy;
end;
procedure TServiceManager.EndLockingProcess;
begin
if Active then
Active := False;
AllowLocking := False;
end;
procedure TServiceManager.EnumerateAndAddServices(const AServices: PEnumServiceStatus; const AByesNeeded: DWORD);
var
LIndex: DWORD;
LServicesLoopPointer: PEnumServiceStatus;
LServicesReturned: DWORD;
LResumeHandle: DWORD;
LBytesNeeded: DWORD;
begin
LServicesReturned := 0;
LResumeHandle := 0;
LBytesNeeded := AByesNeeded;
if not EnumServicesStatus(FManagerHandle, SERVICE_WIN32, SERVICE_STATE_ALL, AServices, LBytesNeeded, LBytesNeeded,
LServicesReturned, LResumeHandle) then
Exit;
LServicesLoopPointer := AServices;
LIndex := 0;
while LIndex <= LServicesReturned - 1 do
begin
ServiceToLists(LServicesLoopPointer^);
Inc(LServicesLoopPointer);
Inc(LIndex);
end;
end;
function TServiceManager.GetActive: Boolean;
begin
Result := FManagerHandle <> 0;
end;
function TServiceManager.GetError: Boolean;
begin
Result := (FLastErrorCode <> 0) or (FLastSystemErrorCode <> 0);
end;
function TServiceManager.GetErrorMessage: string;
begin
Result := '';
if FLastErrorCode <> 0 then
Result := Format('Error (%d) with message:', [FLastErrorCode, FLastErrorMessage])
else if FLastSystemErrorCode <> 0 then
Result := Format('System error (%d) with message:', [FLastSystemErrorCode, FLastSystemErrorMessage]);
end;
function TServiceManager.GetManagerHandle: SC_HANDLE;
begin
Result := FManagerHandle;
end;
function TServiceManager.GetService(const AIndex: Integer): TServiceInfo;
begin
Result := FServicesList[AIndex];
end;
function TServiceManager.ServiceByName(const AServiceName: string; const AAllowUnkown: Boolean = False): TServiceInfo;
begin
if not FServicesByName.TryGetValue(AServiceName.ToLower, Result) then
begin
Result := nil;
if not FGetServiceListOnActive then
begin
if not Active then
begin
HandleError(SERVICELIST_NOT_ACTIVE);
Exit;
end;
Result := InitializeSingleService(AServiceName);
if Assigned(Result) then
AddServiceInfoToLists(Result);
end;
if not AAllowUnkown and not Assigned(Result) then
HandleError(SERVICE_NOT_FOUND);
end;
end;
function TServiceManager.GetServiceCount: Integer;
begin
Result := FServicesList.Count;
end;
function TServiceManager.GetServicesByDisplayName: TArray<TServiceInfo>;
begin
Result := FServicesList.ToArray;
SortArray(Result);
end;
procedure TServiceManager.HandleError(const AErrorCode: Integer; const AForceException: Boolean = False);
var
LErrorInfo: TErrorInfo;
LOSError: EOSError;
begin
if AErrorCode = LAST_OS_ERROR then
begin
FLastSystemErrorCode := GetLastError;
if FLastSystemErrorCode <> 0 then
FLastSystemErrorMessage := SysErrorMessage(FLastSystemErrorCode)
else
FLastSystemErrorMessage := SUnkOSError;
if FRaiseExceptions or AForceException then
begin
if FLastSystemErrorCode <> 0 then
LOSError := EOSError.CreateResFmt(@SOSError, [FLastSystemErrorCode, FLastSystemErrorMessage, ''])
else
LOSError := EOSError.CreateRes(@SUnkOSError);
LOSError.ErrorCode := FLastSystemErrorCode;
raise LOSError at ReturnAddress;
end;
end
else
begin
FLastErrorCode := AErrorCode;
LErrorInfo := ErrorInfoArray[AErrorCode - 1];
FLastErrorMessage := LErrorInfo.ErrorMessage;
if FRaiseExceptions or AForceException then
raise LErrorInfo.ExceptionClass.Create(FLastErrorMessage) at ReturnAddress;
end;
end;
function TServiceManager.InitializeSingleService(const AServiceName: string): TServiceInfo;
begin
Result := TServiceInfo.Create(Self);
try
if not Result.InitializeByName(AServiceName) then
FreeAndNil(Result);
except
FreeAndNil(Result);
end;
end;
procedure TServiceManager.ServiceToLists(const AServiceEnumStatus: ENUM_SERVICE_STATUS);
var
LServiceInfo: TServiceInfo;
begin
LServiceInfo := TServiceInfo.Create(Self);
LServiceInfo.FServiceName := AServiceEnumStatus.lpServiceName;
LServiceInfo.FDisplayName := AServiceEnumStatus.lpDisplayName;
LServiceInfo.FServiceStatus := AServiceEnumStatus.ServiceStatus;
AddServiceInfoToLists(LServiceInfo);
end;
procedure TServiceManager.SetActive(const ASetToActive: Boolean);
begin
if ASetToActive then
Open
else
Close;
end;
procedure TServiceManager.SetHostName(const AHostName: string);
begin
if Active then
begin
HandleError(IS_ACTIVE);
Exit;
end;
FHostName := AHostName;
end;
procedure TServiceManager.SortArray(var AServiceInfoArray: TArray<TServiceInfo>);
begin
TArray.Sort<TServiceInfo>(AServiceInfoArray, TDelegatedComparer<TServiceInfo>.Construct(
function(const ALeft, ARight:TServiceInfo): Integer
begin
Result := TComparer<string>.Default.Compare(ALeft.DisplayName, ARight.DisplayName);
end)
);
end;
(*
procedure TServiceManager.DeleteService(Index: Integer);
begin
// todo: implementation
raise Exception.Create('Not implemented');
end;
*)
function TServiceManager.Lock: Boolean;
begin
Result := False;
if not FAllowLocking then
begin
HandleError(LOCKING_NOT_ALLOWED);
Exit;
end;
ResetLastError;
FLockHandle := LockServiceDatabase(FManagerHandle);
if FLockHandle = nil then
begin
HandleError(LAST_OS_ERROR);
Exit;
end
else
Result := True;
end;
function TServiceManager.Open: Boolean;
var
LDesiredAccess: DWORD;
begin
if Active then
Exit(True);
Result := False;
ResetLastError;
if not CheckOS then
Exit;
// Open service manager
LDesiredAccess := SC_MANAGER_CONNECT or SC_MANAGER_ENUMERATE_SERVICE;
if FAllowLocking then
Inc(LDesiredAccess, SC_MANAGER_LOCK);
FManagerHandle := OpenSCManager(PChar(FHostName), nil, LDesiredAccess);
if not Active then
begin
HandleError(LAST_OS_ERROR);
Exit;
end;
// Fetch the srvices list
Result := GetActive;
if Result and FGetServiceListOnActive then
Result := RebuildServicesList;
end;
function TServiceManager.Unlock: Boolean;
begin
// We are unlocked already
if FLockHandle = nil then
Exit(True);
Result := False;
ResetLastError;
// Unlock...
if not UnlockServiceDatabase(FLockHandle) then
begin
HandleError(LAST_OS_ERROR);
Exit;
end;
FLockHandle := nil;
Result := FLockHandle = nil;
end;
procedure TServiceManager.SetAllowLocking(const AValue: Boolean);
begin
if Active then
begin
HandleError(OPERATION_NOT_ALLOWED_WHILE_ACTIVE);
Exit;
end;
FAllowLocking := AValue;
end;
{ TServiceInfo }
procedure TServiceInfo.CleanupHandle;
begin
if FServiceHandle = 0 then
Exit;
CloseServiceHandle(FServiceHandle);
FServiceHandle := 0;
FServiceHandleAccess := 0;
end;
constructor TServiceInfo.Create(const AParentServiceManager: TServiceManager);
begin
inherited Create;
FServiceManager := AParentServiceManager;
FConfigQueried := False;
FServiceHandle := 0;
FServiceHandleAccess := 0;
FLive := False;
end;
function TServiceInfo.DependenciesToList(const AQServicesStatus: PEnumServiceStatus; const AServiceInfoCount: Integer): TArray<TServiceInfo>;
var
LServiceName: string;
LIndex: Integer;
LLoopStatusPointer: PEnumServiceStatus;
LServiceInfo: TServiceInfo;
LDependentSerevices: TList<TServiceInfo>;
begin
Result := [];
LDependentSerevices := TList<TServiceInfo>.Create;
try
LLoopStatusPointer := AQServicesStatus;
LIndex := 0;
while LIndex <= AServiceInfoCount - 1 do
begin
LServiceName := LLoopStatusPointer^.lpServiceName;
{ Here we have weird issue.
Getting dependencies of "Windows audio" -service.
we get dirrent name (AarSvc) than than expected AudioEndpointBuilder for the
"Windows Audio Endpoint Builder" - service, hence True parameter for ServiceByName call.
This is about, Agent Activation Runtime (AarSvc) Service, maybe it is not true service some how,
but possible, did not dig up info. Services manager shows 3 dependencies, two of them is returned
here as expected.
So we need to have the True parameter at ServiceByName call, that there might be service name
that could not be found. Until fixed, if even possible.
}
LServiceInfo := FServiceManager.ServiceByName(LServiceName, True);
if Assigned(LServiceInfo) then
LDependentSerevices.Add(LServiceInfo);
Inc(LLoopStatusPointer);
Inc(LIndex);
end;
Result := LDependentSerevices.ToArray;
FServiceManager.SortArray(Result);
finally
LDependentSerevices.Free;
end;
end;
function TServiceInfo.Dependents: TArray<TServiceInfo>;
var
LServicesStatus: PEnumServiceStatus;
LBytesNeeded: DWORD;
LServicesReturned: DWORD;
begin
Result := [];
if GetHandle(SERVICE_ENUMERATE_DEPENDENTS) then
try
// See how many dependents we have...
LServicesStatus := nil;
LBytesNeeded := 0;
LServicesReturned := 0;
if EnumDependentServices(FServiceHandle, SERVICE_ACTIVE + SERVICE_INACTIVE, LServicesStatus, 0, LBytesNeeded,
LServicesReturned) then
Exit;
if GetLastError <> ERROR_MORE_DATA then
begin
FServiceManager.HandleError(LAST_OS_ERROR);
Exit;
end;
// Allocate the buffer needed and fetch all info...
GetMem(LServicesStatus, LBytesNeeded);
try
if not EnumDependentServices(FServiceHandle, SERVICE_ACTIVE + SERVICE_INACTIVE, LServicesStatus, LBytesNeeded,
LBytesNeeded, LServicesReturned) then
begin
FServiceManager.HandleError(LAST_OS_ERROR);
Exit;
end;
Result := DependenciesToList(LServicesStatus, LServicesReturned);
finally
FreeMem(LServicesStatus);
end;
finally
CleanupHandle;
end;
end;
destructor TServiceInfo.Destroy;
begin
CleanupHandle;
inherited Destroy;
end;
function TServiceInfo.GetHandle(const AAccess: DWORD): Boolean;
begin
if HandleOK then
begin
if AAccess = FServiceHandleAccess then
Exit(True)
else
begin
FServiceManager.HandleError(SERVICE_ACCESS_DIFFERS);
Exit(False);
end;
end;
FServiceManager.ResetLastError;
FServiceHandle := OpenService(FServiceManager.GetManagerHandle, PChar(FServiceName), AAccess);
Result := HandleOK;
if not Result then
begin
FServiceManager.HandleError(LAST_OS_ERROR);
Exit;
end
else
FServiceHandleAccess := AAccess;
end;
function TServiceInfo.GetState: TServiceState;
begin
if FLive then
Query;
case FServiceStatus.dwCurrentState of
SERVICE_STOPPED: Result := ssStopped;
SERVICE_START_PENDING: Result := ssStartPending;
SERVICE_STOP_PENDING: Result := ssStopPending;
SERVICE_RUNNING: Result := ssRunning;
SERVICE_CONTINUE_PENDING: Result := ssContinuePending;
SERVICE_PAUSE_PENDING: Result := ssPausePending;
SERVICE_PAUSED: Result := ssPaused;
else
begin
FServiceManager.HandleError(SERVICE_STATE_UNKNOWN, True);
Result := ssStopped; // Make compiler happy
end;
end;
end;
function TServiceInfo.HandleOK: Boolean;
begin
Result := FServiceHandle <> 0;
end;
function TServiceInfo.InitializeByName(const AServiceName: string): Boolean;
begin
FServiceName := AServiceName;
Result := QueryConfig;
if Result then
Result := Query;
end;
function TServiceInfo.Query: Boolean;
var
LStatus: TServiceStatus;
begin
Result := False;
FServiceManager.ResetLastError;
if HandleOK then
begin
if not QueryServiceStatus(FServiceHandle, LStatus) then
begin
FServiceManager.HandleError(LAST_OS_ERROR);
Exit;
end;
end
else
begin
if not GetHandle(SERVICE_QUERY_STATUS) then
Exit;
try
if not QueryServiceStatus(FServiceHandle, LStatus) then
begin
FServiceManager.HandleError(LAST_OS_ERROR);
Exit;
end;
finally
CleanupHandle;
end;
end;
FServiceStatus := LStatus;
Result := True;
end;
function TServiceInfo.Continue(const AWait: Boolean = True): Boolean;
var
LStatus: TServiceStatus;
begin
Result := False;
if GetHandle(SERVICE_QUERY_STATUS or SERVICE_PAUSE_CONTINUE) then
try
if not (saPauseContinue in ServiceAccepts) then
begin
FServiceManager.HandleError(SERVICE_CANNOT_CONTINUE);
Exit;
end;
if not ControlService(FServiceHandle, SERVICE_CONTROL_CONTINUE, LStatus) then
begin
FServiceManager.HandleError(LAST_OS_ERROR);
Exit;
end;
if AWait then
if not WaitFor(SERVICE_RUNNING) then
Exit;
Result := True;
finally
CleanupHandle;
end;
end;
procedure TServiceInfo.ParseBinaryPath;
var
LCommanlineStart: Integer;
begin
FPath := '';
FFileName := '';
FCommandLine := '';
if FBinaryPathName <> '' then
begin
LCommanlineStart := FBinaryPathName.IndexOf('" ');
if LCommanlineStart < 0 then
LCommanlineStart := FBinaryPathName.IndexOf(' ');
if LCommanlineStart > 0 then
begin
FCommandLine := FBinaryPathName.Substring(LCommanlineStart + 2);
FFileName := FBinaryPathName.Substring(0, LCommanlineStart + 1);
end
else
FFileName := FBinaryPathName;
FFileName := FFileName.DeQuotedString('"');
FPath := ExtractFilePath(FFileName);
FFileName := ExtractFileName(FFileName);
end;
end;
function TServiceInfo.Pause(const AWait: Boolean = True): Boolean;
var
LStatus: TServiceStatus;
begin
Result := False;
if GetHandle(SERVICE_QUERY_STATUS or SERVICE_PAUSE_CONTINUE) then
try
if not (saPauseContinue in ServiceAccepts) then
begin
FServiceManager.HandleError(SERVICE_CANNOT_PAUSE);
Exit;
end;
if not ControlService(FServiceHandle,SERVICE_CONTROL_PAUSE, LStatus) then
begin
FServiceManager.HandleError(LAST_OS_ERROR);
Exit;
end;
if AWait then
if not WaitFor(SERVICE_PAUSED) then
Exit;
Result := True;
finally
CleanupHandle;
end;
end;
function TServiceInfo.Start(const AWait: Boolean = True): Boolean;
var
LServiceArgumentVectors: PChar;
begin
Result := False;
if GetHandle(SERVICE_QUERY_STATUS or SERVICE_START) then
try
LServiceArgumentVectors := nil;
if not StartService(FServiceHandle, 0, LServiceArgumentVectors) then
begin
FServiceManager.HandleError(LAST_OS_ERROR);
Exit;
end;
if AWait then
if not WaitFor(SERVICE_RUNNING) then
Exit;
Result := True;
finally
CleanupHandle;
end;
end;
function TServiceInfo.Stop(const AWait: Boolean = True): Boolean;
var
LStatus: TServiceStatus;
begin
Result := False;
if GetHandle(SERVICE_QUERY_STATUS or SERVICE_STOP) then
try
if not (saStop in ServiceAccepts) then
begin
FServiceManager.HandleError(SERVICE_CANNOT_STOP);
Exit;
end;
if not ControlService(FServiceHandle,SERVICE_CONTROL_STOP, LStatus) then
begin