Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 组件

Expand Down
20 changes: 15 additions & 5 deletions internal/components/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"time"

"modavd/internal/errs"
"modavd/internal/hostproxy"
"modavd/internal/root"
)

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
38 changes: 0 additions & 38 deletions internal/components/fetch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package components

import (
"context"
"net/url"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -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;<local>", ""},
{"https://mirrors.cloud.tencent.com/x", "127.0.0.1:7890", "*.google.com;<local>", "http://127.0.0.1:7890"},
{"https://intranet/x", "127.0.0.1:7890", "<local>", ""},
{"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")
Expand Down
6 changes: 0 additions & 6 deletions internal/components/proxy_other.go

This file was deleted.

16 changes: 16 additions & 0 deletions internal/components/proxy_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
56 changes: 45 additions & 11 deletions internal/components/proxy.go → internal/hostproxy/hostproxy.go
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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
Expand Down
120 changes: 120 additions & 0 deletions internal/hostproxy/hostproxy_test.go
Original file line number Diff line number Diff line change
@@ -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;<local>", ""},
{"https://mirrors.cloud.tencent.com/x", "127.0.0.1:7890", "*.google.com;<local>", "http://127.0.0.1:7890"},
{"https://intranet/x", "127.0.0.1:7890", "<local>", ""},
{"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: "<local>"})
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")
}
}
6 changes: 6 additions & 0 deletions internal/hostproxy/system_other.go
Original file line number Diff line number Diff line change
@@ -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{} }
Original file line number Diff line number Diff line change
@@ -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).
Expand Down
Loading
Loading