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

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