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

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