diff --git a/README.en.md b/README.en.md index 0f1c3878..b128e2c7 100644 --- a/README.en.md +++ b/README.en.md @@ -165,7 +165,8 @@ Double-click `ModAVD.exe` in the package root: it starts a local server that lis - The update source is chosen in the manager's "Settings" (`设置`): GitHub (the latest Release of `ModAVD/ModAVD`, the full package) or MirrorChyan (downloads need a CDK, and it can provide delta packages; on errors it downloads from GitHub instead and says so in the result's `notices`). The CDK is encrypted with Windows DPAPI and stored in `%LOCALAPPDATA%\ModAVD\update-settings.json`; only this Windows user can decrypt it, and it is not written to logs and does not appear on the command line or in API responses. For now the manager can only change the settings and check for updates; the "Update" (`更新`) button is not available. - Only files from the package are swapped: `avd\`, `mas-avd.json` (only `components.emulator` is changed and an `updateHistory` entry is recorded), `sdk\platform-tools`, `sdk\system-images`, `logs\` and so on are never touched; `sdk\emulator` is replaced as a whole. A root folder that sets `sdkRoot` in `mas-avd.json` is not updated. - `--automas-version` is the version of the calling AUTO-MAS: if the first line of the new version's announcement requires a higher AUTO-MAS, it does not install. -- Exit codes: being unable to check (offline, rate-limited, a GitHub error) is 9 (`update_unavailable`), a downloaded package that fails verification is also 9 (`update_rejected`), and a program in use or an update already in progress is 5. Go does not read the Windows system proxy; it only honors `HTTPS_PROXY` / `NO_PROXY`. +- Exit codes: being unable to check (offline, rate-limited, a GitHub error) is 9 (`update_unavailable`), a downloaded package that fails verification is also 9 (`update_rejected`), and a program in use or an update already in progress is 5. +- The proxy follows the same rules as `components fetch`; see "Proxy" in the next section. ## Fetching the Google components diff --git a/README.md b/README.md index 23398230..ad4cf9fb 100644 --- a/README.md +++ b/README.md @@ -165,7 +165,8 @@ claude mcp add --transport stdio --scope user modavd '--' D:\ModAVD\tools\modavd - 更新源在管理器的「设置」里选:GitHub(`ModAVD/ModAVD` 的最新 Release,整包)或 Mirror 酱(填了 CDK 才能下载,能拿到增量包;出错时改从 GitHub 下,并在结果的 `notices` 里写明)。CDK 用 Windows DPAPI 加密存在 `%LOCALAPPDATA%\ModAVD\update-settings.json`,只有这个 Windows 用户能解开,不写日志、不出现在命令行和接口返回里。管理器里暂时只能改设置和检查更新,「更新」按钮不可用。 - 只换包里的文件:`avd\`、`mas-avd.json`(只改 `components.emulator` 并记一条 `updateHistory`)、`sdk\platform-tools`、`sdk\system-images`、`logs\` 等一律不碰;`sdk\emulator` 整个换掉。根目录在 `mas-avd.json` 里设了 `sdkRoot` 的不更新。 - `--automas-version` 是调用方 AUTO-MAS 的版本:新版的公告第一行要求更高的 AUTO-MAS 时不装。 -- 退出码:查不了(断网、限流、GitHub 出错)是 9(`update_unavailable`),下载的包没通过核对也是 9(`update_rejected`),有程序在用、正在更新是 5。Go 不读 Windows 的系统代理,只认 `HTTPS_PROXY` / `NO_PROXY`。 +- 退出码:查不了(断网、限流、GitHub 出错)是 9(`update_unavailable`),下载的包没通过核对也是 9(`update_rejected`),有程序在用、正在更新是 5。 +- 代理和 `components fetch` 是同一套规则,见下一节的「代理」。 ## 补全 Google 组件 diff --git a/internal/components/download.go b/internal/components/download.go index c048459a..78ca0846 100644 --- a/internal/components/download.go +++ b/internal/components/download.go @@ -21,6 +21,7 @@ import ( "time" "modavd/internal/errs" + "modavd/internal/hostproxy" "modavd/internal/root" ) @@ -67,7 +68,7 @@ func (f *fetcher) httpClient() *http.Client { d := f.o.ConnectTimeout f.client = &http.Client{ Transport: &http.Transport{ - Proxy: requestProxy, + Proxy: hostproxy.ForRequest, DialContext: (&net.Dialer{Timeout: d}).DialContext, TLSHandshakeTimeout: d, ResponseHeaderTimeout: d, @@ -190,7 +191,7 @@ func (f *fetcher) license(ctx context.Context) (text, from string, err error) { if text == "" { f.where = "获取许可协议清单 " + licenseManifest + ",试过的镜像都不行" return "", "", errs.New(errs.ComponentsUnavailable, "取不到《Android SDK 许可协议》全文,什么也没有下载(各镜像的情况:"+ - strings.Join(reasons, ";")+")").WithAdvice("请检查网络后重试") + strings.Join(reasons, ";")+")").WithAdvice(netAdvice("请检查网络后重试")) } if len(failed) > 0 { var names []string @@ -397,11 +398,20 @@ func (f *fetcher) download(ctx context.Context, c root.SDKComponent) (string, er return zipFile, nil } f.where = "下载 " + c.URL - code := errs.ComponentsUnavailable + code, advice := errs.ComponentsUnavailable, netAdvice("检查网络后再运行一次") if rejected { - code = errs.ComponentsRejected + code, advice = errs.ComponentsRejected, "检查网络后再运行一次" } - return "", errs.New(code, "所有镜像都没下成:"+strings.Join(reasons, ";")).WithAdvice("检查网络后再运行一次") + return "", errs.New(code, "所有镜像都没下成:"+strings.Join(reasons, ";")).WithAdvice(advice) +} + +// netAdvice is the advice for mirrors that could not be reached: the HTTPS_PROXY hint when the Internet settings use +// an auto-config script (hostproxy.Advice), else base. +func netAdvice(base string) string { + if a := hostproxy.Advice(); a != "" { + return a + } + return base } // downloadOne is one try (the script's Invoke-Download): it resumes part from its size, checks status and headers diff --git a/internal/components/fetch_test.go b/internal/components/fetch_test.go index 8ef75bbe..568360de 100644 --- a/internal/components/fetch_test.go +++ b/internal/components/fetch_test.go @@ -2,7 +2,6 @@ package components import ( "context" - "net/url" "os" "path/filepath" "strings" @@ -155,43 +154,6 @@ func TestLicenseText(t *testing.T) { } } -func TestProxyFor(t *testing.T) { - u := func(s string) *url.URL { - p, err := url.Parse(s) - if err != nil { - t.Fatal(err) - } - return p - } - cases := []struct { - target, server, override, want string - }{ - {"https://dl.google.com/x", "127.0.0.1:7890", "", "http://127.0.0.1:7890"}, - {"https://dl.google.com/x", "http=10.0.0.1:80;https=10.0.0.2:443", "", "http://10.0.0.2:443"}, - {"http://dl.google.com/x", "http=10.0.0.1:80;https=10.0.0.2:443", "", "http://10.0.0.1:80"}, - {"https://dl.google.com/x", "http=10.0.0.1:80", "", ""}, - {"https://dl.google.com/x", "http://proxy.example:3128", "", "http://proxy.example:3128"}, - {"https://dl.google.com/x", "127.0.0.1:7890", "*.google.com;", ""}, - {"https://mirrors.cloud.tencent.com/x", "127.0.0.1:7890", "*.google.com;", "http://127.0.0.1:7890"}, - {"https://intranet/x", "127.0.0.1:7890", "", ""}, - {"https://DL.Google.COM/x", "127.0.0.1:7890", "dl.google.*", ""}, - } - for _, c := range cases { - got := proxyFor(u(c.target), c.server, c.override) - if (got == nil && c.want != "") || (got != nil && got.String() != c.want) { - t.Errorf("%s %q %q: %v, want %q", c.target, c.server, c.override, got, c.want) - } - } - for _, h := range []string{"localhost", "127.0.0.1", "::1"} { - if !isLoopback(h) { - t.Errorf("%s not loopback", h) - } - } - if isLoopback("dl.google.com") || !wildcard("a*c", "abbbc") || wildcard("a*c", "abd") || !wildcard("*", "") { - t.Error("wildcard") - } -} - // TestSetAsideRel: the result names a set-aside directory relative to the root. func TestSetAsideRel(t *testing.T) { sdk := filepath.Join(t.TempDir(), "sdk") diff --git a/internal/components/proxy_other.go b/internal/components/proxy_other.go deleted file mode 100644 index 4c151cb6..00000000 --- a/internal/components/proxy_other.go +++ /dev/null @@ -1,6 +0,0 @@ -//go:build !windows - -package components - -// systemProxy: only Windows has the Internet settings fetch-components.ps1 used; elsewhere the environment decides. -func systemProxy() (server, override string, ok bool) { return "", "", false } diff --git a/internal/components/proxy_test.go b/internal/components/proxy_test.go new file mode 100644 index 00000000..13561fe4 --- /dev/null +++ b/internal/components/proxy_test.go @@ -0,0 +1,16 @@ +package components + +import ( + "net/http" + "reflect" + "testing" + + "modavd/internal/hostproxy" +) + +func TestClientProxy(t *testing.T) { + tr, ok := (&fetcher{}).httpClient().Transport.(*http.Transport) + if !ok || reflect.ValueOf(tr.Proxy).Pointer() != reflect.ValueOf(hostproxy.ForRequest).Pointer() { + t.Error("the download client does not use hostproxy.ForRequest") + } +} diff --git a/internal/components/proxy.go b/internal/hostproxy/hostproxy.go similarity index 53% rename from internal/components/proxy.go rename to internal/hostproxy/hostproxy.go index fce1b88a..3266a946 100644 --- a/internal/components/proxy.go +++ b/internal/hostproxy/hostproxy.go @@ -1,4 +1,9 @@ -package components +// Package hostproxy is the proxy the manager's own downloads use (components fetch, update): HTTPS_PROXY / +// HTTP_PROXY / NO_PROXY when any of them is set, else the static proxy of the Windows Internet settings (the proxy +// set by hand under "Internet Options" or Settings > Network > Proxy, which is also where proxy programs put theirs). +// A proxy auto-config script (PAC, WPAD) is not evaluated: set HTTPS_PROXY for such a network (Advice says so). +// Loopback targets (local test mirrors) always go direct. +package hostproxy import ( "net" @@ -8,26 +13,55 @@ import ( "strings" ) -// requestProxy is the proxy of a request. The script's HttpWebRequest uses the Windows proxy settings; Go reads only -// the environment. So: HTTPS_PROXY / HTTP_PROXY / NO_PROXY when any of them is set (like update), else the static -// proxy of the Windows Internet settings (systemProxy). A proxy auto-config script (PAC, WPAD) is not evaluated: set -// HTTPS_PROXY for such a network. Loopback addresses (local test mirrors) always go direct. -func requestProxy(req *http.Request) (*url.URL, error) { - for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "NO_PROXY", "no_proxy"} { +var envKeys = []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "NO_PROXY", "no_proxy"} + +// envSet: one of the proxy variables is set, so the environment decides alone. +func envSet() bool { + for _, k := range envKeys { if os.Getenv(k) != "" { - return http.ProxyFromEnvironment(req) + return true } } + return false +} + +// ForRequest is an http.Transport Proxy. +func ForRequest(req *http.Request) (*url.URL, error) { + if envSet() { + return http.ProxyFromEnvironment(req) + } if isLoopback(req.URL.Hostname()) { return nil, nil } - server, override, ok := systemProxy() - if !ok { + s := system() + if !s.enabled { return nil, nil } - return proxyFor(req.URL, server, override), nil + return proxyFor(req.URL, s.server, s.override), nil } +// Advice is the hint for a failed download when the proxy may be the cause: "" unless no proxy was used because the +// Internet settings use an auto-config script. +func Advice() string { + if envSet() { + return "" + } + if s := system(); !s.enabled && s.autoConfig { + return "这台电脑的代理是自动配置脚本(PAC),本程序不读它;请把 HTTPS_PROXY 环境变量设成代理的地址(比如 http://127.0.0.1:7890)再试" + } + return "" +} + +// settings are the Internet settings that matter here. +type settings struct { + enabled bool // ProxyEnable and a ProxyServer + server, override string // ProxyServer, ProxyOverride + autoConfig bool // AutoConfigURL is set +} + +// system reads them (a variable for the tests). +var system = readSystem + func isLoopback(host string) bool { if strings.EqualFold(host, "localhost") { return true diff --git a/internal/hostproxy/hostproxy_test.go b/internal/hostproxy/hostproxy_test.go new file mode 100644 index 00000000..2b06db12 --- /dev/null +++ b/internal/hostproxy/hostproxy_test.go @@ -0,0 +1,120 @@ +package hostproxy + +import ( + "net/http" + "net/url" + "testing" +) + +func mustURL(t *testing.T, s string) *url.URL { + t.Helper() + p, err := url.Parse(s) + if err != nil { + t.Fatal(err) + } + return p +} + +// noEnv clears the proxy variables for the test and stubs the Internet settings. +func noEnv(t *testing.T, s settings) { + for _, k := range envKeys { + t.Setenv(k, "") + } + saved := system + system = func() settings { return s } + t.Cleanup(func() { system = saved }) +} + +func TestProxyFor(t *testing.T) { + cases := []struct { + target, server, override, want string + }{ + {"https://dl.google.com/x", "127.0.0.1:7890", "", "http://127.0.0.1:7890"}, + {"https://dl.google.com/x", "http=10.0.0.1:80;https=10.0.0.2:443", "", "http://10.0.0.2:443"}, + {"http://dl.google.com/x", "http=10.0.0.1:80;https=10.0.0.2:443", "", "http://10.0.0.1:80"}, + {"https://dl.google.com/x", "http=10.0.0.1:80", "", ""}, + {"https://dl.google.com/x", "http://proxy.example:3128", "", "http://proxy.example:3128"}, + {"https://dl.google.com/x", "127.0.0.1:7890", "*.google.com;", ""}, + {"https://mirrors.cloud.tencent.com/x", "127.0.0.1:7890", "*.google.com;", "http://127.0.0.1:7890"}, + {"https://intranet/x", "127.0.0.1:7890", "", ""}, + {"https://DL.Google.COM/x", "127.0.0.1:7890", "dl.google.*", ""}, + } + for _, c := range cases { + got := proxyFor(mustURL(t, c.target), c.server, c.override) + if (got == nil && c.want != "") || (got != nil && got.String() != c.want) { + t.Errorf("%s %q %q: %v, want %q", c.target, c.server, c.override, got, c.want) + } + } + for _, h := range []string{"localhost", "127.0.0.1", "::1"} { + if !isLoopback(h) { + t.Errorf("%s not loopback", h) + } + } + if isLoopback("dl.google.com") || !wildcard("a*c", "abbbc") || wildcard("a*c", "abd") || !wildcard("*", "") { + t.Error("wildcard") + } +} + +// TestForRequestSystem: without the variables the Internet settings decide; loopback targets go direct. +func TestForRequestSystem(t *testing.T) { + noEnv(t, settings{enabled: true, server: "127.0.0.1:7890", override: ""}) + for target, want := range map[string]string{ + "https://api.github.com/repos": "http://127.0.0.1:7890", + "https://127.0.0.1:8443/x": "", + "http://localhost/x": "", + "https://intranet/x": "", + } { + got, err := ForRequest(&http.Request{URL: mustURL(t, target)}) + if err != nil || (got == nil) != (want == "") || (got != nil && got.String() != want) { + t.Errorf("%s: %v %v, want %q", target, got, err, want) + } + } + for _, s := range []settings{{autoConfig: true}, {server: "127.0.0.1:7890"}} { // PAC only; turned off, address left + noEnv(t, s) + if got, _ := ForRequest(&http.Request{URL: mustURL(t, "https://api.github.com/")}); got != nil { + t.Errorf("%+v: %v", s, got) + } + } +} + +// TestForRequestEnv: any of the variables set, the environment alone decides (NO_PROXY included) and the Internet +// settings are not read. The only test here that calls http.ProxyFromEnvironment, which reads the environment once +// per process. +func TestForRequestEnv(t *testing.T) { + noEnv(t, settings{enabled: true, server: "10.9.9.9:1"}) + t.Setenv("HTTPS_PROXY", "http://127.0.0.1:3128") + t.Setenv("NO_PROXY", "mirrors.example") + got, err := ForRequest(&http.Request{URL: mustURL(t, "https://api.github.com/")}) + if err != nil || got == nil || got.String() != "http://127.0.0.1:3128" { + t.Errorf("HTTPS_PROXY: %v %v", got, err) + } + if got, _ := ForRequest(&http.Request{URL: mustURL(t, "https://mirrors.example/x")}); got != nil { + t.Errorf("NO_PROXY: %v", got) + } + if Advice() != "" { + t.Error("advice with the variables set") + } +} + +// TestAdvice: only a PAC without a static proxy, and no variables, gets the HTTPS_PROXY hint. +func TestAdvice(t *testing.T) { + for _, c := range []struct { + s settings + want bool + }{ + {settings{}, false}, + {settings{autoConfig: true}, true}, + {settings{autoConfig: true, enabled: true, server: "127.0.0.1:7890"}, false}, + {settings{enabled: true, server: "127.0.0.1:7890"}, false}, + } { + noEnv(t, c.s) + if got := Advice(); (got != "") != c.want { + t.Errorf("%+v: %q", c.s, got) + } + } + noEnv(t, settings{autoConfig: true}) + t.Setenv("no_proxy", "mirrors.example") // any of the variables, NO_PROXY alone too: the environment decides + if !envSet() || Advice() != "" { + t.Error("NO_PROXY alone") + } +} diff --git a/internal/hostproxy/system_other.go b/internal/hostproxy/system_other.go new file mode 100644 index 00000000..69e939c5 --- /dev/null +++ b/internal/hostproxy/system_other.go @@ -0,0 +1,6 @@ +//go:build !windows + +package hostproxy + +// readSystem: only Windows has the Internet settings; elsewhere the environment decides. +func readSystem() settings { return settings{} } diff --git a/internal/components/proxy_windows.go b/internal/hostproxy/system_windows.go similarity index 67% rename from internal/components/proxy_windows.go rename to internal/hostproxy/system_windows.go index d40cc783..b4f05444 100644 --- a/internal/components/proxy_windows.go +++ b/internal/hostproxy/system_windows.go @@ -1,30 +1,31 @@ //go:build windows -package components +package hostproxy import ( "syscall" "unsafe" ) -// systemProxy reads the static proxy of the current user's Internet settings (HKCU\Software\Microsoft\Windows\ -// CurrentVersion\Internet Settings: ProxyEnable, ProxyServer, ProxyOverride), read only. ok=false when none is on. -func systemProxy() (server, override string, ok bool) { +// readSystem reads the current user's Internet settings (HKCU\Software\Microsoft\Windows\CurrentVersion\Internet +// Settings: ProxyEnable, ProxyServer, ProxyOverride, AutoConfigURL), read only. +func readSystem() settings { path, err := syscall.UTF16PtrFromString(`Software\Microsoft\Windows\CurrentVersion\Internet Settings`) if err != nil { - return "", "", false + return settings{} } var k syscall.Handle if syscall.RegOpenKeyEx(syscall.HKEY_CURRENT_USER, path, 0, syscall.KEY_READ, &k) != nil { - return "", "", false + return settings{} } defer syscall.RegCloseKey(k) + s := settings{autoConfig: regString(k, "AutoConfigURL") != ""} var enable uint32 - if !regValue(k, "ProxyEnable", syscall.REG_DWORD, unsafe.Slice((*byte)(unsafe.Pointer(&enable)), 4)) || enable == 0 { - return "", "", false + if regValue(k, "ProxyEnable", syscall.REG_DWORD, unsafe.Slice((*byte)(unsafe.Pointer(&enable)), 4)) && enable != 0 { + s.server, s.override = regString(k, "ProxyServer"), regString(k, "ProxyOverride") + s.enabled = s.server != "" } - server, override = regString(k, "ProxyServer"), regString(k, "ProxyOverride") - return server, override, server != "" + return s } // regValue reads a value of type want into buf (exactly filled for a DWORD). diff --git a/internal/update/proxy_test.go b/internal/update/proxy_test.go new file mode 100644 index 00000000..1dc61e8a --- /dev/null +++ b/internal/update/proxy_test.go @@ -0,0 +1,17 @@ +package update + +import ( + "net/http" + "reflect" + "testing" + + "modavd/internal/hostproxy" +) + +// The update finds the proxy where components fetch does: the Windows settings too, not only the environment. +func TestClientProxy(t *testing.T) { + tr, ok := (&Updater{}).client().Transport.(*http.Transport) + if !ok || reflect.ValueOf(tr.Proxy).Pointer() != reflect.ValueOf(hostproxy.ForRequest).Pointer() { + t.Error("the update client does not use hostproxy.ForRequest") + } +} diff --git a/internal/update/source.go b/internal/update/source.go index e8e736a9..3c3c6522 100644 --- a/internal/update/source.go +++ b/internal/update/source.go @@ -22,6 +22,7 @@ import ( "modavd/internal/buildinfo" "modavd/internal/errs" + "modavd/internal/hostproxy" "modavd/internal/jsonord" "modavd/internal/root" ) @@ -92,7 +93,7 @@ func (u *Updater) client() *http.Client { return u.httpClient } return &http.Client{Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, // HTTPS_PROXY / NO_PROXY; Go does not read the system proxy + Proxy: hostproxy.ForRequest, // the same proxy as components fetch DialContext: (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext, TLSHandshakeTimeout: 10 * time.Second, ResponseHeaderTimeout: 30 * time.Second, @@ -117,7 +118,7 @@ func (u *Updater) githubLatest(ctx context.Context) (*release, error) { req.Header.Set("User-Agent", userAgent()) resp, err := u.client().Do(req) if err != nil { - return nil, sourceError("连不上 GitHub(%s)", netErrText(err, "")) + return nil, sourceError("连不上 GitHub(%s)", netErrText(err, "")).WithAdvice(hostproxy.Advice()) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { @@ -371,7 +372,7 @@ func (u *Updater) download(ctx context.Context, r *release) (string, error) { os.Remove(part) return "", sourceError("下载中断,再更新一次会重新下载(从 Mirror 酱下载 %d 次都没成:%v)", downloadAttempts, lastErr) } - return "", sourceError("下载 %s 失败: %v", r.assetName, lastErr) + return "", sourceError("下载 %s 失败: %v", r.assetName, lastErr).WithAdvice(hostproxy.Advice()) } st, err := os.Stat(part) if err != nil || st.Size() != r.size {