This repository was archived by the owner on Jul 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 652
Expand file tree
/
Copy pathSystemProxy.cs
More file actions
295 lines (243 loc) · 9.62 KB
/
SystemProxy.cs
File metadata and controls
295 lines (243 loc) · 9.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.Win32;
using Titanium.Web.Proxy.Models;
// Helper classes for setting system proxy settings
namespace Titanium.Web.Proxy.Helpers;
internal class HttpSystemProxyValue
{
public HttpSystemProxyValue(string hostName, int port, ProxyProtocolType protocolType)
{
HostName = hostName;
Port = port;
ProtocolType = protocolType;
}
internal string HostName { get; }
internal int Port { get; }
internal ProxyProtocolType ProtocolType { get; }
public override string ToString()
{
string protocol;
switch (ProtocolType)
{
case ProxyProtocolType.Http:
protocol = ProxyServer.UriSchemeHttp;
break;
case ProxyProtocolType.Https:
protocol = ProxyServer.UriSchemeHttps;
break;
default:
throw new Exception("Unsupported protocol type");
}
return $"{protocol}={HostName}:{Port}";
}
}
/// <summary>
/// Manage system proxy settings
/// </summary>
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleType",
Justification = "Reviewed.")]
internal class SystemProxyManager
{
private const string RegKeyInternetSettings = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
private const string RegAutoConfigUrl = "AutoConfigURL";
private const string RegProxyEnable = "ProxyEnable";
private const string RegProxyServer = "ProxyServer";
private const string RegProxyOverride = "ProxyOverride";
internal const int InternetOptionSettingsChanged = 39;
internal const int InternetOptionRefresh = 37;
private ProxyInfo? originalValues;
public SystemProxyManager()
{
AppDomain.CurrentDomain.ProcessExit += (o, args) => RestoreOriginalSettings();
if (Environment.UserInteractive && NativeMethods.GetConsoleWindow() != IntPtr.Zero)
{
var handler = new NativeMethods.ConsoleEventDelegate(eventType =>
{
if (eventType != 2) return false;
RestoreOriginalSettings();
return false;
});
NativeMethods.Handler = handler;
// On Console exit make sure we also exit the proxy
NativeMethods.SetConsoleCtrlHandler(handler, true);
}
}
/// <summary>
/// Set the HTTP and/or HTTPS proxy server for current machine
/// </summary>
/// <param name="hostname"></param>
/// <param name="port"></param>
/// <param name="protocolType"></param>
/// <param name="bypassRules"></param>
internal void SetProxy(string hostname, int port, ProxyProtocolType protocolType, string bypassRules)
{
using (var reg = OpenInternetSettingsKey())
{
if (reg == null) return;
SaveOriginalProxyConfiguration(reg);
PrepareRegistry(reg);
var existingContent = reg.GetValue(RegProxyServer) as string;
var existingSystemProxyValues = ProxyInfo.GetSystemProxyValues(existingContent);
existingSystemProxyValues.RemoveAll(x => (protocolType & x.ProtocolType) != 0);
if ((protocolType & ProxyProtocolType.Http) != 0)
existingSystemProxyValues.Add(new HttpSystemProxyValue(hostname, port, ProxyProtocolType.Http));
if ((protocolType & ProxyProtocolType.Https) != 0)
existingSystemProxyValues.Add(new HttpSystemProxyValue(hostname, port, ProxyProtocolType.Https));
reg.DeleteValue(RegAutoConfigUrl, false);
reg.SetValue(RegProxyEnable, 1);
reg.SetValue(RegProxyServer,
string.Join(";", existingSystemProxyValues.Select(x => x.ToString()).ToArray()));
reg.SetValue(RegProxyOverride, bypassRules);
Refresh();
}
}
/// <summary>
/// Remove the HTTP and/or HTTPS proxy setting from current machine
/// </summary>
internal void RemoveProxy(ProxyProtocolType protocolType, bool saveOriginalConfig = true)
{
using (var reg = OpenInternetSettingsKey())
{
if (reg == null) return;
if (saveOriginalConfig) SaveOriginalProxyConfiguration(reg);
if (reg.GetValue(RegProxyServer) != null)
{
var existingContent = reg.GetValue(RegProxyServer) as string;
var existingSystemProxyValues = ProxyInfo.GetSystemProxyValues(existingContent);
existingSystemProxyValues.RemoveAll(x => (protocolType & x.ProtocolType) != 0);
if (existingSystemProxyValues.Count != 0)
{
reg.SetValue(RegProxyEnable, 1);
reg.SetValue(RegProxyServer,
string.Join(";", existingSystemProxyValues.Select(x => x.ToString()).ToArray()));
}
else
{
reg.SetValue(RegProxyEnable, 0);
reg.SetValue(RegProxyServer, string.Empty);
}
}
Refresh();
}
}
/// <summary>
/// Removes all types of proxy settings (both http and https)
/// </summary>
internal void DisableAllProxy()
{
using (var reg = OpenInternetSettingsKey())
{
if (reg == null) return;
SaveOriginalProxyConfiguration(reg);
reg.SetValue(RegProxyEnable, 0);
reg.SetValue(RegProxyServer, string.Empty);
Refresh();
}
}
internal void SetAutoProxyUrl(string url)
{
using (var reg = OpenInternetSettingsKey())
{
if (reg == null) return;
SaveOriginalProxyConfiguration(reg);
reg.SetValue(RegAutoConfigUrl, url);
Refresh();
}
}
internal void SetProxyOverride(string proxyOverride)
{
using (var reg = OpenInternetSettingsKey())
{
if (reg == null) return;
SaveOriginalProxyConfiguration(reg);
reg.SetValue(RegProxyOverride, proxyOverride);
Refresh();
}
}
internal void RestoreOriginalSettings()
{
if (originalValues == null) return;
using (var reg = Registry.CurrentUser.OpenSubKey(RegKeyInternetSettings, true))
{
if (reg == null) return;
var ov = originalValues;
if (ov.AutoConfigUrl != null)
reg.SetValue(RegAutoConfigUrl, ov.AutoConfigUrl);
else
reg.DeleteValue(RegAutoConfigUrl, false);
if (ov.ProxyEnable.HasValue)
reg.SetValue(RegProxyEnable, ov.ProxyEnable.Value);
else
reg.DeleteValue(RegProxyEnable, false);
if (ov.ProxyServer != null)
reg.SetValue(RegProxyServer, ov.ProxyServer);
else
reg.DeleteValue(RegProxyServer, false);
if (ov.ProxyOverride != null)
reg.SetValue(RegProxyOverride, ov.ProxyOverride);
else
reg.DeleteValue(RegProxyOverride, false);
// This should not be needed, but sometimes the values are not stored into the registry
// at system shutdown without flushing.
reg.Flush();
originalValues = null;
const int smShuttingdown = 0x2000;
var windows7Version = new Version(6, 1);
if (Environment.OSVersion.Version > windows7Version ||
NativeMethods.GetSystemMetrics(smShuttingdown) == 0)
// Do not call refresh() in Windows 7 or earlier at system shutdown.
// SetInternetOption in the refresh method re-enables ProxyEnable registry value
// in Windows 7 or earlier at system shutdown.
Refresh();
}
}
internal ProxyInfo? GetProxyInfoFromRegistry()
{
using (var reg = OpenInternetSettingsKey())
{
if (reg == null) return null;
return GetProxyInfoFromRegistry(reg);
}
}
private ProxyInfo GetProxyInfoFromRegistry(RegistryKey reg)
{
var pi = new ProxyInfo(null,
reg.GetValue(RegAutoConfigUrl) as string,
reg.GetValue(RegProxyEnable) as int?,
reg.GetValue(RegProxyServer) as string,
reg.GetValue(RegProxyOverride) as string);
return pi;
}
private void SaveOriginalProxyConfiguration(RegistryKey reg)
{
if (originalValues != null) return;
originalValues = GetProxyInfoFromRegistry(reg);
}
/// <summary>
/// Prepares the proxy server registry (create empty values if they don't exist)
/// </summary>
/// <param name="reg"></param>
private static void PrepareRegistry(RegistryKey reg)
{
if (reg.GetValue(RegProxyEnable) == null) reg.SetValue(RegProxyEnable, 0);
if (reg.GetValue(RegProxyServer) == null || reg.GetValue(RegProxyEnable) as int? == 0)
reg.SetValue(RegProxyServer, string.Empty);
}
/// <summary>
/// Refresh the settings so that the system know about a change in proxy setting
/// </summary>
private static void Refresh()
{
NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionSettingsChanged, IntPtr.Zero, 0);
NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionRefresh, IntPtr.Zero, 0);
}
/// <summary>
/// Opens the registry key with the internet settings
/// </summary>
private static RegistryKey? OpenInternetSettingsKey()
{
return Registry.CurrentUser?.OpenSubKey(RegKeyInternetSettings, true);
}
}