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.9 kB

10 years ago
12 years ago
12 years ago
8 years ago
12 years ago
12 years ago
12 years ago
12 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
12 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. /// </summary>
  34. [STAThread]
  35. private static void Main(string[] args)
  36. {
  37. #region Single Instance and IPC
  38. bool hasAnotherInstance = !mutex.WaitOne(TimeSpan.Zero, true);
  39. // store args for further use
  40. Args = args;
  41. Parser.Default.ParseArguments<CommandLineOption>(args)
  42. .WithParsed(opt => Options = opt)
  43. .WithNotParsed(e => e.Output());
  44. if (hasAnotherInstance)
  45. {
  46. if (!string.IsNullOrWhiteSpace(Options.OpenUrl))
  47. {
  48. IPCService.RequestOpenUrl(Options.OpenUrl);
  49. }
  50. else
  51. {
  52. MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.")
  53. + Environment.NewLine
  54. + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
  55. I18N.GetString("Shadowsocks is already running."));
  56. }
  57. return;
  58. }
  59. #endregion
  60. #region Enviroment Setup
  61. Directory.SetCurrentDirectory(WorkingDirectory);
  62. // todo: initialize the NLog configuartion
  63. Model.NLogConfig.TouchAndApplyNLogConfig();
  64. // .NET Framework 4.7.2 on Win7 compatibility
  65. ServicePointManager.SecurityProtocol |=
  66. SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
  67. #endregion
  68. #region Compactibility Check
  69. // Check OS since we are using dual-mode socket
  70. if (!Utils.IsWinVistaOrHigher())
  71. {
  72. MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
  73. "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  74. return;
  75. }
  76. // Check .NET Framework version
  77. if (!Utils.IsSupportedRuntimeVersion())
  78. {
  79. if (DialogResult.OK == MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to {0} or later.", "4.7.2"),
  80. "Shadowsocks Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error))
  81. {
  82. Process.Start("https://dotnet.microsoft.com/download/dotnet-framework/net472");
  83. }
  84. return;
  85. }
  86. #endregion
  87. #region Event Handlers Setup
  88. Utils.ReleaseMemory(true);
  89. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
  90. // handle UI exceptions
  91. Application.ThreadException += Application_ThreadException;
  92. // handle non-UI exceptions
  93. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  94. Application.ApplicationExit += Application_ApplicationExit;
  95. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  96. Application.EnableVisualStyles();
  97. Application.SetCompatibleTextRenderingDefault(false);
  98. AutoStartup.RegisterForRestart(true);
  99. #endregion
  100. #if DEBUG
  101. // truncate privoxy log file while debugging
  102. string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
  103. if (File.Exists(privoxyLogFilename))
  104. using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
  105. #endif
  106. MainController = new ShadowsocksController();
  107. MenuController = new MenuViewController(MainController);
  108. HotKeys.Init(MainController);
  109. MainController.Start();
  110. #region IPC Handler and Arguement Process
  111. IPCService ipcService = new IPCService();
  112. Task.Run(() => ipcService.RunServer());
  113. ipcService.OpenUrlRequested += (_1, e) => MainController.AskAddServerBySSURL(e.Url);
  114. if (!string.IsNullOrWhiteSpace(Options.OpenUrl))
  115. {
  116. MainController.AskAddServerBySSURL(Options.OpenUrl);
  117. }
  118. #endregion
  119. Application.Run();
  120. }
  121. private static int exited = 0;
  122. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  123. {
  124. if (Interlocked.Increment(ref exited) == 1)
  125. {
  126. string errMsg = e.ExceptionObject.ToString();
  127. logger.Error(errMsg);
  128. MessageBox.Show(
  129. $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errMsg}",
  130. "Shadowsocks non-UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  131. Application.Exit();
  132. }
  133. }
  134. private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
  135. {
  136. if (Interlocked.Increment(ref exited) == 1)
  137. {
  138. string errorMsg = $"Exception Detail: {Environment.NewLine}{e.Exception}";
  139. logger.Error(errorMsg);
  140. MessageBox.Show(
  141. $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errorMsg}",
  142. "Shadowsocks UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  143. Application.Exit();
  144. }
  145. }
  146. private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  147. {
  148. switch (e.Mode)
  149. {
  150. case PowerModes.Resume:
  151. logger.Info("os wake up");
  152. if (MainController != null)
  153. {
  154. Task.Factory.StartNew(() =>
  155. {
  156. Thread.Sleep(10 * 1000);
  157. try
  158. {
  159. MainController.Start(false);
  160. logger.Info("controller started");
  161. }
  162. catch (Exception ex)
  163. {
  164. logger.LogUsefulException(ex);
  165. }
  166. });
  167. }
  168. break;
  169. case PowerModes.Suspend:
  170. if (MainController != null)
  171. {
  172. MainController.Stop();
  173. logger.Info("controller stopped");
  174. }
  175. logger.Info("os suspend");
  176. break;
  177. }
  178. }
  179. private static void Application_ApplicationExit(object sender, EventArgs e)
  180. {
  181. // detach static event handlers
  182. Application.ApplicationExit -= Application_ApplicationExit;
  183. SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
  184. Application.ThreadException -= Application_ThreadException;
  185. HotKeys.Destroy();
  186. if (MainController != null)
  187. {
  188. MainController.Stop();
  189. MainController = null;
  190. }
  191. }
  192. }
  193. }