| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/subtle" |
| 6 | "encoding/base64" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "net" |
| 11 | "net/http" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "time" |
| 17 | |
| 18 | "al.essio.dev/pkg/shellescape" |
| 19 | |
| 20 | "github.com/sylvinus/agent-vm/internal/cage" |
| 21 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 22 | ) |
| 23 | |
| 24 | |
| 25 | |
| 26 | var maintenanceOrigins = map[string]bool{ |
| 27 | "deb.debian.org": true, "security.debian.org": true, |
| 28 | "archive.ubuntu.com": true, "security.ubuntu.com": true, "ports.ubuntu.com": true, |
| 29 | "github.com": true, "objects.githubusercontent.com": true, "release-assets.githubusercontent.com": true, |
| 30 | "registry.npmjs.org": true, "downloads.claude.ai": true, "deb.nodesource.com": true, |
| 31 | } |
| 32 | |
| 33 | type maintenanceProxy struct { |
| 34 | token string |
| 35 | ctx context.Context |
| 36 | dial func(context.Context, string, string) (net.Conn, error) |
| 37 | transport *http.Transport |
| 38 | mu sync.Mutex |
| 39 | connections map[net.Conn]bool |
| 40 | closed bool |
| 41 | } |
| 42 | |
| 43 | func maintenanceDestination(address string, connect bool) bool { |
| 44 | host, port, err := net.SplitHostPort(address) |
| 45 | if err != nil { |
| 46 | return false |
| 47 | } |
| 48 | if connect && port != "443" { |
| 49 | return false |
| 50 | } |
| 51 | if !connect && port != "80" { |
| 52 | return false |
| 53 | } |
| 54 | host = strings.ToLower(host) |
| 55 | switch host { |
| 56 | case "mirrors.nju.edu.cn", "mirrors.ustc.edu.cn", "cdn.npmmirror.com", "storage.googleapis.com", "codeload.github.com": |
| 57 | return connect |
| 58 | } |
| 59 | return maintenanceOrigins[host] |
| 60 | } |
| 61 | func (p *maintenanceProxy) track(conn net.Conn) bool { |
| 62 | p.mu.Lock() |
| 63 | defer p.mu.Unlock() |
| 64 | if p.closed { |
| 65 | conn.Close() |
| 66 | return false |
| 67 | } |
| 68 | p.connections[conn] = true |
| 69 | return true |
| 70 | } |
| 71 | func (p *maintenanceProxy) close() { |
| 72 | p.mu.Lock() |
| 73 | defer p.mu.Unlock() |
| 74 | p.closed = true |
| 75 | for conn := range p.connections { |
| 76 | conn.Close() |
| 77 | } |
| 78 | p.transport.CloseIdleConnections() |
| 79 | } |
| 80 | func (p *maintenanceProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 81 | expected := "Basic " + base64.StdEncoding.EncodeToString([]byte("cage-install:"+p.token)) |
| 82 | if subtle.ConstantTimeCompare([]byte(r.Header.Get("Proxy-Authorization")), []byte(expected)) != 1 { |
| 83 | w.Header().Set("Proxy-Authenticate", `Basic realm="Cage maintenance"`) |
| 84 | http.Error(w, "Maintenance authentication required", 407) |
| 85 | return |
| 86 | } |
| 87 | if r.Method == http.MethodConnect { |
| 88 | if !maintenanceDestination(r.Host, true) { |
| 89 | http.Error(w, "Not a Cage software source", 403) |
| 90 | return |
| 91 | } |
| 92 | remote, err := p.dial(p.ctx, "tcp", r.Host) |
| 93 | if err != nil { |
| 94 | http.Error(w, "Software source proxy unavailable", 502) |
| 95 | return |
| 96 | } |
| 97 | if !p.track(remote) { |
| 98 | return |
| 99 | } |
| 100 | defer func() { remote.Close(); p.mu.Lock(); delete(p.connections, remote); p.mu.Unlock() }() |
| 101 | hijacker, ok := w.(http.Hijacker) |
| 102 | if !ok { |
| 103 | http.Error(w, "Tunnel unavailable", 500) |
| 104 | return |
| 105 | } |
| 106 | local, buffer, err := hijacker.Hijack() |
| 107 | if err != nil { |
| 108 | return |
| 109 | } |
| 110 | if !p.track(local) { |
| 111 | return |
| 112 | } |
| 113 | defer func() { local.Close(); p.mu.Lock(); delete(p.connections, local); p.mu.Unlock() }() |
| 114 | if _, err = buffer.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil { |
| 115 | return |
| 116 | } |
| 117 | if err = buffer.Flush(); err != nil { |
| 118 | return |
| 119 | } |
| 120 | done := make(chan struct{}) |
| 121 | go func() { _, _ = io.Copy(remote, buffer); remote.Close(); close(done) }() |
| 122 | _, _ = io.Copy(local, remote) |
| 123 | local.Close() |
| 124 | remote.Close() |
| 125 | <-done |
| 126 | return |
| 127 | } |
| 128 | if r.Method != http.MethodGet && r.Method != http.MethodHead { |
| 129 | http.Error(w, "Read-only software source", 405) |
| 130 | return |
| 131 | } |
| 132 | address := r.URL.Host |
| 133 | if r.URL.Port() == "" { |
| 134 | address = net.JoinHostPort(r.URL.Hostname(), "80") |
| 135 | } |
| 136 | if r.URL.Scheme != "http" || r.URL.User != nil || !maintenanceDestination(address, false) { |
| 137 | http.Error(w, "Not a Cage software source", 403) |
| 138 | return |
| 139 | } |
| 140 | request := r.Clone(p.ctx) |
| 141 | request.RequestURI = "" |
| 142 | request.Header = r.Header.Clone() |
| 143 | request.Header.Del("Proxy-Authorization") |
| 144 | request.Header.Del("Proxy-Connection") |
| 145 | response, err := p.transport.RoundTrip(request) |
| 146 | if err != nil { |
| 147 | http.Error(w, "Software source proxy unavailable", 502) |
| 148 | return |
| 149 | } |
| 150 | defer response.Body.Close() |
| 151 | for name, values := range response.Header { |
| 152 | if strings.EqualFold(name, "Connection") { |
| 153 | continue |
| 154 | } |
| 155 | for _, value := range values { |
| 156 | w.Header().Add(name, value) |
| 157 | } |
| 158 | } |
| 159 | w.WriteHeader(response.StatusCode) |
| 160 | _, _ = io.Copy(w, response.Body) |
| 161 | } |
| 162 | |
| 163 | const maintenancePort = 18961 |
| 164 | |
| 165 | |
| 166 | |
| 167 | func maintenanceScript(script, token string) string { |
| 168 | return fmt.Sprintf(`set -euo pipefail |
| 169 | umask 077 |
| 170 | cage_maintenance_dir=$(mktemp -d) |
| 171 | trap 'rm -rf "$cage_maintenance_dir"' EXIT |
| 172 | export CAGE_INSTALL_PROXY='http://cage-install:%[email protected]:%d' |
| 173 | export CAGE_APT_CONFIG="$cage_maintenance_dir/apt.conf" |
| 174 | printf 'Acquire::http::Proxy "%%s";\nAcquire::https::Proxy "%%s";\nAcquire::Retries "1";\nAcquire::http::Timeout "15";\nAcquire::https::Timeout "15";\n' "$CAGE_INSTALL_PROXY" "$CAGE_INSTALL_PROXY" > "$CAGE_APT_CONFIG" |
| 175 | unset ALL_PROXY all_proxy NO_PROXY no_proxy FTP_PROXY ftp_proxy |
| 176 | export http_proxy="$CAGE_INSTALL_PROXY" https_proxy="$CAGE_INSTALL_PROXY" HTTP_PROXY="$CAGE_INSTALL_PROXY" HTTPS_PROXY="$CAGE_INSTALL_PROXY" |
| 177 | ( |
| 178 | umask 022 |
| 179 | %s |
| 180 | ) |
| 181 | `, token, maintenancePort, script) |
| 182 | } |
| 183 | |
| 184 | |
| 185 | |
| 186 | func StartGuestServices(ctx context.Context, configPath string, cfg cage.Config, stdout, stderr io.Writer) error { |
| 187 | prefs := Preferences{BalancedDisplay: true} |
| 188 | data, err := os.ReadFile(filepath.Join(filepath.Dir(configPath), "workbench.json")) |
| 189 | if err == nil { |
| 190 | prefs.BalancedDisplay = false |
| 191 | if err = json.Unmarshal(data, &prefs); err != nil { |
| 192 | return fmt.Errorf("读取工作台画质设置失败: %w", err) |
| 193 | } |
| 194 | } else if !os.IsNotExist(err) { |
| 195 | return err |
| 196 | } |
| 197 | scale := "2" |
| 198 | if prefs.BalancedDisplay { |
| 199 | scale = "1.5" |
| 200 | } |
| 201 | return RunMaintenanceScript(ctx, configPath, "export CAGE_DISPLAY_SCALE="+scale+"\n"+cfg.StartScript(), stdout, stderr) |
| 202 | } |
| 203 | |
| 204 | func RunMaintenanceScript(ctx context.Context, configPath, script string, stdout, stderr io.Writer) error { |
| 205 | cfg, err := cage.Load(configPath) |
| 206 | if err != nil { |
| 207 | return err |
| 208 | } |
| 209 | profile := filepath.Dir(configPath) |
| 210 | if err = cfg.RequireManagedProxy(profile); err != nil { |
| 211 | return err |
| 212 | } |
| 213 | egress, err := cage.NewEgress(cfg) |
| 214 | if err != nil { |
| 215 | return err |
| 216 | } |
| 217 | |
| 218 | |
| 219 | ctx, cancel := context.WithCancel(ctx) |
| 220 | defer cancel() |
| 221 | listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 222 | if err != nil { |
| 223 | return err |
| 224 | } |
| 225 | proxy := &maintenanceProxy{token: randomToken(), ctx: ctx, dial: egress.DialContext, connections: make(map[net.Conn]bool)} |
| 226 | proxy.transport = &http.Transport{Proxy: nil, DialContext: egress.DialContext, DisableKeepAlives: true} |
| 227 | server := &http.Server{Handler: proxy, ReadHeaderTimeout: 10 * time.Second} |
| 228 | go func() { _ = server.Serve(listener) }() |
| 229 | defer server.Close() |
| 230 | defer proxy.close() |
| 231 | stop := context.AfterFunc(ctx, func() { _ = server.Close(); proxy.close() }) |
| 232 | defer stop() |
| 233 | s := &Server{profile: profile} |
| 234 | forward := fmt.Sprintf("127.0.0.1:%d:%s", maintenancePort, listener.Addr().String()) |
| 235 | command := "sudo systemd-run --quiet --pipe --wait --collect --unit=cage-maintenance-operation --property=User=cage --property=RuntimeMaxSec=infinity --property=KillMode=control-group --setenv=HOME=/home/cage --working-directory=" + shellescape.Quote(guestPath(s.environmentDir())) + " /bin/bash -se" |
| 236 | cmd := s.sshCommandWithForwarding(ctx, "-o", "ExitOnForwardFailure=yes", "-R", forward, "-T", s.sshTarget(), "--", command) |
| 237 | cmd.Stdin = strings.NewReader(maintenanceScript(cage.DebianPrepareScript+"\n"+script, proxy.token)) |
| 238 | var output failureOutput |
| 239 | cmd.Stdout = output.writer(stdout) |
| 240 | cmd.Stderr = output.writer(stderr) |
| 241 | if err = cmd.Run(); err != nil { |
| 242 | if ctx.Err() != nil { |
| 243 | cleanup, finish := context.WithTimeout(context.Background(), 5*time.Second) |
| 244 | defer finish() |
| 245 | _, _ = s.guest(cleanup, "sudo systemctl stop cage-maintenance-operation.service") |
| 246 | return ctx.Err() |
| 247 | } |
| 248 | diagnostics.Log("error", "maintenance", fmt.Sprintf("software installation error=%v", err)) |
| 249 | return executionFailure("安装或更新环境软件", err, output.String()) |
| 250 | } |
| 251 | return nil |
| 252 | } |