Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:zap: Improve Linux GNOME system proxy detection https://github.com/siyuan-note/siyuan/issues/20535

Daniel69ce7a88eeb7
diff --git a/kernel/util/system_proxy_linux.go b/kernel/util/system_proxy_linux.go
new file mode 100644
index 0000000000..3f89400442
--- /dev/null
+++ b/kernel/util/system_proxy_linux.go
@@ -0,0 +1,254 @@
+//go:build linux && !android
+
+package util
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "net/url"
+ "os"
+ "os/exec"
+ "strconv"
+ "strings"
+ "time"
+ "unicode"
+)
+
+const gnomeProxySchema = "org.gnome.system.proxy"
+
+type gnomeProxySettingReader func(context.Context, string, string) (string, error)
+
+func readSystemNetworkProxy() (*systemNetworkProxyConfig, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ return readGNOMENetworkProxy(ctx, os.Getenv, readGNOMEProxySetting)
+}
+
+// readGNOMENetworkProxy 仅在 GNOME 会话且没有显式代理环境配置时读取桌面代理。
+// 整组保留环境代理,避免将两个来源的 HTTP 和 HTTPS 配置混合。
+func readGNOMENetworkProxy(ctx context.Context, getenv func(string) string, read gnomeProxySettingReader) (*systemNetworkProxyConfig, error) {
+ if !isGNOMEProxySession(getenv) {
+ return nil, nil
+ }
+ for _, name := range []string{"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy"} {
+ if getenv(name) != "" {
+ return nil, nil
+ }
+ }
+ get := func(schema, key string) (string, error) {
+ value, err := read(ctx, schema, key)
+ if err != nil {
+ // 不记录设置内容或命令标准错误,避免泄露代理配置。
+ return "", fmt.Errorf("read GNOME proxy setting %s.%s failed", schema, key)
+ }
+ return strings.TrimSpace(value), nil
+ }
+ getString := func(schema, key string) (string, error) {
+ value, err := get(schema, key)
+ if err != nil {
+ return "", err
+ }
+ parsed, rest, err := consumeGNOMEProxyString(value)
+ if err != nil || strings.TrimSpace(rest) != "" {
+ return "", fmt.Errorf("invalid GNOME proxy string %s.%s", schema, key)
+ }
+ return parsed, nil
+ }
+ mode, err := getString(gnomeProxySchema, "mode")
+ if err != nil {
+ return nil, err
+ }
+ switch mode {
+ case "none":
+ return nil, nil
+ case "auto":
+ return nil, fmt.Errorf("GNOME automatic proxy configuration is not supported")
+ case "manual":
+ default:
+ return nil, fmt.Errorf("invalid GNOME proxy mode")
+ }
+ proxies := make(map[string]string, 3)
+ for _, protocol := range []string{"http", "https", "socks"} {
+ schema := gnomeProxySchema + "." + protocol
+ host, readErr := getString(schema, "host")
+ if readErr != nil {
+ return nil, readErr
+ }
+ if host == "" {
+ continue
+ }
+ portValue, readErr := get(schema, "port")
+ if readErr != nil {
+ return nil, readErr
+ }
+ port, parseErr := strconv.Atoi(portValue)
+ if parseErr != nil || port < 0 || port > 65535 {
+ return nil, fmt.Errorf("invalid GNOME proxy port for %s", protocol)
+ }
+ if port == 0 {
+ continue
+ }
+ if protocol == "http" {
+ auth, authErr := get(schema, "use-authentication")
+ if authErr != nil {
+ return nil, authErr
+ }
+ if auth != "false" {
+ return nil, fmt.Errorf("GNOME authenticated HTTP proxy is not supported")
+ }
+ }
+ proxy, parseErr := gnomeProxyURL(host, port, protocol)
+ if parseErr != nil {
+ return nil, parseErr
+ }
+ proxies[protocol] = proxy
+ }
+ ret := &systemNetworkProxyConfig{HTTPProxy: proxies["http"], HTTPSProxy: proxies["https"]}
+ // GNOME 的 HTTPS 未单独配置时复用 HTTP,然后才回退 SOCKS。
+ if ret.HTTPSProxy == "" {
+ ret.HTTPSProxy = ret.HTTPProxy
+ }
+ if ret.HTTPProxy == "" {
+ ret.HTTPProxy = proxies["socks"]
+ }
+ if ret.HTTPSProxy == "" {
+ ret.HTTPSProxy = proxies["socks"]
+ }
+ if ret.HTTPProxy == "" && ret.HTTPSProxy == "" {
+ return nil, nil
+ }
+ ignore, err := get(gnomeProxySchema, "ignore-hosts")
+ if err != nil {
+ return nil, err
+ }
+ bypass, err := parseGNOMEProxyStrings(ignore)
+ if err != nil {
+ return nil, err
+ }
+ // GNOME 的前导点和通配域名同时包含主域名,NO_PROXY 的对应写法只匹配子域名。
+ for i, entry := range bypass {
+ entry = strings.TrimSpace(entry)
+ bypass[i] = strings.TrimPrefix(strings.TrimPrefix(entry, "*."), ".")
+ if bypass[i] == "*" {
+ // GNOME 不把单独的星号作为全局直连规则。
+ bypass[i] = ""
+ }
+ }
+ // 单独设置 NO_PROXY 不阻止读取桌面代理;保留两方的直连例外。
+ environmentBypass := getenv("no_proxy")
+ if environmentBypass == "" {
+ environmentBypass = getenv("NO_PROXY")
+ }
+ bypass = append(bypass, strings.Split(environmentBypass, ",")...)
+ seen := map[string]bool{}
+ entries := []string{}
+ for _, entry := range bypass {
+ entry = strings.TrimSpace(entry)
+ if strings.ContainsAny(entry, ",\x00\r\n") {
+ return nil, fmt.Errorf("invalid GNOME proxy bypass entry")
+ }
+ if entry != "" && !seen[entry] {
+ seen[entry] = true
+ entries = append(entries, entry)
+ }
+ }
+ ret.NoProxy = strings.Join(entries, ",")
+ return ret, nil
+}
+
+func isGNOMEProxySession(getenv func(string) string) bool {
+ desktop := getenv("XDG_CURRENT_DESKTOP")
+ if desktop != "" {
+ for _, name := range strings.Split(desktop, ":") {
+ if strings.EqualFold(strings.TrimSpace(name), "GNOME") {
+ return true
+ }
+ }
+ return false
+ }
+ for _, name := range []string{"XDG_SESSION_DESKTOP", "DESKTOP_SESSION"} {
+ session := strings.ToLower(getenv(name))
+ switch session {
+ case "gnome", "gnome-classic", "gnome-xorg", "gnome-wayland":
+ return true
+ }
+ if session != "" {
+ return false
+ }
+ }
+ return false
+}
+
+func readGNOMEProxySetting(ctx context.Context, schema, key string) (string, error) {
+ // 不经过 shell;调用方只传入固定的 schema 和 key,整个读取流程共享超时。
+ cmd := exec.CommandContext(ctx, "gsettings", "get", schema, key)
+ cmd.WaitDelay = 100 * time.Millisecond
+ output, err := cmd.Output()
+ return string(output), err
+}
+
+func gnomeProxyURL(host string, port int, protocol string) (string, error) {
+ if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
+ host = host[1 : len(host)-1]
+ }
+ if host == "" || strings.ContainsAny(host, "/\\@?#[]") || strings.IndexFunc(host, func(r rune) bool {
+ return unicode.IsSpace(r) || unicode.IsControl(r)
+ }) >= 0 || (strings.Contains(host, ":") && net.ParseIP(host) == nil) {
+ return "", fmt.Errorf("invalid GNOME proxy host for %s", protocol)
+ }
+ scheme := "http"
+ if protocol == "socks" {
+ scheme = "socks5"
+ }
+ return (&url.URL{Scheme: scheme, Host: net.JoinHostPort(host, strconv.Itoa(port))}).String(), nil
+}
+
+// consumeGNOMEProxyString 解析 gsettings 输出的 GVariant 引号字符串,不执行转义后的内容。
+func consumeGNOMEProxyString(value string) (string, string, error) {
+ value = strings.TrimSpace(value)
+ if len(value) < 2 || (value[0] != '\'' && value[0] != '"') {
+ return "", "", fmt.Errorf("invalid GNOME proxy string")
+ }
+ quote := value[0]
+ value = value[1:]
+ var result strings.Builder
+ for len(value) > 0 {
+ if value[0] == quote {
+ return result.String(), value[1:], nil
+ }
+ char, _, tail, err := strconv.UnquoteChar(value, quote)
+ if err != nil {
+ return "", "", fmt.Errorf("invalid GNOME proxy string escape")
+ }
+ result.WriteRune(char)
+ value = tail
+ }
+ return "", "", fmt.Errorf("unterminated GNOME proxy string")
+}
+
+func parseGNOMEProxyStrings(value string) ([]string, error) {
+ value = strings.TrimSpace(strings.TrimPrefix(value, "@as "))
+ if !strings.HasPrefix(value, "[") {
+ return nil, fmt.Errorf("invalid GNOME proxy bypass list")
+ }
+ value = strings.TrimSpace(value[1:])
+ result := []string{}
+ for !strings.HasPrefix(value, "]") {
+ entry, rest, err := consumeGNOMEProxyString(value)
+ if err != nil {
+ return nil, err
+ }
+ result = append(result, entry)
+ value = strings.TrimSpace(rest)
+ if strings.HasPrefix(value, ",") {
+ value = strings.TrimSpace(value[1:])
+ } else if !strings.HasPrefix(value, "]") {
+ return nil, fmt.Errorf("invalid GNOME proxy bypass separator")
+ }
+ }
+ if strings.TrimSpace(value[1:]) != "" {
+ return nil, fmt.Errorf("invalid GNOME proxy bypass suffix")
+ }
+ return result, nil
+}
diff --git a/kernel/util/system_proxy_linux_integration_test.go b/kernel/util/system_proxy_linux_integration_test.go
new file mode 100644
index 0000000000..05158e8b8a
--- /dev/null
+++ b/kernel/util/system_proxy_linux_integration_test.go
@@ -0,0 +1,77 @@
+//go:build linux && !android
+
+package util
+
+import (
+ "context"
+ "os"
+ "testing"
+)
+
+func TestGNOMEProxyModeTransitions(t *testing.T) {
+ for _, name := range networkProxyEnvironmentNames {
+ t.Setenv(name, "")
+ }
+ t.Setenv("XDG_CURRENT_DESKTOP", "GNOME")
+ originalEnvironment, originalLoader := systemNetworkProxyEnvironment, loadSystemNetworkProxy
+ systemNetworkProxyEnvironment = map[string]networkProxyEnvironmentValue{
+ "NO_PROXY": {value: "private.example", set: true},
+ }
+ t.Cleanup(func() {
+ systemNetworkProxyEnvironment, loadSystemNetworkProxy = originalEnvironment, originalLoader
+ })
+ settings := gnomeProxyTestSettings()
+ loads := 0
+ loadSystemNetworkProxy = func() (*systemNetworkProxyConfig, error) {
+ loads++
+ return readGNOMENetworkProxy(context.Background(), os.Getenv, readGNOMEProxyTestSettings(settings))
+ }
+ for i := 0; i < 2; i++ {
+ SetNetworkProxy("socks5://manual:1080", false)
+ if got := os.Getenv("HTTPS_PROXY"); got != "socks5://manual:1080" {
+ t.Fatalf("manual proxy = %q", got)
+ }
+ if loads != i {
+ t.Fatal("manual proxy must not load GNOME")
+ }
+ SetNetworkProxy("", true)
+ if got := os.Getenv("HTTP_PROXY"); got != "http://127.0.0.1:7890" {
+ t.Fatalf("system HTTP = %q", got)
+ }
+ if got := os.Getenv("HTTPS_PROXY"); got != "http://127.0.0.1:7891" {
+ t.Fatalf("system HTTPS = %q", got)
+ }
+ if got := os.Getenv("NO_PROXY"); got != "localhost,127.0.0.0/8,::1,private.example" {
+ t.Fatalf("system bypass = %q", got)
+ }
+ SetNetworkProxy("", false)
+ if got := os.Getenv("HTTP_PROXY"); got != "" {
+ t.Fatalf("direct HTTP = %q", got)
+ }
+ if got := os.Getenv("HTTPS_PROXY"); got != "" {
+ t.Fatalf("direct HTTPS = %q", got)
+ }
+ if got := os.Getenv("NO_PROXY"); got != "private.example" {
+ t.Fatalf("direct bypass = %q", got)
+ }
+ if loads != i+1 {
+ t.Fatal("direct mode must not load GNOME")
+ }
+ }
+ // 重新进入系统模式恢复启动配置,不把上一次手动设置误当成显式环境变量。
+ systemNetworkProxyEnvironment["https_proxy"] = networkProxyEnvironmentValue{value: "http://environment:8080", set: true}
+ loadSystemNetworkProxy = func() (*systemNetworkProxyConfig, error) {
+ return readGNOMENetworkProxy(context.Background(), os.Getenv, func(context.Context, string, string) (string, error) {
+ t.Fatal("startup environment must bypass GNOME reads")
+ return "", nil
+ })
+ }
+ SetNetworkProxy("socks5://manual:1080", false)
+ SetNetworkProxy("", true)
+ if got := os.Getenv("https_proxy"); got != "http://environment:8080" {
+ t.Fatalf("restored HTTPS = %q", got)
+ }
+ if got := os.Getenv("HTTP_PROXY"); got != "" {
+ t.Fatalf("mixed GNOME HTTP with environment HTTPS: %q", got)
+ }
+}
diff --git a/kernel/util/system_proxy_linux_test.go b/kernel/util/system_proxy_linux_test.go
new file mode 100644
index 0000000000..e4ffab7c85
--- /dev/null
+++ b/kernel/util/system_proxy_linux_test.go
@@ -0,0 +1,270 @@
+//go:build linux && !android
+
+package util
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+func gnomeProxyTestSettings() map[string]string {
+ return map[string]string{
+ gnomeProxySchema + ".mode": "'manual'",
+ gnomeProxySchema + ".ignore-hosts": "['localhost', '127.0.0.0/8', '::1']",
+ gnomeProxySchema + ".http.host": "'127.0.0.1'",
+ gnomeProxySchema + ".http.port": "7890",
+ gnomeProxySchema + ".http.use-authentication": "false",
+ gnomeProxySchema + ".https.host": "'127.0.0.1'",
+ gnomeProxySchema + ".https.port": "7891",
+ gnomeProxySchema + ".socks.host": "'::1'",
+ gnomeProxySchema + ".socks.port": "7892",
+ }
+}
+
+func readGNOMEProxyTestSettings(settings map[string]string) gnomeProxySettingReader {
+ return func(ctx context.Context, schema, key string) (string, error) {
+ if err := ctx.Err(); err != nil {
+ return "", err
+ }
+ value, ok := settings[schema+"."+key]
+ if !ok {
+ return "", errors.New("setting unavailable")
+ }
+ return value, nil
+ }
+}
+
+func TestGNOMEProxySession(t *testing.T) {
+ for _, test := range []struct {
+ current, session, desktop string
+ want bool
+ }{
+ {"GNOME", "", "", true},
+ {"ubuntu:GNOME", "", "", true},
+ {"GNOME:GNOME-Classic", "", "", true},
+ {"gnome", "", "", true},
+ {"KDE", "gnome", "gnome", false},
+ {"X-Cinnamon", "", "", false},
+ {"", "gnome", "", true},
+ {"", "", "gnome-classic", true},
+ {"", "plasma", "", false},
+ {"", "plasma", "gnome", false},
+ {"", "", "", false},
+ } {
+ env := map[string]string{"XDG_CURRENT_DESKTOP": test.current, "XDG_SESSION_DESKTOP": test.session, "DESKTOP_SESSION": test.desktop}
+ if got := isGNOMEProxySession(func(name string) string { return env[name] }); got != test.want {
+ t.Errorf("session %#v = %v, want %v", test, got, test.want)
+ }
+ }
+}
+
+func TestGNOMENetworkProxyEnvironmentPriority(t *testing.T) {
+ for _, variable := range []string{"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy"} {
+ t.Run(variable, func(t *testing.T) {
+ env := map[string]string{"XDG_CURRENT_DESKTOP": "GNOME", variable: "http://environment:8080"}
+ read := func(context.Context, string, string) (string, error) {
+ t.Fatal("explicit proxy environment must not read GNOME settings")
+ return "", nil
+ }
+ got, err := readGNOMENetworkProxy(context.Background(), func(name string) string { return env[name] }, read)
+ if err != nil || got != nil {
+ t.Fatalf("got %#v, %v; want environment fallback", got, err)
+ }
+ })
+ }
+ for _, desktop := range []string{"KDE", "XFCE", ""} {
+ got, err := readGNOMENetworkProxy(context.Background(), func(name string) string {
+ if name == "XDG_CURRENT_DESKTOP" {
+ return desktop
+ }
+ return ""
+ }, func(context.Context, string, string) (string, error) {
+ t.Fatal("other desktops must not invoke gsettings")
+ return "", nil
+ })
+ if err != nil || got != nil {
+ t.Fatalf("desktop %q: got %#v, %v", desktop, got, err)
+ }
+ }
+}
+
+func TestGNOMENetworkProxy(t *testing.T) {
+ for _, test := range []struct {
+ name, httpHost, httpPort, httpsHost, socksHost string
+ wantHTTP, wantHTTPS string
+ }{
+ {"separate HTTP HTTPS", "'127.0.0.1'", "7890", "'secure.example'", "'::1'", "http://127.0.0.1:7890", "http://secure.example:7891"},
+ {"HTTPS falls back to HTTP before SOCKS", "'proxy.example'", "7890", "''", "'::1'", "http://proxy.example:7890", "http://proxy.example:7890"},
+ {"SOCKS only", "''", "7890", "''", "'::1'", "socks5://[::1]:7892", "socks5://[::1]:7892"},
+ {"SOCKS with HTTPS", "''", "7890", "'secure.example'", "'::1'", "socks5://[::1]:7892", "http://secure.example:7891"},
+ {"disabled HTTP port", "'proxy.example'", "0", "''", "'::1'", "socks5://[::1]:7892", "socks5://[::1]:7892"},
+ {"bracketed IPv6", "'[2001:db8::1]'", "7890", "''", "''", "http://[2001:db8::1]:7890", "http://[2001:db8::1]:7890"},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ settings := gnomeProxyTestSettings()
+ settings[gnomeProxySchema+".http.host"] = test.httpHost
+ settings[gnomeProxySchema+".http.port"] = test.httpPort
+ settings[gnomeProxySchema+".https.host"] = test.httpsHost
+ settings[gnomeProxySchema+".socks.host"] = test.socksHost
+ env := map[string]string{"XDG_CURRENT_DESKTOP": "GNOME", "no_proxy": "private.example,localhost", "NO_PROXY": "ignored.example"}
+ got, err := readGNOMENetworkProxy(context.Background(), func(name string) string { return env[name] }, readGNOMEProxyTestSettings(settings))
+ want := &systemNetworkProxyConfig{HTTPProxy: test.wantHTTP, HTTPSProxy: test.wantHTTPS, NoProxy: "localhost,127.0.0.0/8,::1,private.example"}
+ if err != nil || !reflect.DeepEqual(got, want) {
+ t.Fatalf("got %#v, %v; want %#v", got, err, want)
+ }
+ })
+ }
+}
+
+func TestGNOMEProxyBypassSemantics(t *testing.T) {
+ settings := gnomeProxyTestSettings()
+ settings[gnomeProxySchema+".ignore-hosts"] = "['*.corp.example', '.other.example', 'corp.example', '*', '10.0.0.0/8', '2001:db8::/32']"
+ env := map[string]string{"XDG_CURRENT_DESKTOP": "GNOME", "no_proxy": "*.env.example,.private.example"}
+ got, err := readGNOMENetworkProxy(context.Background(), func(name string) string { return env[name] }, readGNOMEProxyTestSettings(settings))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "corp.example,other.example,10.0.0.0/8,2001:db8::/32,*.env.example,.private.example"
+ if got.NoProxy != want {
+ t.Fatalf("bypass = %q, want %q", got.NoProxy, want)
+ }
+}
+
+func TestGNOMENetworkProxyInvalidSettings(t *testing.T) {
+ for _, test := range []struct{ key, value string }{
+ {"mode", "'auto'"}, {"mode", "'unknown'"}, {"mode", "manual"},
+ {"http.host", "'http://bad'"}, {"http.host", "'user@host'"}, {"http.host", "'host:8080'"},
+ {"http.host", "'host name'"}, {"http.host", "'host\\nname'"}, {"http.host", "'unterminated"},
+ {"http.port", "-1"}, {"http.port", "65536"}, {"http.port", "'7890'"},
+ {"http.use-authentication", "true"}, {"http.use-authentication", "invalid"},
+ {"ignore-hosts", "['one' 'two']"}, {"ignore-hosts", "['one,two']"},
+ } {
+ t.Run(test.key+"/"+test.value, func(t *testing.T) {
+ settings := gnomeProxyTestSettings()
+ settings[gnomeProxySchema+"."+test.key] = test.value
+ got, err := readGNOMENetworkProxy(context.Background(), func(name string) string {
+ if name == "XDG_CURRENT_DESKTOP" {
+ return "GNOME"
+ }
+ return ""
+ }, readGNOMEProxyTestSettings(settings))
+ if err == nil || got != nil {
+ t.Fatalf("got %#v, %v; want error without partial proxy config", got, err)
+ }
+ })
+ }
+}
+
+func TestGNOMENetworkProxyUnavailable(t *testing.T) {
+ getenv := func(name string) string {
+ if name == "XDG_CURRENT_DESKTOP" {
+ return "GNOME"
+ }
+ return ""
+ }
+ settings := gnomeProxyTestSettings()
+ settings[gnomeProxySchema+".mode"] = "'none'"
+ if got, err := readGNOMENetworkProxy(context.Background(), getenv, readGNOMEProxyTestSettings(settings)); err != nil || got != nil {
+ t.Fatalf("disabled proxy = %#v, %v", got, err)
+ }
+ for _, key := range []string{"http.host", "https.host", "socks.host"} {
+ settings[gnomeProxySchema+"."+key] = "''"
+ }
+ settings[gnomeProxySchema+".mode"] = "'manual'"
+ if got, err := readGNOMENetworkProxy(context.Background(), getenv, readGNOMEProxyTestSettings(settings)); err != nil || got != nil {
+ t.Fatalf("empty manual proxy = %#v, %v", got, err)
+ }
+ if got, err := readGNOMENetworkProxy(context.Background(), getenv, readGNOMEProxyTestSettings(nil)); err == nil || got != nil {
+ t.Fatalf("missing schema = %#v, %v", got, err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if got, err := readGNOMENetworkProxy(ctx, getenv, readGNOMEProxyTestSettings(gnomeProxyTestSettings())); err == nil || got != nil {
+ t.Fatalf("cancelled read = %#v, %v", got, err)
+ }
+}
+
+func TestGNOMEProxyGVariantStrings(t *testing.T) {
+ for _, test := range []struct {
+ input string
+ want []string
+ }{
+ {"@as []", []string{}}, {"[]", []string{}},
+ {`['localhost', "quoted'host", 'escaped\'host', 'back\\slash', '\u4e2d',]`, []string{"localhost", "quoted'host", "escaped'host", `back\slash`, "中"}},
+ } {
+ got, err := parseGNOMEProxyStrings(test.input)
+ if err != nil || !reflect.DeepEqual(got, test.want) {
+ t.Fatalf("parse %q = %#v, %v", test.input, got, err)
+ }
+ }
+ for _, input := range []string{"", "[", "['x'", "['x']junk", "['x',,]", "['\\q']", "['x' 'y']"} {
+ if _, err := parseGNOMEProxyStrings(input); err == nil {
+ t.Fatalf("accepted invalid list %q", input)
+ }
+ }
+}
+
+func TestGNOMEProxyCommandTimeoutAndMissing(t *testing.T) {
+ dir := t.TempDir()
+ t.Setenv("PATH", dir)
+ if _, err := readGNOMEProxySetting(context.Background(), gnomeProxySchema, "mode"); err == nil {
+ t.Fatal("missing command must fail")
+ }
+ // 用本地替身验证超时,不读取或修改真实桌面配置。
+ script := "#!/bin/sh\nexec /bin/sleep 10\n"
+ if err := os.WriteFile(filepath.Join(dir, "gsettings"), []byte(script), 0700); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+ started := time.Now()
+ if _, err := readGNOMEProxySetting(ctx, gnomeProxySchema, "mode"); err == nil {
+ t.Fatal("timed out command must fail")
+ }
+ if time.Since(started) > time.Second {
+ t.Fatal("gsettings timeout was not bounded")
+ }
+ if !strings.Contains(ctx.Err().Error(), "deadline") {
+ t.Fatalf("unexpected context error: %v", ctx.Err())
+ }
+}
+
+func TestGNOMEProxyGSettingsKeyfile(t *testing.T) {
+ gsettings, err := exec.LookPath("gsettings")
+ if err != nil {
+ t.Skip("gsettings is not installed")
+ }
+ // 隔离到临时 keyfile 后端,不读取或更改当前用户的 dconf 数据。
+ t.Setenv("GSETTINGS_BACKEND", "keyfile")
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_CURRENT_DESKTOP", "GNOME")
+ for _, name := range []string{"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "NO_PROXY", "no_proxy"} {
+ t.Setenv(name, "")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ schemas, err := exec.CommandContext(ctx, gsettings, "list-schemas").Output()
+ if err != nil || !strings.Contains(string(schemas), gnomeProxySchema+"\n") {
+ t.Skip("GNOME proxy schema is not installed")
+ }
+ settings := gnomeProxyTestSettings()
+ settings[gnomeProxySchema+".ignore-hosts"] = "['*.corp.example', '::1']"
+ for name, value := range settings {
+ index := strings.LastIndex(name, ".")
+ if output, err := exec.CommandContext(ctx, gsettings, "set", name[:index], name[index+1:], value).CombinedOutput(); err != nil {
+ t.Fatalf("configure isolated setting %s: %v, %s", name, err, output)
+ }
+ }
+ got, err := readSystemNetworkProxy()
+ want := &systemNetworkProxyConfig{HTTPProxy: "http://127.0.0.1:7890", HTTPSProxy: "http://127.0.0.1:7891", NoProxy: "corp.example,::1"}
+ if err != nil || !reflect.DeepEqual(got, want) {
+ t.Fatalf("real gsettings read = %#v, %v; want %#v", got, err, want)
+ }
+}
diff --git a/kernel/util/system_proxy_other.go b/kernel/util/system_proxy_other.go
index 7677b94004..369b2da6e0 100644
--- a/kernel/util/system_proxy_other.go
+++ b/kernel/util/system_proxy_other.go
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
-//go:build !windows
+//go:build !windows && (!linux || android)
package util