Debian Codegraph @

test/support/windows-integration/plugins/module_utils/Ansible.Service.cs

raw
1 using Microsoft.Win32.SafeHandles;
2 using System;
3 using System.Collections.Generic;
4 using System.Linq;
5 using System.Runtime.InteropServices;
6 using System.Security.Principal;
7 using System.Text;
8 using Ansible.Privilege;
9
10 namespace Ansible.Service
11 {
12 internal class NativeHelpers
13 {
14 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
15 public struct ENUM_SERVICE_STATUSW
16 {
17 public string lpServiceName;
18 public string lpDisplayName;
19 public SERVICE_STATUS ServiceStatus;
20 }
21
22 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
23 public struct QUERY_SERVICE_CONFIGW
24 {
25 public ServiceType dwServiceType;
26 public ServiceStartType dwStartType;
27 public ErrorControl dwErrorControl;
28 [MarshalAs(UnmanagedType.LPWStr)] public string lpBinaryPathName;
29 [MarshalAs(UnmanagedType.LPWStr)] public string lpLoadOrderGroup;
30 public Int32 dwTagId;
31 public IntPtr lpDependencies; // Can't rely on marshaling as dependencies are delimited by \0.
32 [MarshalAs(UnmanagedType.LPWStr)] public string lpServiceStartName;
33 [MarshalAs(UnmanagedType.LPWStr)] public string lpDisplayName;
34 }
35
36 [StructLayout(LayoutKind.Sequential)]
37 public struct SC_ACTION
38 {
39 public FailureAction Type;
40 public UInt32 Delay;
41 }
42
43 [StructLayout(LayoutKind.Sequential)]
44 public struct SERVICE_DELAYED_AUTO_START_INFO
45 {
46 public bool fDelayedAutostart;
47 }
48
49 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
50 public struct SERVICE_DESCRIPTIONW
51 {
52 [MarshalAs(UnmanagedType.LPWStr)] public string lpDescription;
53 }
54
55 [StructLayout(LayoutKind.Sequential)]
56 public struct SERVICE_FAILURE_ACTIONS_FLAG
57 {
58 public bool fFailureActionsOnNonCrashFailures;
59 }
60
61 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
62 public struct SERVICE_FAILURE_ACTIONSW
63 {
64 public UInt32 dwResetPeriod;
65 [MarshalAs(UnmanagedType.LPWStr)] public string lpRebootMsg;
66 [MarshalAs(UnmanagedType.LPWStr)] public string lpCommand;
67 public UInt32 cActions;
68 public IntPtr lpsaActions;
69 }
70
71 [StructLayout(LayoutKind.Sequential)]
72 public struct SERVICE_LAUNCH_PROTECTED_INFO
73 {
74 public LaunchProtection dwLaunchProtected;
75 }
76
77 [StructLayout(LayoutKind.Sequential)]
78 public struct SERVICE_PREFERRED_NODE_INFO
79 {
80 public UInt16 usPreferredNode;
81 public bool fDelete;
82 }
83
84 [StructLayout(LayoutKind.Sequential)]
85 public struct SERVICE_PRESHUTDOWN_INFO
86 {
87 public UInt32 dwPreshutdownTimeout;
88 }
89
90 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
91 public struct SERVICE_REQUIRED_PRIVILEGES_INFOW
92 {
93 // Can't rely on marshaling as privileges are delimited by \0.
94 public IntPtr pmszRequiredPrivileges;
95 }
96
97 [StructLayout(LayoutKind.Sequential)]
98 public struct SERVICE_SID_INFO
99 {
100 public ServiceSidInfo dwServiceSidType;
101 }
102
103 [StructLayout(LayoutKind.Sequential)]
104 public struct SERVICE_STATUS
105 {
106 public ServiceType dwServiceType;
107 public ServiceStatus dwCurrentState;
108 public ControlsAccepted dwControlsAccepted;
109 public UInt32 dwWin32ExitCode;
110 public UInt32 dwServiceSpecificExitCode;
111 public UInt32 dwCheckPoint;
112 public UInt32 dwWaitHint;
113 }
114
115 [StructLayout(LayoutKind.Sequential)]
116 public struct SERVICE_STATUS_PROCESS
117 {
118 public ServiceType dwServiceType;
119 public ServiceStatus dwCurrentState;
120 public ControlsAccepted dwControlsAccepted;
121 public UInt32 dwWin32ExitCode;
122 public UInt32 dwServiceSpecificExitCode;
123 public UInt32 dwCheckPoint;
124 public UInt32 dwWaitHint;
125 public UInt32 dwProcessId;
126 public ServiceFlags dwServiceFlags;
127 }
128
129 [StructLayout(LayoutKind.Sequential)]
130 public struct SERVICE_TRIGGER
131 {
132 public TriggerType dwTriggerType;
133 public TriggerAction dwAction;
134 public IntPtr pTriggerSubtype;
135 public UInt32 cDataItems;
136 public IntPtr pDataItems;
137 }
138
139 [StructLayout(LayoutKind.Sequential)]
140 public struct SERVICE_TRIGGER_SPECIFIC_DATA_ITEM
141 {
142 public TriggerDataType dwDataType;
143 public UInt32 cbData;
144 public IntPtr pData;
145 }
146
147 [StructLayout(LayoutKind.Sequential)]
148 public struct SERVICE_TRIGGER_INFO
149 {
150 public UInt32 cTriggers;
151 public IntPtr pTriggers;
152 public IntPtr pReserved;
153 }
154
155 public enum ConfigInfoLevel : uint
156 {
157 SERVICE_CONFIG_DESCRIPTION = 0x00000001,
158 SERVICE_CONFIG_FAILURE_ACTIONS = 0x00000002,
159 SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 0x00000003,
160 SERVICE_CONFIG_FAILURE_ACTIONS_FLAG = 0x00000004,
161 SERVICE_CONFIG_SERVICE_SID_INFO = 0x00000005,
162 SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO = 0x00000006,
163 SERVICE_CONFIG_PRESHUTDOWN_INFO = 0x00000007,
164 SERVICE_CONFIG_TRIGGER_INFO = 0x00000008,
165 SERVICE_CONFIG_PREFERRED_NODE = 0x00000009,
166 SERVICE_CONFIG_LAUNCH_PROTECTED = 0x0000000c,
167 }
168 }
169
170 internal class NativeMethods
171 {
172 [DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
173 public static extern bool ChangeServiceConfigW(
174 SafeHandle hService,
175 ServiceType dwServiceType,
176 ServiceStartType dwStartType,
177 ErrorControl dwErrorControl,
178 string lpBinaryPathName,
179 string lpLoadOrderGroup,
180 IntPtr lpdwTagId,
181 string lpDependencies,
182 string lpServiceStartName,
183 string lpPassword,
184 string lpDisplayName);
185
186 [DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
187 public static extern bool ChangeServiceConfig2W(
188 SafeHandle hService,
189 NativeHelpers.ConfigInfoLevel dwInfoLevel,
190 IntPtr lpInfo);
191
192 [DllImport("Advapi32.dll", SetLastError = true)]
193 public static extern bool CloseServiceHandle(
194 IntPtr hSCObject);
195
196 [DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
197 public static extern SafeServiceHandle CreateServiceW(
198 SafeHandle hSCManager,
199 string lpServiceName,
200 string lpDisplayName,
201 ServiceRights dwDesiredAccess,
202 ServiceType dwServiceType,
203 ServiceStartType dwStartType,
204 ErrorControl dwErrorControl,
205 string lpBinaryPathName,
206 string lpLoadOrderGroup,
207 IntPtr lpdwTagId,
208 string lpDependencies,
209 string lpServiceStartName,
210 string lpPassword);
211
212 [DllImport("Advapi32.dll", SetLastError = true)]
213 public static extern bool DeleteService(
214 SafeHandle hService);
215
216 [DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
217 public static extern bool EnumDependentServicesW(
218 SafeHandle hService,
219 UInt32 dwServiceState,
220 SafeMemoryBuffer lpServices,
221 UInt32 cbBufSize,
222 out UInt32 pcbBytesNeeded,
223 out UInt32 lpServicesReturned);
224
225 [DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
226 public static extern SafeServiceHandle OpenSCManagerW(
227 string lpMachineName,
228 string lpDatabaseNmae,
229 SCMRights dwDesiredAccess);
230
231 [DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
232 public static extern SafeServiceHandle OpenServiceW(
233 SafeHandle hSCManager,
234 string lpServiceName,
235 ServiceRights dwDesiredAccess);
236
237 [DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
238 public static extern bool QueryServiceConfigW(
239 SafeHandle hService,
240 IntPtr lpServiceConfig,
241 UInt32 cbBufSize,
242 out UInt32 pcbBytesNeeded);
243
244 [DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
245 public static extern bool QueryServiceConfig2W(
246 SafeHandle hservice,
247 NativeHelpers.ConfigInfoLevel dwInfoLevel,
248 IntPtr lpBuffer,
249 UInt32 cbBufSize,
250 out UInt32 pcbBytesNeeded);
251
252 [DllImport("Advapi32.dll", SetLastError = true)]
253 public static extern bool QueryServiceStatusEx(
254 SafeHandle hService,
255 UInt32 InfoLevel,
256 IntPtr lpBuffer,
257 UInt32 cbBufSize,
258 out UInt32 pcbBytesNeeded);
259 }
260
261 internal class SafeMemoryBuffer : SafeHandleZeroOrMinusOneIsInvalid
262 {
263 public UInt32 BufferLength { get; internal set; }
264
265 public SafeMemoryBuffer() : base(true) { }
266 public SafeMemoryBuffer(int cb) : base(true)
267 {
268 BufferLength = (UInt32)cb;
269 base.SetHandle(Marshal.AllocHGlobal(cb));
270 }
271 public SafeMemoryBuffer(IntPtr handle) : base(true)
272 {
273 base.SetHandle(handle);
274 }
275
276 protected override bool ReleaseHandle()
277 {
278 Marshal.FreeHGlobal(handle);
279 return true;
280 }
281 }
282
283 internal class SafeServiceHandle : SafeHandleZeroOrMinusOneIsInvalid
284 {
285 public SafeServiceHandle() : base(true) { }
286 public SafeServiceHandle(IntPtr handle) : base(true) { this.handle = handle; }
287
288 protected override bool ReleaseHandle()
289 {
290 return NativeMethods.CloseServiceHandle(handle);
291 }
292 }
293
294 [Flags]
295 public enum ControlsAccepted : uint
296 {
297 None = 0x00000000,
298 Stop = 0x00000001,
299 PauseContinue = 0x00000002,
300 Shutdown = 0x00000004,
301 ParamChange = 0x00000008,
302 NetbindChange = 0x00000010,
303 HardwareProfileChange = 0x00000020,
304 PowerEvent = 0x00000040,
305 SessionChange = 0x00000080,
306 PreShutdown = 0x00000100,
307 }
308
309 public enum ErrorControl : uint
310 {
311 Ignore = 0x00000000,
312 Normal = 0x00000001,
313 Severe = 0x00000002,
314 Critical = 0x00000003,
315 }
316
317 public enum FailureAction : uint
318 {
319 None = 0x00000000,
320 Restart = 0x00000001,
321 Reboot = 0x00000002,
322 RunCommand = 0x00000003,
323 }
324
325 public enum LaunchProtection : uint
326 {
327 None = 0,
328 Windows = 1,
329 WindowsLight = 2,
330 AntimalwareLight = 3,
331 }
332
333 [Flags]
334 public enum SCMRights : uint
335 {
336 Connect = 0x00000001,
337 CreateService = 0x00000002,
338 EnumerateService = 0x00000004,
339 Lock = 0x00000008,
340 QueryLockStatus = 0x00000010,
341 ModifyBootConfig = 0x00000020,
342 AllAccess = 0x000F003F,
343 }
344
345 [Flags]
346 public enum ServiceFlags : uint
347 {
348 None = 0x0000000,
349 RunsInSystemProcess = 0x00000001,
350 }
351
352 [Flags]
353 public enum ServiceRights : uint
354 {
355 QueryConfig = 0x00000001,
356 ChangeConfig = 0x00000002,
357 QueryStatus = 0x00000004,
358 EnumerateDependents = 0x00000008,
359 Start = 0x00000010,
360 Stop = 0x00000020,
361 PauseContinue = 0x00000040,
362 Interrogate = 0x00000080,
363 UserDefinedControl = 0x00000100,
364 Delete = 0x00010000,
365 ReadControl = 0x00020000,
366 WriteDac = 0x00040000,
367 WriteOwner = 0x00080000,
368 AllAccess = 0x000F01FF,
369 AccessSystemSecurity = 0x01000000,
370 }
371
372 public enum ServiceStartType : uint
373 {
374 BootStart = 0x00000000,
375 SystemStart = 0x00000001,
376 AutoStart = 0x00000002,
377 DemandStart = 0x00000003,
378 Disabled = 0x00000004,
379
380 // Not part of ChangeServiceConfig enumeration but built by the Srvice class for the StartType property.
381 AutoStartDelayed = 0x1000000
382 }
383
384 [Flags]
385 public enum ServiceType : uint
386 {
387 KernelDriver = 0x00000001,
388 FileSystemDriver = 0x00000002,
389 Adapter = 0x00000004,
390 RecognizerDriver = 0x00000008,
391 Driver = KernelDriver | FileSystemDriver | RecognizerDriver,
392 Win32OwnProcess = 0x00000010,
393 Win32ShareProcess = 0x00000020,
394 Win32 = Win32OwnProcess | Win32ShareProcess,
395 UserProcess = 0x00000040,
396 UserOwnprocess = Win32OwnProcess | UserProcess,
397 UserShareProcess = Win32ShareProcess | UserProcess,
398 UserServiceInstance = 0x00000080,
399 InteractiveProcess = 0x00000100,
400 PkgService = 0x00000200,
401 }
402
403 public enum ServiceSidInfo : uint
404 {
405 None,
406 Unrestricted,
407 Restricted = 3,
408 }
409
410 public enum ServiceStatus : uint
411 {
412 Stopped = 0x00000001,
413 StartPending = 0x00000002,
414 StopPending = 0x00000003,
415 Running = 0x00000004,
416 ContinuePending = 0x00000005,
417 PausePending = 0x00000006,
418 Paused = 0x00000007,
419 }
420
421 public enum TriggerAction : uint
422 {
423 ServiceStart = 0x00000001,
424 ServiceStop = 0x000000002,
425 }
426
427 public enum TriggerDataType : uint
428 {
429 Binary = 00000001,
430 String = 0x00000002,
431 Level = 0x00000003,
432 KeywordAny = 0x00000004,
433 KeywordAll = 0x00000005,
434 }
435
436 public enum TriggerType : uint
437 {
438 DeviceInterfaceArrival = 0x00000001,
439 IpAddressAvailability = 0x00000002,
440 DomainJoin = 0x00000003,
441 FirewallPortEvent = 0x00000004,
442 GroupPolicy = 0x00000005,
443 NetworkEndpoint = 0x00000006,
444 Custom = 0x00000014,
445 }
446
447 public class ServiceManagerException : System.ComponentModel.Win32Exception
448 {
449 private string _msg;
450
451 public ServiceManagerException(string message) : this(Marshal.GetLastWin32Error(), message) { }
452 public ServiceManagerException(int errorCode, string message) : base(errorCode)
453 {
454 _msg = String.Format("{0} ({1}, Win32ErrorCode {2} - 0x{2:X8})", message, base.Message, errorCode);
455 }
456
457 public override string Message { get { return _msg; } }
458 public static explicit operator ServiceManagerException(string message)
459 {
460 return new ServiceManagerException(message);
461 }
462 }
463
464 public class Action
465 {
466 public FailureAction Type;
467 public UInt32 Delay;
468 }
469
470 public class FailureActions
471 {
472 public UInt32? ResetPeriod = null; // Get is always populated, can be null on set to preserve existing.
473 public string RebootMsg = null;
474 public string Command = null;
475 public List<Action> Actions = null;
476
477 public FailureActions() { }
478
479 internal FailureActions(NativeHelpers.SERVICE_FAILURE_ACTIONSW actions)
480 {
481 ResetPeriod = actions.dwResetPeriod;
482 RebootMsg = actions.lpRebootMsg;
483 Command = actions.lpCommand;
484 Actions = new List<Action>();
485
486 int actionLength = Marshal.SizeOf(typeof(NativeHelpers.SC_ACTION));
487 for (int i = 0; i < actions.cActions; i++)
488 {
489 IntPtr actionPtr = IntPtr.Add(actions.lpsaActions, i * actionLength);
490
491 NativeHelpers.SC_ACTION rawAction = (NativeHelpers.SC_ACTION)Marshal.PtrToStructure(
492 actionPtr, typeof(NativeHelpers.SC_ACTION));
493
494 Actions.Add(new Action()
495 {
496 Type = rawAction.Type,
497 Delay = rawAction.Delay,
498 });
499 }
500 }
501 }
502
503 public class TriggerItem
504 {
505 public TriggerDataType Type;
506 public object Data; // Can be string, List<string>, byte, byte[], or Int64 depending on Type.
507
508 public TriggerItem() { }
509
510 internal TriggerItem(NativeHelpers.SERVICE_TRIGGER_SPECIFIC_DATA_ITEM dataItem)
511 {
512 Type = dataItem.dwDataType;
513
514 byte[] itemBytes = new byte[dataItem.cbData];
515 Marshal.Copy(dataItem.pData, itemBytes, 0, itemBytes.Length);
516
517 switch (dataItem.dwDataType)
518 {
519 case TriggerDataType.String:
520 string value = Encoding.Unicode.GetString(itemBytes, 0, itemBytes.Length);
521
522 if (value.EndsWith("\0\0"))
523 {
524 // Multistring with a delimiter of \0 and terminated with \0\0.
525 Data = new List<string>(value.Split(new char[1] { '\0' }, StringSplitOptions.RemoveEmptyEntries));
526 }
527 else
528 // Just a single string with null character at the end, strip it off.
529 Data = value.Substring(0, value.Length - 1);
530 break;
531 case TriggerDataType.Level:
532 Data = itemBytes[0];
533 break;
534 case TriggerDataType.KeywordAll:
535 case TriggerDataType.KeywordAny:
536 Data = BitConverter.ToUInt64(itemBytes, 0);
537 break;
538 default:
539 Data = itemBytes;
540 break;
541 }
542 }
543 }
544
545 public class Trigger
546 {
547 // https://docs.microsoft.com/en-us/windows/win32/api/winsvc/ns-winsvc-service_trigger
548 public const string NAMED_PIPE_EVENT_GUID = "1f81d131-3fac-4537-9e0c-7e7b0c2f4b55";
549 public const string RPC_INTERFACE_EVENT_GUID = "bc90d167-9470-4139-a9ba-be0bbbf5b74d";
550 public const string DOMAIN_JOIN_GUID = "1ce20aba-9851-4421-9430-1ddeb766e809";
551 public const string DOMAIN_LEAVE_GUID = "ddaf516e-58c2-4866-9574-c3b615d42ea1";
552 public const string FIREWALL_PORT_OPEN_GUID = "b7569e07-8421-4ee0-ad10-86915afdad09";
553 public const string FIREWALL_PORT_CLOSE_GUID = "a144ed38-8e12-4de4-9d96-e64740b1a524";
554 public const string MACHINE_POLICY_PRESENT_GUID = "659fcae6-5bdb-4da9-b1ff-ca2a178d46e0";
555 public const string NETWORK_MANAGER_FIRST_IP_ADDRESS_ARRIVAL_GUID = "4f27f2de-14e2-430b-a549-7cd48cbc8245";
556 public const string NETWORK_MANAGER_LAST_IP_ADDRESS_REMOVAL_GUID = "cc4ba62a-162e-4648-847a-b6bdf993e335";
557 public const string USER_POLICY_PRESENT_GUID = "54fb46c8-f089-464c-b1fd-59d1b62c3b50";
558
559 public TriggerType Type;
560 public TriggerAction Action;
561 public Guid SubType;
562 public List<TriggerItem> DataItems = new List<TriggerItem>();
563
564 public Trigger() { }
565
566 internal Trigger(NativeHelpers.SERVICE_TRIGGER trigger)
567 {
568 Type = trigger.dwTriggerType;
569 Action = trigger.dwAction;
570 SubType = (Guid)Marshal.PtrToStructure(trigger.pTriggerSubtype, typeof(Guid));
571
572 int dataItemLength = Marshal.SizeOf(typeof(NativeHelpers.SERVICE_TRIGGER_SPECIFIC_DATA_ITEM));
573 for (int i = 0; i < trigger.cDataItems; i++)
574 {
575 IntPtr dataPtr = IntPtr.Add(trigger.pDataItems, i * dataItemLength);
576
577 var dataItem = (NativeHelpers.SERVICE_TRIGGER_SPECIFIC_DATA_ITEM)Marshal.PtrToStructure(
578 dataPtr, typeof(NativeHelpers.SERVICE_TRIGGER_SPECIFIC_DATA_ITEM));
579
580 DataItems.Add(new TriggerItem(dataItem));
581 }
582 }
583 }
584
585 public class Service : IDisposable
586 {
587 private const UInt32 SERVICE_NO_CHANGE = 0xFFFFFFFF;
588
589 private SafeServiceHandle _scmHandle;
590 private SafeServiceHandle _serviceHandle;
591 private SafeMemoryBuffer _rawServiceConfig;
592 private NativeHelpers.SERVICE_STATUS_PROCESS _statusProcess;
593
594 private NativeHelpers.QUERY_SERVICE_CONFIGW _ServiceConfig
595 {
596 get
597 {
598 return (NativeHelpers.QUERY_SERVICE_CONFIGW)Marshal.PtrToStructure(
599 _rawServiceConfig.DangerousGetHandle(), typeof(NativeHelpers.QUERY_SERVICE_CONFIGW));
600 }
601 }
602
603 // ServiceConfig
604 public string ServiceName { get; private set; }
605
606 public ServiceType ServiceType
607 {
608 get { return _ServiceConfig.dwServiceType; }
609 set { ChangeServiceConfig(serviceType: value); }
610 }
611
612 public ServiceStartType StartType
613 {
614 get
615 {
616 ServiceStartType startType = _ServiceConfig.dwStartType;
617 if (startType == ServiceStartType.AutoStart)
618 {
619 var value = QueryServiceConfig2<NativeHelpers.SERVICE_DELAYED_AUTO_START_INFO>(
620 NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_DELAYED_AUTO_START_INFO);
621
622 if (value.fDelayedAutostart)
623 startType = ServiceStartType.AutoStartDelayed;
624 }
625
626 return startType;
627 }
628 set
629 {
630 ServiceStartType newStartType = value;
631 bool delayedStart = false;
632 if (value == ServiceStartType.AutoStartDelayed)
633 {
634 newStartType = ServiceStartType.AutoStart;
635 delayedStart = true;
636 }
637
638 ChangeServiceConfig(startType: newStartType);
639
640 var info = new NativeHelpers.SERVICE_DELAYED_AUTO_START_INFO()
641 {
642 fDelayedAutostart = delayedStart,
643 };
644 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, info);
645 }
646 }
647
648 public ErrorControl ErrorControl
649 {
650 get { return _ServiceConfig.dwErrorControl; }
651 set { ChangeServiceConfig(errorControl: value); }
652 }
653
654 public string Path
655 {
656 get { return _ServiceConfig.lpBinaryPathName; }
657 set { ChangeServiceConfig(binaryPath: value); }
658 }
659
660 public string LoadOrderGroup
661 {
662 get { return _ServiceConfig.lpLoadOrderGroup; }
663 set { ChangeServiceConfig(loadOrderGroup: value); }
664 }
665
666 public List<string> DependentOn
667 {
668 get
669 {
670 StringBuilder deps = new StringBuilder();
671 IntPtr depPtr = _ServiceConfig.lpDependencies;
672
673 bool wasNull = false;
674 while (true)
675 {
676 // Get the current char at the pointer and add it to the StringBuilder.
677 byte[] charBytes = new byte[sizeof(char)];
678 Marshal.Copy(depPtr, charBytes, 0, charBytes.Length);
679 depPtr = IntPtr.Add(depPtr, charBytes.Length);
680 char currentChar = BitConverter.ToChar(charBytes, 0);
681 deps.Append(currentChar);
682
683 // If the previous and current char is \0 exit the loop.
684 if (currentChar == '\0' && wasNull)
685 break;
686 wasNull = currentChar == '\0';
687 }
688
689 return new List<string>(deps.ToString().Split(new char[1] { '\0' },
690 StringSplitOptions.RemoveEmptyEntries));
691 }
692 set { ChangeServiceConfig(dependencies: value); }
693 }
694
695 public IdentityReference Account
696 {
697 get
698 {
699 if (_ServiceConfig.lpServiceStartName == null)
700 // User services don't have the start name specified and will be null.
701 return null;
702 else if (_ServiceConfig.lpServiceStartName == "LocalSystem")
703 // Special string used for the SYSTEM account, this is the same even for different localisations.
704 return (NTAccount)new SecurityIdentifier("S-1-5-18").Translate(typeof(NTAccount));
705 else
706 return new NTAccount(_ServiceConfig.lpServiceStartName);
707 }
708 set
709 {
710 string startName = null;
711 string pass = null;
712
713 if (value != null)
714 {
715 // Create a SID and convert back from a SID to get the Netlogon form regardless of the input
716 // specified.
717 SecurityIdentifier accountSid = (SecurityIdentifier)value.Translate(typeof(SecurityIdentifier));
718 NTAccount accountName = (NTAccount)accountSid.Translate(typeof(NTAccount));
719 string[] accountSplit = accountName.Value.Split(new char[1] { '\\' }, 2);
720
721 // SYSTEM, Local Service, Network Service
722 List<string> serviceAccounts = new List<string> { "S-1-5-18", "S-1-5-19", "S-1-5-20" };
723
724 // Well known service accounts and MSAs should have no password set. Explicitly blank out the
725 // existing password to ensure older passwords are no longer stored by Windows.
726 if (serviceAccounts.Contains(accountSid.Value) || accountSplit[1].EndsWith("$"))
727 pass = "";
728
729 // The SYSTEM account uses this special string to specify that account otherwise use the original
730 // NTAccount value in case it is in a custom format (not Netlogon) for a reason.
731 if (accountSid.Value == serviceAccounts[0])
732 startName = "LocalSystem";
733 else
734 startName = value.Translate(typeof(NTAccount)).Value;
735 }
736
737 ChangeServiceConfig(startName: startName, password: pass);
738 }
739 }
740
741 public string Password { set { ChangeServiceConfig(password: value); } }
742
743 public string DisplayName
744 {
745 get { return _ServiceConfig.lpDisplayName; }
746 set { ChangeServiceConfig(displayName: value); }
747 }
748
749 // ServiceConfig2
750
751 public string Description
752 {
753 get
754 {
755 var value = QueryServiceConfig2<NativeHelpers.SERVICE_DESCRIPTIONW>(
756 NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_DESCRIPTION);
757
758 return value.lpDescription;
759 }
760 set
761 {
762 var info = new NativeHelpers.SERVICE_DESCRIPTIONW()
763 {
764 lpDescription = value,
765 };
766 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_DESCRIPTION, info);
767 }
768 }
769
770 public FailureActions FailureActions
771 {
772 get
773 {
774 using (SafeMemoryBuffer b = QueryServiceConfig2(
775 NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS))
776 {
777 NativeHelpers.SERVICE_FAILURE_ACTIONSW value = (NativeHelpers.SERVICE_FAILURE_ACTIONSW)
778 Marshal.PtrToStructure(b.DangerousGetHandle(), typeof(NativeHelpers.SERVICE_FAILURE_ACTIONSW));
779
780 return new FailureActions(value);
781 }
782 }
783 set
784 {
785 // dwResetPeriod and lpsaActions must be set together, we need to read the existing config if someone
786 // wants to update 1 or the other but both aren't explicitly defined.
787 UInt32? resetPeriod = value.ResetPeriod;
788 List<Action> actions = value.Actions;
789 if ((resetPeriod != null && actions == null) || (resetPeriod == null && actions != null))
790 {
791 FailureActions existingValue = this.FailureActions;
792
793 if (resetPeriod != null && existingValue.Actions.Count == 0)
794 throw new ArgumentException(
795 "Cannot set FailureAction ResetPeriod without explicit Actions and no existing Actions");
796 else if (resetPeriod == null)
797 resetPeriod = (UInt32)existingValue.ResetPeriod;
798
799 if (actions == null)
800 actions = existingValue.Actions;
801 }
802
803 var info = new NativeHelpers.SERVICE_FAILURE_ACTIONSW()
804 {
805 dwResetPeriod = resetPeriod == null ? 0 : (UInt32)resetPeriod,
806 lpRebootMsg = value.RebootMsg,
807 lpCommand = value.Command,
808 cActions = actions == null ? 0 : (UInt32)actions.Count,
809 lpsaActions = IntPtr.Zero,
810 };
811
812 // null means to keep the existing actions whereas an empty list deletes the actions.
813 if (actions == null)
814 {
815 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, info);
816 return;
817 }
818
819 int actionLength = Marshal.SizeOf(typeof(NativeHelpers.SC_ACTION));
820 using (SafeMemoryBuffer buffer = new SafeMemoryBuffer(actionLength * actions.Count))
821 {
822 info.lpsaActions = buffer.DangerousGetHandle();
823 HashSet<string> privileges = new HashSet<string>();
824
825 for (int i = 0; i < actions.Count; i++)
826 {
827 IntPtr actionPtr = IntPtr.Add(info.lpsaActions, i * actionLength);
828 NativeHelpers.SC_ACTION action = new NativeHelpers.SC_ACTION()
829 {
830 Delay = actions[i].Delay,
831 Type = actions[i].Type,
832 };
833 Marshal.StructureToPtr(action, actionPtr, false);
834
835 // Need to make sure the SeShutdownPrivilege is enabled when adding a reboot failure action.
836 if (action.Type == FailureAction.Reboot)
837 privileges.Add("SeShutdownPrivilege");
838 }
839
840 using (new PrivilegeEnabler(true, privileges.ToList().ToArray()))
841 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, info);
842 }
843 }
844 }
845
846 public bool FailureActionsOnNonCrashFailures
847 {
848 get
849 {
850 var value = QueryServiceConfig2<NativeHelpers.SERVICE_FAILURE_ACTIONS_FLAG>(
851 NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS_FLAG);
852
853 return value.fFailureActionsOnNonCrashFailures;
854 }
855 set
856 {
857 var info = new NativeHelpers.SERVICE_FAILURE_ACTIONS_FLAG()
858 {
859 fFailureActionsOnNonCrashFailures = value,
860 };
861 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, info);
862 }
863 }
864
865 public ServiceSidInfo ServiceSidInfo
866 {
867 get
868 {
869 var value = QueryServiceConfig2<NativeHelpers.SERVICE_SID_INFO>(
870 NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_SERVICE_SID_INFO);
871
872 return value.dwServiceSidType;
873 }
874 set
875 {
876 var info = new NativeHelpers.SERVICE_SID_INFO()
877 {
878 dwServiceSidType = value,
879 };
880 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_SERVICE_SID_INFO, info);
881 }
882 }
883
884 public List<string> RequiredPrivileges
885 {
886 get
887 {
888 using (SafeMemoryBuffer buffer = QueryServiceConfig2(
889 NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO))
890 {
891 var value = (NativeHelpers.SERVICE_REQUIRED_PRIVILEGES_INFOW)Marshal.PtrToStructure(
892 buffer.DangerousGetHandle(), typeof(NativeHelpers.SERVICE_REQUIRED_PRIVILEGES_INFOW));
893
894 int structLength = Marshal.SizeOf(value);
895 int stringLength = ((int)buffer.BufferLength - structLength) / sizeof(char);
896
897 if (stringLength > 0)
898 {
899 string privilegesString = Marshal.PtrToStringUni(value.pmszRequiredPrivileges, stringLength);
900 return new List<string>(privilegesString.Split(new char[1] { '\0' },
901 StringSplitOptions.RemoveEmptyEntries));
902 }
903 else
904 return new List<string>();
905 }
906 }
907 set
908 {
909 string privilegeString = String.Join("\0", value ?? new List<string>()) + "\0\0";
910
911 using (SafeMemoryBuffer buffer = new SafeMemoryBuffer(Marshal.StringToHGlobalUni(privilegeString)))
912 {
913 var info = new NativeHelpers.SERVICE_REQUIRED_PRIVILEGES_INFOW()
914 {
915 pmszRequiredPrivileges = buffer.DangerousGetHandle(),
916 };
917 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO, info);
918 }
919 }
920 }
921
922 public UInt32 PreShutdownTimeout
923 {
924 get
925 {
926 var value = QueryServiceConfig2<NativeHelpers.SERVICE_PRESHUTDOWN_INFO>(
927 NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_PRESHUTDOWN_INFO);
928
929 return value.dwPreshutdownTimeout;
930 }
931 set
932 {
933 var info = new NativeHelpers.SERVICE_PRESHUTDOWN_INFO()
934 {
935 dwPreshutdownTimeout = value,
936 };
937 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_PRESHUTDOWN_INFO, info);
938 }
939 }
940
941 public List<Trigger> Triggers
942 {
943 get
944 {
945 List<Trigger> triggers = new List<Trigger>();
946
947 using (SafeMemoryBuffer b = QueryServiceConfig2(
948 NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_TRIGGER_INFO))
949 {
950 var value = (NativeHelpers.SERVICE_TRIGGER_INFO)Marshal.PtrToStructure(
951 b.DangerousGetHandle(), typeof(NativeHelpers.SERVICE_TRIGGER_INFO));
952
953 int triggerLength = Marshal.SizeOf(typeof(NativeHelpers.SERVICE_TRIGGER));
954 for (int i = 0; i < value.cTriggers; i++)
955 {
956 IntPtr triggerPtr = IntPtr.Add(value.pTriggers, i * triggerLength);
957 var trigger = (NativeHelpers.SERVICE_TRIGGER)Marshal.PtrToStructure(triggerPtr,
958 typeof(NativeHelpers.SERVICE_TRIGGER));
959
960 triggers.Add(new Trigger(trigger));
961 }
962 }
963
964 return triggers;
965 }
966 set
967 {
968 var info = new NativeHelpers.SERVICE_TRIGGER_INFO()
969 {
970 cTriggers = value == null ? 0 : (UInt32)value.Count,
971 pTriggers = IntPtr.Zero,
972 pReserved = IntPtr.Zero,
973 };
974
975 if (info.cTriggers == 0)
976 {
977 try
978 {
979 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_TRIGGER_INFO, info);
980 }
981 catch (ServiceManagerException e)
982 {
983 // Can fail with ERROR_INVALID_PARAMETER if no triggers were already set on the service, just
984 // continue as the service is what we want it to be.
985 if (e.NativeErrorCode != 87)
986 throw;
987 }
988 return;
989 }
990
991 // Due to the dynamic nature of the trigger structure(s) we need to manually calculate the size of the
992 // data items on each trigger if present. This also serializes the raw data items to bytes here.
993 int structDataLength = 0;
994 int dataLength = 0;
995 Queue<byte[]> dataItems = new Queue<byte[]>();
996 foreach (Trigger trigger in value)
997 {
998 if (trigger.DataItems == null || trigger.DataItems.Count == 0)
999 continue;
1000
1001 foreach (TriggerItem dataItem in trigger.DataItems)
1002 {
1003 structDataLength += Marshal.SizeOf(typeof(NativeHelpers.SERVICE_TRIGGER_SPECIFIC_DATA_ITEM));
1004
1005 byte[] dataItemBytes;
1006 Type dataItemType = dataItem.Data.GetType();
1007 if (dataItemType == typeof(byte))
1008 dataItemBytes = new byte[1] { (byte)dataItem.Data };
1009 else if (dataItemType == typeof(byte[]))
1010 dataItemBytes = (byte[])dataItem.Data;
1011 else if (dataItemType == typeof(UInt64))
1012 dataItemBytes = BitConverter.GetBytes((UInt64)dataItem.Data);
1013 else if (dataItemType == typeof(string))
1014 dataItemBytes = Encoding.Unicode.GetBytes((string)dataItem.Data + "\0");
1015 else if (dataItemType == typeof(List<string>))
1016 dataItemBytes = Encoding.Unicode.GetBytes(
1017 String.Join("\0", (List<string>)dataItem.Data) + "\0");
1018 else
1019 throw new ArgumentException(String.Format("Trigger data type '{0}' not a value type",
1020 dataItemType.Name));
1021
1022 dataLength += dataItemBytes.Length;
1023 dataItems.Enqueue(dataItemBytes);
1024 }
1025 }
1026
1027 using (SafeMemoryBuffer triggerBuffer = new SafeMemoryBuffer(
1028 value.Count * Marshal.SizeOf(typeof(NativeHelpers.SERVICE_TRIGGER))))
1029 using (SafeMemoryBuffer triggerGuidBuffer = new SafeMemoryBuffer(
1030 value.Count * Marshal.SizeOf(typeof(Guid))))
1031 using (SafeMemoryBuffer dataItemBuffer = new SafeMemoryBuffer(structDataLength))
1032 using (SafeMemoryBuffer dataBuffer = new SafeMemoryBuffer(dataLength))
1033 {
1034 info.pTriggers = triggerBuffer.DangerousGetHandle();
1035
1036 IntPtr triggerPtr = triggerBuffer.DangerousGetHandle();
1037 IntPtr guidPtr = triggerGuidBuffer.DangerousGetHandle();
1038 IntPtr dataItemPtr = dataItemBuffer.DangerousGetHandle();
1039 IntPtr dataPtr = dataBuffer.DangerousGetHandle();
1040
1041 foreach (Trigger trigger in value)
1042 {
1043 int dataCount = trigger.DataItems == null ? 0 : trigger.DataItems.Count;
1044 var rawTrigger = new NativeHelpers.SERVICE_TRIGGER()
1045 {
1046 dwTriggerType = trigger.Type,
1047 dwAction = trigger.Action,
1048 pTriggerSubtype = guidPtr,
1049 cDataItems = (UInt32)dataCount,
1050 pDataItems = dataCount == 0 ? IntPtr.Zero : dataItemPtr,
1051 };
1052 guidPtr = StructureToPtr(trigger.SubType, guidPtr);
1053
1054 for (int i = 0; i < rawTrigger.cDataItems; i++)
1055 {
1056 byte[] dataItemBytes = dataItems.Dequeue();
1057 var rawTriggerData = new NativeHelpers.SERVICE_TRIGGER_SPECIFIC_DATA_ITEM()
1058 {
1059 dwDataType = trigger.DataItems[i].Type,
1060 cbData = (UInt32)dataItemBytes.Length,
1061 pData = dataPtr,
1062 };
1063 Marshal.Copy(dataItemBytes, 0, dataPtr, dataItemBytes.Length);
1064 dataPtr = IntPtr.Add(dataPtr, dataItemBytes.Length);
1065
1066 dataItemPtr = StructureToPtr(rawTriggerData, dataItemPtr);
1067 }
1068
1069 triggerPtr = StructureToPtr(rawTrigger, triggerPtr);
1070 }
1071
1072 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_TRIGGER_INFO, info);
1073 }
1074 }
1075 }
1076
1077 public UInt16? PreferredNode
1078 {
1079 get
1080 {
1081 try
1082 {
1083 var value = QueryServiceConfig2<NativeHelpers.SERVICE_PREFERRED_NODE_INFO>(
1084 NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_PREFERRED_NODE);
1085
1086 return value.usPreferredNode;
1087 }
1088 catch (ServiceManagerException e)
1089 {
1090 // If host has no NUMA support this will fail with ERROR_INVALID_PARAMETER
1091 if (e.NativeErrorCode == 0x00000057) // ERROR_INVALID_PARAMETER
1092 return null;
1093
1094 throw;
1095 }
1096 }
1097 set
1098 {
1099 var info = new NativeHelpers.SERVICE_PREFERRED_NODE_INFO();
1100 if (value == null)
1101 info.fDelete = true;
1102 else
1103 info.usPreferredNode = (UInt16)value;
1104 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_PREFERRED_NODE, info);
1105 }
1106 }
1107
1108 public LaunchProtection LaunchProtection
1109 {
1110 get
1111 {
1112 var value = QueryServiceConfig2<NativeHelpers.SERVICE_LAUNCH_PROTECTED_INFO>(
1113 NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_LAUNCH_PROTECTED);
1114
1115 return value.dwLaunchProtected;
1116 }
1117 set
1118 {
1119 var info = new NativeHelpers.SERVICE_LAUNCH_PROTECTED_INFO()
1120 {
1121 dwLaunchProtected = value,
1122 };
1123 ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel.SERVICE_CONFIG_LAUNCH_PROTECTED, info);
1124 }
1125 }
1126
1127 // ServiceStatus
1128 public ServiceStatus State { get { return _statusProcess.dwCurrentState; } }
1129
1130 public ControlsAccepted ControlsAccepted { get { return _statusProcess.dwControlsAccepted; } }
1131
1132 public UInt32 Win32ExitCode { get { return _statusProcess.dwWin32ExitCode; } }
1133
1134 public UInt32 ServiceExitCode { get { return _statusProcess.dwServiceSpecificExitCode; } }
1135
1136 public UInt32 Checkpoint { get { return _statusProcess.dwCheckPoint; } }
1137
1138 public UInt32 WaitHint { get { return _statusProcess.dwWaitHint; } }
1139
1140 public UInt32 ProcessId { get { return _statusProcess.dwProcessId; } }
1141
1142 public ServiceFlags ServiceFlags { get { return _statusProcess.dwServiceFlags; } }
1143
1144 public Service(string name) : this(name, ServiceRights.AllAccess) { }
1145
1146 public Service(string name, ServiceRights access) : this(name, access, SCMRights.Connect) { }
1147
1148 public Service(string name, ServiceRights access, SCMRights scmAccess)
1149 {
1150 ServiceName = name;
1151 _scmHandle = OpenSCManager(scmAccess);
1152 _serviceHandle = NativeMethods.OpenServiceW(_scmHandle, name, access);
1153 if (_serviceHandle.IsInvalid)
1154 throw new ServiceManagerException(String.Format("Failed to open service '{0}'", name));
1155
1156 Refresh();
1157 }
1158
1159 private Service(SafeServiceHandle scmHandle, SafeServiceHandle serviceHandle, string name)
1160 {
1161 ServiceName = name;
1162 _scmHandle = scmHandle;
1163 _serviceHandle = serviceHandle;
1164
1165 Refresh();
1166 }
1167
1168 // EnumDependentServices
1169 public List<string> DependedBy
1170 {
1171 get
1172 {
1173 UInt32 bytesNeeded = 0;
1174 UInt32 numServices = 0;
1175 NativeMethods.EnumDependentServicesW(_serviceHandle, 3, new SafeMemoryBuffer(IntPtr.Zero), 0,
1176 out bytesNeeded, out numServices);
1177
1178 using (SafeMemoryBuffer buffer = new SafeMemoryBuffer((int)bytesNeeded))
1179 {
1180 if (!NativeMethods.EnumDependentServicesW(_serviceHandle, 3, buffer, bytesNeeded, out bytesNeeded,
1181 out numServices))
1182 {
1183 throw new ServiceManagerException("Failed to enumerated dependent services");
1184 }
1185
1186 List<string> dependents = new List<string>();
1187 Type enumType = typeof(NativeHelpers.ENUM_SERVICE_STATUSW);
1188 for (int i = 0; i < numServices; i++)
1189 {
1190 var service = (NativeHelpers.ENUM_SERVICE_STATUSW)Marshal.PtrToStructure(
1191 IntPtr.Add(buffer.DangerousGetHandle(), i * Marshal.SizeOf(enumType)), enumType);
1192
1193 dependents.Add(service.lpServiceName);
1194 }
1195
1196 return dependents;
1197 }
1198 }
1199 }
1200
1201 public static Service Create(string name, string binaryPath, string displayName = null,
1202 ServiceType serviceType = ServiceType.Win32OwnProcess,
1203 ServiceStartType startType = ServiceStartType.DemandStart, ErrorControl errorControl = ErrorControl.Normal,
1204 string loadOrderGroup = null, List<string> dependencies = null, string startName = null,
1205 string password = null)
1206 {
1207 SafeServiceHandle scmHandle = OpenSCManager(SCMRights.CreateService | SCMRights.Connect);
1208
1209 if (displayName == null)
1210 displayName = name;
1211
1212 string depString = null;
1213 if (dependencies != null && dependencies.Count > 0)
1214 depString = String.Join("\0", dependencies) + "\0\0";
1215
1216 SafeServiceHandle serviceHandle = NativeMethods.CreateServiceW(scmHandle, name, displayName,
1217 ServiceRights.AllAccess, serviceType, startType, errorControl, binaryPath,
1218 loadOrderGroup, IntPtr.Zero, depString, startName, password);
1219
1220 if (serviceHandle.IsInvalid)
1221 throw new ServiceManagerException(String.Format("Failed to create new service '{0}'", name));
1222
1223 return new Service(scmHandle, serviceHandle, name);
1224 }
1225
1226 public void Delete()
1227 {
1228 if (!NativeMethods.DeleteService(_serviceHandle))
1229 throw new ServiceManagerException("Failed to delete service");
1230 Dispose();
1231 }
1232
1233 public void Dispose()
1234 {
1235 if (_serviceHandle != null)
1236 _serviceHandle.Dispose();
1237
1238 if (_scmHandle != null)
1239 _scmHandle.Dispose();
1240 GC.SuppressFinalize(this);
1241 }
1242
1243 public void Refresh()
1244 {
1245 UInt32 bytesNeeded;
1246 NativeMethods.QueryServiceConfigW(_serviceHandle, IntPtr.Zero, 0, out bytesNeeded);
1247
1248 _rawServiceConfig = new SafeMemoryBuffer((int)bytesNeeded);
1249 if (!NativeMethods.QueryServiceConfigW(_serviceHandle, _rawServiceConfig.DangerousGetHandle(), bytesNeeded,
1250 out bytesNeeded))
1251 {
1252 throw new ServiceManagerException("Failed to query service config");
1253 }
1254
1255 NativeMethods.QueryServiceStatusEx(_serviceHandle, 0, IntPtr.Zero, 0, out bytesNeeded);
1256 using (SafeMemoryBuffer buffer = new SafeMemoryBuffer((int)bytesNeeded))
1257 {
1258 if (!NativeMethods.QueryServiceStatusEx(_serviceHandle, 0, buffer.DangerousGetHandle(), bytesNeeded,
1259 out bytesNeeded))
1260 {
1261 throw new ServiceManagerException("Failed to query service status");
1262 }
1263
1264 _statusProcess = (NativeHelpers.SERVICE_STATUS_PROCESS)Marshal.PtrToStructure(
1265 buffer.DangerousGetHandle(), typeof(NativeHelpers.SERVICE_STATUS_PROCESS));
1266 }
1267 }
1268
1269 private void ChangeServiceConfig(ServiceType serviceType = (ServiceType)SERVICE_NO_CHANGE,
1270 ServiceStartType startType = (ServiceStartType)SERVICE_NO_CHANGE,
1271 ErrorControl errorControl = (ErrorControl)SERVICE_NO_CHANGE, string binaryPath = null,
1272 string loadOrderGroup = null, List<string> dependencies = null, string startName = null,
1273 string password = null, string displayName = null)
1274 {
1275 string depString = null;
1276 if (dependencies != null && dependencies.Count > 0)
1277 depString = String.Join("\0", dependencies) + "\0\0";
1278
1279 if (!NativeMethods.ChangeServiceConfigW(_serviceHandle, serviceType, startType, errorControl, binaryPath,
1280 loadOrderGroup, IntPtr.Zero, depString, startName, password, displayName))
1281 {
1282 throw new ServiceManagerException("Failed to change service config");
1283 }
1284
1285 Refresh();
1286 }
1287
1288 private void ChangeServiceConfig2(NativeHelpers.ConfigInfoLevel infoLevel, object info)
1289 {
1290 using (SafeMemoryBuffer buffer = new SafeMemoryBuffer(Marshal.SizeOf(info)))
1291 {
1292 Marshal.StructureToPtr(info, buffer.DangerousGetHandle(), false);
1293
1294 if (!NativeMethods.ChangeServiceConfig2W(_serviceHandle, infoLevel, buffer.DangerousGetHandle()))
1295 throw new ServiceManagerException("Failed to change service config");
1296 }
1297 }
1298
1299 private static SafeServiceHandle OpenSCManager(SCMRights desiredAccess)
1300 {
1301 SafeServiceHandle handle = NativeMethods.OpenSCManagerW(null, null, desiredAccess);
1302 if (handle.IsInvalid)
1303 throw new ServiceManagerException("Failed to open SCManager");
1304
1305 return handle;
1306 }
1307
1308 private T QueryServiceConfig2<T>(NativeHelpers.ConfigInfoLevel infoLevel)
1309 {
1310 using (SafeMemoryBuffer buffer = QueryServiceConfig2(infoLevel))
1311 return (T)Marshal.PtrToStructure(buffer.DangerousGetHandle(), typeof(T));
1312 }
1313
1314 private SafeMemoryBuffer QueryServiceConfig2(NativeHelpers.ConfigInfoLevel infoLevel)
1315 {
1316 UInt32 bytesNeeded = 0;
1317 NativeMethods.QueryServiceConfig2W(_serviceHandle, infoLevel, IntPtr.Zero, 0, out bytesNeeded);
1318
1319 SafeMemoryBuffer buffer = new SafeMemoryBuffer((int)bytesNeeded);
1320 if (!NativeMethods.QueryServiceConfig2W(_serviceHandle, infoLevel, buffer.DangerousGetHandle(), bytesNeeded,
1321 out bytesNeeded))
1322 {
1323 throw new ServiceManagerException(String.Format("QueryServiceConfig2W({0}) failed",
1324 infoLevel.ToString()));
1325 }
1326
1327 return buffer;
1328 }
1329
1330 private static IntPtr StructureToPtr(object structure, IntPtr ptr)
1331 {
1332 Marshal.StructureToPtr(structure, ptr, false);
1333 return IntPtr.Add(ptr, Marshal.SizeOf(structure));
1334 }
1335
1336 ~Service() { Dispose(); }
1337 }
1338 }