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

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