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

10 years ago
12 years ago
12 years ago
8 years ago
12 years ago
12 years ago
12 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. using Microsoft.Win32;
  2. using NLog;
  3. using Shadowsocks.Controller;
  4. using Shadowsocks.Controller.Hotkeys;
  5. using Shadowsocks.Util;
  6. using Shadowsocks.View;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.IO.Pipes;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using System.Windows.Forms;
  18. namespace Shadowsocks
  19. {
  20. internal static class Program
  21. {
  22. private static readonly Logger logger = LogManager.GetCurrentClassLogger();
  23. public static ShadowsocksController MainController { get; private set; }
  24. public static MenuViewController MenuController { get; private set; }
  25. public static string[] Args { get; private set; }
  26. /// <summary>
  27. /// 应用程序的主入口点。
  28. /// </summary>
  29. /// </summary>
  30. [STAThread]
  31. private static void Main(string[] args)
  32. {
  33. Directory.SetCurrentDirectory(Application.StartupPath);
  34. // todo: initialize the NLog configuartion
  35. Model.NLogConfig.TouchAndApplyNLogConfig();
  36. // .NET Framework 4.7.2 on Win7 compatibility
  37. ServicePointManager.SecurityProtocol |=
  38. SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
  39. // store args for further use
  40. Args = args;
  41. // Check OS since we are using dual-mode socket
  42. if (!Utils.IsWinVistaOrHigher())
  43. {
  44. MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
  45. "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  46. return;
  47. }
  48. // Check .NET Framework version
  49. if (!Utils.IsSupportedRuntimeVersion())
  50. {
  51. if (DialogResult.OK == MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to {0} or later.", "4.7.2"),
  52. "Shadowsocks Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error))
  53. {
  54. Process.Start("https://dotnet.microsoft.com/download/dotnet-framework/net472");
  55. }
  56. return;
  57. }
  58. string pipename = $"Shadowsocks\\{Application.StartupPath.GetHashCode()}";
  59. string addedUrl = null;
  60. using (NamedPipeClientStream pipe = new NamedPipeClientStream(pipename))
  61. {
  62. bool pipeExist = false;
  63. try
  64. {
  65. pipe.Connect(10);
  66. pipeExist = true;
  67. }
  68. catch (TimeoutException)
  69. {
  70. pipeExist = false;
  71. }
  72. // TODO: switch to better argv parser when it's getting complicate
  73. List<string> alist = Args.ToList();
  74. // check --open-url param
  75. int urlidx = alist.IndexOf("--open-url") + 1;
  76. if (urlidx > 0)
  77. {
  78. if (Args.Length <= urlidx)
  79. {
  80. return;
  81. }
  82. // --open-url exist, and no other instance, add it later
  83. if (!pipeExist)
  84. {
  85. addedUrl = Args[urlidx];
  86. }
  87. // has other instance, send url via pipe then exit
  88. else
  89. {
  90. byte[] b = Encoding.UTF8.GetBytes(Args[urlidx]);
  91. byte[] opAddUrl = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(1));
  92. byte[] blen = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(b.Length));
  93. pipe.Write(opAddUrl, 0, 4); // opcode addurl
  94. pipe.Write(blen, 0, 4);
  95. pipe.Write(b, 0, b.Length);
  96. pipe.Close();
  97. return;
  98. }
  99. }
  100. // has another instance, and no need to communicate with it return
  101. else if (pipeExist)
  102. {
  103. Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
  104. if (oldProcesses.Length > 0)
  105. {
  106. Process oldProcess = oldProcesses[0];
  107. }
  108. MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.")
  109. + Environment.NewLine
  110. + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
  111. I18N.GetString("Shadowsocks is already running."));
  112. return;
  113. }
  114. }
  115. Utils.ReleaseMemory(true);
  116. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
  117. // handle UI exceptions
  118. Application.ThreadException += Application_ThreadException;
  119. // handle non-UI exceptions
  120. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  121. Application.ApplicationExit += Application_ApplicationExit;
  122. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  123. Application.EnableVisualStyles();
  124. Application.SetCompatibleTextRenderingDefault(false);
  125. AutoStartup.RegisterForRestart(true);
  126. Directory.SetCurrentDirectory(Application.StartupPath);
  127. #if DEBUG
  128. // truncate privoxy log file while debugging
  129. string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
  130. if (File.Exists(privoxyLogFilename))
  131. using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
  132. #endif
  133. MainController = new ShadowsocksController();
  134. MenuController = new MenuViewController(MainController);
  135. HotKeys.Init(MainController);
  136. MainController.Start();
  137. NamedPipeServer namedPipeServer = new NamedPipeServer();
  138. Task.Run(() => namedPipeServer.Run(pipename));
  139. namedPipeServer.AddUrlRequested += (_1, e) => MainController.AskAddServerBySSURL(e.Url);
  140. if (!addedUrl.IsNullOrEmpty())
  141. {
  142. MainController.AskAddServerBySSURL(addedUrl);
  143. }
  144. Application.Run();
  145. }
  146. private static int exited = 0;
  147. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  148. {
  149. if (Interlocked.Increment(ref exited) == 1)
  150. {
  151. string errMsg = e.ExceptionObject.ToString();
  152. logger.Error(errMsg);
  153. MessageBox.Show(
  154. $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errMsg}",
  155. "Shadowsocks non-UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  156. Application.Exit();
  157. }
  158. }
  159. private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
  160. {
  161. if (Interlocked.Increment(ref exited) == 1)
  162. {
  163. string errorMsg = $"Exception Detail: {Environment.NewLine}{e.Exception}";
  164. logger.Error(errorMsg);
  165. MessageBox.Show(
  166. $"{I18N.GetString("Unexpected error, shadowsocks will exit. Please report to")} https://github.com/shadowsocks/shadowsocks-windows/issues {Environment.NewLine}{errorMsg}",
  167. "Shadowsocks UI Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  168. Application.Exit();
  169. }
  170. }
  171. private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  172. {
  173. switch (e.Mode)
  174. {
  175. case PowerModes.Resume:
  176. logger.Info("os wake up");
  177. if (MainController != null)
  178. {
  179. Task.Factory.StartNew(() =>
  180. {
  181. Thread.Sleep(10 * 1000);
  182. try
  183. {
  184. MainController.Start(false);
  185. logger.Info("controller started");
  186. }
  187. catch (Exception ex)
  188. {
  189. logger.LogUsefulException(ex);
  190. }
  191. });
  192. }
  193. break;
  194. case PowerModes.Suspend:
  195. if (MainController != null)
  196. {
  197. MainController.Stop();
  198. logger.Info("controller stopped");
  199. }
  200. logger.Info("os suspend");
  201. break;
  202. }
  203. }
  204. private static void Application_ApplicationExit(object sender, EventArgs e)
  205. {
  206. // detach static event handlers
  207. Application.ApplicationExit -= Application_ApplicationExit;
  208. SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
  209. Application.ThreadException -= Application_ThreadException;
  210. HotKeys.Destroy();
  211. if (MainController != null)
  212. {
  213. MainController.Stop();
  214. MainController = null;
  215. }
  216. }
  217. }
  218. }