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.4 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. namespace Shadowsocks
  21. {
  22. internal static class Program
  23. {
  24. private static readonly Logger logger = LogManager.GetCurrentClassLogger();
  25. public static ShadowsocksController MainController { get; private set; }
  26. public static MenuViewController MenuController { get; private set; }
  27. public static CommandLineOption Options { get; private set; }
  28. public static string[] Args { get; private set; }
  29. // https://github.com/dotnet/runtime/issues/13051#issuecomment-510267727
  30. public static readonly string ExecutablePath = Process.GetCurrentProcess().MainModule?.FileName;
  31. public static readonly string WorkingDirectory = Path.GetDirectoryName(ExecutablePath);
  32. private static readonly Mutex mutex = new Mutex(true, $"Shadowsocks_{ExecutablePath.GetHashCode()}");
  33. /// <summary>
  34. /// 应用程序的主入口点。
  35. /// </summary>
  36. /// </summary>
  37. [STAThread]
  38. private 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. // .NET Framework 4.7.2 on Win7 compatibility
  68. ServicePointManager.SecurityProtocol |=
  69. SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
  70. #endregion
  71. #region Compactibility Check
  72. // Check OS since we are using dual-mode socket
  73. if (!Utils.IsWinVistaOrHigher())
  74. {
  75. MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
  76. "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  77. return;
  78. }
  79. // Check .NET Framework version
  80. if (!Utils.IsSupportedRuntimeVersion())
  81. {
  82. if (DialogResult.OK == MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to {0} or later.", "4.7.2"),
  83. "Shadowsocks Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error))
  84. {
  85. Process.Start("https://dotnet.microsoft.com/download/dotnet-framework/net472");
  86. }
  87. return;
  88. }
  89. #endregion
  90. #region Event Handlers Setup
  91. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
  92. // handle UI exceptions
  93. Application.ThreadException += Application_ThreadException;
  94. // handle non-UI exceptions
  95. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  96. Application.ApplicationExit += Application_ApplicationExit;
  97. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  98. Application.EnableVisualStyles();
  99. Application.SetCompatibleTextRenderingDefault(false);
  100. AutoStartup.RegisterForRestart(true);
  101. #endregion
  102. // We would use this in v5.
  103. // Parameters would have to be dropped from views' constructors (VersionUpdatePromptView)
  104. //Locator.CurrentMutable.RegisterViewsForViewModels(Assembly.GetCallingAssembly());
  105. #if DEBUG
  106. // truncate privoxy log file while debugging
  107. string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
  108. if (File.Exists(privoxyLogFilename))
  109. using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
  110. #endif
  111. MainController = new ShadowsocksController();
  112. MenuController = new MenuViewController(MainController);
  113. HotKeys.Init(MainController);
  114. MainController.Start();
  115. // Update online config
  116. Task.Run(async () =>
  117. {
  118. await Task.Delay(10 * 1000);
  119. await MainController.UpdateAllOnlineConfig();
  120. });
  121. #region IPC Handler and Arguement Process
  122. IPCService ipcService = new IPCService();
  123. Task.Run(() => ipcService.RunServer());
  124. ipcService.OpenUrlRequested += (_1, e) => MainController.AskAddServerBySSURL(e.Url);
  125. if (!string.IsNullOrWhiteSpace(Options.OpenUrl))
  126. {
  127. MainController.AskAddServerBySSURL(Options.OpenUrl);
  128. }
  129. #endregion
  130. Application.Run();
  131. }
  132. private static int exited = 0;
  133. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  134. {
  135. if (Interlocked.Increment(ref exited) == 1)
  136. {
  137. string errMsg = e.ExceptionObject.ToString();
  138. logger.Error(errMsg);
  139. MessageBox.Show(
  140. $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errMsg}",
  141. "Shadowsocks non-UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  142. Application.Exit();
  143. }
  144. }
  145. private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
  146. {
  147. if (Interlocked.Increment(ref exited) == 1)
  148. {
  149. string errorMsg = $"Exception Detail: {Environment.NewLine}{e.Exception}";
  150. logger.Error(errorMsg);
  151. MessageBox.Show(
  152. $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errorMsg}",
  153. "Shadowsocks UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  154. Application.Exit();
  155. }
  156. }
  157. private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  158. {
  159. switch (e.Mode)
  160. {
  161. case PowerModes.Resume:
  162. logger.Info("os wake up");
  163. if (MainController != null)
  164. {
  165. Task.Factory.StartNew(() =>
  166. {
  167. Thread.Sleep(10 * 1000);
  168. try
  169. {
  170. MainController.Start(true);
  171. logger.Info("controller started");
  172. }
  173. catch (Exception ex)
  174. {
  175. logger.LogUsefulException(ex);
  176. }
  177. });
  178. }
  179. break;
  180. case PowerModes.Suspend:
  181. if (MainController != null)
  182. {
  183. MainController.Stop();
  184. logger.Info("controller stopped");
  185. }
  186. logger.Info("os suspend");
  187. break;
  188. }
  189. }
  190. private static void Application_ApplicationExit(object sender, EventArgs e)
  191. {
  192. // detach static event handlers
  193. Application.ApplicationExit -= Application_ApplicationExit;
  194. SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
  195. Application.ThreadException -= Application_ThreadException;
  196. HotKeys.Destroy();
  197. if (MainController != null)
  198. {
  199. MainController.Stop();
  200. MainController = null;
  201. }
  202. }
  203. }
  204. }