| 1 | package hostproxy |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "os/exec" |
| 10 | "strconv" |
| 11 | "strings" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | func systemProxy(req *http.Request) (*url.URL, error) { |
| 16 | if _, err := exec.LookPath("gsettings"); err != nil { |
| 17 | return nil, nil |
| 18 | } |
| 19 | ctx, cancel := context.WithTimeout(req.Context(), 3*time.Second) |
| 20 | defer cancel() |
| 21 | output, err := exec.CommandContext(ctx, "gsettings", "list-recursively", "org.gnome.system.proxy").Output() |
| 22 | if err != nil { |
| 23 | return nil, errors.New("无法读取主机桌面代理设置,请检查代理软件或设置 HTTPS_PROXY;未切换直连") |
| 24 | } |
| 25 | return gnomeProxy(req, string(output)) |
| 26 | } |
| 27 | |
| 28 | func gnomeProxy(req *http.Request, settings string) (*url.URL, error) { |
| 29 | values := map[string]string{} |
| 30 | for _, line := range strings.Split(settings, "\n") { |
| 31 | parts := strings.SplitN(line, " ", 3) |
| 32 | if len(parts) == 3 { |
| 33 | values[parts[0]+" "+parts[1]] = strings.Trim(parts[2], " '") |
| 34 | } |
| 35 | } |
| 36 | switch values["org.gnome.system.proxy mode"] { |
| 37 | case "auto": |
| 38 | return nil, errors.New("此 Linux 构建暂不解析桌面 PAC,请启用主机 TUN 或设置 HTTPS_PROXY 后继续下载") |
| 39 | case "manual": |
| 40 | address := func(protocol string) string { |
| 41 | prefix := "org.gnome.system.proxy." + protocol + " " |
| 42 | host, port := values[prefix+"host"], values[prefix+"port"] |
| 43 | if host == "" || port == "0" || port == "" { |
| 44 | return "" |
| 45 | } |
| 46 | scheme := "http://" |
| 47 | if protocol == "socks" { |
| 48 | scheme = "socks5://" |
| 49 | } |
| 50 | return scheme + net.JoinHostPort(host, port) |
| 51 | } |
| 52 | httpProxy, httpsProxy, socks := address("http"), address("https"), address("socks") |
| 53 | if values["org.gnome.system.proxy use-same-proxy"] == "true" { |
| 54 | httpsProxy = httpProxy |
| 55 | } |
| 56 | if httpProxy == "" { |
| 57 | httpProxy = socks |
| 58 | } |
| 59 | if httpsProxy == "" { |
| 60 | httpsProxy = socks |
| 61 | } |
| 62 | bypass := strings.Trim(values["org.gnome.system.proxy ignore-hosts"], "[]") |
| 63 | var hosts []string |
| 64 | for _, entry := range strings.Split(bypass, ",") { |
| 65 | entry = strings.TrimSpace(entry) |
| 66 | if entry == "" { |
| 67 | continue |
| 68 | } |
| 69 | if value, err := strconv.Unquote(strings.ReplaceAll(entry, "'", "\"")); err == nil { |
| 70 | hosts = append(hosts, value) |
| 71 | } |
| 72 | } |
| 73 | return staticProxy(req, httpProxy, httpsProxy, strings.Join(hosts, ",")) |
| 74 | default: |
| 75 | return nil, nil |
| 76 | } |
| 77 | } |