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.2 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. // Update online config
  90. Task.Run(async () =>
  91. {
  92. await Task.Delay(10 * 1000);
  93. await MainController.UpdateAllOnlineConfig();
  94. });
  95. #region IPC Handler and Arguement Process
  96. IPCService ipcService = new IPCService();
  97. Task.Run(() => ipcService.RunServer());
  98. ipcService.OpenUrlRequested += (_1, e) => MainController.AskAddServerBySSURL(e.Url);
  99. if (!string.IsNullOrWhiteSpace(Options.OpenUrl))
  100. {
  101. MainController.AskAddServerBySSURL(Options.OpenUrl);
  102. }
  103. #endregion
  104. Application.Run();
  105. }
  106. private static int exited = 0;
  107. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  108. {
  109. if (Interlocked.Increment(ref exited) == 1)
  110. {
  111. string errMsg = e.ExceptionObject.ToString();
  112. logger.Error(errMsg);
  113. MessageBox.Show(
  114. $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errMsg}",
  115. "Shadowsocks non-UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  116. Application.Exit();
  117. }
  118. }
  119. private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
  120. {
  121. if (Interlocked.Increment(ref exited) == 1)
  122. {
  123. string errorMsg = $"Exception Detail: {Environment.NewLine}{e.Exception}";
  124. logger.Error(errorMsg);
  125. MessageBox.Show(
  126. $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errorMsg}",
  127. "Shadowsocks UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  128. Application.Exit();
  129. }
  130. }
  131. private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  132. {
  133. switch (e.Mode)
  134. {
  135. case PowerModes.Resume:
  136. logger.Info("os wake up");
  137. if (MainController != null)
  138. {
  139. Task.Factory.StartNew(() =>
  140. {
  141. Thread.Sleep(10 * 1000);
  142. try
  143. {
  144. MainController.Start(false);
  145. logger.Info("controller started");
  146. }
  147. catch (Exception ex)
  148. {
  149. logger.LogUsefulException(ex);
  150. }
  151. });
  152. }
  153. break;
  154. case PowerModes.Suspend:
  155. if (MainController != null)
  156. {
  157. MainController.Stop();
  158. logger.Info("controller stopped");
  159. }
  160. logger.Info("os suspend");
  161. break;
  162. }
  163. }
  164. private static void Application_ApplicationExit(object sender, EventArgs e)
  165. {
  166. // detach static event handlers
  167. Application.ApplicationExit -= Application_ApplicationExit;
  168. SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
  169. Application.ThreadException -= Application_ThreadException;
  170. HotKeys.Destroy();
  171. if (MainController != null)
  172. {
  173. MainController.Stop();
  174. MainController = null;
  175. }
  176. }
  177. }
  178. }