-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsysproxy.go
More file actions
304 lines (281 loc) · 9.39 KB
/
Copy pathsysproxy.go
File metadata and controls
304 lines (281 loc) · 9.39 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
296
297
298
299
300
301
302
303
304
// Package sysproxy provides cross-platform system proxy management.
//
// It supports setting, clearing, and querying the OS system proxy on
// macOS (networksetup), Linux (gsettings / kwriteconfig5, /etc/environment),
// and Windows (registry + Credential Manager).
//
// Quick start:
//
// err := sysproxy.Set("http://proxy.example.com:8080", sysproxy.ScopeGlobal)
// err = sysproxy.Unset(sysproxy.ScopeGlobal)
// err = sysproxy.SetContext(ctx, "http://proxy.example.com:8080", sysproxy.ScopeGlobal)
//
// // temporary proxy — auto-restored on return
// err = sysproxy.WithProxy(ctx, "socks5://proxy.example.com:1080", sysproxy.ScopeGlobal, func(ctx context.Context) error {
// return doRequest(ctx)
// })
package sysproxy
import (
"context"
"fmt"
)
// ProxyScope defines the lifetime and reach of a proxy setting.
type ProxyScope int
const (
// ScopeShell sets proxy only for the current process via env vars.
ScopeShell ProxyScope = iota
// ScopeUser persists proxy for the current user (rc files on Unix, PS profile on Windows).
ScopeUser
// ScopeGlobal sets the system-wide proxy (requires elevated privileges on most platforms).
ScopeGlobal
)
// String returns a human-readable name for the scope.
func (s ProxyScope) String() string {
switch s {
case ScopeShell:
return "shell"
case ScopeUser:
return "user"
case ScopeGlobal:
return "global"
default:
return "unknown"
}
}
// ProxyConfig holds per-protocol proxy URLs for SetMulti and the current
// system configuration returned by GetConfig. Any field left empty is ignored
// by SetMulti; empty fields returned by GetConfig indicate that protocol has
// no proxy configured. PAC is populated by GetConfig when the OS is in
// auto-proxy mode; SetMulti ignores it — use SetPAC to switch modes.
type ProxyConfig struct {
HTTP string `json:"http,omitempty"`
HTTPS string `json:"https,omitempty"`
SOCKS string `json:"socks,omitempty"`
NoProxy string `json:"no_proxy,omitempty"` // comma-separated bypass list, e.g. "localhost,10.0.0.0/8"
PAC string `json:"pac,omitempty"` // populated by GetConfig when auto-proxy is active
}
// Set configures the OS system proxy to proxyURL for the given scope.
//
// err := sysproxy.Set("http://user:pass@proxy.example.com:8080", sysproxy.ScopeGlobal)
func Set(proxyURL string, scope ProxyScope) error {
return SetContext(context.Background(), proxyURL, scope)
}
// SetContext configures the OS system proxy to proxyURL for the given scope,
// aborting before side effects if ctx is already canceled.
func SetContext(ctx context.Context, proxyURL string, scope ProxyScope) error {
if err := validateProxyURL(proxyURL); err != nil {
return err
}
ctx = normalizeContext(ctx)
if err := ctx.Err(); err != nil {
return err
}
p, err := parse(proxyURL)
if err != nil {
return err
}
switch scope {
case ScopeShell:
setEnvVars(proxyURL)
logf("set proxy scope=shell url=%s", proxyURL)
return nil
case ScopeUser:
setEnvVars(proxyURL)
err = setUser(proxyURL)
logf("set proxy scope=user url=%s err=%v", proxyURL, err)
return err
case ScopeGlobal:
setEnvVars(proxyURL)
err = activeBackend.SetGlobal(ctx, p)
logf("set proxy scope=global url=%s err=%v", proxyURL, err)
return err
default:
return fmt.Errorf("sysproxy: invalid scope %d", scope)
}
}
// Unset clears the OS system proxy for the given scope.
//
// err := sysproxy.Unset(sysproxy.ScopeGlobal)
func Unset(scope ProxyScope) error {
return UnsetContext(context.Background(), scope)
}
// UnsetContext clears the OS system proxy for the given scope, aborting before
// side effects if ctx is already canceled.
func UnsetContext(ctx context.Context, scope ProxyScope) error {
ctx = normalizeContext(ctx)
if err := ctx.Err(); err != nil {
return err
}
switch scope {
case ScopeShell:
unsetEnvVars()
logf("unset proxy scope=shell")
return nil
case ScopeUser:
unsetEnvVars()
err := unsetUser()
logf("unset proxy scope=user err=%v", err)
return err
case ScopeGlobal:
unsetEnvVars()
err := activeBackend.UnsetGlobal(ctx)
logf("unset proxy scope=global err=%v", err)
return err
default:
return fmt.Errorf("sysproxy: invalid scope %d", scope)
}
}
// Get returns the current system proxy URL, or an error if none is configured.
func Get() (string, error) {
return GetContext(context.Background())
}
// GetContext returns the current system proxy URL, or an error if none is
// configured.
func GetContext(ctx context.Context) (string, error) {
ctx = normalizeContext(ctx)
if err := ctx.Err(); err != nil {
return "", err
}
return activeBackend.GetGlobal(ctx)
}
// GetConfig returns the per-protocol proxy configuration currently active in
// the OS system settings. Fields are empty when that protocol has no proxy set.
// Only ScopeGlobal is supported; read os.Getenv for shell-scope values.
func GetConfig() (ProxyConfig, error) {
return GetConfigContext(context.Background())
}
// GetConfigContext is like GetConfig but respects context cancellation.
func GetConfigContext(ctx context.Context) (ProxyConfig, error) {
ctx = normalizeContext(ctx)
if err := ctx.Err(); err != nil {
return ProxyConfig{}, err
}
return activeBackend.GetGlobalConfig(ctx)
}
// SetMulti configures per-protocol proxies. Any field left empty is not changed.
func SetMulti(cfg ProxyConfig, scope ProxyScope) error {
return SetMultiContext(context.Background(), cfg, scope)
}
// SetMultiContext configures per-protocol proxies. Any field left empty is not
// changed.
func SetMultiContext(ctx context.Context, cfg ProxyConfig, scope ProxyScope) error {
for _, u := range []string{cfg.HTTP, cfg.HTTPS, cfg.SOCKS} {
if u != "" {
if err := validateProxyURL(u); err != nil {
return err
}
}
}
ctx = normalizeContext(ctx)
if err := ctx.Err(); err != nil {
return err
}
switch scope {
case ScopeShell:
setEnvVarsMulti(cfg)
return nil
case ScopeUser:
setEnvVarsMulti(cfg)
return setUserMulti(cfg)
case ScopeGlobal:
setEnvVarsMulti(cfg)
return activeBackend.SetGlobalMulti(ctx, cfg)
default:
return fmt.Errorf("sysproxy: invalid scope %d", scope)
}
}
// SetPAC configures the OS system proxy to use a Proxy Auto-Config (PAC) URL.
// pacURL must start with http://, https://, or file://.
func SetPAC(pacURL string, scope ProxyScope) error {
return SetPACContext(context.Background(), pacURL, scope)
}
// SetPACContext configures the OS system proxy to use a Proxy Auto-Config
// (PAC) URL. pacURL must start with http://, https://, or file://.
func SetPACContext(ctx context.Context, pacURL string, scope ProxyScope) error {
if err := validatePACURL(pacURL); err != nil {
return err
}
ctx = normalizeContext(ctx)
if err := ctx.Err(); err != nil {
return err
}
switch scope {
case ScopeShell:
setEnvVarsPAC(pacURL)
return nil
case ScopeUser:
setEnvVarsPAC(pacURL)
return setUserPAC(pacURL)
case ScopeGlobal:
setEnvVarsPAC(pacURL)
return activeBackend.SetGlobalPAC(ctx, pacURL)
default:
return fmt.Errorf("sysproxy: invalid scope %d", scope)
}
}
// WithProxy temporarily sets the proxy for the duration of fn, then restores
// the previous proxy state (or clears it if no proxy was set before).
// The restore snapshot covers the full ProxyConfig — HTTP, HTTPS, SOCKS,
// NoProxy, and PAC — not just the HTTP field.
//
// err := sysproxy.WithProxy(ctx, "socks5://proxy:1080", sysproxy.ScopeGlobal, func(ctx context.Context) error {
// return doRequest(ctx)
// })
func WithProxy(ctx context.Context, proxyURL string, scope ProxyScope, fn func(context.Context) error) error {
ctx = normalizeContext(ctx)
snapshot, hadSnapshot := snapshotForRestore(scope)
if err := SetContext(ctx, proxyURL, scope); err != nil && !IsNonCritical(err) {
return err
}
defer restoreSnapshot(scope, snapshot, hadSnapshot)
return fn(ctx)
}
// WithProxyMulti is the multi-protocol variant of WithProxy: it applies cfg
// via SetMulti and restores the previous full configuration on return.
func WithProxyMulti(ctx context.Context, cfg ProxyConfig, scope ProxyScope, fn func(context.Context) error) error {
ctx = normalizeContext(ctx)
snapshot, hadSnapshot := snapshotForRestore(scope)
if err := SetMultiContext(ctx, cfg, scope); err != nil && !IsNonCritical(err) {
return err
}
defer restoreSnapshot(scope, snapshot, hadSnapshot)
return fn(ctx)
}
// snapshotForRestore reads the current global config so WithProxy* can undo
// its change. ScopeShell/ScopeUser have no read-back path, so the caller
// restores by Unset.
func snapshotForRestore(scope ProxyScope) (ProxyConfig, bool) {
if scope != ScopeGlobal {
return ProxyConfig{}, false
}
cfg, err := GetConfig()
if err != nil {
return ProxyConfig{}, false
}
return cfg, true
}
// restoreSnapshot re-applies snap after WithProxy / WithProxyMulti finishes.
// Restore errors are logged and swallowed so they do not shadow fn's error.
func restoreSnapshot(scope ProxyScope, snap ProxyConfig, had bool) {
if !had {
if err := Unset(scope); err != nil && !IsNonCritical(err) {
logf("WithProxy: restore Unset failed: %v", err)
}
return
}
if snap.PAC != "" {
if err := SetPAC(snap.PAC, scope); err != nil && !IsNonCritical(err) {
logf("WithProxy: restore SetPAC failed: %v", err)
}
return
}
if snap.HTTP == "" && snap.HTTPS == "" && snap.SOCKS == "" {
if err := Unset(scope); err != nil && !IsNonCritical(err) {
logf("WithProxy: restore Unset failed: %v", err)
}
return
}
if err := SetMulti(snap, scope); err != nil && !IsNonCritical(err) {
logf("WithProxy: restore SetMulti failed: %v", err)
}
}