Main.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. using Advapi32;
  16. using System.Management;
  17. namespace winsw
  18. {
  19. public struct SERVICE_STATUS
  20. {
  21. public int serviceType;
  22. public int currentState;
  23. public int controlsAccepted;
  24. public int win32ExitCode;
  25. public int serviceSpecificExitCode;
  26. public int checkPoint;
  27. public int waitHint;
  28. }
  29. public enum State
  30. {
  31. SERVICE_STOPPED = 0x00000001,
  32. SERVICE_START_PENDING = 0x00000002,
  33. SERVICE_STOP_PENDING = 0x00000003,
  34. SERVICE_RUNNING = 0x00000004,
  35. SERVICE_CONTINUE_PENDING = 0x00000005,
  36. SERVICE_PAUSE_PENDING = 0x00000006,
  37. SERVICE_PAUSED = 0x00000007,
  38. }
  39. public class WrapperService : ServiceBase, EventLogger
  40. {
  41. [DllImport("ADVAPI32.DLL")]
  42. private static extern bool SetServiceStatus(IntPtr hServiceStatus, ref SERVICE_STATUS lpServiceStatus);
  43. [DllImport("Kernel32.dll", SetLastError = true)]
  44. public static extern int SetStdHandle(int device, IntPtr handle);
  45. private SERVICE_STATUS wrapperServiceStatus;
  46. private Process process = new Process();
  47. private ServiceDescriptor descriptor;
  48. private Dictionary<string, string> envs;
  49. /// <summary>
  50. /// Indicates to the watch dog thread that we are going to terminate the process,
  51. /// so don't try to kill us when the child exits.
  52. /// </summary>
  53. private bool orderlyShutdown;
  54. private bool systemShuttingdown;
  55. public WrapperService()
  56. {
  57. this.descriptor = new ServiceDescriptor();
  58. this.ServiceName = descriptor.Id;
  59. this.CanShutdown = true;
  60. this.CanStop = true;
  61. this.CanPauseAndContinue = false;
  62. this.AutoLog = true;
  63. this.systemShuttingdown = false;
  64. }
  65. /// <summary>
  66. /// Process the file copy instructions, so that we can replace files that are always in use while
  67. /// the service runs.
  68. /// </summary>
  69. private void HandleFileCopies()
  70. {
  71. var file = descriptor.BasePath + ".copies";
  72. if (!File.Exists(file))
  73. return; // nothing to handle
  74. try
  75. {
  76. using (var tr = new StreamReader(file,Encoding.UTF8))
  77. {
  78. string line;
  79. while ((line = tr.ReadLine()) != null)
  80. {
  81. LogEvent("Handling copy: " + line);
  82. string[] tokens = line.Split('>');
  83. if (tokens.Length > 2)
  84. {
  85. LogEvent("Too many delimiters in " + line);
  86. continue;
  87. }
  88. CopyFile(tokens[0], tokens[1]);
  89. }
  90. }
  91. }
  92. finally
  93. {
  94. File.Delete(file);
  95. }
  96. }
  97. /// <summary>
  98. /// File replacement.
  99. /// </summary>
  100. private void CopyFile(string sourceFileName, string destFileName)
  101. {
  102. try
  103. {
  104. File.Delete(destFileName);
  105. File.Move(sourceFileName, destFileName);
  106. }
  107. catch (IOException e)
  108. {
  109. LogEvent("Failed to copy :" + sourceFileName + " to " + destFileName + " because " + e.Message);
  110. }
  111. }
  112. /// <summary>
  113. /// Starts a thread that protects the execution with a try/catch block.
  114. /// It appears that in .NET, unhandled exception in any thread causes the app to terminate
  115. /// http://msdn.microsoft.com/en-us/library/ms228965.aspx
  116. /// </summary>
  117. private void StartThread(ThreadStart main)
  118. {
  119. new Thread(delegate() {
  120. try
  121. {
  122. main();
  123. }
  124. catch (Exception e)
  125. {
  126. WriteEvent("Thread failed unexpectedly",e);
  127. }
  128. }).Start();
  129. }
  130. /// <summary>
  131. /// Handle the creation of the logfiles based on the optional logmode setting.
  132. /// </summary>
  133. private void HandleLogfiles()
  134. {
  135. string logDirectory = descriptor.LogDirectory;
  136. if (!Directory.Exists(logDirectory))
  137. {
  138. Directory.CreateDirectory(logDirectory);
  139. }
  140. LogHandler logAppender = descriptor.LogHandler;
  141. logAppender.EventLogger = this;
  142. logAppender.log(process.StandardOutput.BaseStream, process.StandardError.BaseStream);
  143. }
  144. public void LogEvent(String message)
  145. {
  146. if (systemShuttingdown)
  147. {
  148. /* NOP - cannot call EventLog because of shutdown. */
  149. }
  150. else
  151. {
  152. EventLog.WriteEntry(message);
  153. }
  154. }
  155. public void LogEvent(String message, EventLogEntryType type)
  156. {
  157. if (systemShuttingdown)
  158. {
  159. /* NOP - cannot call EventLog because of shutdown. */
  160. }
  161. else
  162. {
  163. EventLog.WriteEntry(message, type);
  164. }
  165. }
  166. private void WriteEvent(Exception exception)
  167. {
  168. WriteEvent(exception.Message + "\nStacktrace:" + exception.StackTrace);
  169. }
  170. private void WriteEvent(String message, Exception exception)
  171. {
  172. WriteEvent(message + "\nMessage:" + exception.Message + "\nStacktrace:" + exception.StackTrace);
  173. }
  174. private void WriteEvent(String message)
  175. {
  176. string logfilename = Path.Combine(descriptor.LogDirectory, descriptor.BaseName + ".wrapper.log");
  177. StreamWriter log = new StreamWriter(logfilename, true);
  178. log.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + message);
  179. log.Flush();
  180. log.Close();
  181. }
  182. protected override void OnStart(string[] _)
  183. {
  184. envs = descriptor.EnvironmentVariables;
  185. foreach (string key in envs.Keys)
  186. {
  187. LogEvent("envar " + key + '=' + envs[key]);
  188. }
  189. HandleFileCopies();
  190. // handle downloads
  191. foreach (Download d in descriptor.Downloads)
  192. {
  193. LogEvent("Downloading: " + d.From+ " to "+d.To);
  194. try
  195. {
  196. d.Perform();
  197. }
  198. catch (Exception e)
  199. {
  200. LogEvent("Failed to download " + d.From + " to " + d.To + "\n" + e.Message);
  201. WriteEvent("Failed to download " + d.From +" to "+d.To, e);
  202. // but just keep going
  203. }
  204. }
  205. string startarguments = descriptor.Startarguments;
  206. if (startarguments == null)
  207. {
  208. startarguments = descriptor.Arguments;
  209. }
  210. else
  211. {
  212. startarguments += " " + descriptor.Arguments;
  213. }
  214. LogEvent("Starting " + descriptor.Executable + ' ' + startarguments);
  215. WriteEvent("Starting " + descriptor.Executable + ' ' + startarguments);
  216. StartProcess(process, startarguments, descriptor.Executable);
  217. // send stdout and stderr to its respective output file.
  218. HandleLogfiles();
  219. process.StandardInput.Close(); // nothing for you to read!
  220. }
  221. protected override void OnShutdown()
  222. {
  223. // WriteEvent("OnShutdown");
  224. try
  225. {
  226. this.systemShuttingdown = true;
  227. StopIt();
  228. }
  229. catch (Exception ex)
  230. {
  231. WriteEvent("Shutdown exception", ex);
  232. }
  233. }
  234. protected override void OnStop()
  235. {
  236. // WriteEvent("OnStop");
  237. try
  238. {
  239. StopIt();
  240. }
  241. catch (Exception ex)
  242. {
  243. WriteEvent("Stop exception", ex);
  244. }
  245. }
  246. private void StopIt()
  247. {
  248. string stoparguments = descriptor.Stoparguments;
  249. LogEvent("Stopping " + descriptor.Id);
  250. WriteEvent("Stopping " + descriptor.Id);
  251. orderlyShutdown = true;
  252. if (stoparguments == null)
  253. {
  254. try
  255. {
  256. WriteEvent("ProcessKill " + process.Id);
  257. StopProcessAndChildren(process.Id);
  258. }
  259. catch (InvalidOperationException)
  260. {
  261. // already terminated
  262. }
  263. }
  264. else
  265. {
  266. SignalShutdownPending();
  267. stoparguments += " " + descriptor.Arguments;
  268. Process stopProcess = new Process();
  269. String executable = descriptor.StopExecutable;
  270. if (executable == null)
  271. {
  272. executable = descriptor.Executable;
  273. }
  274. StartProcess(stopProcess, stoparguments, executable);
  275. WriteEvent("WaitForProcessToExit "+process.Id+"+"+stopProcess.Id);
  276. WaitForProcessToExit(process);
  277. WaitForProcessToExit(stopProcess);
  278. SignalShutdownComplete();
  279. }
  280. if (systemShuttingdown && descriptor.BeepOnShutdown)
  281. {
  282. Console.Beep();
  283. }
  284. WriteEvent("Finished " + descriptor.Id);
  285. }
  286. private void StopProcessAndChildren(int pid)
  287. {
  288. var searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
  289. foreach (var mo in searcher.Get())
  290. {
  291. StopProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
  292. }
  293. try
  294. {
  295. var proc = Process.GetProcessById(pid);
  296. proc.Kill();
  297. }
  298. catch (ArgumentException)
  299. {
  300. // Process already exited.
  301. }
  302. }
  303. private void WaitForProcessToExit(Process process)
  304. {
  305. SignalShutdownPending();
  306. try
  307. {
  308. // WriteEvent("WaitForProcessToExit [start]");
  309. while (!process.WaitForExit(descriptor.SleepTime.Milliseconds))
  310. {
  311. SignalShutdownPending();
  312. // WriteEvent("WaitForProcessToExit [repeat]");
  313. }
  314. }
  315. catch (InvalidOperationException)
  316. {
  317. // already terminated
  318. }
  319. // WriteEvent("WaitForProcessToExit [finished]");
  320. }
  321. private void SignalShutdownPending()
  322. {
  323. IntPtr handle = this.ServiceHandle;
  324. wrapperServiceStatus.checkPoint++;
  325. wrapperServiceStatus.waitHint = descriptor.WaitHint.Milliseconds;
  326. // WriteEvent("SignalShutdownPending " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  327. wrapperServiceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
  328. SetServiceStatus(handle, ref wrapperServiceStatus);
  329. }
  330. private void SignalShutdownComplete()
  331. {
  332. IntPtr handle = this.ServiceHandle;
  333. wrapperServiceStatus.checkPoint++;
  334. // WriteEvent("SignalShutdownComplete " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  335. wrapperServiceStatus.currentState = (int)State.SERVICE_STOPPED;
  336. SetServiceStatus(handle, ref wrapperServiceStatus);
  337. }
  338. private void StartProcess(Process process, string arguments, String executable)
  339. {
  340. var ps = process.StartInfo;
  341. ps.FileName = executable;
  342. ps.Arguments = arguments;
  343. ps.WorkingDirectory = descriptor.WorkingDirectory;
  344. ps.CreateNoWindow = false;
  345. ps.UseShellExecute = false;
  346. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  347. ps.RedirectStandardOutput = true;
  348. ps.RedirectStandardError = true;
  349. foreach (string key in envs.Keys)
  350. System.Environment.SetEnvironmentVariable(key, envs[key]);
  351. // ps.EnvironmentVariables[key] = envs[key]; // bugged (lower cases all variable names due to StringDictionary being used, see http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=326163)
  352. process.Start();
  353. WriteEvent("Started " + process.Id);
  354. // monitor the completion of the process
  355. StartThread(delegate()
  356. {
  357. string msg = process.Id + " - " + process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  358. process.WaitForExit();
  359. try
  360. {
  361. if (orderlyShutdown)
  362. {
  363. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Information);
  364. }
  365. else
  366. {
  367. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Warning);
  368. Environment.Exit(process.ExitCode);
  369. }
  370. }
  371. catch (InvalidOperationException ioe)
  372. {
  373. LogEvent("WaitForExit " + ioe.Message);
  374. }
  375. try
  376. {
  377. process.Dispose();
  378. }
  379. catch (InvalidOperationException ioe)
  380. {
  381. LogEvent("Dispose " + ioe.Message);
  382. }
  383. });
  384. }
  385. public static int Main(string[] args)
  386. {
  387. try
  388. {
  389. Run(args);
  390. return 0;
  391. }
  392. catch (WmiException e)
  393. {
  394. Console.Error.WriteLine(e);
  395. return (int)e.ErrorCode;
  396. }
  397. catch (Exception e)
  398. {
  399. Console.Error.WriteLine(e);
  400. return -1;
  401. }
  402. }
  403. private static void ThrowNoSuchService()
  404. {
  405. throw new WmiException(ReturnValue.NoSuchService);
  406. }
  407. public static void Run(string[] _args)
  408. {
  409. if (_args.Length > 0)
  410. {
  411. var d = new ServiceDescriptor();
  412. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  413. Win32Service s = svc.Select(d.Id);
  414. var args = new List<string>(Array.AsReadOnly(_args));
  415. if (args[0] == "/redirect")
  416. {
  417. // Redirect output
  418. // One might ask why we support this when the caller
  419. // can redirect the output easily. The answer is for supporting UAC.
  420. // On UAC-enabled Windows such as Vista, SCM operation requires
  421. // elevated privileges, thus winsw.exe needs to be launched
  422. // accordingly. This in turn limits what the caller can do,
  423. // and among other things it makes it difficult for the caller
  424. // to read stdout/stderr. Thus redirection becomes handy.
  425. var f = new FileStream(args[1], FileMode.Create);
  426. var w = new StreamWriter(f);
  427. w.AutoFlush = true;
  428. Console.SetOut(w);
  429. Console.SetError(w);
  430. var handle = f.Handle;
  431. SetStdHandle(-11, handle); // set stdout
  432. SetStdHandle(-12, handle); // set stder
  433. args = args.GetRange(2, args.Count - 2);
  434. }
  435. args[0] = args[0].ToLower();
  436. if (args[0] == "install")
  437. {
  438. string username=null, password=null;
  439. if (args.Count > 1 && args[1] == "/p")
  440. {
  441. // we expected username/password on stdin
  442. Console.Write("Username: ");
  443. username = Console.ReadLine();
  444. Console.Write("Password: ");
  445. password = ReadPassword();
  446. }
  447. else
  448. {
  449. if (d.HasServiceAccount())
  450. {
  451. username = d.ServiceAccountUser;
  452. password = d.ServiceAccountPassword;
  453. }
  454. }
  455. svc.Create (
  456. d.Id,
  457. d.Caption,
  458. "\"" + d.ExecutablePath + "\"",
  459. WMI.ServiceType.OwnProcess,
  460. ErrorControl.UserNotified,
  461. StartMode.Automatic,
  462. d.Interactive,
  463. username,
  464. password,
  465. d.ServiceDependencies);
  466. // update the description
  467. /* Somehow this doesn't work, even though it doesn't report an error
  468. Win32Service s = svc.Select(d.Id);
  469. s.Description = d.Description;
  470. s.Commit();
  471. */
  472. // so using a classic method to set the description. Ugly.
  473. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  474. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  475. var actions = d.FailureActions;
  476. if (actions.Count > 0)
  477. {// set the failure actions
  478. using (Advapi32.ServiceManager scm = new Advapi32.ServiceManager())
  479. {
  480. using (Advapi32.Service sc = scm.Open(d.Id))
  481. {
  482. sc.ChangeConfig(d.ResetFailureAfter, actions);
  483. }
  484. }
  485. }
  486. }
  487. if (args[0] == "uninstall")
  488. {
  489. if (s == null)
  490. return; // there's no such service, so consider it already uninstalled
  491. try
  492. {
  493. s.Delete();
  494. }
  495. catch (WmiException e)
  496. {
  497. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  498. return; // it's already uninstalled, so consider it a success
  499. throw e;
  500. }
  501. }
  502. if (args[0] == "start")
  503. {
  504. if (s == null) ThrowNoSuchService();
  505. s.StartService();
  506. }
  507. if (args[0] == "stop")
  508. {
  509. if (s == null) ThrowNoSuchService();
  510. s.StopService();
  511. }
  512. if (args[0] == "restart")
  513. {
  514. if (s == null)
  515. ThrowNoSuchService();
  516. if(s.Started)
  517. s.StopService();
  518. while (s.Started)
  519. {
  520. Thread.Sleep(1000);
  521. s = svc.Select(d.Id);
  522. }
  523. s.StartService();
  524. }
  525. if (args[0] == "status")
  526. {
  527. if (s == null)
  528. Console.WriteLine("NonExistent");
  529. else if (s.Started)
  530. Console.WriteLine("Started");
  531. else
  532. Console.WriteLine("Stopped");
  533. }
  534. if (args[0] == "test")
  535. {
  536. WrapperService wsvc = new WrapperService();
  537. wsvc.OnStart(args.ToArray());
  538. Thread.Sleep(1000);
  539. wsvc.OnStop();
  540. }
  541. return;
  542. }
  543. ServiceBase.Run(new WrapperService());
  544. }
  545. private static string ReadPassword()
  546. {
  547. StringBuilder buf = new StringBuilder();
  548. ConsoleKeyInfo key;
  549. while (true)
  550. {
  551. key = Console.ReadKey(true);
  552. if (key.Key == ConsoleKey.Enter)
  553. {
  554. return buf.ToString();
  555. }
  556. else if (key.Key == ConsoleKey.Backspace)
  557. {
  558. buf.Remove(buf.Length - 1, 1);
  559. Console.Write("\b \b");
  560. }
  561. else
  562. {
  563. Console.Write('*');
  564. buf.Append(key.KeyChar);
  565. }
  566. }
  567. }
  568. }
  569. }