You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Program.cs 8.0 kB

11 years ago
13 years ago
13 years ago
9 years ago
6 years ago
13 years ago
13 years ago
11 years ago
11 years ago
11 years ago
13 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
13 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.IO.Pipes;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using CommandLine;
  11. using Microsoft.Win32;
  12. using NLog;
  13. using Shadowsocks.Controller;
  14. using Shadowsocks.Controller.Hotkeys;
  15. using Shadowsocks.Util;
  16. using Shadowsocks.View;
  17. namespace Shadowsocks
  18. {
  19. internal static class Program
  20. {
  21. private static readonly Logger logger = LogManager.GetCurrentClassLogger();
  22. public static ShadowsocksController MainController { get; private set; }
  23. public static MenuViewController MenuController { get; private set; }
  24. public static CommandLineOption Options { get; private set; }
  25. public static string[] Args { get; private set; }
  26. // https://github.com/dotnet/runtime/issues/13051#issuecomment-510267727
  27. public static readonly string ExecutablePath = Process.GetCurrentProcess().MainModule?.FileName;
  28. public static readonly string WorkingDirectory = Path.GetDirectoryName(ExecutablePath);
  29. private static readonly Mutex mutex = new Mutex(true, $"Shadowsocks_{ExecutablePath.GetHashCode()}");
  30. /// <summary>
  31. /// 应用程序的主入口点。
  32. /// </summary>
  33. [STAThread]
  34. static void Main(string[] args)
  35. {
  36. #region Single Instance and IPC
  37. bool hasAnotherInstance = !mutex.WaitOne(TimeSpan.Zero, true);
  38. // store args for further use
  39. Args = args;
  40. Parser.Default.ParseArguments<CommandLineOption>(args)
  41. .WithParsed(opt => Options = opt)
  42. .WithNotParsed(e => e.Output());
  43. if (hasAnotherInstance)
  44. {
  45. if (!string.IsNullOrWhiteSpace(Options.OpenUrl))
  46. {
  47. IPCService.RequestOpenUrl(Options.OpenUrl);
  48. }
  49. else
  50. {
  51. MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.")
  52. + Environment.NewLine
  53. + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
  54. I18N.GetString("Shadowsocks is already running."));
  55. }
  56. return;
  57. }
  58. #endregion
  59. #region Enviroment Setup
  60. Directory.SetCurrentDirectory(WorkingDirectory);
  61. // todo: initialize the NLog configuartion
  62. Model.NLogConfig.TouchAndApplyNLogConfig();
  63. #endregion
  64. #region Event Handlers Setup
  65. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
  66. // handle UI exceptions
  67. Application.ThreadException += Application_ThreadException;
  68. // handle non-UI exceptions
  69. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  70. Application.ApplicationExit += Application_ApplicationExit;
  71. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  72. Application.EnableVisualStyles();
  73. Application.SetCompatibleTextRenderingDefault(false);
  74. AutoStartup.RegisterForRestart(true);
  75. #endregion
  76. // See https://github.com/dotnet/runtime/issues/13051
  77. // we have to do this for self-contained executables
  78. Directory.SetCurrentDirectory(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
  79. #if DEBUG
  80. // truncate privoxy log file while debugging
  81. string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
  82. if (File.Exists(privoxyLogFilename))
  83. using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
  84. #endif
  85. MainController = new ShadowsocksController();
  86. MenuController = new MenuViewController(MainController);
  87. HotKeys.Init(MainController);
  88. MainController.Start();
  89. #region IPC Handler and Arguement Process
  90. IPCService ipcService = new IPCService();
  91. Task.Run(() => ipcService.RunServer());
  92. ipcService.OpenUrlRequested += (_1, e) => MainController.AskAddServerBySSURL(e.Url);
  93. if (!string.IsNullOrWhiteSpace(Options.OpenUrl))
  94. {
  95. MainController.AskAddServerBySSURL(Options.OpenUrl);
  96. }
  97. #endregion
  98. Application.Run();
  99. }
  100. private static int exited = 0;
  101. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  102. {
  103. if (Interlocked.Increment(ref exited) == 1)
  104. {
  105. string errMsg = e.ExceptionObject.ToString();
  106. logger.Error(errMsg);
  107. MessageBox.Show(
  108. $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errMsg}",
  109. "Shadowsocks non-UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  110. Application.Exit();
  111. }
  112. }
  113. private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
  114. {
  115. if (Interlocked.Increment(ref exited) == 1)
  116. {
  117. string errorMsg = $"Exception Detail: {Environment.NewLine}{e.Exception}";
  118. logger.Error(errorMsg);
  119. MessageBox.Show(
  120. $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errorMsg}",
  121. "Shadowsocks UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  122. Application.Exit();
  123. }
  124. }
  125. private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  126. {
  127. switch (e.Mode)
  128. {
  129. case PowerModes.Resume:
  130. logger.Info("os wake up");
  131. if (MainController != null)
  132. {
  133. Task.Factory.StartNew(() =>
  134. {
  135. Thread.Sleep(10 * 1000);
  136. try
  137. {
  138. MainController.Start(false);
  139. logger.Info("controller started");
  140. }
  141. catch (Exception ex)
  142. {
  143. logger.LogUsefulException(ex);
  144. }
  145. });
  146. }
  147. break;
  148. case PowerModes.Suspend:
  149. if (MainController != null)
  150. {
  151. MainController.Stop();
  152. logger.Info("controller stopped");
  153. }
  154. logger.Info("os suspend");
  155. break;
  156. }
  157. }
  158. private static void Application_ApplicationExit(object sender, EventArgs e)
  159. {
  160. // detach static event handlers
  161. Application.ApplicationExit -= Application_ApplicationExit;
  162. SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
  163. Application.ThreadException -= Application_ThreadException;
  164. HotKeys.Destroy();
  165. if (MainController != null)
  166. {
  167. MainController.Stop();
  168. MainController = null;
  169. }
  170. }
  171. }
  172. }