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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using NLog;
  7. namespace Shadowsocks.WPF.Services.SystemProxy
  8. {
  9. #region Windows API data structure definition
  10. public enum InternetOptions
  11. {
  12. Refresh = 37,
  13. SettingsChanged = 39,
  14. PerConnectionOption = 75,
  15. ProxySettingChanged = 95,
  16. }
  17. public enum InternetPerConnectionOptionEnum
  18. {
  19. Flags = 1,
  20. ProxyServer = 2,
  21. ProxyBypass = 3,
  22. AutoConfigUrl = 4,
  23. AutoDiscovery = 5,
  24. AutoConfigSecondaryUrl = 6,
  25. AutoConfigReloadDelay = 7,
  26. AutoConfigLastDetectTime = 8,
  27. AutoConfigLastDetectUrl = 9,
  28. FlagsUI = 10,
  29. }
  30. [Flags]
  31. public enum InternetPerConnectionFlags
  32. {
  33. Direct = 0x01,
  34. Proxy = 0x02,
  35. AutoProxyUrl = 0x04,
  36. AutoDetect = 0x08,
  37. }
  38. [StructLayout(LayoutKind.Explicit)]
  39. public struct InternetPerConnectionOptionUnion : IDisposable
  40. {
  41. [FieldOffset(0)]
  42. public int dwValue;
  43. [FieldOffset(0)]
  44. public IntPtr pszValue;
  45. [FieldOffset(0)]
  46. public System.Runtime.InteropServices.ComTypes.FILETIME ftValue;
  47. public void Dispose()
  48. {
  49. Dispose(true);
  50. GC.SuppressFinalize(this);
  51. }
  52. private void Dispose(bool disposing)
  53. {
  54. if (disposing)
  55. {
  56. if (pszValue != IntPtr.Zero)
  57. {
  58. Marshal.FreeHGlobal(pszValue);
  59. pszValue = IntPtr.Zero;
  60. }
  61. }
  62. }
  63. }
  64. [StructLayout(LayoutKind.Sequential)]
  65. public struct InternetPerConnectionOption
  66. {
  67. public int dwOption;
  68. public InternetPerConnectionOptionUnion Value;
  69. }
  70. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  71. public struct InternetPerConnectionOptionList : IDisposable
  72. {
  73. public int Size;
  74. // The connection to be set. NULL means LAN.
  75. public IntPtr Connection;
  76. public int OptionCount;
  77. public int OptionError;
  78. // List of INTERNET_PER_CONN_OPTIONs.
  79. public IntPtr pOptions;
  80. public void Dispose()
  81. {
  82. Dispose(true);
  83. GC.SuppressFinalize(this);
  84. }
  85. private void Dispose(bool disposing)
  86. {
  87. if (disposing)
  88. {
  89. if (Connection != IntPtr.Zero)
  90. {
  91. Marshal.FreeHGlobal(Connection);
  92. Connection = IntPtr.Zero;
  93. }
  94. if (pOptions != IntPtr.Zero)
  95. {
  96. Marshal.FreeHGlobal(pOptions);
  97. pOptions = IntPtr.Zero;
  98. }
  99. }
  100. }
  101. }
  102. #endregion
  103. public class WinINetSetting
  104. {
  105. public InternetPerConnectionFlags Flags = InternetPerConnectionFlags.Direct;
  106. public string ProxyServer = string.Empty;
  107. public string ProxyBypass = string.Empty;
  108. public string AutoConfigUrl = string.Empty;
  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. initialSetting = 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;
  138. }
  139. }
  140. finally
  141. {
  142. if (initialSetting == null)
  143. initialSetting = new();
  144. }
  145. }
  146. public static void ProxyGlobal(string server, string bypass)
  147. {
  148. List<InternetPerConnectionOption> options = new List<InternetPerConnectionOption>
  149. {
  150. GetOption(InternetPerConnectionOptionEnum.Flags,InternetPerConnectionFlags.Proxy|InternetPerConnectionFlags.Direct),
  151. GetOption(InternetPerConnectionOptionEnum.ProxyServer,server),
  152. GetOption(InternetPerConnectionOptionEnum.ProxyBypass,bypass),
  153. };
  154. Exec(options);
  155. }
  156. public static void ProxyPAC(string url)
  157. {
  158. List<InternetPerConnectionOption> options = new List<InternetPerConnectionOption>
  159. {
  160. GetOption(InternetPerConnectionOptionEnum.Flags,InternetPerConnectionFlags.AutoProxyUrl|InternetPerConnectionFlags.Direct),
  161. GetOption(InternetPerConnectionOptionEnum.AutoConfigUrl,url),
  162. };
  163. Exec(options);
  164. }
  165. public static void Direct()
  166. {
  167. List<InternetPerConnectionOption> options = new List<InternetPerConnectionOption>
  168. {
  169. GetOption(InternetPerConnectionOptionEnum.Flags,InternetPerConnectionFlags.Direct),
  170. };
  171. Exec(options);
  172. }
  173. public static void Restore()
  174. {
  175. Set(initialSetting);
  176. }
  177. public static void Set(WinINetSetting setting)
  178. {
  179. List<InternetPerConnectionOption> options = new List<InternetPerConnectionOption>
  180. {
  181. GetOption(InternetPerConnectionOptionEnum.Flags,setting.Flags),
  182. GetOption(InternetPerConnectionOptionEnum.ProxyServer,setting.ProxyServer),
  183. GetOption(InternetPerConnectionOptionEnum.ProxyBypass,setting.ProxyBypass),
  184. GetOption(InternetPerConnectionOptionEnum.AutoConfigUrl,setting.AutoConfigUrl),
  185. };
  186. Exec(options);
  187. }
  188. public static void Reset()
  189. {
  190. Set(new WinINetSetting());
  191. }
  192. #region Windows API wrapper
  193. public static WinINetSetting Query()
  194. {
  195. if (!operational)
  196. {
  197. return new WinINetSetting();
  198. }
  199. List<InternetPerConnectionOption> options = new List<InternetPerConnectionOption>
  200. {
  201. new InternetPerConnectionOption{dwOption = (int)InternetPerConnectionOptionEnum.FlagsUI},
  202. new InternetPerConnectionOption{dwOption = (int)InternetPerConnectionOptionEnum.ProxyServer},
  203. new InternetPerConnectionOption{dwOption = (int)InternetPerConnectionOptionEnum.ProxyBypass},
  204. new InternetPerConnectionOption{dwOption = (int)InternetPerConnectionOptionEnum.AutoConfigUrl},
  205. };
  206. (IntPtr unmanagedList, int listSize) = PrepareOptionList(options, "");
  207. bool ok = InternetQueryOption(IntPtr.Zero, (int)InternetOptions.PerConnectionOption, unmanagedList, ref listSize);
  208. if (!ok)
  209. {
  210. throw new Win32Exception(Marshal.GetLastWin32Error());
  211. }
  212. WinINetSetting proxy = new WinINetSetting();
  213. InternetPerConnectionOptionList ret = Marshal.PtrToStructure<InternetPerConnectionOptionList>(unmanagedList);
  214. IntPtr p = ret.pOptions;
  215. int nOption = ret.OptionCount;
  216. List<InternetPerConnectionOption> outOptions = new List<InternetPerConnectionOption>();
  217. for (int i = 0; i < nOption; i++)
  218. {
  219. InternetPerConnectionOption o = Marshal.PtrToStructure<InternetPerConnectionOption>(p);
  220. outOptions.Add(o);
  221. p += Marshal.SizeOf(o);
  222. }
  223. foreach (InternetPerConnectionOption o in outOptions)
  224. {
  225. switch ((InternetPerConnectionOptionEnum)o.dwOption)
  226. {
  227. case InternetPerConnectionOptionEnum.FlagsUI:
  228. case InternetPerConnectionOptionEnum.Flags:
  229. proxy.Flags = (InternetPerConnectionFlags)o.Value.dwValue;
  230. break;
  231. case InternetPerConnectionOptionEnum.AutoConfigUrl:
  232. proxy.AutoConfigUrl = Marshal.PtrToStringAuto(o.Value.pszValue) ?? "";
  233. break;
  234. case InternetPerConnectionOptionEnum.ProxyBypass:
  235. proxy.ProxyBypass = Marshal.PtrToStringAuto(o.Value.pszValue) ?? "";
  236. break;
  237. case InternetPerConnectionOptionEnum.ProxyServer:
  238. proxy.ProxyServer = Marshal.PtrToStringAuto(o.Value.pszValue) ?? "";
  239. break;
  240. default:
  241. break;
  242. }
  243. }
  244. return proxy;
  245. }
  246. private static InternetPerConnectionOption GetOption(
  247. InternetPerConnectionOptionEnum option,
  248. InternetPerConnectionFlags flag
  249. )
  250. {
  251. return new InternetPerConnectionOption
  252. {
  253. dwOption = (int)option,
  254. Value =
  255. {
  256. dwValue = (int)flag,
  257. }
  258. };
  259. }
  260. private static InternetPerConnectionOption GetOption(
  261. InternetPerConnectionOptionEnum option,
  262. string param
  263. )
  264. {
  265. return new InternetPerConnectionOption
  266. {
  267. dwOption = (int)option,
  268. Value =
  269. {
  270. pszValue = Marshal.StringToCoTaskMemAuto(param),
  271. }
  272. };
  273. }
  274. private static (IntPtr, int) PrepareOptionList(List<InternetPerConnectionOption> options, string connName)
  275. {
  276. int len = options.Sum(o => Marshal.SizeOf(o));
  277. IntPtr buf = Marshal.AllocCoTaskMem(len);
  278. IntPtr cur = buf;
  279. foreach (InternetPerConnectionOption o in options)
  280. {
  281. Marshal.StructureToPtr(o, cur, false);
  282. cur += Marshal.SizeOf(o);
  283. }
  284. InternetPerConnectionOptionList optionList = new InternetPerConnectionOptionList
  285. {
  286. pOptions = buf,
  287. OptionCount = options.Count,
  288. Connection = string.IsNullOrEmpty(connName)
  289. ? IntPtr.Zero
  290. : Marshal.StringToHGlobalAuto(connName),
  291. OptionError = 0,
  292. };
  293. int listSize = Marshal.SizeOf(optionList);
  294. optionList.Size = listSize;
  295. IntPtr unmanagedList = Marshal.AllocCoTaskMem(listSize);
  296. Marshal.StructureToPtr(optionList, unmanagedList, true);
  297. return (unmanagedList, listSize);
  298. }
  299. private static void ClearOptionList(IntPtr list)
  300. {
  301. InternetPerConnectionOptionList l = Marshal.PtrToStructure<InternetPerConnectionOptionList>(list);
  302. Marshal.FreeCoTaskMem(l.pOptions);
  303. Marshal.FreeCoTaskMem(list);
  304. }
  305. private static void Exec(List<InternetPerConnectionOption> options)
  306. {
  307. Exec(options, "");
  308. foreach (string conn in RAS.GetAllConnections())
  309. {
  310. Exec(options, conn);
  311. }
  312. }
  313. private static void Exec(List<InternetPerConnectionOption> options, string connName)
  314. {
  315. if (!operational)
  316. {
  317. return;
  318. }
  319. (IntPtr unmanagedList, int listSize) = PrepareOptionList(options, connName);
  320. bool ok = InternetSetOption(
  321. IntPtr.Zero,
  322. (int)InternetOptions.PerConnectionOption,
  323. unmanagedList,
  324. listSize
  325. );
  326. if (!ok)
  327. {
  328. throw new Win32Exception(Marshal.GetLastWin32Error());
  329. }
  330. ClearOptionList(unmanagedList);
  331. ok = InternetSetOption(
  332. IntPtr.Zero,
  333. (int)InternetOptions.ProxySettingChanged,
  334. IntPtr.Zero,
  335. 0
  336. );
  337. if (!ok)
  338. {
  339. throw new Win32Exception(Marshal.GetLastWin32Error());
  340. }
  341. ok = InternetSetOption(
  342. IntPtr.Zero,
  343. (int)InternetOptions.Refresh,
  344. IntPtr.Zero,
  345. 0
  346. );
  347. if (!ok)
  348. {
  349. throw new Win32Exception(Marshal.GetLastWin32Error());
  350. }
  351. }
  352. [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
  353. public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
  354. [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
  355. private static extern bool InternetQueryOption(IntPtr hInternet, uint dwOption, IntPtr lpBuffer, ref int lpdwBufferLength);
  356. #endregion
  357. }
  358. }