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.

WinINet.cs 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. using Newtonsoft.Json;
  2. using NLog;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Runtime.InteropServices;
  9. namespace Shadowsocks.Util.SystemProxy
  10. {
  11. public enum InternetOptions
  12. {
  13. Refresh = 37,
  14. SettingsChanged = 39,
  15. PerConnectionOption = 75,
  16. ProxySettingChanged = 95,
  17. }
  18. public enum InternetPerConnectionOptionEnum
  19. {
  20. Flags = 1,
  21. ProxyServer = 2,
  22. ProxyBypass = 3,
  23. AutoConfigUrl = 4,
  24. AutoDiscovery = 5,
  25. AutoConfigSecondaryUrl = 6,
  26. AutoConfigReloadDelay = 7,
  27. AutoConfigLastDetectTime = 8,
  28. AutoConfigLastDetectUrl = 9,
  29. FlagsUI = 10,
  30. }
  31. [Flags]
  32. public enum InternetPerConnectionFlags
  33. {
  34. Direct = 0x01,
  35. Proxy = 0x02,
  36. AutoProxyUrl = 0x04,
  37. AutoDetect = 0x08,
  38. }
  39. [StructLayout(LayoutKind.Explicit)]
  40. public struct InternetPerConnectionOptionUnion : IDisposable
  41. {
  42. [FieldOffset(0)]
  43. public int dwValue;
  44. [FieldOffset(0)]
  45. public IntPtr pszValue;
  46. [FieldOffset(0)]
  47. public System.Runtime.InteropServices.ComTypes.FILETIME ftValue;
  48. public void Dispose()
  49. {
  50. Dispose(true);
  51. GC.SuppressFinalize(this);
  52. }
  53. private void Dispose(bool disposing)
  54. {
  55. if (disposing)
  56. {
  57. if (pszValue != IntPtr.Zero)
  58. {
  59. Marshal.FreeHGlobal(pszValue);
  60. pszValue = IntPtr.Zero;
  61. }
  62. }
  63. }
  64. }
  65. [StructLayout(LayoutKind.Sequential)]
  66. public struct InternetPerConnectionOption
  67. {
  68. public int dwOption;
  69. public InternetPerConnectionOptionUnion Value;
  70. }
  71. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  72. public struct InternetPerConnectionOptionList : IDisposable
  73. {
  74. public int Size;
  75. // The connection to be set. NULL means LAN.
  76. public IntPtr Connection;
  77. public int OptionCount;
  78. public int OptionError;
  79. // List of INTERNET_PER_CONN_OPTIONs.
  80. public IntPtr pOptions;
  81. public void Dispose()
  82. {
  83. Dispose(true);
  84. GC.SuppressFinalize(this);
  85. }
  86. private void Dispose(bool disposing)
  87. {
  88. if (disposing)
  89. {
  90. if (Connection != IntPtr.Zero)
  91. {
  92. Marshal.FreeHGlobal(Connection);
  93. Connection = IntPtr.Zero;
  94. }
  95. if (pOptions != IntPtr.Zero)
  96. {
  97. Marshal.FreeHGlobal(pOptions);
  98. pOptions = IntPtr.Zero;
  99. }
  100. }
  101. }
  102. }
  103. public class WinINetSetting
  104. {
  105. public InternetPerConnectionFlags Flags = InternetPerConnectionFlags.Direct;
  106. public string ProxyServer;
  107. public string ProxyBypass;
  108. public string AutoConfigUrl;
  109. }
  110. public class WinINet
  111. {
  112. private static readonly Logger logger = LogManager.GetCurrentClassLogger();
  113. private const string SettingFile = "wininet-setting.json";
  114. private static WinINetSetting initialSetting;
  115. public static bool operational { get; private set; } = true;
  116. static WinINet()
  117. {
  118. try
  119. {
  120. Query();
  121. }
  122. catch (DllNotFoundException)
  123. {
  124. operational = false;
  125. // Not on windows
  126. logger.Info("You are not running on Windows platform, system proxy will disable");
  127. }
  128. catch (Win32Exception we)
  129. {
  130. if (we.NativeErrorCode == 12178)
  131. {
  132. logger.Warn("WPAD service is not running, system proxy will disable");
  133. // WPAD not running
  134. }
  135. else
  136. {
  137. throw we;
  138. }
  139. }
  140. Load();
  141. }
  142. public static void ProxyGlobal(string server, string bypass)
  143. {
  144. List<InternetPerConnectionOption> options = new List<InternetPerConnectionOption>
  145. {
  146. GetOption(InternetPerConnectionOptionEnum.Flags,InternetPerConnectionFlags.Proxy|InternetPerConnectionFlags.Direct),
  147. GetOption(InternetPerConnectionOptionEnum.ProxyServer,server),
  148. GetOption(InternetPerConnectionOptionEnum.ProxyBypass,bypass),
  149. };
  150. Exec(options);
  151. }
  152. public static void ProxyPAC(string url)
  153. {
  154. List<InternetPerConnectionOption> options = new List<InternetPerConnectionOption>
  155. {
  156. GetOption(InternetPerConnectionOptionEnum.Flags,InternetPerConnectionFlags.AutoProxyUrl|InternetPerConnectionFlags.Direct),
  157. GetOption(InternetPerConnectionOptionEnum.AutoConfigUrl,url),
  158. };
  159. Exec(options);
  160. }
  161. public static void Direct()
  162. {
  163. List<InternetPerConnectionOption> options = new List<InternetPerConnectionOption>
  164. {
  165. GetOption(InternetPerConnectionOptionEnum.Flags,InternetPerConnectionFlags.Direct),
  166. };
  167. Exec(options);
  168. }
  169. private static void Load()
  170. {
  171. try
  172. {
  173. string configContent = File.ReadAllText(Utils.GetTempPath(SettingFile));
  174. initialSetting = JsonConvert.DeserializeObject<WinINetSetting>(configContent);
  175. }
  176. catch (Exception)
  177. {
  178. // Suppress all exceptions. finally block will initialize new user config settings.
  179. }
  180. finally
  181. {
  182. initialSetting ??= new WinINetSetting();
  183. }
  184. }
  185. private static void Save()
  186. {
  187. try
  188. {
  189. using (StreamWriter sw = new StreamWriter(File.Open(Utils.GetTempPath(SettingFile), FileMode.Create)))
  190. {
  191. string jsonString = JsonConvert.SerializeObject(initialSetting, Formatting.Indented);
  192. sw.Write(jsonString);
  193. sw.Flush();
  194. }
  195. }
  196. catch (IOException)
  197. {
  198. // logger.LogUsefulException(e);
  199. }
  200. }
  201. private static void Record()
  202. {
  203. initialSetting ??= Query();
  204. }
  205. public static void Restore()
  206. {
  207. Set(initialSetting);
  208. }
  209. public static void Set(WinINetSetting setting)
  210. {
  211. List<InternetPerConnectionOption> options = new List<InternetPerConnectionOption>
  212. {
  213. GetOption(InternetPerConnectionOptionEnum.Flags,setting.Flags),
  214. GetOption(InternetPerConnectionOptionEnum.ProxyServer,setting.ProxyServer),
  215. GetOption(InternetPerConnectionOptionEnum.ProxyBypass,setting.ProxyBypass),
  216. GetOption(InternetPerConnectionOptionEnum.AutoConfigUrl,setting.AutoConfigUrl),
  217. };
  218. Exec(options);
  219. }
  220. public static void Reset()
  221. {
  222. Set(new WinINetSetting
  223. {
  224. Flags = InternetPerConnectionFlags.Direct,
  225. ProxyServer = "",
  226. ProxyBypass = "",
  227. AutoConfigUrl = "",
  228. });
  229. }
  230. public static WinINetSetting Query()
  231. {
  232. if (!operational)
  233. {
  234. return new WinINetSetting();
  235. }
  236. List<InternetPerConnectionOption> options = new List<InternetPerConnectionOption>
  237. {
  238. new InternetPerConnectionOption{dwOption = (int)InternetPerConnectionOptionEnum.FlagsUI},
  239. new InternetPerConnectionOption{dwOption = (int)InternetPerConnectionOptionEnum.ProxyServer},
  240. new InternetPerConnectionOption{dwOption = (int)InternetPerConnectionOptionEnum.ProxyBypass},
  241. new InternetPerConnectionOption{dwOption = (int)InternetPerConnectionOptionEnum.AutoConfigUrl},
  242. };
  243. (IntPtr unmanagedList, int listSize) = PrepareOptionList(options, null);
  244. bool ok = InternetQueryOption(IntPtr.Zero, (int)InternetOptions.PerConnectionOption, unmanagedList, ref listSize);
  245. if (!ok)
  246. {
  247. throw new Win32Exception(Marshal.GetLastWin32Error());
  248. }
  249. WinINetSetting proxy = new WinINetSetting();
  250. InternetPerConnectionOptionList ret = Marshal.PtrToStructure<InternetPerConnectionOptionList>(unmanagedList);
  251. IntPtr p = ret.pOptions;
  252. int nOption = ret.OptionCount;
  253. List<InternetPerConnectionOption> outOptions = new List<InternetPerConnectionOption>();
  254. for (int i = 0; i < nOption; i++)
  255. {
  256. InternetPerConnectionOption o = Marshal.PtrToStructure<InternetPerConnectionOption>(p);
  257. outOptions.Add(o);
  258. p += Marshal.SizeOf(o);
  259. }
  260. foreach (InternetPerConnectionOption o in outOptions)
  261. {
  262. switch ((InternetPerConnectionOptionEnum)o.dwOption)
  263. {
  264. case InternetPerConnectionOptionEnum.FlagsUI:
  265. case InternetPerConnectionOptionEnum.Flags:
  266. proxy.Flags = (InternetPerConnectionFlags)o.Value.dwValue;
  267. break;
  268. case InternetPerConnectionOptionEnum.AutoConfigUrl:
  269. proxy.AutoConfigUrl = Marshal.PtrToStringAuto(o.Value.pszValue);
  270. break;
  271. case InternetPerConnectionOptionEnum.ProxyBypass:
  272. proxy.ProxyBypass = Marshal.PtrToStringAuto(o.Value.pszValue);
  273. break;
  274. case InternetPerConnectionOptionEnum.ProxyServer:
  275. proxy.ProxyServer = Marshal.PtrToStringAuto(o.Value.pszValue);
  276. break;
  277. default:
  278. break;
  279. }
  280. }
  281. return proxy;
  282. }
  283. private static InternetPerConnectionOption GetOption(
  284. InternetPerConnectionOptionEnum option,
  285. InternetPerConnectionFlags flag
  286. )
  287. {
  288. return new InternetPerConnectionOption
  289. {
  290. dwOption = (int)option,
  291. Value =
  292. {
  293. dwValue = (int)flag,
  294. }
  295. };
  296. }
  297. private static InternetPerConnectionOption GetOption(
  298. InternetPerConnectionOptionEnum option,
  299. string param
  300. )
  301. {
  302. return new InternetPerConnectionOption
  303. {
  304. dwOption = (int)option,
  305. Value =
  306. {
  307. pszValue = Marshal.StringToCoTaskMemAuto(param),
  308. }
  309. };
  310. }
  311. private static (IntPtr, int) PrepareOptionList(List<InternetPerConnectionOption> options, string connName)
  312. {
  313. int len = options.Sum(o => Marshal.SizeOf(o));
  314. IntPtr buf = Marshal.AllocCoTaskMem(len);
  315. IntPtr cur = buf;
  316. foreach (InternetPerConnectionOption o in options)
  317. {
  318. Marshal.StructureToPtr(o, cur, false);
  319. cur += Marshal.SizeOf(o);
  320. }
  321. InternetPerConnectionOptionList optionList = new InternetPerConnectionOptionList
  322. {
  323. pOptions = buf,
  324. OptionCount = options.Count,
  325. Connection = string.IsNullOrEmpty(connName)
  326. ? IntPtr.Zero
  327. : Marshal.StringToHGlobalAuto(connName),
  328. OptionError = 0,
  329. };
  330. int listSize = Marshal.SizeOf(optionList);
  331. optionList.Size = listSize;
  332. IntPtr unmanagedList = Marshal.AllocCoTaskMem(listSize);
  333. Marshal.StructureToPtr(optionList, unmanagedList, true);
  334. return (unmanagedList, listSize);
  335. }
  336. private static void ClearOptionList(IntPtr list)
  337. {
  338. InternetPerConnectionOptionList l = Marshal.PtrToStructure<InternetPerConnectionOptionList>(list);
  339. Marshal.FreeCoTaskMem(l.pOptions);
  340. Marshal.FreeCoTaskMem(list);
  341. }
  342. private static void Exec(List<InternetPerConnectionOption> options)
  343. {
  344. // TODO: optimize load and save
  345. Load();
  346. Record();
  347. Exec(options, null);
  348. foreach (string conn in RAS.GetAllConnections())
  349. {
  350. Exec(options, conn);
  351. }
  352. Save();
  353. }
  354. private static void Exec(List<InternetPerConnectionOption> options, string connName)
  355. {
  356. if (!operational)
  357. {
  358. return;
  359. }
  360. (IntPtr unmanagedList, int listSize) = PrepareOptionList(options, connName);
  361. bool ok = InternetSetOption(
  362. IntPtr.Zero,
  363. (int)InternetOptions.PerConnectionOption,
  364. unmanagedList,
  365. listSize
  366. );
  367. if (!ok)
  368. {
  369. throw new Win32Exception(Marshal.GetLastWin32Error());
  370. }
  371. ClearOptionList(unmanagedList);
  372. ok = InternetSetOption(
  373. IntPtr.Zero,
  374. (int)InternetOptions.ProxySettingChanged,
  375. IntPtr.Zero,
  376. 0
  377. );
  378. if (!ok)
  379. {
  380. throw new Win32Exception(Marshal.GetLastWin32Error());
  381. }
  382. ok = InternetSetOption(
  383. IntPtr.Zero,
  384. (int)InternetOptions.Refresh,
  385. IntPtr.Zero,
  386. 0
  387. );
  388. if (!ok)
  389. {
  390. throw new Win32Exception(Marshal.GetLastWin32Error());
  391. }
  392. }
  393. [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
  394. public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
  395. [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
  396. private static extern bool InternetQueryOption(IntPtr hInternet, uint dwOption, IntPtr lpBuffer, ref int lpdwBufferLength);
  397. }
  398. }