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 10 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 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. List<string> customBypass = new List<string>(_userSettings.BypassList.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
  82. customBypass.AddRange(_lanIP);
  83. string[] realBypassStrings = customBypass.Distinct().ToArray();
  84. string realBypassString = string.Join(";", realBypassStrings);
  85. arguments = global
  86. ? $"global {proxyServer} {realBypassString}"
  87. : $"pac {pacURL}";
  88. }
  89. else
  90. {
  91. // restore user settings
  92. var flags = _userSettings.Flags;
  93. var proxy_server = _userSettings.ProxyServer ?? "-";
  94. var bypass_list = _userSettings.BypassList ?? "-";
  95. var pac_url = _userSettings.PacUrl ?? "-";
  96. arguments = $"set {flags} {proxy_server} {bypass_list} {pac_url}";
  97. // have to get new settings
  98. _userSettings.UserSettingsRecorded = false;
  99. }
  100. Save();
  101. ExecSysproxy(arguments);
  102. }
  103. // set system proxy to 1 (null) (null) (null)
  104. public static bool ResetIEProxy()
  105. {
  106. try
  107. {
  108. // clear user-wininet.json
  109. _userSettings = new SysproxyConfig();
  110. Save();
  111. // clear system setting
  112. ExecSysproxy("set 1 - - -");
  113. }
  114. catch (Exception e)
  115. {
  116. return false;
  117. }
  118. return true;
  119. }
  120. private static void ExecSysproxy(string arguments)
  121. {
  122. // using event to avoid hanging when redirect standard output/error
  123. // ref: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
  124. // and http://blog.csdn.net/zhangweixing0/article/details/7356841
  125. using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
  126. using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
  127. {
  128. using (var process = new Process())
  129. {
  130. // Configure the process using the StartInfo properties.
  131. process.StartInfo.FileName = Utils.GetTempPath("sysproxy.exe");
  132. process.StartInfo.Arguments = arguments;
  133. process.StartInfo.WorkingDirectory = Utils.GetTempPath();
  134. process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  135. process.StartInfo.UseShellExecute = false;
  136. process.StartInfo.RedirectStandardError = true;
  137. process.StartInfo.RedirectStandardOutput = true;
  138. // Need to provide encoding info, or output/error strings we got will be wrong.
  139. process.StartInfo.StandardOutputEncoding = Encoding.Unicode;
  140. process.StartInfo.StandardErrorEncoding = Encoding.Unicode;
  141. process.StartInfo.CreateNoWindow = true;
  142. StringBuilder output = new StringBuilder();
  143. StringBuilder error = new StringBuilder();
  144. process.OutputDataReceived += (sender, e) =>
  145. {
  146. if (e.Data == null)
  147. {
  148. outputWaitHandle.Set();
  149. }
  150. else
  151. {
  152. output.AppendLine(e.Data);
  153. }
  154. };
  155. process.ErrorDataReceived += (sender, e) =>
  156. {
  157. if (e.Data == null)
  158. {
  159. errorWaitHandle.Set();
  160. }
  161. else
  162. {
  163. error.AppendLine(e.Data);
  164. }
  165. };
  166. try
  167. {
  168. process.Start();
  169. process.BeginErrorReadLine();
  170. process.BeginOutputReadLine();
  171. process.WaitForExit();
  172. }
  173. catch (System.ComponentModel.Win32Exception e)
  174. {
  175. // log the arguements
  176. throw new ProxyException(ProxyExceptionType.FailToRun, process.StartInfo.Arguments, e);
  177. }
  178. var stderr = error.ToString();
  179. var stdout = output.ToString();
  180. var exitCode = process.ExitCode;
  181. if (exitCode != (int)RET_ERRORS.RET_NO_ERROR)
  182. {
  183. throw new ProxyException(ProxyExceptionType.SysproxyExitError, stderr);
  184. }
  185. if (arguments == "query")
  186. {
  187. if (stdout.IsNullOrWhiteSpace() || stdout.IsNullOrEmpty())
  188. {
  189. // we cannot get user settings
  190. throw new ProxyException(ProxyExceptionType.QueryReturnEmpty);
  191. }
  192. _queryStr = stdout;
  193. }
  194. }
  195. }
  196. }
  197. private static void Save()
  198. {
  199. try
  200. {
  201. using (StreamWriter sw = new StreamWriter(File.Open(Utils.GetTempPath(_userWininetConfigFile), FileMode.Create)))
  202. {
  203. string jsonString = JsonConvert.SerializeObject(_userSettings, Formatting.Indented);
  204. sw.Write(jsonString);
  205. sw.Flush();
  206. }
  207. }
  208. catch (IOException e)
  209. {
  210. Logging.LogUsefulException(e);
  211. }
  212. }
  213. private static void Read()
  214. {
  215. try
  216. {
  217. string configContent = File.ReadAllText(Utils.GetTempPath(_userWininetConfigFile));
  218. _userSettings = JsonConvert.DeserializeObject<SysproxyConfig>(configContent);
  219. }
  220. catch (Exception)
  221. {
  222. // Suppress all exceptions. finally block will initialize new user config settings.
  223. }
  224. finally
  225. {
  226. if (_userSettings == null) _userSettings = new SysproxyConfig();
  227. }
  228. }
  229. private static void ParseQueryStr(string str)
  230. {
  231. string[] userSettingsArr = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
  232. // sometimes sysproxy output in utf16le instead of ascii
  233. // manually translate it
  234. if (userSettingsArr.Length != 4)
  235. {
  236. byte[] strByte = Encoding.ASCII.GetBytes(str);
  237. str = Encoding.Unicode.GetString(strByte);
  238. userSettingsArr = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
  239. // still fail, throw exception with string hexdump
  240. if (userSettingsArr.Length != 4)
  241. {
  242. throw new ProxyException(ProxyExceptionType.QueryReturnMalformed, BitConverter.ToString(strByte));
  243. }
  244. }
  245. _userSettings.Flags = userSettingsArr[0];
  246. // handle output from WinINET
  247. if (userSettingsArr[1] == "(null)") _userSettings.ProxyServer = null;
  248. else _userSettings.ProxyServer = userSettingsArr[1];
  249. if (userSettingsArr[2] == "(null)") _userSettings.BypassList = null;
  250. else _userSettings.BypassList = userSettingsArr[2];
  251. if (userSettingsArr[3] == "(null)") _userSettings.PacUrl = null;
  252. else _userSettings.PacUrl = userSettingsArr[3];
  253. _userSettings.UserSettingsRecorded = true;
  254. }
  255. }
  256. }