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.

Sysproxy.cs 8.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Text;
  5. using System.Threading;
  6. using Shadowsocks.Controller;
  7. using Shadowsocks.Properties;
  8. using Shadowsocks.Model;
  9. using Newtonsoft.Json;
  10. namespace Shadowsocks.Util.SystemProxy
  11. {
  12. public static class Sysproxy
  13. {
  14. private const string _userWininetConfigFile = "user-wininet.json";
  15. private static string _queryStr;
  16. // In general, this won't change
  17. // format:
  18. // <flags><CR-LF>
  19. // <proxy-server><CR-LF>
  20. // <bypass-list><CR-LF>
  21. // <pac-url>
  22. private static SysproxyConfig _userSettings = null;
  23. enum RET_ERRORS : int
  24. {
  25. RET_NO_ERROR = 0,
  26. INVALID_FORMAT = 1,
  27. NO_PERMISSION = 2,
  28. SYSCALL_FAILED = 3,
  29. NO_MEMORY = 4,
  30. INVAILD_OPTION_COUNT = 5,
  31. };
  32. static Sysproxy()
  33. {
  34. try
  35. {
  36. FileManager.UncompressFile(Utils.GetTempPath("sysproxy.exe"),
  37. Environment.Is64BitOperatingSystem ? Resources.sysproxy64_exe : Resources.sysproxy_exe);
  38. }
  39. catch (IOException e)
  40. {
  41. Logging.LogUsefulException(e);
  42. }
  43. }
  44. public static void SetIEProxy(bool enable, bool global, string proxyServer, string pacURL)
  45. {
  46. Read();
  47. if (!_userSettings.UserSettingsRecorded)
  48. {
  49. // record user settings
  50. ExecSysproxy("query");
  51. ParseQueryStr(_queryStr);
  52. }
  53. string arguments;
  54. if (enable)
  55. {
  56. arguments = global
  57. ? $"global {proxyServer} <local>;localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*"
  58. : $"pac {pacURL}";
  59. }
  60. else
  61. {
  62. // restore user settings
  63. var flags = _userSettings.Flags;
  64. var proxy_server = _userSettings.ProxyServer ?? "-";
  65. var bypass_list = _userSettings.BypassList ?? "-";
  66. var pac_url = _userSettings.PacUrl ?? "-";
  67. arguments = $"set {flags} {proxy_server} {bypass_list} {pac_url}";
  68. // have to get new settings
  69. _userSettings.UserSettingsRecorded = false;
  70. }
  71. Save();
  72. ExecSysproxy(arguments);
  73. }
  74. private static void ExecSysproxy(string arguments)
  75. {
  76. // using event to avoid hanging when redirect standard output/error
  77. // ref: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
  78. // and http://blog.csdn.net/zhangweixing0/article/details/7356841
  79. using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
  80. using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
  81. {
  82. using (var process = new Process())
  83. {
  84. // Configure the process using the StartInfo properties.
  85. process.StartInfo.FileName = Utils.GetTempPath("sysproxy.exe");
  86. process.StartInfo.Arguments = arguments;
  87. process.StartInfo.WorkingDirectory = Utils.GetTempPath();
  88. process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  89. process.StartInfo.UseShellExecute = false;
  90. process.StartInfo.RedirectStandardError = true;
  91. process.StartInfo.RedirectStandardOutput = true;
  92. // Need to provide encoding info, or output/error strings we got will be wrong.
  93. process.StartInfo.StandardOutputEncoding = Encoding.Unicode;
  94. process.StartInfo.StandardErrorEncoding = Encoding.Unicode;
  95. process.StartInfo.CreateNoWindow = true;
  96. StringBuilder output = new StringBuilder();
  97. StringBuilder error = new StringBuilder();
  98. process.OutputDataReceived += (sender, e) =>
  99. {
  100. if (e.Data == null)
  101. {
  102. outputWaitHandle.Set();
  103. }
  104. else
  105. {
  106. output.AppendLine(e.Data);
  107. }
  108. };
  109. process.ErrorDataReceived += (sender, e) =>
  110. {
  111. if (e.Data == null)
  112. {
  113. errorWaitHandle.Set();
  114. }
  115. else
  116. {
  117. error.AppendLine(e.Data);
  118. }
  119. };
  120. process.Start();
  121. process.BeginErrorReadLine();
  122. process.BeginOutputReadLine();
  123. process.WaitForExit();
  124. var stderr = error.ToString();
  125. var stdout = output.ToString();
  126. var exitCode = process.ExitCode;
  127. if (exitCode != (int)RET_ERRORS.RET_NO_ERROR)
  128. {
  129. throw new ProxyException(stderr);
  130. }
  131. if (arguments == "query") {
  132. if (stdout.IsNullOrWhiteSpace() || stdout.IsNullOrEmpty()) {
  133. // we cannot get user settings
  134. throw new ProxyException("failed to query wininet settings");
  135. }
  136. _queryStr = stdout;
  137. }
  138. }
  139. }
  140. }
  141. private static void Save()
  142. {
  143. try
  144. {
  145. using (StreamWriter sw = new StreamWriter(File.Open(Utils.GetTempPath(_userWininetConfigFile), FileMode.Create)))
  146. {
  147. string jsonString = JsonConvert.SerializeObject(_userSettings, Formatting.Indented);
  148. sw.Write(jsonString);
  149. sw.Flush();
  150. }
  151. }
  152. catch (IOException e)
  153. {
  154. Logging.LogUsefulException(e);
  155. }
  156. }
  157. private static void Read()
  158. {
  159. try
  160. {
  161. string configContent = File.ReadAllText(Utils.GetTempPath(_userWininetConfigFile));
  162. _userSettings = JsonConvert.DeserializeObject<SysproxyConfig>(configContent);
  163. } catch(Exception) {
  164. // Suppress all exceptions. finally block will initialize new user config settings.
  165. } finally {
  166. if (_userSettings == null) _userSettings = new SysproxyConfig();
  167. }
  168. }
  169. private static void ParseQueryStr(string str)
  170. {
  171. string[] userSettingsArr = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
  172. _userSettings.Flags = userSettingsArr[0];
  173. // handle output from WinINET
  174. if (userSettingsArr[1] == "(null)") _userSettings.ProxyServer = null;
  175. else _userSettings.ProxyServer = userSettingsArr[1];
  176. if (userSettingsArr[2] == "(null)") _userSettings.BypassList = null;
  177. else _userSettings.BypassList = userSettingsArr[2];
  178. if (userSettingsArr[3] == "(null)") _userSettings.PacUrl = null;
  179. else _userSettings.PacUrl = userSettingsArr[3];
  180. _userSettings.UserSettingsRecorded = true;
  181. }
  182. }
  183. }