Skip to content

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

:bug: Make the system network proxy effective on Windows https://github.com/siyuan-note/siyuan/issues/18819

Daniel5e311bf3bef3
diff --git a/app/electron/main.js b/app/electron/main.js
index 5ee97509fa..6045248962 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -345,12 +345,12 @@ const windowNavigate = (currentWindow, windowType) => {
});
};
-const setProxy = (proxyURL, webContents) => {
- if (proxyURL.startsWith("system://")) {
+const setProxy = (proxyURL, webContents, proxyMode) => {
+ if (proxyMode === "system" || (!proxyMode && proxyURL.startsWith("://"))) {
console.log("network proxy [system]");
return webContents.session.setProxy({mode: "system"});
}
- if (proxyURL.startsWith("://")) {
+ if (proxyMode === "direct") {
console.log("network proxy [direct]");
return webContents.session.setProxy({mode: "direct"});
}
@@ -1079,7 +1079,9 @@ const initMainWindow = (currentKernelPort = kernelPort) => {
net.fetch(getServer(currentKernelPort) + "/api/system/getNetwork", {method: "POST"}).then((response) => {
return response.json();
}).then((response) => {
- const setProxyDone = setProxy(`${response.data.proxy.scheme}://${response.data.proxy.host}:${response.data.proxy.port}`, currentWindow.webContents);
+ const proxyMode = response.data.proxy.scheme === "system" ? "system" : response.data.proxy.scheme === "" ? "direct" : "fixed_servers";
+ const setProxyDone = setProxy(`${response.data.proxy.scheme}://${response.data.proxy.host}:${response.data.proxy.port}`,
+ currentWindow.webContents, proxyMode);
Promise.race([
Promise.resolve(setProxyDone),
new Promise((resolve) => setTimeout(resolve, 5000)), // setProxy 永久 pending 时的超时兜底
@@ -1800,7 +1802,7 @@ app.whenReady().then(() => {
return event.sender.session.availableSpellCheckerLanguages;
}
if (data.cmd === "setProxy") {
- return setProxy(data.proxyURL, event.sender);
+ return setProxy(data.proxyURL, event.sender, data.proxyMode);
}
if (data.cmd === "showSaveDialog") {
return dialog.showSaveDialog(data);
diff --git a/app/src/config/tabs/appTab.ts b/app/src/config/tabs/appTab.ts
index 402156ba27..57ff158e94 100644
--- a/app/src/config/tabs/appTab.ts
+++ b/app/src/config/tabs/appTab.ts
@@ -263,7 +263,8 @@ const mountNetworkProxy = (root: HTMLElement) => {
/// #if !BROWSER
ipcRenderer.invoke(Constants.SIYUAN_GET, {
cmd: "setProxy",
- proxyURL: `${window.siyuan.config.system.networkProxy.scheme}://${window.siyuan.config.system.networkProxy.host}:${window.siyuan.config.system.networkProxy.port}`,
+ proxyMode: scheme === "system" ? "system" : scheme === "" ? "direct" : "fixed_servers",
+ proxyURL: scheme === "system" ? "://" : `${scheme}://${host}:${port}`,
}).then(() => {
exportLayout({
errorExit: false,
diff --git a/kernel/util/runtime.go b/kernel/util/runtime.go
index 9087028f6c..41e6aed10e 100644
--- a/kernel/util/runtime.go
+++ b/kernel/util/runtime.go
@@ -213,12 +213,18 @@ func GetDeviceName() string {
func SetNetworkProxy(proxyURL string, useSystem bool) {
if useSystem {
restoreSystemNetworkProxyEnvironment()
- } else {
- for _, name := range networkProxyEnvironmentNames {
- if err := os.Setenv(name, proxyURL); err != nil {
- logging.LogErrorf("set env [%s] failed: %s", name, err)
- }
+ systemProxy, err := loadSystemNetworkProxy()
+ if err != nil {
+ logging.LogWarnf("load system network proxy failed: %s", err)
+ } else if nil != systemProxy {
+ setNetworkProxyEnvironment(networkProxyHTTPEnvironmentNames, systemProxy.HTTPProxy)
+ setNetworkProxyEnvironment(networkProxyHTTPSEnvironmentNames, systemProxy.HTTPSProxy)
+ setNetworkProxyEnvironment(networkProxyBypassEnvironmentNames, systemProxy.NoProxy)
}
+ } else {
+ setNetworkProxyEnvironment(networkProxyHTTPEnvironmentNames, proxyURL)
+ setNetworkProxyEnvironment(networkProxyHTTPSEnvironmentNames, proxyURL)
+ restoreNetworkProxyEnvironment(networkProxyBypassEnvironmentNames)
}
if useSystem {
@@ -233,7 +239,12 @@ func SetNetworkProxy(proxyURL string, useSystem bool) {
closeOpenAIIdleConnections()
}
-var networkProxyEnvironmentNames = []string{"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"}
+var (
+ networkProxyHTTPEnvironmentNames = []string{"HTTP_PROXY", "http_proxy"}
+ networkProxyHTTPSEnvironmentNames = []string{"HTTPS_PROXY", "https_proxy"}
+ networkProxyBypassEnvironmentNames = []string{"NO_PROXY", "no_proxy"}
+ networkProxyEnvironmentNames = []string{"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "NO_PROXY", "no_proxy"}
+)
type networkProxyEnvironmentValue struct {
value string
@@ -250,18 +261,28 @@ var systemNetworkProxyEnvironment = func() map[string]networkProxyEnvironmentVal
}()
func restoreSystemNetworkProxyEnvironment() {
- for _, name := range networkProxyEnvironmentNames {
+ restoreNetworkProxyEnvironment(networkProxyEnvironmentNames)
+}
+
+func restoreNetworkProxyEnvironment(names []string) {
+ for _, name := range names {
value := systemNetworkProxyEnvironment[name]
if value.set {
- if err := os.Setenv(name, value.value); err != nil {
- logging.LogErrorf("set env [%s] failed: %s", name, err)
- }
+ setNetworkProxyEnvironment([]string{name}, value.value)
} else if err := os.Unsetenv(name); err != nil {
logging.LogErrorf("unset env [%s] failed: %s", name, err)
}
}
}
+func setNetworkProxyEnvironment(names []string, value string) {
+ for _, name := range names {
+ if err := os.Setenv(name, value); err != nil {
+ logging.LogErrorf("set env [%s] failed: %s", name, err)
+ }
+ }
+}
+
func networkProxyLogValue(rawURL string) string {
proxyURL, err := url.Parse(rawURL)
if err != nil {
diff --git a/kernel/util/runtime_test.go b/kernel/util/runtime_test.go
index b3fe3bd427..78b607cba1 100644
--- a/kernel/util/runtime_test.go
+++ b/kernel/util/runtime_test.go
@@ -27,24 +27,40 @@ func TestSetNetworkProxy(t *testing.T) {
}
original := systemNetworkProxyEnvironment
systemNetworkProxyEnvironment = map[string]networkProxyEnvironmentValue{
- "HTTP_PROXY": {value: "http://system-http", set: true},
- "HTTPS_PROXY": {value: "http://system-https", set: true},
- "http_proxy": {value: "http://system-http", set: true},
- "https_proxy": {value: "http://system-https", set: true},
+ "HTTP_PROXY": {value: "http://environment-http", set: true},
+ "HTTPS_PROXY": {value: "http://environment-https", set: true},
+ "http_proxy": {value: "http://environment-http", set: true},
+ "https_proxy": {value: "http://environment-https", set: true},
+ "NO_PROXY": {value: "environment.local", set: true},
+ "no_proxy": {value: "environment.local", set: true},
+ }
+ originalLoader := loadSystemNetworkProxy
+ loadSystemNetworkProxy = func() (*systemNetworkProxyConfig, error) {
+ return &systemNetworkProxyConfig{
+ HTTPProxy: "http://system-http",
+ HTTPSProxy: "http://system-https",
+ NoProxy: "localhost,10.0.0.0/8",
+ }, nil
}
t.Cleanup(func() {
systemNetworkProxyEnvironment = original
+ loadSystemNetworkProxy = originalLoader
})
SetNetworkProxy("http://configured", false)
- for _, name := range networkProxyEnvironmentNames {
+ for _, name := range append(networkProxyHTTPEnvironmentNames, networkProxyHTTPSEnvironmentNames...) {
if got := os.Getenv(name); got != "http://configured" {
t.Fatalf("%s = %q, want configured proxy", name, got)
}
}
+ for _, name := range networkProxyBypassEnvironmentNames {
+ if got := os.Getenv(name); got != "environment.local" {
+ t.Fatalf("%s = %q, want original bypass", name, got)
+ }
+ }
SetNetworkProxy("", false)
- for _, name := range networkProxyEnvironmentNames {
+ for _, name := range append(networkProxyHTTPEnvironmentNames, networkProxyHTTPSEnvironmentNames...) {
if got := os.Getenv(name); got != "" {
t.Fatalf("%s = %q, want direct connection", name, got)
}
@@ -57,4 +73,7 @@ func TestSetNetworkProxy(t *testing.T) {
if got := os.Getenv("HTTPS_PROXY"); got != "http://system-https" {
t.Fatalf("HTTPS_PROXY = %q, want system proxy", got)
}
+ if got := os.Getenv("NO_PROXY"); got != "localhost,10.0.0.0/8" {
+ t.Fatalf("NO_PROXY = %q, want system bypass", got)
+ }
}
diff --git a/kernel/util/system_proxy.go b/kernel/util/system_proxy.go
new file mode 100644
index 0000000000..7bbf5e70b4
--- /dev/null
+++ b/kernel/util/system_proxy.go
@@ -0,0 +1,166 @@
+// 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 (
+ "fmt"
+ "net"
+ "net/url"
+ "strconv"
+ "strings"
+)
+
+type systemNetworkProxyConfig struct {
+ HTTPProxy string
+ HTTPSProxy string
+ NoProxy string
+}
+
+var loadSystemNetworkProxy = readSystemNetworkProxy
+
+func parseSystemNetworkProxy(proxyServer, proxyOverride string) (*systemNetworkProxyConfig, error) {
+ proxyServer = strings.TrimSpace(proxyServer)
+ if "" == proxyServer {
+ return nil, nil
+ }
+
+ ret := &systemNetworkProxyConfig{NoProxy: parseSystemNetworkProxyBypass(proxyOverride)}
+ if !strings.Contains(proxyServer, "=") {
+ proxyURL, err := normalizeSystemNetworkProxyURL(proxyServer, "http")
+ if err != nil {
+ return nil, err
+ }
+ ret.HTTPProxy, ret.HTTPSProxy = proxyURL, proxyURL
+ return ret, nil
+ }
+
+ proxies := map[string]string{}
+ for _, field := range strings.Split(proxyServer, ";") {
+ parts := strings.SplitN(field, "=", 2)
+ if 2 != len(parts) {
+ continue
+ }
+ name, address := strings.ToLower(strings.TrimSpace(parts[0])), strings.TrimSpace(parts[1])
+ if "" != address {
+ proxies[name] = address
+ }
+ }
+
+ var err error
+ if address := proxies["http"]; "" != address {
+ if ret.HTTPProxy, err = normalizeSystemNetworkProxyURL(address, "http"); err != nil {
+ return nil, err
+ }
+ }
+ if address := proxies["https"]; "" != address {
+ if ret.HTTPSProxy, err = normalizeSystemNetworkProxyURL(address, "http"); err != nil {
+ return nil, err
+ }
+ }
+ socksAddress := proxies["socks5"]
+ if "" == socksAddress {
+ socksAddress = proxies["socks"]
+ }
+ if "" != socksAddress {
+ socksProxy, parseErr := normalizeSystemNetworkProxyURL(socksAddress, "socks5")
+ if parseErr != nil {
+ return nil, parseErr
+ }
+ if "" == ret.HTTPProxy {
+ ret.HTTPProxy = socksProxy
+ }
+ if "" == ret.HTTPSProxy {
+ ret.HTTPSProxy = socksProxy
+ }
+ }
+ if "" == ret.HTTPProxy && "" == ret.HTTPSProxy {
+ return nil, fmt.Errorf("system proxy does not contain a supported HTTP, HTTPS or SOCKS proxy")
+ }
+ return ret, nil
+}
+
+func normalizeSystemNetworkProxyURL(address, defaultScheme string) (string, error) {
+ address = strings.TrimSpace(address)
+ if !strings.Contains(address, "://") {
+ address = defaultScheme + "://" + address
+ }
+ proxyURL, err := url.Parse(address)
+ if err != nil || "" == proxyURL.Host {
+ return "", fmt.Errorf("invalid system proxy address")
+ }
+ switch strings.ToLower(proxyURL.Scheme) {
+ case "http", "https", "socks5", "socks5h":
+ default:
+ return "", fmt.Errorf("unsupported system proxy protocol [%s]", proxyURL.Scheme)
+ }
+ return proxyURL.String(), nil
+}
+
+func parseSystemNetworkProxyBypass(proxyOverride string) string {
+ entries := []string{}
+ seen := map[string]bool{}
+ add := func(entry string) {
+ if "" != entry && !seen[entry] {
+ entries = append(entries, entry)
+ seen[entry] = true
+ }
+ }
+ for _, field := range strings.Split(proxyOverride, ";") {
+ field = strings.TrimSpace(field)
+ if strings.EqualFold(field, "<local>") {
+ add("localhost")
+ add("127.0.0.1")
+ add("::1")
+ continue
+ }
+ if cidr, ok := systemNetworkProxyWildcardCIDR(field); ok {
+ add(cidr)
+ continue
+ }
+ add(field)
+ }
+ return strings.Join(entries, ",")
+}
+
+func systemNetworkProxyWildcardCIDR(pattern string) (string, bool) {
+ parts := strings.Split(pattern, ".")
+ if len(parts) < 2 || 4 < len(parts) || "*" != parts[len(parts)-1] {
+ return "", false
+ }
+ fixed := len(parts) - 1
+ for i, part := range parts {
+ if i >= fixed {
+ if "*" != part {
+ return "", false
+ }
+ continue
+ }
+ value, err := strconv.Atoi(part)
+ if err != nil || value < 0 || 255 < value {
+ return "", false
+ }
+ }
+ addressParts := append([]string{}, parts[:fixed]...)
+ for len(addressParts) < 4 {
+ addressParts = append(addressParts, "0")
+ }
+ cidr := strings.Join(addressParts, ".") + "/" + strconv.Itoa(fixed*8)
+ if _, _, err := net.ParseCIDR(cidr); err != nil {
+ return "", false
+ }
+ return cidr, true
+}
diff --git a/kernel/util/system_proxy_other.go b/kernel/util/system_proxy_other.go
new file mode 100644
index 0000000000..7677b94004
--- /dev/null
+++ b/kernel/util/system_proxy_other.go
@@ -0,0 +1,23 @@
+// 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 !windows
+
+package util
+
+func readSystemNetworkProxy() (*systemNetworkProxyConfig, error) {
+ return nil, nil
+}
diff --git a/kernel/util/system_proxy_test.go b/kernel/util/system_proxy_test.go
new file mode 100644
index 0000000000..21f6a032a8
--- /dev/null
+++ b/kernel/util/system_proxy_test.go
@@ -0,0 +1,71 @@
+// 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 "testing"
+
+func TestParseSystemNetworkProxy(t *testing.T) {
+ tests := []struct {
+ name string
+ proxyServer string
+ proxyOverride string
+ wantHTTP string
+ wantHTTPS string
+ wantNoProxy string
+ }{
+ {
+ name: "shared HTTP proxy",
+ proxyServer: "127.0.0.1:10808",
+ proxyOverride: "<local>;localhost;127.*;10.*;172.16.*;192.168.*",
+ wantHTTP: "http://127.0.0.1:10808",
+ wantHTTPS: "http://127.0.0.1:10808",
+ wantNoProxy: "localhost,127.0.0.1,::1,127.0.0.0/8,10.0.0.0/8,172.16.0.0/16,192.168.0.0/16",
+ },
+ {
+ name: "protocol-specific proxies",
+ proxyServer: "http=proxy.example.com:80;https=secure.example.com:81",
+ wantHTTP: "http://proxy.example.com:80",
+ wantHTTPS: "http://secure.example.com:81",
+ },
+ {
+ name: "SOCKS proxy fallback",
+ proxyServer: "socks=127.0.0.1:1080",
+ wantHTTP: "socks5://127.0.0.1:1080",
+ wantHTTPS: "socks5://127.0.0.1:1080",
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ got, err := parseSystemNetworkProxy(test.proxyServer, test.proxyOverride)
+ if err != nil {
+ t.Fatalf("parse system proxy failed: %v", err)
+ }
+ if got.HTTPProxy != test.wantHTTP || got.HTTPSProxy != test.wantHTTPS || got.NoProxy != test.wantNoProxy {
+ t.Fatalf("parse system proxy = %#v, want HTTP %q, HTTPS %q, no proxy %q", got, test.wantHTTP, test.wantHTTPS, test.wantNoProxy)
+ }
+ })
+ }
+}
+
+func TestParseSystemNetworkProxyRejectsUnsupportedProxy(t *testing.T) {
+ if _, err := parseSystemNetworkProxy("ftp=proxy.example.com:21", ""); nil == err {
+ t.Fatal("unsupported system proxy should fail")
+ }
+ if _, err := parseSystemNetworkProxy("http://", ""); nil == err {
+ t.Fatal("invalid system proxy should fail")
+ }
+}
diff --git a/kernel/util/system_proxy_windows.go b/kernel/util/system_proxy_windows.go
new file mode 100644
index 0000000000..24c54beed2
--- /dev/null
+++ b/kernel/util/system_proxy_windows.go
@@ -0,0 +1,71 @@
+// 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 windows
+
+package util
+
+import (
+ "errors"
+
+ "golang.org/x/sys/windows/registry"
+)
+
+func readSystemNetworkProxy() (*systemNetworkProxyConfig, error) {
+ key, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.QUERY_VALUE)
+ if err != nil {
+ return nil, err
+ }
+ defer key.Close()
+
+ autoConfigURL, _, err := key.GetStringValue("AutoConfigURL")
+ if nil == err && "" != autoConfigURL {
+ return nil, errors.New("automatic proxy configuration is not supported")
+ }
+ if nil != err && registry.ErrNotExist != err {
+ return nil, err
+ }
+ autoDetect, _, err := key.GetIntegerValue("AutoDetect")
+ if nil == err && 0 != autoDetect {
+ return nil, errors.New("automatic proxy detection is not supported")
+ }
+ if nil != err && registry.ErrNotExist != err {
+ return nil, err
+ }
+
+ enabled, _, err := key.GetIntegerValue("ProxyEnable")
+ if registry.ErrNotExist == err {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ if 0 == enabled {
+ return nil, nil
+ }
+
+ proxyServer, _, err := key.GetStringValue("ProxyServer")
+ if err != nil {
+ return nil, err
+ }
+ proxyOverride, _, err := key.GetStringValue("ProxyOverride")
+ if registry.ErrNotExist == err {
+ proxyOverride = ""
+ } else if err != nil {
+ return nil, err
+ }
+ return parseSystemNetworkProxy(proxyServer, proxyOverride)
+}