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 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. using Newtonsoft.Json;
  2. using Shadowsocks.Controller;
  3. using Shadowsocks.Model;
  4. using Shadowsocks.Properties;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading;
  12. namespace Shadowsocks.Util.SystemProxy
  13. {
  14. public static class Sysproxy
  15. {
  16. private const string _userWininetConfigFile = "user-wininet.json";
  17. private readonly static string[] _lanIP = {
  18. "<local>",
  19. "localhost",
  20. "127.*",
  21. "10.*",
  22. "172.16.*",
  23. "172.17.*",
  24. "172.18.*",
  25. "172.19.*",
  26. "172.20.*",
  27. "172.21.*",
  28. "172.22.*",
  29. "172.23.*",
  30. "172.24.*",
  31. "172.25.*",
  32. "172.26.*",
  33. "172.27.*",
  34. "172.28.*",
  35. "172.29.*",
  36. "172.30.*",
  37. "172.31.*",
  38. "192.168.*"
  39. };
  40. private static string _queryStr;
  41. // In general, this won't change
  42. // format:
  43. // <flags><CR-LF>
  44. // <proxy-server><CR-LF>
  45. // <bypass-list><CR-LF>
  46. // <pac-url>
  47. private static SysproxyConfig _userSettings = null;
  48. enum RET_ERRORS : int
  49. {
  50. RET_NO_ERROR = 0,
  51. INVALID_FORMAT = 1,
  52. NO_PERMISSION = 2,
  53. SYSCALL_FAILED = 3,
  54. NO_MEMORY = 4,
  55. INVAILD_OPTION_COUNT = 5,
  56. };
  57. static Sysproxy()
  58. {
  59. try
  60. {
  61. FileManager.UncompressFile(Utils.GetTempPath("sysproxy.exe"),
  62. Environment.Is64BitOperatingSystem ? Resources.sysproxy64_exe : Resources.sysproxy_exe);
  63. }
  64. catch (IOException e)
  65. {
  66. Logging.LogUsefulException(e);
  67. }
  68. }
  69. public static void SetIEProxy(bool enable, bool global, string proxyServer, string pacURL)
  70. {
  71. Read();
  72. if (!_userSettings.UserSettingsRecorded)
  73. {
  74. // record user settings
  75. ExecSysproxy("query");
  76. ParseQueryStr(_queryStr);
  77. }
  78. string arguments;
  79. if (enable)
  80. {
  81. string customBypassString = _userSettings.BypassList ?? "";
  82. List<string> customBypassList = new List<string>(customBypassString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
  83. customBypassList.AddRange(_lanIP);
  84. string[] realBypassList = customBypassList.Distinct().ToArray();
  85. string realBypassString = string.Join(";", realBypassList);
  86. arguments = global
  87. ? $"global {proxyServer} {realBypassString}"
  88. : $"pac {pacURL}";
  89. }
  90. else
  91. {
  92. // restore user settings
  93. var flags = _userSettings.Flags;
  94. var proxy_server = _userSettings.ProxyServer ?? "-";
  95. var bypass_list = _userSettings.BypassList ?? "-";
  96. var pac_url = _userSettings.PacUrl ?? "-";
  97. arguments = $"set {flags} {proxy_server} {bypass_list} {pac_url}";
  98. // have to get new settings
  99. _userSettings.UserSettingsRecorded = false;
  100. }
  101. Save();
  102. ExecSysproxy(arguments);
  103. }
  104. // set system proxy to 1 (null) (null) (null)
  105. public static bool ResetIEProxy()
  106. {
  107. try
  108. {
  109. // clear user-wininet.json
  110. _userSettings = new SysproxyConfig();
  111. Save();
  112. // clear system setting
  113. ExecSysproxy("set 1 - - -");
  114. }
  115. catch (Exception)
  116. {
  117. return false;
  118. }
  119. return true;
  120. }
  121. private static void ExecSysproxy(string arguments)
  122. {
  123. // using event to avoid hanging when redirect standard output/error
  124. // ref: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
  125. // and http://blog.csdn.net/zhangweixing0/article/details/7356841
  126. using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
  127. using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
  128. {
  129. using (var process = new Process())
  130. {
  131. // Configure the process using the StartInfo properties.
  132. process.StartInfo.FileName = Utils.GetTempPath("sysproxy.exe");
  133. process.StartInfo.Arguments = arguments;
  134. process.StartInfo.WorkingDirectory = Utils.GetTempPath();
  135. process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  136. process.StartInfo.UseShellExecute = false;
  137. process.StartInfo.RedirectStandardError = true;
  138. process.StartInfo.RedirectStandardOutput = true;
  139. // Need to provide encoding info, or output/error strings we got will be wrong.
  140. process.StartInfo.StandardOutputEncoding = Encoding.Unicode;
  141. process.StartInfo.StandardErrorEncoding = Encoding.Unicode;
  142. process.StartInfo.CreateNoWindow = true;
  143. StringBuilder output = new StringBuilder();
  144. StringBuilder error = new StringBuilder();
  145. process.OutputDataReceived += (sender, e) =>
  146. {
  147. if (e.Data == null)
  148. {
  149. outputWaitHandle.Set();
  150. }
  151. else
  152. {
  153. output.AppendLine(e.Data);
  154. }
  155. };
  156. process.ErrorDataReceived += (sender, e) =>
  157. {
  158. if (e.Data == null)
  159. {
  160. errorWaitHandle.Set();
  161. }
  162. else
  163. {
  164. error.AppendLine(e.Data);
  165. }
  166. };
  167. try
  168. {
  169. process.Start();
  170. process.BeginErrorReadLine();
  171. process.BeginOutputReadLine();
  172. process.WaitForExit();
  173. }
  174. catch (System.ComponentModel.Win32Exception e)
  175. {
  176. // log the arguments
  177. throw new ProxyException(ProxyExceptionType.FailToRun, process.StartInfo.Arguments, e);
  178. }
  179. var stderr = error.ToString();
  180. var stdout = output.ToString();
  181. var exitCode = process.ExitCode;
  182. if (exitCode != (int)RET_ERRORS.RET_NO_ERROR)
  183. {
  184. throw new ProxyException(ProxyExceptionType.SysproxyExitError, stderr);
  185. }
  186. if (arguments == "query")
  187. {
  188. if (stdout.IsNullOrWhiteSpace() || stdout.IsNullOrEmpty())
  189. {
  190. // we cannot get user settings
  191. throw new ProxyException(ProxyExceptionType.QueryReturnEmpty);
  192. }
  193. _queryStr = stdout;
  194. }
  195. }
  196. }
  197. }
  198. private static void Save()
  199. {
  200. try
  201. {
  202. using (StreamWriter sw = new StreamWriter(File.Open(Utils.GetTempPath(_userWininetConfigFile), FileMode.Create)))
  203. {
  204. string jsonString = JsonConvert.SerializeObject(_userSettings, Formatting.Indented);
  205. sw.Write(jsonString);
  206. sw.Flush();
  207. }
  208. }
  209. catch (IOException e)
  210. {
  211. Logging.LogUsefulException(e);
  212. }
  213. }
  214. private static void Read()
  215. {
  216. try
  217. {
  218. string configContent = File.ReadAllText(Utils.GetTempPath(_userWininetConfigFile));
  219. _userSettings = JsonConvert.DeserializeObject<SysproxyConfig>(configContent);
  220. }
  221. catch (Exception)
  222. {
  223. // Suppress all exceptions. finally block will initialize new user config settings.
  224. }
  225. finally
  226. {
  227. if (_userSettings == null) _userSettings = new SysproxyConfig();
  228. }
  229. }
  230. private static void ParseQueryStr(string str)
  231. {
  232. string[] userSettingsArr = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
  233. // sometimes sysproxy output in utf16le instead of ascii
  234. // manually translate it
  235. if (userSettingsArr.Length != 4)
  236. {
  237. byte[] strByte = Encoding.ASCII.GetBytes(str);
  238. str = Encoding.Unicode.GetString(strByte);
  239. userSettingsArr = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
  240. // still fail, throw exception with string hexdump
  241. if (userSettingsArr.Length != 4)
  242. {
  243. throw new ProxyException(ProxyExceptionType.QueryReturnMalformed, BitConverter.ToString(strByte));
  244. }
  245. }
  246. _userSettings.Flags = userSettingsArr[0];
  247. // handle output from WinINET
  248. if (userSettingsArr[1] == "(null)") _userSettings.ProxyServer = null;
  249. else _userSettings.ProxyServer = userSettingsArr[1];
  250. if (userSettingsArr[2] == "(null)") _userSettings.BypassList = null;
  251. else _userSettings.BypassList = userSettingsArr[2];
  252. if (userSettingsArr[3] == "(null)") _userSettings.PacUrl = null;
  253. else _userSettings.PacUrl = userSettingsArr[3];
  254. _userSettings.UserSettingsRecorded = true;
  255. }
  256. }
  257. }