Advapi32.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Runtime.InteropServices;
  5. using System.ComponentModel;
  6. namespace Advapi32
  7. {
  8. class ServiceManager : IDisposable
  9. {
  10. private IntPtr Handle;
  11. public ServiceManager()
  12. {
  13. Handle = Advapi32.OpenSCManager(null, null, (uint)SCM_ACCESS.SC_MANAGER_ALL_ACCESS);
  14. if (Handle == IntPtr.Zero)
  15. {
  16. throw new Exception(String.Format("Error connecting to Service Control Manager. Error provided was: 0x{0:X}", Marshal.GetLastWin32Error()));
  17. }
  18. }
  19. public Service Open(string serviceName)
  20. {
  21. IntPtr svcHandle = Advapi32.OpenService(Handle, serviceName, (int)SERVICE_ACCESS.SERVICE_ALL_ACCESS);
  22. if (svcHandle == IntPtr.Zero)
  23. {
  24. throw new Exception(String.Format("Error opening service for modifying. Error returned was: 0x{0:X}", Marshal.GetLastWin32Error()));
  25. }
  26. Console.WriteLine("Opened " + serviceName);
  27. return new Service(svcHandle);
  28. }
  29. public void Dispose()
  30. {
  31. if (Handle != IntPtr.Zero)
  32. Advapi32.CloseServiceHandle(Handle);
  33. Handle = IntPtr.Zero;
  34. }
  35. }
  36. class Service : IDisposable
  37. {
  38. internal IntPtr Handle;
  39. internal Service(IntPtr service)
  40. {
  41. Handle = service;
  42. }
  43. public void ChangeConfig(TimeSpan failureResetPeriod)
  44. {
  45. SERVICE_FAILURE_ACTIONS sfa = new SERVICE_FAILURE_ACTIONS();
  46. sfa.dwResetPeriod = failureResetPeriod.Seconds;
  47. sfa.lpRebootMsg = ""; // delete message
  48. sfa.lpCommand = ""; // delete the command to run
  49. sfa.cActions = 0;
  50. SC_ACTION[] lpsaActions = new SC_ACTION[2];
  51. lpsaActions[0] = new SC_ACTION(SC_ACTION_TYPE.SC_ACTION_RESTART, 1000);
  52. lpsaActions[1] = new SC_ACTION(SC_ACTION_TYPE.SC_ACTION_RESTART, 2000);
  53. lpsaActions[1] = new SC_ACTION(SC_ACTION_TYPE.SC_ACTION_RESTART, 5000);
  54. sfa.lpsaActions = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(SC_ACTION)) * 2);
  55. try
  56. {
  57. for (int i = 0; i < lpsaActions.Length; i++)
  58. {
  59. Marshal.StructureToPtr(lpsaActions[i], sfa.lpsaActions/* new IntPtr(sfa.lpsaActions.ToInt64() + i * Marshal.SizeOf(typeof(SC_ACTION)))*/, false);
  60. }
  61. Console.WriteLine("Changing config to 2: sizeof(x)"+Marshal.SizeOf(typeof(SC_ACTION)));
  62. int x = Marshal.GetLastWin32Error();
  63. sfa.lpsaActions = IntPtr.Zero;
  64. if (!Advapi32.ChangeServiceConfig2(Handle, SERVICE_CONFIG_INFOLEVEL.SERVICE_CONFIG_FAILURE_ACTIONS, sfa))
  65. throw new Exception("Failed to change the failure actions", new Win32Exception());
  66. throw new Exception("OK:" + x + "/" + Marshal.GetLastWin32Error(), new Win32Exception());
  67. }
  68. finally
  69. {
  70. Marshal.FreeCoTaskMem(sfa.lpsaActions);
  71. }
  72. }
  73. public void Dispose()
  74. {
  75. if (Handle!=IntPtr.Zero)
  76. Advapi32.CloseServiceHandle(Handle);
  77. Handle = IntPtr.Zero;
  78. }
  79. }
  80. /// <summary>
  81. /// Advapi32.dll wrapper for performing additional service related operations that are not
  82. /// available in WMI.
  83. /// </summary>
  84. internal class Advapi32
  85. {
  86. [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  87. [return: MarshalAs(UnmanagedType.Bool)]
  88. internal static extern bool ChangeServiceConfig2(IntPtr hService, SERVICE_CONFIG_INFOLEVEL dwInfoLevel, IntPtr lpInfo);
  89. [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  90. [return: MarshalAs(UnmanagedType.Bool)]
  91. internal static extern bool ChangeServiceConfig2(IntPtr hService, SERVICE_CONFIG_INFOLEVEL dwInfoLevel, SERVICE_FAILURE_ACTIONS sfa);
  92. [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  93. internal static extern IntPtr OpenSCManager(string machineName, string databaseName, uint dwAccess);
  94. [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  95. internal static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, uint dwDesiredAccess);
  96. [DllImport("advapi32.dll", SetLastError = true)]
  97. [return: MarshalAs(UnmanagedType.Bool)]
  98. internal static extern bool CloseServiceHandle(IntPtr hSCObject);
  99. }
  100. internal enum SCM_ACCESS : uint
  101. {
  102. /// <summary>
  103. /// Required to connect to the service control manager.
  104. /// </summary>
  105. SC_MANAGER_CONNECT = 0x00001,
  106. /// <summary>
  107. /// Required to call the CreateService function to create a service
  108. /// object and add it to the database.
  109. /// </summary>
  110. SC_MANAGER_CREATE_SERVICE = 0x00002,
  111. /// <summary>
  112. /// Required to call the EnumServicesStatusEx function to list the
  113. /// services that are in the database.
  114. /// </summary>
  115. SC_MANAGER_ENUMERATE_SERVICE = 0x00004,
  116. /// <summary>
  117. /// Required to call the LockServiceDatabase function to acquire a
  118. /// lock on the database.
  119. /// </summary>
  120. SC_MANAGER_LOCK = 0x00008,
  121. /// <summary>
  122. /// Required to call the QueryServiceLockStatus function to retrieve
  123. /// the lock status information for the database.
  124. /// </summary>
  125. SC_MANAGER_QUERY_LOCK_STATUS = 0x00010,
  126. /// <summary>
  127. /// Required to call the NotifyBootConfigStatus function.
  128. /// </summary>
  129. SC_MANAGER_MODIFY_BOOT_CONFIG = 0x00020,
  130. /// <summary>
  131. /// Includes STANDARD_RIGHTS_REQUIRED, in addition to all access
  132. /// rights in this table.
  133. /// </summary>
  134. SC_MANAGER_ALL_ACCESS = ACCESS_MASK.STANDARD_RIGHTS_REQUIRED |
  135. SC_MANAGER_CONNECT |
  136. SC_MANAGER_CREATE_SERVICE |
  137. SC_MANAGER_ENUMERATE_SERVICE |
  138. SC_MANAGER_LOCK |
  139. SC_MANAGER_QUERY_LOCK_STATUS |
  140. SC_MANAGER_MODIFY_BOOT_CONFIG,
  141. GENERIC_READ = ACCESS_MASK.STANDARD_RIGHTS_READ |
  142. SC_MANAGER_ENUMERATE_SERVICE |
  143. SC_MANAGER_QUERY_LOCK_STATUS,
  144. GENERIC_WRITE = ACCESS_MASK.STANDARD_RIGHTS_WRITE |
  145. SC_MANAGER_CREATE_SERVICE |
  146. SC_MANAGER_MODIFY_BOOT_CONFIG,
  147. GENERIC_EXECUTE = ACCESS_MASK.STANDARD_RIGHTS_EXECUTE |
  148. SC_MANAGER_CONNECT | SC_MANAGER_LOCK,
  149. GENERIC_ALL = SC_MANAGER_ALL_ACCESS,
  150. }
  151. [Flags]
  152. internal enum SERVICE_ACCESS : uint
  153. {
  154. STANDARD_RIGHTS_REQUIRED = 0xF0000,
  155. SERVICE_QUERY_CONFIG = 0x00001,
  156. SERVICE_CHANGE_CONFIG = 0x00002,
  157. SERVICE_QUERY_STATUS = 0x00004,
  158. SERVICE_ENUMERATE_DEPENDENTS = 0x00008,
  159. SERVICE_START = 0x00010,
  160. SERVICE_STOP = 0x00020,
  161. SERVICE_PAUSE_CONTINUE = 0x00040,
  162. SERVICE_INTERROGATE = 0x00080,
  163. SERVICE_USER_DEFINED_CONTROL = 0x00100,
  164. SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |
  165. SERVICE_QUERY_CONFIG |
  166. SERVICE_CHANGE_CONFIG |
  167. SERVICE_QUERY_STATUS |
  168. SERVICE_ENUMERATE_DEPENDENTS |
  169. SERVICE_START |
  170. SERVICE_STOP |
  171. SERVICE_PAUSE_CONTINUE |
  172. SERVICE_INTERROGATE |
  173. SERVICE_USER_DEFINED_CONTROL)
  174. }
  175. [Flags]
  176. internal enum ACCESS_MASK : uint
  177. {
  178. DELETE = 0x00010000,
  179. READ_CONTROL = 0x00020000,
  180. WRITE_DAC = 0x00040000,
  181. WRITE_OWNER = 0x00080000,
  182. SYNCHRONIZE = 0x00100000,
  183. STANDARD_RIGHTS_REQUIRED = 0x000f0000,
  184. STANDARD_RIGHTS_READ = 0x00020000,
  185. STANDARD_RIGHTS_WRITE = 0x00020000,
  186. STANDARD_RIGHTS_EXECUTE = 0x00020000,
  187. STANDARD_RIGHTS_ALL = 0x001f0000,
  188. SPECIFIC_RIGHTS_ALL = 0x0000ffff,
  189. ACCESS_SYSTEM_SECURITY = 0x01000000,
  190. MAXIMUM_ALLOWED = 0x02000000,
  191. GENERIC_READ = 0x80000000,
  192. GENERIC_WRITE = 0x40000000,
  193. GENERIC_EXECUTE = 0x20000000,
  194. GENERIC_ALL = 0x10000000,
  195. DESKTOP_READOBJECTS = 0x00000001,
  196. DESKTOP_CREATEWINDOW = 0x00000002,
  197. DESKTOP_CREATEMENU = 0x00000004,
  198. DESKTOP_HOOKCONTROL = 0x00000008,
  199. DESKTOP_JOURNALRECORD = 0x00000010,
  200. DESKTOP_JOURNALPLAYBACK = 0x00000020,
  201. DESKTOP_ENUMERATE = 0x00000040,
  202. DESKTOP_WRITEOBJECTS = 0x00000080,
  203. DESKTOP_SWITCHDESKTOP = 0x00000100,
  204. WINSTA_ENUMDESKTOPS = 0x00000001,
  205. WINSTA_READATTRIBUTES = 0x00000002,
  206. WINSTA_ACCESSCLIPBOARD = 0x00000004,
  207. WINSTA_CREATEDESKTOP = 0x00000008,
  208. WINSTA_WRITEATTRIBUTES = 0x00000010,
  209. WINSTA_ACCESSGLOBALATOMS = 0x00000020,
  210. WINSTA_EXITWINDOWS = 0x00000040,
  211. WINSTA_ENUMERATE = 0x00000100,
  212. WINSTA_READSCREEN = 0x00000200,
  213. WINSTA_ALL_ACCESS = 0x0000037f
  214. }
  215. // http://msdn.microsoft.com/en-us/library/windows/desktop/ms685126(v=vs.85).aspx
  216. [StructLayout(LayoutKind.Sequential)]
  217. public struct SC_ACTION
  218. {
  219. public SC_ACTION_TYPE Type;
  220. /// <summary>
  221. /// The time to wait before performing the specified action, in milliseconds.
  222. /// </summary>
  223. public uint Delay;
  224. public SC_ACTION(SC_ACTION_TYPE type, uint delay)
  225. {
  226. this.Type = type;
  227. this.Delay = delay;
  228. }
  229. }
  230. internal enum SERVICE_CONFIG_INFOLEVEL
  231. {
  232. SERVICE_CONFIG_DESCRIPTION = 1,
  233. SERVICE_CONFIG_FAILURE_ACTIONS = 2,
  234. SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 3,
  235. SERVICE_CONFIG_FAILURE_ACTIONS_FLAG = 4,
  236. SERVICE_CONFIG_SERVICE_SID_INFO = 5,
  237. SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO = 6,
  238. SERVICE_CONFIG_PRESHUTDOWN_INFO = 7,
  239. SERVICE_CONFIG_TRIGGER_INFO = 8,
  240. SERVICE_CONFIG_PREFERRED_NODE = 9
  241. }
  242. public enum SC_ACTION_TYPE
  243. {
  244. SC_ACTION_NONE = 0,
  245. SC_ACTION_RESTART = 1,
  246. SC_ACTION_REBOOT = 2,
  247. SC_ACTION_RUN_COMMAND = 3
  248. }
  249. // http://msdn.microsoft.com/en-us/library/windows/desktop/ms685939(v=vs.85).aspx
  250. [StructLayout(LayoutKind.Sequential)]
  251. public struct SERVICE_FAILURE_ACTIONS
  252. {
  253. /// <summary>
  254. /// The time after which to reset the failure count to zero if there are no failures, in seconds.
  255. /// Specify INFINITE to indicate that this value should never be reset.
  256. /// </summary>
  257. public int dwResetPeriod;
  258. [MarshalAs(UnmanagedType.LPTStr)]
  259. public string lpRebootMsg;
  260. [MarshalAs(UnmanagedType.LPTStr)]
  261. public string lpCommand;
  262. public int cActions;
  263. public IntPtr/*SC_ACTION[]*/ lpsaActions;
  264. }
  265. }