ServiceDescriptor.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Runtime.InteropServices;
  7. using System.ServiceProcess;
  8. using System.Text;
  9. using System.IO;
  10. using System.Net;
  11. using WMI;
  12. using System.Xml;
  13. using System.Threading;
  14. using Microsoft.Win32;
  15. namespace winsw
  16. {
  17. /// <summary>
  18. /// In-memory representation of the configuration file.
  19. /// </summary>
  20. public class ServiceDescriptor
  21. {
  22. private readonly XmlDocument dom = new XmlDocument();
  23. /// <summary>
  24. /// Where did we find the configuration file?
  25. ///
  26. /// This string is "c:\abc\def\ghi" when the configuration XML is "c:\abc\def\ghi.xml"
  27. /// </summary>
  28. public readonly string BasePath;
  29. /// <summary>
  30. /// The file name portion of the configuration file.
  31. ///
  32. /// In the above example, this would be "ghi".
  33. /// </summary>
  34. public readonly string BaseName;
  35. public static string ExecutablePath
  36. {
  37. get
  38. {
  39. // this returns the executable name as given by the calling process, so
  40. // it needs to be absolutized.
  41. string p = Environment.GetCommandLineArgs()[0];
  42. return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p);
  43. }
  44. }
  45. public ServiceDescriptor()
  46. {
  47. // find co-located configuration xml. We search up to the ancestor directories to simplify debugging,
  48. // as well as trimming off ".vshost" suffix (which is used during debugging)
  49. string p = ExecutablePath;
  50. string baseName = Path.GetFileNameWithoutExtension(p);
  51. if (baseName.EndsWith(".vshost")) baseName = baseName.Substring(0, baseName.Length - 7);
  52. while (true)
  53. {
  54. p = Path.GetDirectoryName(p);
  55. if (File.Exists(Path.Combine(p, baseName + ".xml")))
  56. break;
  57. }
  58. // register the base directory as environment variable so that future expansions can refer to this.
  59. Environment.SetEnvironmentVariable("BASE", p);
  60. BaseName = baseName;
  61. BasePath = Path.Combine(p, BaseName);
  62. dom.Load(BasePath + ".xml");
  63. }
  64. private string SingleElement(string tagName)
  65. {
  66. var n = dom.SelectSingleNode("//" + tagName);
  67. if (n == null) throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
  68. return Environment.ExpandEnvironmentVariables(n.InnerText);
  69. }
  70. /// <summary>
  71. /// Path to the executable.
  72. /// </summary>
  73. public string Executable
  74. {
  75. get
  76. {
  77. return SingleElement("executable");
  78. }
  79. }
  80. /// <summary>
  81. /// Optionally specify a different Path to an executable to shutdown the service.
  82. /// </summary>
  83. public string StopExecutable
  84. {
  85. get
  86. {
  87. return SingleElement("stopexecutable");
  88. }
  89. }
  90. /// <summary>
  91. /// Arguments or multiple optional argument elements which overrule the arguments element.
  92. /// </summary>
  93. public string Arguments
  94. {
  95. get
  96. {
  97. string arguments = AppendTags("argument");
  98. if (arguments == null)
  99. {
  100. var tagName = "arguments";
  101. var argumentsNode = dom.SelectSingleNode("//" + tagName);
  102. if (argumentsNode == null)
  103. {
  104. if (AppendTags("startargument") == null)
  105. {
  106. throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
  107. }
  108. else
  109. {
  110. return "";
  111. }
  112. }
  113. return Environment.ExpandEnvironmentVariables(argumentsNode.InnerText);
  114. }
  115. else
  116. {
  117. return arguments;
  118. }
  119. }
  120. }
  121. /// <summary>
  122. /// Multiple optional startargument elements.
  123. /// </summary>
  124. public string Startarguments
  125. {
  126. get
  127. {
  128. return AppendTags("startargument");
  129. }
  130. }
  131. /// <summary>
  132. /// Multiple optional stopargument elements.
  133. /// </summary>
  134. public string Stoparguments
  135. {
  136. get
  137. {
  138. return AppendTags("stopargument");
  139. }
  140. }
  141. /// <summary>
  142. /// Combines the contents of all the elements of the given name,
  143. /// or return null if no element exists. Handles whitespace quotatoin.
  144. /// </summary>
  145. private string AppendTags(string tagName)
  146. {
  147. XmlNode argumentNode = dom.SelectSingleNode("//" + tagName);
  148. if (argumentNode == null)
  149. {
  150. return null;
  151. }
  152. else
  153. {
  154. string arguments = "";
  155. foreach (XmlNode argument in dom.SelectNodes("//" + tagName))
  156. {
  157. string token = Environment.ExpandEnvironmentVariables(argument.InnerText);
  158. if (token.StartsWith("\"") && token.EndsWith("\""))
  159. {
  160. // for backward compatibility, if the argument is already quoted, leave it as is.
  161. // in earlier versions we didn't handle quotation, so the user might have worked
  162. // around it by themselves
  163. }
  164. else
  165. {
  166. if (token.Contains(" "))
  167. {
  168. token = '"' + token + '"';
  169. }
  170. }
  171. arguments += " " + token;
  172. }
  173. return arguments;
  174. }
  175. }
  176. /// <summary>
  177. /// LogDirectory is the service wrapper executable directory or the optionally specified logpath element.
  178. /// </summary>
  179. public string LogDirectory
  180. {
  181. get
  182. {
  183. XmlNode loggingNode = dom.SelectSingleNode("//logpath");
  184. if (loggingNode != null)
  185. {
  186. return Environment.ExpandEnvironmentVariables(loggingNode.InnerText);
  187. }
  188. else
  189. {
  190. return Path.GetDirectoryName(ExecutablePath);
  191. }
  192. }
  193. }
  194. /// <summary>
  195. /// Logmode to 'reset', 'rotate' once or 'append' [default] the out.log and err.log files.
  196. /// </summary>
  197. public string Logmode
  198. {
  199. get
  200. {
  201. XmlNode logmodeNode = dom.SelectSingleNode("//logmode");
  202. if (logmodeNode == null)
  203. {
  204. return "append";
  205. }
  206. else
  207. {
  208. return logmodeNode.InnerText;
  209. }
  210. }
  211. }
  212. /// <summary>
  213. /// Optionally specified depend services that must start before this service starts.
  214. /// </summary>
  215. public string[] ServiceDependencies
  216. {
  217. get
  218. {
  219. System.Collections.ArrayList serviceDependencies = new System.Collections.ArrayList();
  220. foreach (XmlNode depend in dom.SelectNodes("//depend"))
  221. {
  222. serviceDependencies.Add(depend.InnerText);
  223. }
  224. return (string[])serviceDependencies.ToArray(typeof(string));
  225. }
  226. }
  227. public string Id
  228. {
  229. get
  230. {
  231. return SingleElement("id");
  232. }
  233. }
  234. public string Caption
  235. {
  236. get
  237. {
  238. return SingleElement("name");
  239. }
  240. }
  241. public string Description
  242. {
  243. get
  244. {
  245. return SingleElement("description");
  246. }
  247. }
  248. /// <summary>
  249. /// True if the service should when finished on shutdown.
  250. /// </summary>
  251. public bool BeepOnShutdown
  252. {
  253. get
  254. {
  255. return dom.SelectSingleNode("//beeponshutdown") != null;
  256. }
  257. }
  258. /// <summary>
  259. /// The estimated time required for a pending stop operation, in milliseconds (default 15 secs).
  260. /// Before the specified amount of time has elapsed, the service should make its next call to the SetServiceStatus function
  261. /// with either an incremented checkPoint value or a change in currentState. (see http://msdn.microsoft.com/en-us/library/ms685996.aspx)
  262. /// </summary>
  263. public int WaitHint
  264. {
  265. get
  266. {
  267. XmlNode waithintNode = dom.SelectSingleNode("//waithint");
  268. if (waithintNode == null)
  269. {
  270. return 15000;
  271. }
  272. else
  273. {
  274. return int.Parse(waithintNode.InnerText);
  275. }
  276. }
  277. }
  278. /// <summary>
  279. /// The time, in milliseconds (default 1 sec), before the service should make its next call to the SetServiceStatus function
  280. /// with an incremented checkPoint value.
  281. /// Do not wait longer than the wait hint. A good interval is one-tenth of the wait hint but not less than 1 second and not more than 10 seconds.
  282. /// </summary>
  283. public int SleepTime
  284. {
  285. get
  286. {
  287. XmlNode sleeptimeNode = dom.SelectSingleNode("//sleeptime");
  288. if (sleeptimeNode == null)
  289. {
  290. return 1000;
  291. }
  292. else
  293. {
  294. return int.Parse(sleeptimeNode.InnerText);
  295. }
  296. }
  297. }
  298. /// <summary>
  299. /// True if the service can interact with the desktop.
  300. /// </summary>
  301. public bool Interactive
  302. {
  303. get
  304. {
  305. return dom.SelectSingleNode("//interactive") != null;
  306. }
  307. }
  308. /// <summary>
  309. /// Environment variable overrides
  310. /// </summary>
  311. public Dictionary<string, string> EnvironmentVariables
  312. {
  313. get
  314. {
  315. Dictionary<string, string> map = new Dictionary<string, string>();
  316. foreach (XmlNode n in dom.SelectNodes("//env"))
  317. {
  318. string key = n.Attributes["name"].Value;
  319. string value = Environment.ExpandEnvironmentVariables(n.Attributes["value"].Value);
  320. map[key] = value;
  321. Environment.SetEnvironmentVariable(key, value);
  322. }
  323. return map;
  324. }
  325. }
  326. /// <summary>
  327. /// List of downloads to be performed by the wrapper before starting
  328. /// a service.
  329. /// </summary>
  330. public List<Download> Downloads
  331. {
  332. get
  333. {
  334. List<Download> r = new List<Download>();
  335. foreach (XmlNode n in dom.SelectNodes("//download"))
  336. {
  337. r.Add(new Download(n));
  338. }
  339. return r;
  340. }
  341. }
  342. }
  343. }