Skip to content

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

:sparkles: Support macOS system network proxy detection https://github.com/siyuan-note/siyuan/issues/20801

Danielaf332fd4009d
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260614104204-staofnm.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260614104204-staofnm.sy
index 3f56738461..5eaacd6e6e 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260614104204-staofnm.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260614104204-staofnm.sy
@@ -6,7 +6,7 @@
"id": "20260614104204-staofnm",
"title": "Network Proxy",
"type": "doc",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -44,7 +44,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260614104245-1vghukz",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -109,7 +109,7 @@
"ListData": {},
"Properties": {
"id": "20260614104245-nkm2226",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -145,7 +145,7 @@
"Type": "NodeListItem",
"Properties": {
"id": "20261016112115-7c46gfq",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"ListData": {
"BulletChar": 42,
@@ -157,12 +157,40 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261016112115-mlgnje1",
- "updated": "20261016112115"
+ "updated": "20261022120655"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "System mode uses supported system settings or the proxy environment inherited when the kernel started. The kernel reads manual proxy settings on Windows, Linux GNOME, and macOS; on Linux and macOS, explicit proxy environment variables take priority. These readers do not support automatic PAC configuration; Windows and macOS automatic detection is also unsupported. On other platforms the kernel retains its initial proxy environment instead of reading OS settings"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "ID": "20261022120655-quj9zir",
+ "Type": "NodeListItem",
+ "Properties": {
+ "id": "20261022120655-quj9zir",
+ "updated": "20261022120655"
+ },
+ "ListData": {
+ "BulletChar": 42,
+ "Marker": "Kg=="
+ },
+ "Children": [
+ {
+ "ID": "20261022120655-un99ra6",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261022120655-un99ra6",
+ "updated": "20261022120655"
},
"Children": [
{
"Type": "NodeText",
- "Data": "System mode uses supported system settings or the proxy environment inherited when the kernel started. The kernel reads manual Windows proxy settings and manual Linux GNOME settings; on Linux, explicit proxy environment variables take priority. These readers do not support automatic PAC configuration, and Windows automatic detection is unsupported. On other platforms the kernel retains its initial proxy environment instead of reading OS settings"
+ "Data": "macOS supports manual HTTP, HTTPS, and SOCKS5 proxies. The bypass list is converted to NO_PROXY rules, supporting IP addresses, CIDR ranges (including 169.254/16), domains, leading *. domain patterns, and trailing IPv4 wildcards such as 10.*. Exclude simple hostnames and other wildcard patterns are unsupported; use explicit bypass entries instead. If reading or conversion fails, the kernel logs a warning and retains its startup proxy environment. To apply changed macOS proxy settings, restart the kernel or switch to another proxy mode and back to system mode"
}
]
}
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260614104254-4ifhixg.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260614104254-4ifhixg.sy
index 6a74d04107..2863a85d10 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260614104254-4ifhixg.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260614104254-4ifhixg.sy
@@ -6,7 +6,7 @@
"id": "20260614104254-4ifhixg",
"title": "网络代理",
"type": "doc",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -44,7 +44,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260614104306-tylh2a2",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -109,7 +109,7 @@
"ListData": {},
"Properties": {
"id": "20260614104306-s1ddhjq",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -145,7 +145,7 @@
"Type": "NodeListItem",
"Properties": {
"id": "20261016112115-zd0i0ab",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"ListData": {
"BulletChar": 42,
@@ -157,12 +157,40 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261016112115-bggswt8",
- "updated": "20261016112115"
+ "updated": "20261022120655"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "系统模式使用受支持的系统设置,或内核启动时继承的代理环境变量。内核支持读取 Windows、Linux GNOME 和 macOS 的手动代理,Linux 和 macOS 上显式代理环境变量优先。这些读取器不支持自动 PAC 配置,Windows 和 macOS 自动检测也不受支持;其他平台的内核保留启动时的代理环境,不读取操作系统代理设置"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "ID": "20261022120655-1dv9u99",
+ "Type": "NodeListItem",
+ "Properties": {
+ "id": "20261022120655-1dv9u99",
+ "updated": "20261022120655"
+ },
+ "ListData": {
+ "BulletChar": 42,
+ "Marker": "Kg=="
+ },
+ "Children": [
+ {
+ "ID": "20261022120655-iobo4nv",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261022120655-iobo4nv",
+ "updated": "20261022120655"
},
"Children": [
{
"Type": "NodeText",
- "Data": "系统模式使用受支持的系统设置,或内核启动时继承的代理环境变量。内核支持读取 Windows 手动代理和 Linux GNOME 手动代理,Linux 上显式代理环境变量优先。这些读取器不支持自动 PAC 配置,Windows 自动检测也不受支持;其他平台的内核保留启动时的代理环境,不读取操作系统代理设置"
+ "Data": "macOS 支持手动 HTTP、HTTPS 和 SOCKS5 代理。例外列表转换为 NO_PROXY 规则,支持 IP 地址、CIDR 网段(包括 169.254/16)、域名、以 *. 开头的域名模式,以及 10.* 等 IPv4 尾部通配符。不支持“排除简单主机名”和其他通配模式,请改用明确的例外条目。读取或转换失败时,内核记录警告并保留启动时的代理环境。修改 macOS 系统代理后,需重启内核,或先切换到其他代理模式再切回系统模式"
}
]
}
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260614104322-shrqj15.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260614104322-shrqj15.sy
index 2a7cf9a763..f918fa6ee9 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260614104322-shrqj15.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260614104322-shrqj15.sy
@@ -6,7 +6,7 @@
"id": "20260614104322-shrqj15",
"title": "網路代理",
"type": "doc",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -44,7 +44,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260614104332-ojj5e46",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -109,7 +109,7 @@
"ListData": {},
"Properties": {
"id": "20260614104332-3skahri",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -145,7 +145,7 @@
"Type": "NodeListItem",
"Properties": {
"id": "20261016112115-rt8undd",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"ListData": {
"BulletChar": 42,
@@ -157,12 +157,40 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261016112115-6yyf4an",
- "updated": "20261016112115"
+ "updated": "20261022120655"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "系統模式使用支援的系統設定,或核心啟動時繼承的代理環境變數。核心支援讀取 Windows、Linux GNOME 和 macOS 的手動代理,Linux 和 macOS 上明確設定的代理環境變數優先。這些讀取器不支援自動 PAC 設定,Windows 和 macOS 自動偵測也不受支援;其他平台的核心保留啟動時的代理環境,不讀取作業系統代理設定"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "ID": "20261022120655-wdl5gm4",
+ "Type": "NodeListItem",
+ "Properties": {
+ "id": "20261022120655-wdl5gm4",
+ "updated": "20261022120655"
+ },
+ "ListData": {
+ "BulletChar": 42,
+ "Marker": "Kg=="
+ },
+ "Children": [
+ {
+ "ID": "20261022120655-sjevvj7",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261022120655-sjevvj7",
+ "updated": "20261022120655"
},
"Children": [
{
"Type": "NodeText",
- "Data": "系統模式使用支援的系統設定,或核心啟動時繼承的代理環境變數。核心支援讀取 Windows 手動代理和 Linux GNOME 手動代理,Linux 上明確設定的代理環境變數優先。這些讀取器不支援自動 PAC 設定,Windows 自動偵測也不受支援;其他平台的核心保留啟動時的代理環境,不讀取作業系統代理設定"
+ "Data": "macOS 支援手動 HTTP、HTTPS 和 SOCKS5 代理。例外清單轉換為 NO_PROXY 規則,支援 IP 位址、CIDR 網段(包括 169.254/16)、網域、以 *. 開頭的網域模式,以及 10.* 等 IPv4 尾端萬用字元。不支援「排除簡單主機名稱」和其他萬用字元模式,請改用明確的例外項目。讀取或轉換失敗時,核心記錄警告並保留啟動時的代理環境。修改 macOS 系統代理後,需重新啟動核心,或先切換至其他代理模式再切回系統模式"
}
]
}
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260614104715-xe51jlk.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260614104715-xe51jlk.sy
index c9eb040fdb..94ad58027d 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260614104715-xe51jlk.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260614104715-xe51jlk.sy
@@ -6,7 +6,7 @@
"id": "20260614104715-xe51jlk",
"title": "ネットワークプロキシ",
"type": "doc",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -44,7 +44,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260614104730-7u2gg5k",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -105,7 +105,7 @@
"ListData": {},
"Properties": {
"id": "20260614104730-16ja8ya",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"Children": [
{
@@ -141,7 +141,7 @@
"Type": "NodeListItem",
"Properties": {
"id": "20261016112115-s6u6kl7",
- "updated": "20261016112115"
+ "updated": "20261022120655"
},
"ListData": {
"BulletChar": 42,
@@ -153,12 +153,40 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261016112115-ezc3mdr",
- "updated": "20261016112115"
+ "updated": "20261022120655"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "システムモードは、対応する OS 設定またはカーネル起動時に継承したプロキシ環境変数を使用します。カーネルは Windows、Linux GNOME、macOS の手動プロキシを読み取り、Linux と macOS では明示的なプロキシ環境変数を優先します。これらの読み取り処理は自動 PAC 設定に対応せず、Windows と macOS の自動検出にも対応しません。その他の OS では OS 設定を読み取らず、起動時のプロキシ環境を保持します"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "ID": "20261022120655-cbp7kzj",
+ "Type": "NodeListItem",
+ "Properties": {
+ "id": "20261022120655-cbp7kzj",
+ "updated": "20261022120655"
+ },
+ "ListData": {
+ "BulletChar": 42,
+ "Marker": "Kg=="
+ },
+ "Children": [
+ {
+ "ID": "20261022120655-td5nltm",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261022120655-td5nltm",
+ "updated": "20261022120655"
},
"Children": [
{
"Type": "NodeText",
- "Data": "システムモードは、対応する OS 設定またはカーネル起動時に継承したプロキシ環境変数を使用します。カーネルは Windows と Linux GNOME の手動プロキシを読み取り、Linux では明示的なプロキシ環境変数を優先します。これらの読み取り処理は自動 PAC 設定に対応せず、Windows の自動検出にも対応しません。その他の OS では OS 設定を読み取らず、起動時のプロキシ環境を保持します"
+ "Data": "macOS は手動の HTTP、HTTPS、SOCKS5 プロキシに対応しています。除外リストは NO_PROXY ルールに変換され、IP アドレス、CIDR 範囲(169.254/16 を含む)、ドメイン、*. で始まるドメインパターン、10.* などの IPv4 末尾のワイルドカードに対応しています。「単純なホスト名を除外」とその他のワイルドカードパターンには対応していないため、明示的な除外項目を使用してください。読み取りや変換に失敗すると、カーネルは警告を記録し、起動時のプロキシ環境を保持します。macOS のシステムプロキシを変更した後は、カーネルを再起動するか、別のプロキシモードに切り替えてからシステムモードに戻してください"
}
]
}
diff --git a/kernel/util/system_proxy_darwin.go b/kernel/util/system_proxy_darwin.go
new file mode 100644
index 0000000000..3741b2b61f
--- /dev/null
+++ b/kernel/util/system_proxy_darwin.go
@@ -0,0 +1,30 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// 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 darwin && !ios
+
+package util
+
+import (
+ "context"
+ "time"
+)
+
+func readSystemNetworkProxy() (*systemNetworkProxyConfig, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ return readMacOSNetworkProxy(ctx, readMacOSProxyCommand)
+}
diff --git a/kernel/util/system_proxy_macos.go b/kernel/util/system_proxy_macos.go
new file mode 100644
index 0000000000..a6398f2140
--- /dev/null
+++ b/kernel/util/system_proxy_macos.go
@@ -0,0 +1,303 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// 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/>.
+
+package util
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "net/url"
+ "os"
+ "os/exec"
+ "strconv"
+ "strings"
+ "time"
+ "unicode"
+)
+
+type macOSProxyValue struct {
+ scalar string
+ kind string
+ fields map[string]*macOSProxyValue
+}
+
+// readMacOSNetworkProxy 整组保留显式代理环境,避免混合环境和系统设置。
+// 调用方先恢复启动环境;命令及解析错误不包含配置内容或标准错误。
+func readMacOSNetworkProxy(ctx context.Context, read func(context.Context) (string, error)) (*systemNetworkProxyConfig, error) {
+ for _, name := range []string{"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy"} {
+ if os.Getenv(name) != "" {
+ return nil, nil
+ }
+ }
+ output, err := read(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("read macOS system proxy failed")
+ }
+ ret, err := parseMacOSNetworkProxy(output)
+ if err != nil || ret == nil {
+ return ret, err
+ }
+ // 与实际请求读取顺序一致,保留启动环境中的直连例外。
+ bypass := os.Getenv("NO_PROXY")
+ if bypass == "" {
+ bypass = os.Getenv("no_proxy")
+ }
+ if bypass != "" {
+ if ret.NoProxy != "" {
+ ret.NoProxy += ","
+ }
+ ret.NoProxy += bypass
+ }
+ return ret, nil
+}
+
+func readMacOSProxyCommand(ctx context.Context) (string, error) {
+ // 使用固定系统路径且不经过 shell;超时也限制子进程输出管道的等待时间。
+ cmd := exec.CommandContext(ctx, "/usr/sbin/scutil", "--proxy")
+ cmd.WaitDelay = 100 * time.Millisecond
+ output, err := cmd.Output()
+ return string(output), err
+}
+
+func parseMacOSNetworkProxy(output string) (*systemNetworkProxyConfig, error) {
+ if strings.TrimSpace(output) == "No proxy configuration available" {
+ return nil, nil
+ }
+ root, err := parseMacOSProxyDictionary(output)
+ if err != nil {
+ return nil, err
+ }
+ get := func(key string) (string, error) {
+ value := root.fields[key]
+ if value == nil {
+ return "", nil
+ }
+ if value.kind != "" {
+ return "", fmt.Errorf("invalid macOS proxy field %s", key)
+ }
+ return value.scalar, nil
+ }
+ enabled := func(key string) (bool, error) {
+ value, err := get(key)
+ if err != nil || value == "" {
+ return false, err
+ }
+ number, err := strconv.Atoi(value)
+ if err != nil {
+ return false, fmt.Errorf("invalid macOS proxy flag %s", key)
+ }
+ return number != 0, nil
+ }
+ for _, key := range []string{"ProxyAutoConfigEnable", "ProxyAutoDiscoveryEnable"} {
+ on, err := enabled(key)
+ if err != nil {
+ return nil, err
+ }
+ if on {
+ return nil, fmt.Errorf("macOS automatic proxy configuration is not supported")
+ }
+ }
+ proxies := make(map[string]string, 3)
+ for _, protocol := range []string{"HTTP", "HTTPS", "SOCKS"} {
+ on, err := enabled(protocol + "Enable")
+ if err != nil {
+ return nil, err
+ }
+ if !on {
+ continue
+ }
+ host, err := get(protocol + "Proxy")
+ if err != nil {
+ return nil, err
+ }
+ portValue, err := get(protocol + "Port")
+ if err != nil {
+ return nil, err
+ }
+ port, err := strconv.Atoi(portValue)
+ if err != nil || port < 1 || port > 65535 {
+ return nil, fmt.Errorf("invalid macOS proxy port for %s", protocol)
+ }
+ 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 nil, fmt.Errorf("invalid macOS proxy host for %s", protocol)
+ }
+ // HTTPS 表示目标协议,macOS 的安全 Web 代理仍通过 HTTP CONNECT 建立隧道。
+ scheme := "http"
+ if protocol == "SOCKS" {
+ scheme = "socks5"
+ }
+ proxies[protocol] = (&url.URL{Scheme: scheme, Host: net.JoinHostPort(host, strconv.Itoa(port))}).String()
+ }
+ ret := &systemNetworkProxyConfig{HTTPProxy: proxies["HTTP"], HTTPSProxy: proxies["HTTPS"]}
+ // 各目标协议独立配置,缺省时仅回退 SOCKS,不把 HTTP 配置套用于 HTTPS。
+ if ret.HTTPProxy == "" {
+ ret.HTTPProxy = proxies["SOCKS"]
+ }
+ if ret.HTTPSProxy == "" {
+ ret.HTTPSProxy = proxies["SOCKS"]
+ }
+ if ret.HTTPProxy == "" && ret.HTTPSProxy == "" {
+ return nil, nil
+ }
+ simple, err := enabled("ExcludeSimpleHostnames")
+ if err != nil {
+ return nil, err
+ }
+ if simple {
+ return nil, fmt.Errorf("macOS simple-hostname proxy bypass is not supported; disable it and use explicit bypass entries instead")
+ }
+ if exceptions := root.fields["ExceptionsList"]; exceptions != nil {
+ if exceptions.kind != "array" {
+ return nil, fmt.Errorf("invalid macOS proxy bypass list")
+ }
+ entries := make([]string, 0, len(exceptions.fields))
+ seen := map[string]bool{}
+ for i := 0; i < len(exceptions.fields); i++ {
+ value := exceptions.fields[strconv.Itoa(i)]
+ if value == nil || value.kind != "" {
+ return nil, fmt.Errorf("invalid macOS proxy bypass entry")
+ }
+ entry, err := macOSProxyBypassEntry(value.scalar)
+ if err != nil {
+ return nil, err
+ }
+ if entry != "" && !seen[entry] {
+ entries, seen[entry] = append(entries, entry), true
+ }
+ }
+ ret.NoProxy = strings.Join(entries, ",")
+ }
+ return ret, nil
+}
+
+// parseMacOSProxyDictionary 按容器层级解析 scutil 输出,避免把接口内的配置当作全局配置。
+func parseMacOSProxyDictionary(output string) (*macOSProxyValue, error) {
+ invalid := func() (*macOSProxyValue, error) { return nil, fmt.Errorf("invalid macOS proxy configuration") }
+ var root *macOSProxyValue
+ var stack []*macOSProxyValue
+ for line := range strings.SplitSeq(output, "\n") {
+ line = strings.TrimSpace(line)
+ if line == "" {
+ continue
+ }
+ if root == nil {
+ if line != "<dictionary> {" {
+ return invalid()
+ }
+ root = &macOSProxyValue{kind: "dictionary", fields: map[string]*macOSProxyValue{}}
+ stack = append(stack, root)
+ continue
+ }
+ if len(stack) == 0 {
+ return invalid()
+ }
+ if line == "}" {
+ stack = stack[:len(stack)-1]
+ continue
+ }
+ key, value, ok := strings.Cut(line, " : ")
+ if !ok || key == "" {
+ return invalid()
+ }
+ parent := stack[len(stack)-1]
+ if _, exists := parent.fields[key]; exists {
+ return invalid()
+ }
+ node := &macOSProxyValue{scalar: value}
+ parent.fields[key] = node
+ if value == "<dictionary> {" || value == "<array> {" {
+ if len(stack) >= 32 {
+ return invalid()
+ }
+ node.kind = strings.TrimSuffix(strings.TrimPrefix(value, "<"), "> {")
+ node.fields = map[string]*macOSProxyValue{}
+ stack = append(stack, node)
+ }
+ }
+ if root == nil || len(stack) != 0 {
+ return invalid()
+ }
+ return root, nil
+}
+
+func macOSProxyBypassEntry(entry string) (string, error) {
+ entry = strings.TrimSpace(entry)
+ invalid := func() (string, error) { return "", fmt.Errorf("unsupported macOS proxy bypass entry") }
+ if entry == "" || entry == "*" {
+ return entry, nil
+ }
+ if strings.ContainsAny(entry, ",;@?#\\<>") || strings.IndexFunc(entry, func(r rune) bool {
+ return unicode.IsSpace(r) || unicode.IsControl(r)
+ }) >= 0 {
+ return invalid()
+ }
+ if strings.Contains(entry, "/") {
+ // macOS 常见的 169.254/16 需要补齐为 NO_PROXY 接受的 IPv4 CIDR。
+ address, prefix, _ := strings.Cut(entry, "/")
+ if !strings.Contains(address, ":") {
+ parts := strings.Split(address, ".")
+ for len(parts) < 4 {
+ parts = append(parts, "0")
+ }
+ entry = strings.Join(parts, ".") + "/" + prefix
+ }
+ _, network, err := net.ParseCIDR(entry)
+ if err != nil {
+ return invalid()
+ }
+ return network.String(), nil
+ }
+ if strings.Contains(entry, "*") {
+ if strings.HasPrefix(entry, "*.") && !strings.Contains(entry[2:], "*") {
+ return entry, nil
+ }
+ // IPv4 尾部通配符转换为网络段,不接受任意位置的主机名通配符。
+ parts := strings.Split(entry, ".")
+ fixed := 0
+ for fixed < len(parts) && parts[fixed] != "*" {
+ fixed++
+ }
+ if fixed == 0 || fixed == len(parts) || len(parts) > 4 {
+ return invalid()
+ }
+ for _, part := range parts[fixed:] {
+ if part != "*" {
+ return invalid()
+ }
+ }
+ for len(parts) < 4 {
+ parts = append(parts, "0")
+ }
+ for i := fixed; i < 4; i++ {
+ parts[i] = "0"
+ }
+ _, network, err := net.ParseCIDR(strings.Join(parts, ".") + "/" + strconv.Itoa(fixed*8))
+ if err != nil {
+ return invalid()
+ }
+ return network.String(), nil
+ }
+ if strings.Contains(entry, ":") && net.ParseIP(entry) == nil {
+ return invalid()
+ }
+ return entry, nil
+}
diff --git a/kernel/util/system_proxy_macos_integration_test.go b/kernel/util/system_proxy_macos_integration_test.go
new file mode 100644
index 0000000000..6894300073
--- /dev/null
+++ b/kernel/util/system_proxy_macos_integration_test.go
@@ -0,0 +1,135 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// 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/>.
+
+package util
+
+import (
+ "context"
+ "errors"
+ "go/build"
+ "net/http"
+ "os"
+ "testing"
+
+ "github.com/siyuan-note/httpclient"
+)
+
+func TestMacOSProxyPlatformSelection(t *testing.T) {
+ for _, test := range []struct{ platform, want string }{
+ {"darwin", "system_proxy_darwin.go"}, {"ios", "system_proxy_other.go"},
+ {"linux", "system_proxy_linux.go"}, {"android", "system_proxy_other.go"},
+ {"windows", "system_proxy_windows.go"}, {"freebsd", "system_proxy_other.go"},
+ } {
+ t.Run(test.platform, func(t *testing.T) {
+ context := build.Default
+ context.GOOS, context.GOARCH = test.platform, "arm64"
+ for _, file := range []string{"system_proxy_darwin.go", "system_proxy_linux.go", "system_proxy_windows.go", "system_proxy_other.go"} {
+ matches, err := context.MatchFile(".", file)
+ if err != nil || matches != (file == test.want) {
+ t.Errorf("%s matches %s = %t, %v", test.platform, file, matches, err)
+ }
+ }
+ })
+ }
+}
+
+func TestMacOSProxyModeTransitions(t *testing.T) {
+ clearMacOSProxyTestEnvironment(t)
+ originalEnvironment, originalLoader := systemNetworkProxyEnvironment, loadSystemNetworkProxy
+ systemNetworkProxyEnvironment = map[string]networkProxyEnvironmentValue{
+ "NO_PROXY": {value: "startup.example", set: true},
+ "no_proxy": {value: "startup.example", set: true},
+ }
+ t.Cleanup(func() {
+ systemNetworkProxyEnvironment, loadSystemNetworkProxy = originalEnvironment, originalLoader
+ })
+ output := macOSManualProxyFixture
+ var commandError error
+ loads := 0
+ loadSystemNetworkProxy = func() (*systemNetworkProxyConfig, error) {
+ return readMacOSNetworkProxy(context.Background(), func(context.Context) (string, error) {
+ loads++
+ return output, commandError
+ })
+ }
+ assertRoute := func(target, want string) {
+ t.Helper()
+ request, err := http.NewRequest(http.MethodGet, target, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxy, err := httpclient.ProxyFromEnvironment(request)
+ got := ""
+ if proxy != nil {
+ got = proxy.String()
+ }
+ if err != nil || got != want {
+ t.Fatalf("route %s = %q, %v, want %q", target, got, err, want)
+ }
+ }
+ for i := 0; i < 2; i++ {
+ SetNetworkProxy("socks5://manual.example:1080", false)
+ assertRoute("https://public.example", "socks5://manual.example:1080")
+ if loads != i {
+ t.Fatal("manual mode read system settings")
+ }
+ SetNetworkProxy("", true)
+ assertRoute("http://public.example", "http://127.0.0.1:7890")
+ assertRoute("https://public.example", "http://127.0.0.1:7891")
+ assertRoute("https://printer.local", "")
+ assertRoute("https://startup.example", "")
+ if loads != i+1 {
+ t.Fatal("system mode did not read settings")
+ }
+ SetNetworkProxy("", false)
+ assertRoute("https://public.example", "")
+ if os.Getenv("NO_PROXY") != "startup.example" {
+ t.Fatal("direct mode did not restore startup bypass")
+ }
+ }
+ for _, test := range []struct {
+ name, output string
+ failure error
+ }{
+ {"disabled", "<dictionary> {\n}", nil},
+ {"malformed", "invalid secret settings", nil},
+ {"command failure", "", errors.New("secret command output")},
+ {"PAC", "<dictionary> {\nProxyAutoConfigEnable : 1\n}", nil},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ output, commandError = macOSManualProxyFixture, nil
+ SetNetworkProxy("", true)
+ assertRoute("https://public.example", "http://127.0.0.1:7891")
+ output, commandError = test.output, test.failure
+ SetNetworkProxy("", true)
+ assertRoute("https://public.example", "")
+ if os.Getenv("NO_PROXY") != "startup.example" || os.Getenv("no_proxy") != "startup.example" {
+ t.Fatal("system fallback retained stale bypass entries")
+ }
+ })
+ }
+ // 重新进入系统模式恢复启动环境,不把手动代理误认为显式环境配置。
+ systemNetworkProxyEnvironment["https_proxy"] = networkProxyEnvironmentValue{value: "http://startup.example:8080", set: true}
+ systemNetworkProxyEnvironment["HTTPS_PROXY"] = networkProxyEnvironmentValue{value: "http://startup.example:8080", set: true}
+ before := loads
+ SetNetworkProxy("socks5://manual.example:1080", false)
+ SetNetworkProxy("", true)
+ assertRoute("https://public.example", "http://startup.example:8080")
+ assertRoute("http://public.example", "")
+ if loads != before {
+ t.Fatal("explicit startup proxy did not bypass system reader")
+ }
+}
diff --git a/kernel/util/system_proxy_macos_test.go b/kernel/util/system_proxy_macos_test.go
new file mode 100644
index 0000000000..0ea1ddb4a0
--- /dev/null
+++ b/kernel/util/system_proxy_macos_test.go
@@ -0,0 +1,233 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// 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/>.
+
+package util
+
+import (
+ "context"
+ "errors"
+ "net/url"
+ "reflect"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "golang.org/x/net/http/httpproxy"
+)
+
+const macOSManualProxyFixture = `<dictionary> {
+ ExceptionsList : <array> {
+ 0 : *.local
+ 1 : 169.254/16
+ 2 : 10.*
+ 3 : ::1
+ 4 : private.example
+ 5 : *.local
+ }
+ ExcludeSimpleHostnames : 0
+ HTTPEnable : 1
+ HTTPPort : 7890
+ HTTPProxy : 127.0.0.1
+ HTTPSEnable : 1
+ HTTPSPort : 7891
+ HTTPSProxy : 127.0.0.1
+ SOCKSEnable : 1
+ SOCKSPort : 7892
+ SOCKSProxy : 127.0.0.1
+}`
+
+func TestParseMacOSNetworkProxy(t *testing.T) {
+ tests := []struct {
+ name, input string
+ want *systemNetworkProxyConfig
+ }{
+ {"manual proxies and bypass", macOSManualProxyFixture, &systemNetworkProxyConfig{
+ HTTPProxy: "http://127.0.0.1:7890", HTTPSProxy: "http://127.0.0.1:7891",
+ NoProxy: "*.local,169.254.0.0/16,10.0.0.0/8,::1,private.example",
+ }},
+ {"HTTP does not supply HTTPS", "<dictionary> {\nHTTPEnable : 1\nHTTPProxy : localhost\nHTTPPort : 8080\n}",
+ &systemNetworkProxyConfig{HTTPProxy: "http://localhost:8080"}},
+ {"HTTPS does not supply HTTP", "<dictionary> {\nHTTPSEnable : 1\nHTTPSProxy : proxy.example\nHTTPSPort : 8081\n}",
+ &systemNetworkProxyConfig{HTTPSProxy: "http://proxy.example:8081"}},
+ {"SOCKS fallback and IPv6", "<dictionary> {\nSOCKSEnable : 1\nSOCKSProxy : ::1\nSOCKSPort : 1080\n}",
+ &systemNetworkProxyConfig{HTTPProxy: "socks5://[::1]:1080", HTTPSProxy: "socks5://[::1]:1080"}},
+ {"HTTP and SOCKS fallback", "<dictionary> {\nHTTPEnable : 1\nHTTPProxy : proxy.example\nHTTPPort : 8080\nSOCKSEnable : 1\nSOCKSProxy : [::1]\nSOCKSPort : 1080\n}",
+ &systemNetworkProxyConfig{HTTPProxy: "http://proxy.example:8080", HTTPSProxy: "socks5://[::1]:1080"}},
+ {"disabled stale values", "<dictionary> {\nHTTPEnable : 0\nHTTPProxy : stale\nHTTPPort : invalid\n}", nil},
+ {"empty dictionary", "<dictionary> {\n}", nil},
+ {"no configuration", "No proxy configuration available\n", nil},
+ {"nested settings do not enable global proxy", "<dictionary> {\n__SCOPED__ : <dictionary> {\nen0 : <dictionary> {\nHTTPEnable : 1\nHTTPProxy : scoped.example\nHTTPPort : 8080\n}\n}\n}", nil},
+ {"disabled PAC URL", "<dictionary> {\nProxyAutoConfigEnable : 0\nProxyAutoConfigURLString : http://pac.example/proxy.pac\n}", nil},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ got, err := parseMacOSNetworkProxy(test.input)
+ if err != nil || !reflect.DeepEqual(got, test.want) {
+ t.Fatalf("proxy = %#v, error = %v, want %#v", got, err, test.want)
+ }
+ })
+ }
+}
+
+func TestParseMacOSNetworkProxyRejectsInvalidConfig(t *testing.T) {
+ for _, test := range []struct{ name, input string }{
+ {"empty output", ""},
+ {"unclosed dictionary", "<dictionary> {\nHTTPEnable : 1"},
+ {"extra closing brace", "<dictionary> {\n}\n}"},
+ {"trailing output", "<dictionary> {\n}\nsecret"},
+ {"duplicate key", "<dictionary> {\nHTTPEnable : 1\nHTTPEnable : 0\n}"},
+ {"invalid flag", "<dictionary> {\nHTTPEnable : true\n}"},
+ {"PAC", "<dictionary> {\nProxyAutoConfigEnable : 1\n}"},
+ {"automatic discovery", "<dictionary> {\nProxyAutoDiscoveryEnable : 1\n}"},
+ {"missing host", "<dictionary> {\nHTTPEnable : 1\nHTTPPort : 8080\n}"},
+ {"missing port", "<dictionary> {\nHTTPEnable : 1\nHTTPProxy : secret.example\n}"},
+ {"zero port", strings.Replace(macOSManualProxyFixture, "HTTPPort : 7890", "HTTPPort : 0", 1)},
+ {"negative port", strings.Replace(macOSManualProxyFixture, "HTTPPort : 7890", "HTTPPort : -1", 1)},
+ {"large port", strings.Replace(macOSManualProxyFixture, "HTTPPort : 7890", "HTTPPort : 65536", 1)},
+ {"host contains credentials", strings.Replace(macOSManualProxyFixture, "HTTPProxy : 127.0.0.1", "HTTPProxy : secret:password@host", 1)},
+ {"host contains path", strings.Replace(macOSManualProxyFixture, "HTTPProxy : 127.0.0.1", "HTTPProxy : host/secret", 1)},
+ {"host contains whitespace", strings.Replace(macOSManualProxyFixture, "HTTPProxy : 127.0.0.1", "HTTPProxy : secret host", 1)},
+ {"simple hostname exclusion", strings.Replace(macOSManualProxyFixture, "ExcludeSimpleHostnames : 0", "ExcludeSimpleHostnames : 1", 1)},
+ {"bypass is not array", strings.Replace(macOSManualProxyFixture, "ExceptionsList : <array>", "ExceptionsList : <dictionary>", 1)},
+ {"bypass indices have gap", strings.Replace(macOSManualProxyFixture, "0 : *.local", "8 : *.local", 1)},
+ {"bypass contains delimiter", strings.Replace(macOSManualProxyFixture, "0 : *.local", "0 : secret,*", 1)},
+ {"bypass contains unsupported glob", strings.Replace(macOSManualProxyFixture, "0 : *.local", "0 : secret.*.example", 1)},
+ {"nested flag", "<dictionary> {\nHTTPEnable : <array> {\n}\n}"},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ got, err := parseMacOSNetworkProxy(test.input)
+ if err == nil || got != nil {
+ t.Fatalf("invalid settings accepted: %#v, %v", got, err)
+ }
+ if strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "password") {
+ t.Fatalf("configuration leaked in error: %v", err)
+ }
+ })
+ }
+}
+
+func TestMacOSProxyBypassEntry(t *testing.T) {
+ for _, test := range []struct{ input, want string }{
+ {"169.254/16", "169.254.0.0/16"}, {"10/8", "10.0.0.0/8"},
+ {"192.168.1.3/24", "192.168.1.0/24"}, {"2001:db8::/32", "2001:db8::/32"},
+ {"10.*", "10.0.0.0/8"}, {"192.168.*.*", "192.168.0.0/16"},
+ {"*.local", "*.local"}, {".example.com", ".example.com"},
+ {"private.example", "private.example"}, {"127.0.0.1", "127.0.0.1"}, {"::1", "::1"},
+ {"*", "*"}, {"", ""},
+ } {
+ got, err := macOSProxyBypassEntry(test.input)
+ if err != nil || got != test.want {
+ t.Errorf("bypass %q = %q, %v, want %q", test.input, got, err, test.want)
+ }
+ }
+ for _, input := range []string{"10.999.*", "host.*", "*example.com", "10.*.1", "one,two", "host:80", "host/path", "10/99", "<local>", "host name", "host\x00", "*.*.local"} {
+ if _, err := macOSProxyBypassEntry(input); err == nil {
+ t.Errorf("unsupported bypass %q accepted", input)
+ }
+ }
+}
+
+func TestMacOSProxyRouting(t *testing.T) {
+ proxy, err := parseMacOSNetworkProxy(macOSManualProxyFixture)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resolve := (&httpproxy.Config{HTTPProxy: proxy.HTTPProxy, HTTPSProxy: proxy.HTTPSProxy, NoProxy: proxy.NoProxy}).ProxyFunc()
+ for _, test := range []struct{ target, want string }{
+ {"http://public.example", "http://127.0.0.1:7890"},
+ {"https://public.example", "http://127.0.0.1:7891"},
+ {"https://printer.local", ""}, {"https://169.254.3.4", ""},
+ {"https://10.2.3.4", ""}, {"http://[::1]", ""}, {"https://private.example", ""},
+ } {
+ target, err := url.Parse(test.target)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := resolve(target)
+ actual := ""
+ if got != nil {
+ actual = got.String()
+ }
+ if err != nil || actual != test.want {
+ t.Errorf("route %s = %q, %v, want %q", test.target, actual, err, test.want)
+ }
+ }
+}
+
+func clearMacOSProxyTestEnvironment(t *testing.T) {
+ t.Helper()
+ for _, name := range []string{"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "NO_PROXY", "no_proxy"} {
+ t.Setenv(name, "")
+ }
+}
+
+func TestReadMacOSNetworkProxy(t *testing.T) {
+ t.Run("explicit environment takes priority as a group", func(t *testing.T) {
+ for _, name := range []string{"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy"} {
+ t.Run(name, func(t *testing.T) {
+ clearMacOSProxyTestEnvironment(t)
+ t.Setenv(name, "http://environment.example:8080")
+ got, err := readMacOSNetworkProxy(context.Background(), func(context.Context) (string, error) {
+ t.Fatal("explicit environment should skip scutil")
+ return "", nil
+ })
+ if got != nil || err != nil {
+ t.Fatalf("environment override = %#v, %v", got, err)
+ }
+ })
+ }
+ })
+ t.Run("NO_PROXY does not prevent system reading", func(t *testing.T) {
+ clearMacOSProxyTestEnvironment(t)
+ t.Setenv("NO_PROXY", "environment.example")
+ if runtime.GOOS != "windows" {
+ t.Setenv("no_proxy", "lower.example")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ got, err := readMacOSNetworkProxy(ctx, func(actual context.Context) (string, error) {
+ if actual != ctx {
+ t.Fatal("reader did not receive command context")
+ }
+ return macOSManualProxyFixture, nil
+ })
+ if err != nil || got == nil || !strings.HasSuffix(got.NoProxy, ",environment.example") || strings.Contains(got.NoProxy, "lower.example") {
+ t.Fatalf("bypass merge = %#v, %v", got, err)
+ }
+ })
+ t.Run("lowercase bypass fallback", func(t *testing.T) {
+ clearMacOSProxyTestEnvironment(t)
+ t.Setenv("no_proxy", "lower.example")
+ got, err := readMacOSNetworkProxy(context.Background(), func(context.Context) (string, error) {
+ return macOSManualProxyFixture, nil
+ })
+ if err != nil || got == nil || !strings.HasSuffix(got.NoProxy, ",lower.example") {
+ t.Fatalf("lowercase bypass merge = %#v, %v", got, err)
+ }
+ })
+ t.Run("command failure and cancellation are redacted", func(t *testing.T) {
+ clearMacOSProxyTestEnvironment(t)
+ for _, failure := range []error{errors.New("secret proxy credentials"), context.DeadlineExceeded} {
+ got, err := readMacOSNetworkProxy(context.Background(), func(context.Context) (string, error) {
+ return macOSManualProxyFixture, failure
+ })
+ if got != nil || err == nil || strings.Contains(err.Error(), "secret") {
+ t.Fatalf("command failure = %#v, %v", got, err)
+ }
+ }
+ })
+}
diff --git a/kernel/util/system_proxy_other.go b/kernel/util/system_proxy_other.go
index 369b2da6e0..5899b62fa0 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 && (!linux || android)
+//go:build !windows && (!linux || android) && (!darwin || ios)
package util