ServiceHelper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. using System;
  2. using System.ComponentModel;
  3. using System.Runtime.ConstrainedExecution;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading;
  7. using Microsoft.Win32;
  8. namespace SvdCli.ServiceUtils
  9. {
  10. /// <summary>
  11. /// Windows 服务辅助类
  12. /// </summary>
  13. public static class ServiceHelper
  14. {
  15. /// <summary> 安装服务 </summary>
  16. /// <param name="serviceName">服务名</param>
  17. /// <param name="displayName">友好名称</param>
  18. /// <param name="binaryFilePath">映像文件路径,可带参数</param>
  19. /// <param name="description">服务描述</param>
  20. /// <param name="startType">启动类型</param>
  21. /// <param name="account">启动账户</param>
  22. /// <param name="dependencies">依赖服务</param>
  23. public static void Install(string serviceName, string displayName, string binaryFilePath, string description, ServiceStartType startType, ServiceAccount account = ServiceAccount.LocalSystem, string[] dependencies = null)
  24. {
  25. IntPtr scm = OpenSCManager();
  26. IntPtr service = IntPtr.Zero;
  27. try
  28. {
  29. service = Win32Class.CreateService(scm, serviceName, displayName, Win32Class.SERVICE_ALL_ACCESS, Win32Class.SERVICE_WIN32_OWN_PROCESS, startType, Win32Class.SERVICE_ERROR_NORMAL, binaryFilePath, null, IntPtr.Zero, ProcessDependencies(dependencies), GetServiceAccountName(account), null);
  30. if (service == IntPtr.Zero)
  31. {
  32. if (Marshal.GetLastWin32Error() == 0x431)//ERROR_SERVICE_EXISTS
  33. { throw new ApplicationException("服务已存在!"); }
  34. throw new ApplicationException("服务安装失败!");
  35. }
  36. //设置服务描述
  37. Win32Class.SERVICE_DESCRIPTION sd = new Win32Class.SERVICE_DESCRIPTION();
  38. try
  39. {
  40. sd.description = Marshal.StringToHGlobalUni(description);
  41. Win32Class.ChangeServiceConfig2(service, 1, ref sd);
  42. }
  43. finally
  44. {
  45. Marshal.FreeHGlobal(sd.description); //释放
  46. }
  47. }
  48. finally
  49. {
  50. if (service != IntPtr.Zero)
  51. {
  52. Win32Class.CloseServiceHandle(service);
  53. }
  54. Win32Class.CloseServiceHandle(scm);
  55. }
  56. }
  57. public static string GetBinPath(string serviceName)
  58. {
  59. var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\services\{serviceName}");
  60. return key?.GetValue("ImagePath") == null
  61. ? null
  62. : key.GetValue("ImagePath").ToString();
  63. }
  64. /// <summary> 卸载服务 </summary>
  65. /// <param name="serviceName">服务名</param>
  66. public static void Uninstall(string serviceName)
  67. {
  68. IntPtr scmHandle = IntPtr.Zero;
  69. IntPtr service = IntPtr.Zero;
  70. try
  71. {
  72. service = OpenService(serviceName, out scmHandle);
  73. StopService(service); //停止服务。里面会递归停止从属服务
  74. if (!Win32Class.DeleteService(service) && Marshal.GetLastWin32Error() != 0x430) //忽略已标记为删除的服务。ERROR_SERVICE_MARKED_FOR_DELETE
  75. {
  76. throw new ApplicationException("删除服务失败!");
  77. }
  78. }
  79. catch (ServiceNotExistException) { } //忽略服务不存在的情况
  80. finally
  81. {
  82. if (service != IntPtr.Zero)
  83. {
  84. Win32Class.CloseServiceHandle(service);
  85. Win32Class.CloseServiceHandle(scmHandle);//放if里面是因为如果服务打开失败,在OpenService里就已释放SCM
  86. }
  87. }
  88. }
  89. /// <summary> 转换帐户枚举为有效参数 </summary>
  90. private static string GetServiceAccountName(ServiceAccount account)
  91. {
  92. if (account == ServiceAccount.LocalService)
  93. {
  94. return @"NT AUTHORITY\LocalService";
  95. }
  96. if (account == ServiceAccount.NetworkService)
  97. {
  98. return @"NT AUTHORITY\NetworkService";
  99. }
  100. return null;
  101. }
  102. /// <summary> 处理依赖服务参数 </summary>
  103. private static string ProcessDependencies(string[] dependencies)
  104. {
  105. if (dependencies == null || dependencies.Length == 0)
  106. {
  107. return null;
  108. }
  109. StringBuilder sb = new StringBuilder();
  110. foreach (string s in dependencies)
  111. {
  112. sb.Append(s).Append('\0');
  113. }
  114. sb.Append('\0');
  115. return sb.ToString();
  116. }
  117. /// <summary> 打开服务管理器 </summary>
  118. private static IntPtr OpenSCManager()
  119. {
  120. IntPtr scm = Win32Class.OpenSCManager(null, null, Win32Class.SC_MANAGER_ALL_ACCESS);
  121. if (scm == IntPtr.Zero)
  122. {
  123. throw new ApplicationException("打开服务管理器失败!");
  124. }
  125. return scm;
  126. }
  127. /// <summary> 打开服务 </summary>
  128. /// <param name="serviceName">服务名称</param>
  129. /// <param name="scmHandle">服务管理器句柄。供调用者释放</param>
  130. private static IntPtr OpenService(string serviceName, out IntPtr scmHandle)
  131. {
  132. scmHandle = OpenSCManager();
  133. IntPtr service = Win32Class.OpenService(scmHandle, serviceName, Win32Class.SERVICE_ALL_ACCESS);
  134. if (service == IntPtr.Zero)
  135. {
  136. int errCode = Marshal.GetLastWin32Error();
  137. Win32Class.CloseServiceHandle(scmHandle); //关闭SCM
  138. if (errCode == 0x424) //ERROR_SERVICE_DOES_NOT_EXIST
  139. {
  140. throw new ServiceNotExistException();
  141. }
  142. throw new Win32Exception();
  143. }
  144. return service;
  145. }
  146. /// <summary> 停止服务 </summary>
  147. private static void StopService(IntPtr service)
  148. {
  149. ServiceState currState = GetServiceStatus(service);
  150. if (currState == ServiceState.Stopped)
  151. {
  152. return;
  153. }
  154. if (currState != ServiceState.StopPending)
  155. {
  156. //递归停止从属服务
  157. string[] childSvs = EnumDependentServices(service, EnumServiceState.Active);
  158. if (childSvs.Length != 0)
  159. {
  160. IntPtr scm = OpenSCManager();
  161. try
  162. {
  163. foreach (string childSv in childSvs)
  164. {
  165. StopService(Win32Class.OpenService(scm, childSv, Win32Class.SERVICE_STOP));
  166. }
  167. }
  168. finally
  169. {
  170. Win32Class.CloseServiceHandle(scm);
  171. }
  172. }
  173. Win32Class.SERVICE_STATUS status = new Win32Class.SERVICE_STATUS();
  174. Win32Class.ControlService(service, Win32Class.SERVICE_CONTROL_STOP, ref status); //发送停止指令
  175. }
  176. if (!WaitForStatus(service, ServiceState.Stopped, new TimeSpan(0, 0, 30)))
  177. {
  178. throw new ApplicationException("停止服务失败!");
  179. }
  180. }
  181. /// <summary> 遍历从属服务 </summary>
  182. /// <param name="serviceHandle"></param>
  183. /// <param name="state">选择性遍历(活动、非活动、全部)</param>
  184. private static string[] EnumDependentServices(IntPtr serviceHandle, EnumServiceState state)
  185. {
  186. int bytesNeeded = 0; //存放从属服务的空间大小,由API返回
  187. int numEnumerated = 0; //从属服务数,由API返回
  188. //先尝试以空结构获取,如获取成功说明从属服务为空,否则拿到上述俩值
  189. if (Win32Class.EnumDependentServices(serviceHandle, state, IntPtr.Zero, 0, ref bytesNeeded, ref numEnumerated))
  190. {
  191. return new string[0];
  192. }
  193. if (Marshal.GetLastWin32Error() != 0xEA) //仅当错误值不是大小不够(ERROR_MORE_DATA)时才抛异常
  194. {
  195. throw new Win32Exception();
  196. }
  197. //在非托管区域创建指针
  198. IntPtr structsStart = Marshal.AllocHGlobal(new IntPtr(bytesNeeded));
  199. try
  200. {
  201. //往上述指针处塞存放从属服务的结构组,每个从属服务是一个结构
  202. if (!Win32Class.EnumDependentServices(serviceHandle, state, structsStart, bytesNeeded, ref bytesNeeded, ref numEnumerated))
  203. {
  204. throw new Win32Exception();
  205. }
  206. string[] dependentServices = new string[numEnumerated];
  207. int sizeOfStruct = Marshal.SizeOf(typeof(Win32Class.ENUM_SERVICE_STATUS)); //每个结构的大小
  208. long structsStartAsInt64 = structsStart.ToInt64();
  209. for (int i = 0; i < numEnumerated; i++)
  210. {
  211. Win32Class.ENUM_SERVICE_STATUS structure = new Win32Class.ENUM_SERVICE_STATUS();
  212. IntPtr ptr = new IntPtr(structsStartAsInt64 + i * sizeOfStruct); //根据起始指针、结构次序和结构大小推算各结构起始指针
  213. Marshal.PtrToStructure(ptr, structure); //根据指针拿到结构
  214. dependentServices[i] = structure.serviceName; //从结构中拿到服务名
  215. }
  216. return dependentServices;
  217. }
  218. finally
  219. {
  220. Marshal.FreeHGlobal(structsStart);
  221. }
  222. }
  223. /// <summary> 获取服务状态 </summary>
  224. private static ServiceState GetServiceStatus(IntPtr service)
  225. {
  226. Win32Class.SERVICE_STATUS status = new Win32Class.SERVICE_STATUS();
  227. if (!Win32Class.QueryServiceStatus(service, ref status))
  228. {
  229. throw new ApplicationException("获取服务状态出错!");
  230. }
  231. return status.currentState;
  232. }
  233. /// <summary> 等候服务至目标状态 </summary>
  234. private static bool WaitForStatus(IntPtr serviceHandle, ServiceState desiredStatus, TimeSpan timeout)
  235. {
  236. DateTime startTime = DateTime.Now;
  237. while (GetServiceStatus(serviceHandle) != desiredStatus)
  238. {
  239. if (DateTime.Now - startTime > timeout) { return false; }
  240. Thread.Sleep(200);
  241. }
  242. return true;
  243. }
  244. /// <summary> Win32 API相关 </summary>
  245. private static class Win32Class
  246. {
  247. #region 常量定义
  248. /// <summary>
  249. /// 打开服务管理器时请求的权限:全部
  250. /// </summary>
  251. public const int SC_MANAGER_ALL_ACCESS = 0xF003F;
  252. /// <summary>
  253. /// 服务类型:自有进程类服务
  254. /// </summary>
  255. public const int SERVICE_WIN32_OWN_PROCESS = 0x10;
  256. /// <summary>
  257. /// 打开服务时请求的权限:全部
  258. /// </summary>
  259. public const int SERVICE_ALL_ACCESS = 0xF01FF;
  260. /// <summary>
  261. /// 打开服务时请求的权限:停止
  262. /// </summary>
  263. public const int SERVICE_STOP = 0x20;
  264. /// <summary>
  265. /// 服务操作标记:停止
  266. /// </summary>
  267. public const int SERVICE_CONTROL_STOP = 0x1;
  268. /// <summary>
  269. /// 服务出错行为标记
  270. /// </summary>
  271. public const int SERVICE_ERROR_NORMAL = 0x1;
  272. #endregion 常量定义
  273. #region API所需类和结构定义
  274. /// <summary>
  275. /// 服务状态结构体
  276. /// </summary>
  277. [StructLayout(LayoutKind.Sequential)]
  278. public struct SERVICE_STATUS
  279. {
  280. public int serviceType;
  281. public ServiceState currentState;
  282. public int controlsAccepted;
  283. public int win32ExitCode;
  284. public int serviceSpecificExitCode;
  285. public int checkPoint;
  286. public int waitHint;
  287. }
  288. /// <summary>
  289. /// 服务描述结构体
  290. /// </summary>
  291. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  292. public struct SERVICE_DESCRIPTION
  293. {
  294. public IntPtr description;
  295. }
  296. /// <summary>
  297. /// 服务状态结构体。遍历API会用到
  298. /// </summary>
  299. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  300. public class ENUM_SERVICE_STATUS
  301. {
  302. public string serviceName;
  303. public string displayName;
  304. public int serviceType;
  305. public int currentState;
  306. public int controlsAccepted;
  307. public int win32ExitCode;
  308. public int serviceSpecificExitCode;
  309. public int checkPoint;
  310. public int waitHint;
  311. }
  312. #endregion API所需类和结构定义
  313. #region API定义
  314. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  315. public static extern bool ChangeServiceConfig2(IntPtr serviceHandle, uint infoLevel, ref SERVICE_DESCRIPTION serviceDesc);
  316. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  317. public static extern IntPtr OpenSCManager(string machineName, string databaseName, int dwDesiredAccess);
  318. [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  319. public static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, int dwDesiredAccess);
  320. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  321. public static extern IntPtr CreateService(IntPtr hSCManager, string lpServiceName, string lpDisplayName, int dwDesiredAccess, int dwServiceType, ServiceStartType dwStartType, int dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);
  322. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  323. public static extern bool CloseServiceHandle(IntPtr handle);
  324. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  325. public static extern bool QueryServiceStatus(IntPtr hService, ref SERVICE_STATUS lpServiceStatus);
  326. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  327. public static extern bool DeleteService(IntPtr serviceHandle);
  328. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  329. public static extern bool ControlService(IntPtr hService, int dwControl, ref SERVICE_STATUS lpServiceStatus);
  330. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  331. public static extern bool EnumDependentServices(IntPtr serviceHandle, EnumServiceState serviceState, IntPtr bufferOfENUM_SERVICE_STATUS, int bufSize, ref int bytesNeeded, ref int numEnumerated);
  332. #endregion API定义
  333. }
  334. /// <summary> 服务状态枚举。用于遍历从属服务API </summary>
  335. private enum EnumServiceState
  336. {
  337. Active = 1,
  338. //InActive = 2,
  339. //All = 3
  340. }
  341. /// <summary> 服务状态 </summary>
  342. private enum ServiceState
  343. {
  344. Stopped = 1,
  345. //StartPending = 2,
  346. StopPending = 3,
  347. //Running = 4,
  348. //ContinuePending = 5,
  349. //PausePending = 6,
  350. //Paused = 7
  351. }
  352. }
  353. }