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 9.0 kB

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