Main.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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. if (descriptor.SendSIGINT)
  297. {
  298. WriteEvent("Send SIGINT " + process.Id);
  299. bool successful = SigIntHelper.SendSIGINTToProcess(proc);
  300. if (successful)
  301. {
  302. WriteEvent("SIGINT to" + process.Id + " successful");
  303. }
  304. else
  305. {
  306. WriteEvent("SIGINT to " + process.Id + " failed - Killing as fallback");
  307. proc.Kill();
  308. }
  309. }
  310. else
  311. {
  312. WriteEvent("ProcessKill " + process.Id);
  313. proc.Kill();
  314. }
  315. }
  316. catch (ArgumentException)
  317. {
  318. // Process already exited.
  319. }
  320. }
  321. private void WaitForProcessToExit(Process process)
  322. {
  323. SignalShutdownPending();
  324. try
  325. {
  326. // WriteEvent("WaitForProcessToExit [start]");
  327. while (!process.WaitForExit(descriptor.SleepTime.Milliseconds))
  328. {
  329. SignalShutdownPending();
  330. // WriteEvent("WaitForProcessToExit [repeat]");
  331. }
  332. }
  333. catch (InvalidOperationException)
  334. {
  335. // already terminated
  336. }
  337. // WriteEvent("WaitForProcessToExit [finished]");
  338. }
  339. private void SignalShutdownPending()
  340. {
  341. IntPtr handle = this.ServiceHandle;
  342. wrapperServiceStatus.checkPoint++;
  343. wrapperServiceStatus.waitHint = descriptor.WaitHint.Milliseconds;
  344. // WriteEvent("SignalShutdownPending " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  345. wrapperServiceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
  346. SetServiceStatus(handle, ref wrapperServiceStatus);
  347. }
  348. private void SignalShutdownComplete()
  349. {
  350. IntPtr handle = this.ServiceHandle;
  351. wrapperServiceStatus.checkPoint++;
  352. // WriteEvent("SignalShutdownComplete " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  353. wrapperServiceStatus.currentState = (int)State.SERVICE_STOPPED;
  354. SetServiceStatus(handle, ref wrapperServiceStatus);
  355. }
  356. private void StartProcess(Process process, string arguments, String executable)
  357. {
  358. var ps = process.StartInfo;
  359. ps.FileName = executable;
  360. ps.Arguments = arguments;
  361. ps.WorkingDirectory = descriptor.WorkingDirectory;
  362. ps.CreateNoWindow = false;
  363. ps.UseShellExecute = false;
  364. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  365. ps.RedirectStandardOutput = true;
  366. ps.RedirectStandardError = true;
  367. foreach (string key in envs.Keys)
  368. System.Environment.SetEnvironmentVariable(key, envs[key]);
  369. // 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)
  370. process.Start();
  371. WriteEvent("Started " + process.Id);
  372. // monitor the completion of the process
  373. StartThread(delegate()
  374. {
  375. string msg = process.Id + " - " + process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  376. process.WaitForExit();
  377. try
  378. {
  379. if (orderlyShutdown)
  380. {
  381. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Information);
  382. }
  383. else
  384. {
  385. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Warning);
  386. Environment.Exit(process.ExitCode);
  387. }
  388. }
  389. catch (InvalidOperationException ioe)
  390. {
  391. LogEvent("WaitForExit " + ioe.Message);
  392. }
  393. try
  394. {
  395. process.Dispose();
  396. }
  397. catch (InvalidOperationException ioe)
  398. {
  399. LogEvent("Dispose " + ioe.Message);
  400. }
  401. });
  402. }
  403. public static int Main(string[] args)
  404. {
  405. try
  406. {
  407. Run(args);
  408. return 0;
  409. }
  410. catch (WmiException e)
  411. {
  412. Console.Error.WriteLine(e);
  413. return (int)e.ErrorCode;
  414. }
  415. catch (Exception e)
  416. {
  417. Console.Error.WriteLine(e);
  418. return -1;
  419. }
  420. }
  421. private static void ThrowNoSuchService()
  422. {
  423. throw new WmiException(ReturnValue.NoSuchService);
  424. }
  425. public static void Run(string[] _args)
  426. {
  427. if (_args.Length > 0)
  428. {
  429. var d = new ServiceDescriptor();
  430. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  431. Win32Service s = svc.Select(d.Id);
  432. var args = new List<string>(Array.AsReadOnly(_args));
  433. if (args[0] == "/redirect")
  434. {
  435. // Redirect output
  436. // One might ask why we support this when the caller
  437. // can redirect the output easily. The answer is for supporting UAC.
  438. // On UAC-enabled Windows such as Vista, SCM operation requires
  439. // elevated privileges, thus winsw.exe needs to be launched
  440. // accordingly. This in turn limits what the caller can do,
  441. // and among other things it makes it difficult for the caller
  442. // to read stdout/stderr. Thus redirection becomes handy.
  443. var f = new FileStream(args[1], FileMode.Create);
  444. var w = new StreamWriter(f);
  445. w.AutoFlush = true;
  446. Console.SetOut(w);
  447. Console.SetError(w);
  448. var handle = f.Handle;
  449. SetStdHandle(-11, handle); // set stdout
  450. SetStdHandle(-12, handle); // set stder
  451. args = args.GetRange(2, args.Count - 2);
  452. }
  453. args[0] = args[0].ToLower();
  454. if (args[0] == "install")
  455. {
  456. string username=null, password=null;
  457. if (args.Count > 1 && args[1] == "/p")
  458. {
  459. // we expected username/password on stdin
  460. Console.Write("Username: ");
  461. username = Console.ReadLine();
  462. Console.Write("Password: ");
  463. password = ReadPassword();
  464. }
  465. else
  466. {
  467. if (d.HasServiceAccount())
  468. {
  469. username = d.ServiceAccountUser;
  470. password = d.ServiceAccountPassword;
  471. }
  472. }
  473. svc.Create (
  474. d.Id,
  475. d.Caption,
  476. "\"" + d.ExecutablePath + "\"",
  477. WMI.ServiceType.OwnProcess,
  478. ErrorControl.UserNotified,
  479. StartMode.Automatic,
  480. d.Interactive,
  481. username,
  482. password,
  483. d.ServiceDependencies);
  484. // update the description
  485. /* Somehow this doesn't work, even though it doesn't report an error
  486. Win32Service s = svc.Select(d.Id);
  487. s.Description = d.Description;
  488. s.Commit();
  489. */
  490. // so using a classic method to set the description. Ugly.
  491. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  492. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  493. var actions = d.FailureActions;
  494. if (actions.Count > 0)
  495. {// set the failure actions
  496. using (Advapi32.ServiceManager scm = new Advapi32.ServiceManager())
  497. {
  498. using (Advapi32.Service sc = scm.Open(d.Id))
  499. {
  500. sc.ChangeConfig(d.ResetFailureAfter, actions);
  501. }
  502. }
  503. }
  504. }
  505. if (args[0] == "uninstall")
  506. {
  507. if (s == null)
  508. return; // there's no such service, so consider it already uninstalled
  509. try
  510. {
  511. s.Delete();
  512. }
  513. catch (WmiException e)
  514. {
  515. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  516. return; // it's already uninstalled, so consider it a success
  517. throw e;
  518. }
  519. }
  520. if (args[0] == "start")
  521. {
  522. if (s == null) ThrowNoSuchService();
  523. s.StartService();
  524. }
  525. if (args[0] == "stop")
  526. {
  527. if (s == null) ThrowNoSuchService();
  528. s.StopService();
  529. }
  530. if (args[0] == "restart")
  531. {
  532. if (s == null)
  533. ThrowNoSuchService();
  534. if(s.Started)
  535. s.StopService();
  536. while (s.Started)
  537. {
  538. Thread.Sleep(1000);
  539. s = svc.Select(d.Id);
  540. }
  541. s.StartService();
  542. }
  543. if (args[0] == "status")
  544. {
  545. if (s == null)
  546. Console.WriteLine("NonExistent");
  547. else if (s.Started)
  548. Console.WriteLine("Started");
  549. else
  550. Console.WriteLine("Stopped");
  551. }
  552. if (args[0] == "test")
  553. {
  554. WrapperService wsvc = new WrapperService();
  555. wsvc.OnStart(args.ToArray());
  556. Thread.Sleep(1000);
  557. wsvc.OnStop();
  558. }
  559. return;
  560. }
  561. ServiceBase.Run(new WrapperService());
  562. }
  563. private static string ReadPassword()
  564. {
  565. StringBuilder buf = new StringBuilder();
  566. ConsoleKeyInfo key;
  567. while (true)
  568. {
  569. key = Console.ReadKey(true);
  570. if (key.Key == ConsoleKey.Enter)
  571. {
  572. return buf.ToString();
  573. }
  574. else if (key.Key == ConsoleKey.Backspace)
  575. {
  576. buf.Remove(buf.Length - 1, 1);
  577. Console.Write("\b \b");
  578. }
  579. else
  580. {
  581. Console.Write('*');
  582. buf.Append(key.KeyChar);
  583. }
  584. }
  585. }
  586. }
  587. }