提交记录新增internal/cliconversation/activity.go+73 −0看文件
新增internal/cliconversation/provider.go+338 −0看文件
新增internal/cliconversation/provider_approval.go+189 −0看文件
新增internal/cliconversation/provider_approval_test.go+108 −0看文件
新增internal/cliconversation/provider_test.go+270 −0看文件
新增internal/clipboardfiles/archive.go+222 −0看文件
新增internal/clipboardfiles/ownership.go+230 −0看文件
新增internal/clipboardfiles/ownership_test.go+101 −0看文件
新增internal/clipboardfiles/ownership_unix.go+10 −0看文件
新增internal/clipboardfiles/ownership_unix_test.go+50 −0看文件
新增internal/clipboardfiles/ownership_windows.go+13 −0看文件
新增internal/clipboardfiles/ownership_windows_test.go+43 −0看文件
新增internal/guestos/components.go+224 −0看文件
新增internal/guestos/components_test.go+96 −0看文件
新增internal/guestos/host_source_test.go+137 −0看文件
新增internal/guestos/hyperv_instance.go+23 −0看文件
新增internal/guestos/hyperv_instance.ps1+49 −0看文件
新增internal/guestos/hyperv_instance_nonwindows.go+14 −0看文件
新增internal/guestos/hyperv_instance_test.go+27 −0看文件
新增internal/guestos/hyperv_instance_windows.go+70 −0看文件
新增internal/guestos/inspect.go+64 −0看文件
新增internal/guestos/inspect_darwin.go+17 −0看文件
新增internal/guestos/inspect_linux.go+26 −0看文件
新增internal/guestos/inspect_other.go+9 −0看文件
新增internal/guestos/inspect_windows.go+8 −0看文件
新增internal/guestos/install_other.go+13 −0看文件
新增internal/guestos/install_windows.go+40 −0看文件
新增internal/guestos/installation.go+254 −0看文件
新增internal/guestos/installation_test.go+107 −0看文件
新增internal/guestos/mac_host_darwin_arm64.go+121 −0看文件
新增internal/guestos/mac_host_unavailable_darwin.go+15 −0看文件
新增internal/guestos/macos_login.go+24 −0看文件
新增internal/guestos/macos_profile.go+200 −0看文件
新增internal/guestos/macos_profile_test.go+104 −0看文件
新增internal/guestos/macos_provision_test.go+29 −0看文件
新增internal/guestos/macos_serial.go+61 −0看文件
新增internal/guestos/macos_ssh.go+79 −0看文件
新增internal/guestos/maintenance_other.go+13 −0看文件
新增internal/guestos/maintenance_windows.go+39 −0看文件
新增internal/guestos/testdata/hyperv_instance.ps1+55 −0看文件
新增internal/guestos/testdata/windows_lifecycle.ps1+29 −0看文件
新增internal/guestos/testdata/windows_resources.ps1+26 −0看文件
新增internal/guestos/windows_host_enrollment.go+70 −0看文件
新增internal/guestos/windows_host_enrollment_test.go+42 −0看文件
新增internal/guestos/windows_host_enrollment_windows.go+637 −0看文件
新增internal/guestos/windows_host_manager_acl_windows_test.go+61 −0看文件
新增internal/guestos/windows_host_manager_client_windows.go+232 −0看文件
新增internal/guestos/windows_host_manager_e2e_windows_test.go+138 −0看文件
新增internal/guestos/windows_host_manager_server_windows.go+474 −0看文件
新增internal/guestos/windows_host_manager_service_windows.go+60 −0看文件
新增internal/guestos/windows_host_manager_wire.go+117 −0看文件
新增internal/guestos/windows_host_manager_wire_test.go+22 −0看文件
新增internal/guestos/windows_host_storage_windows.go+579 −0看文件
新增internal/guestos/windows_host_windows.go+96 −0看文件
新增internal/guestos/windows_lifecycle.go+6 −0看文件
新增internal/guestos/windows_lifecycle.ps1+23 −0看文件
新增internal/guestos/windows_lifecycle_other.go+12 −0看文件
新增internal/guestos/windows_lifecycle_test.go+22 −0看文件
新增internal/guestos/windows_lifecycle_windows.go+64 −0看文件
新增internal/guestos/windows_profile.go+117 −0看文件
新增internal/guestos/windows_profile_nonwindows.go+6 −0看文件
新增internal/guestos/windows_profile_test.go+91 −0看文件
新增internal/guestos/windows_profile_windows.go+23 −0看文件
新增internal/guestos/windows_resources.go+34 −0看文件
新增internal/guestos/windows_resources.ps1+25 −0看文件
新增internal/guestos/windows_resources_other.go+12 −0看文件
新增internal/guestos/windows_resources_test.go+22 −0看文件
新增internal/guestos/windows_resources_windows.go+62 −0看文件
新增internal/guestos/windows_storage.go+214 −0看文件
新增internal/guestos/windows_storage.ps1+75 −0看文件
新增internal/guestos/windows_storage_nonwindows.go+32 −0看文件
新增internal/guestos/windows_storage_windows.go+47 −0看文件
新增internal/hostimage/catalog_other.go+12 −0看文件
新增internal/hostimage/catalog_windows.go+42 −0看文件
新增internal/hostimage/download.go+275 −0看文件
新增internal/hostimage/identity_unix.go+69 −0看文件
新增internal/hostimage/identity_unix_test.go+12 −0看文件
新增internal/hostimage/identity_windows.go+71 −0看文件
新增internal/hostimage/linux_template.go+122 −0看文件
新增internal/hostimage/lock_unix.go+13 −0看文件
新增internal/hostimage/lock_windows.go+11 −0看文件
新增internal/hostimage/mac_media.go+86 −0看文件
新增internal/hostimage/source.go+361 −0看文件
新增internal/hostimage/source_test.go+298 −0看文件
新增internal/hostimage/ubuntu_test.go+71 −0看文件
新增internal/hostimage/windows_catalog.go+118 −0看文件
新增internal/keepawake/keepawake.go+50 −0看文件
新增internal/keepawake/keepawake_darwin.go+7 −0看文件
新增internal/keepawake/keepawake_darwin_test.go+74 −0看文件
新增internal/keepawake/keepawake_linux.go+7 −0看文件
新增internal/keepawake/keepawake_test.go+60 −0看文件
新增internal/keepawake/keepawake_windows.go+49 −0看文件
新增internal/keepawake/process.go+76 −0看文件
修改internal/limaembed/assets/README+3 −3看文件
新增internal/limaembed/assets_darwin_arm64.go+6 −0看文件
新增internal/limaembed/assets_other.go+10 −0看文件
新增internal/limaembed/host-images/ubuntu-22.04.yaml+11 −0看文件
修改internal/limaembed/limaembed.go+10 −0看文件
修改internal/limaembed/share.go+49 −21看文件
新增internal/limaembed/share_test.go+47 −0看文件
新增internal/maclogin/bridge.h+9 −0看文件
新增internal/maclogin/bridge_darwin.m+84 −0看文件
新增internal/maclogin/login_darwin_arm64.go+300 −0看文件
新增internal/maclogin/screen.go+91 −0看文件
新增internal/maclogin/screen_test.go+51 −0看文件
新增internal/maclogin/typing.go+42 −0看文件
新增internal/maclogin/typing_test.go+26 −0看文件
新增internal/vm/host_source_test.go+52 −0看文件
修改internal/vm/lima.go+38 −5看文件
修改internal/vm/lima_test.go+45 −1看文件
新增internal/vm/macos_guest_e2e_test.go+340 −0看文件
新增internal/vm/macos_install_darwin_arm64.go+222 −0看文件
新增internal/vm/macos_install_darwin_arm64_test.go+130 −0看文件
新增internal/vm/macos_project_e2e_test.go+96 −0看文件
新增internal/vm/macos_resources.go+107 −0看文件
新增internal/vm/macos_resources_darwin_arm64.go+32 −0看文件
新增internal/vm/macos_resources_other.go+9 −0看文件
新增internal/vm/macos_resources_test.go+58 −0看文件
新增internal/vm/start_error.go+81 −0看文件
新增internal/vm/start_error_test.go+69 −0看文件
| @@ -0,0 +1,73 @@ | ||
| 1 | 新增:package cliconversation | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "strings" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:// ToolActivity is a display-only summary. Command bodies, file contents and | |
| 9 | 新增:// tool outputs stay in the CLI transcript. Approval has a separate protocol. | |
| 10 | 新增:type ToolActivity struct { | |
| 11 | 新增: ID string `json:"id"` | |
| 12 | 新增: Name string `json:"name"` | |
| 13 | 新增: Detail string `json:"detail,omitempty"` | |
| 14 | 新增: Status string `json:"status"` | |
| 15 | 新增:} | |
| 16 | 新增: | |
| 17 | 新增:func updateTools(tools []ToolActivity, role string, line []byte) ([]ToolActivity, bool) { | |
| 18 | 新增: var msg struct { | |
| 19 | 新增: Message struct { | |
| 20 | 新增: Content []struct { | |
| 21 | 新增: Type string `json:"type"` | |
| 22 | 新增: ID string `json:"id"` | |
| 23 | 新增: Name string `json:"name"` | |
| 24 | 新增: Input map[string]json.RawMessage `json:"input"` | |
| 25 | 新增: ToolUseID string `json:"tool_use_id"` | |
| 26 | 新增: IsError bool `json:"is_error"` | |
| 27 | 新增: } `json:"content"` | |
| 28 | 新增: } `json:"message"` | |
| 29 | 新增: } | |
| 30 | 新增: if json.Unmarshal(line, &msg) != nil { | |
| 31 | 新增: return tools, false | |
| 32 | 新增: } | |
| 33 | 新增: changed := false | |
| 34 | 新增: for _, b := range msg.Message.Content { | |
| 35 | 新增: if role == "user" && b.Type == "tool_result" { | |
| 36 | 新增: for i := range tools { | |
| 37 | 新增: if tools[i].ID == b.ToolUseID && tools[i].Status == "called" { | |
| 38 | 新增: tools[i].Status = "completed" | |
| 39 | 新增: if b.IsError { | |
| 40 | 新增: tools[i].Status = "failed" | |
| 41 | 新增: } | |
| 42 | 新增: changed = true | |
| 43 | 新增: break | |
| 44 | 新增: } | |
| 45 | 新增: } | |
| 46 | 新增: } | |
| 47 | 新增: if role != "assistant" || (b.Type != "tool_use" && b.Type != "server_tool_use") || !toolNamePattern.MatchString(b.Name) || b.ID == "" || len(b.ID) > 128 || len(tools) >= 64 { | |
| 48 | 新增: continue | |
| 49 | 新增: } | |
| 50 | 新增: duplicate := false | |
| 51 | 新增: for _, item := range tools { | |
| 52 | 新增: if item.ID == b.ID { | |
| 53 | 新增: duplicate = true | |
| 54 | 新增: break | |
| 55 | 新增: } | |
| 56 | 新增: } | |
| 57 | 新增: if duplicate { | |
| 58 | 新增: continue | |
| 59 | 新增: } | |
| 60 | 新增: detail := "" | |
| 61 | 新增: for _, key := range []string{"description", "subject", "file_path", "pattern", "query", "skill", "subagent_type"} { | |
| 62 | 新增: var value string | |
| 63 | 新增: if json.Unmarshal(b.Input[key], &value) == nil && strings.TrimSpace(value) != "" { | |
| 64 | 新增: runes := []rune(strings.TrimSpace(value)) | |
| 65 | 新增: detail = string(runes[:min(len(runes), 160)]) | |
| 66 | 新增: break | |
| 67 | 新增: } | |
| 68 | 新增: } | |
| 69 | 新增: tools = append(tools, ToolActivity{ID: b.ID, Name: b.Name, Detail: detail, Status: "called"}) | |
| 70 | 新增: changed = true | |
| 71 | 新增: } | |
| 72 | 新增: return tools, changed | |
| 73 | 新增:} | |
| @@ -0,0 +1,338 @@ | ||
| 1 | 新增:// Package cliconversation runs a structured Claude Code turn inside an environment | |
| 2 | 新增:// chosen by the caller. It does not select a host, grant a project, or own sessions. | |
| 3 | 新增:package cliconversation | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bufio" | |
| 7 | 新增: "bytes" | |
| 8 | 新增: "context" | |
| 9 | 新增: "encoding/json" | |
| 10 | 新增: "errors" | |
| 11 | 新增: "io" | |
| 12 | 新增: "os/exec" | |
| 13 | 新增: "regexp" | |
| 14 | 新增: "slices" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "time" | |
| 17 | 新增: "unicode/utf8" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:type Runner struct { | |
| 21 | 新增: // Command must bind the supplied context to the guest process and select the | |
| 22 | 新增: // authorized project and CLI profile. Args never contain the user's prompt. | |
| 23 | 新增: Command func(context.Context, string, []string) (*exec.Cmd, error) | |
| 24 | 新增: // Approve returns a decision for this specific call. It must return when | |
| 25 | 新增: // its context is cancelled. Nil selects unattended permission denial. | |
| 26 | 新增: Approve func(context.Context, PermissionRequest) bool | |
| 27 | 新增: // A guest supervisor reads a JSON string on the first line, forwards the | |
| 28 | 新增: // decoded prompt to Claude's stdin, then monitors this pipe for disconnect. | |
| 29 | 新增: SupervisedStdin bool | |
| 30 | 新增: OnTools func([]ToolActivity) | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:type Turn struct { | |
| 34 | 新增: Workspace string | |
| 35 | 新增: SessionID string | |
| 36 | 新增: Prompt string | |
| 37 | 新增: Resume bool | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:type Result struct { | |
| 41 | 新增: Started bool | |
| 42 | 新增: SingleTurn bool | |
| 43 | 新增: Text string | |
| 44 | 新增: DeniedTools []string | |
| 45 | 新增:} | |
| 46 | 新增: | |
| 47 | 新增:var ( | |
| 48 | 新增: sessionIDPattern = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$") | |
| 49 | 新增: toolNamePattern = regexp.MustCompile("^[a-zA-Z0-9_.:-]{1,128}$") | |
| 50 | 新增:) | |
| 51 | 新增: | |
| 52 | 新增:const ( | |
| 53 | 新增: maxPromptBytes = 64 << 10 | |
| 54 | 新增: maxEventBytes = 8 << 20 | |
| 55 | 新增: maxTextBytes = 1 << 20 | |
| 56 | 新增:) | |
| 57 | 新增: | |
| 58 | 新增:// Run emits assistant text deltas in order. Only a successful CLI result and | |
| 59 | 新增:// process exit complete a turn. A caller must not retry an ambiguous failure | |
| 60 | 新增:// automatically: the CLI can persist the user's message before emitting its result. | |
| 61 | 新增:func (r Runner) Run(ctx context.Context, turn Turn, onText func(string)) (Result, error) { | |
| 62 | 新增: if r.Command == nil { | |
| 63 | 新增: return Result{}, errors.New("尚未配置 Cage 客机 Claude Code 命令") | |
| 64 | 新增: } | |
| 65 | 新增: if turn.Workspace == "" || !sessionIDPattern.MatchString(turn.SessionID) { | |
| 66 | 新增: return Result{}, errors.New("Claude Code 项目或会话标识无效") | |
| 67 | 新增: } | |
| 68 | 新增: if len(turn.Prompt) > maxPromptBytes || !utf8.ValidString(turn.Prompt) || strings.TrimSpace(turn.Prompt) == "" { | |
| 69 | 新增: return Result{}, errors.New("消息为空、编码无效或超过 64 KiB") | |
| 70 | 新增: } | |
| 71 | 新增: if err := ctx.Err(); err != nil { | |
| 72 | 新增: return Result{}, err | |
| 73 | 新增: } | |
| 74 | 新增: // Keep the selected guest account's authentication and explicit user rules. | |
| 75 | 新增: // A checked-out project must not add an allow rule or a startup hook simply | |
| 76 | 新增: // because a paired phone starts a non-interactive turn in that directory. | |
| 77 | 新增: args := []string{"--print", "--output-format", "stream-json", "--verbose", | |
| 78 | 新增: "--include-partial-messages", "--safe-mode", "--setting-sources", "user", | |
| 79 | 新增: "--disable-slash-commands"} | |
| 80 | 新增: if r.Approve != nil { | |
| 81 | 新增: args = append(args, "--input-format", "stream-json", "--permission-mode", "manual", | |
| 82 | 新增: "--permission-prompts", "host", "--permission-prompt-tool", "stdio") | |
| 83 | 新增: } else { | |
| 84 | 新增: args = append(args, "--input-format", "text", "--permission-mode", "dontAsk") | |
| 85 | 新增: } | |
| 86 | 新增: if turn.Resume { | |
| 87 | 新增: args = append(args, "--resume", turn.SessionID) | |
| 88 | 新增: } else { | |
| 89 | 新增: args = append(args, "--session-id", turn.SessionID) | |
| 90 | 新增: } | |
| 91 | 新增: | |
| 92 | 新增: runCtx, cancel := context.WithCancel(ctx) | |
| 93 | 新增: defer cancel() | |
| 94 | 新增: cmd, err := r.Command(runCtx, turn.Workspace, args) | |
| 95 | 新增: if err != nil { | |
| 96 | 新增: return Result{}, err | |
| 97 | 新增: } | |
| 98 | 新增: if cmd == nil { | |
| 99 | 新增: return Result{}, errors.New("无法准备 Claude Code 客机命令") | |
| 100 | 新增: } | |
| 101 | 新增: var input io.WriteCloser | |
| 102 | 新增: if r.SupervisedStdin || r.Approve != nil { | |
| 103 | 新增: input, err = cmd.StdinPipe() | |
| 104 | 新增: if err != nil { | |
| 105 | 新增: return Result{}, errors.New("无法准备 Claude Code 客机输入") | |
| 106 | 新增: } | |
| 107 | 新增: defer input.Close() | |
| 108 | 新增: } else { | |
| 109 | 新增: cmd.Stdin = strings.NewReader(turn.Prompt) | |
| 110 | 新增: } | |
| 111 | 新增: reader, writer := io.Pipe() | |
| 112 | 新增: cmd.Stdout = writer | |
| 113 | 新增: // Raw stderr and system/tool events can contain account details, environment | |
| 114 | 新增: // paths and tool arguments. Only selected display fields enter the mobile protocol. | |
| 115 | 新增: cmd.Stderr = io.Discard | |
| 116 | 新增: cmd.WaitDelay = 2 * time.Second | |
| 117 | 新增: if err := cmd.Start(); err != nil { | |
| 118 | 新增: _ = reader.Close() | |
| 119 | 新增: _ = writer.Close() | |
| 120 | 新增: if err := ctx.Err(); err != nil { | |
| 121 | 新增: return Result{}, err | |
| 122 | 新增: } | |
| 123 | 新增: return Result{}, errors.New("无法启动 Claude Code 客机连接") | |
| 124 | 新增: } | |
| 125 | 新增: if input != nil { | |
| 126 | 新增: stop := context.AfterFunc(runCtx, func() { _ = input.Close() }) | |
| 127 | 新增: defer stop() | |
| 128 | 新增: } | |
| 129 | 新增: done := make(chan error, 1) | |
| 130 | 新增: go func() { | |
| 131 | 新增: err := cmd.Wait() | |
| 132 | 新增: _ = writer.Close() | |
| 133 | 新增: done <- err | |
| 134 | 新增: }() | |
| 135 | 新增: var approvals *approvalStream | |
| 136 | 新增: if r.Approve != nil { | |
| 137 | 新增: approvals = &approvalStream{ctx: runCtx, cancel: cancel, input: input, supervised: r.SupervisedStdin, | |
| 138 | 新增: turn: turn, approve: r.Approve, pending: make(map[string]context.CancelFunc), seen: make(map[string]bool)} | |
| 139 | 新增: startup := time.AfterFunc(time.Minute, approvals.expireInitialization) | |
| 140 | 新增: defer startup.Stop() | |
| 141 | 新增: err = approvals.begin() | |
| 142 | 新增: } else if input != nil { | |
| 143 | 新增: // Send concurrently with reading: either side can fill its OS pipe | |
| 144 | 新增: // during startup. The supervisor keeps this stream open until exit. | |
| 145 | 新增: sent := make(chan struct{}) | |
| 146 | 新增: go func() { | |
| 147 | 新增: defer close(sent) | |
| 148 | 新增: if err := json.NewEncoder(input).Encode(turn.Prompt); err != nil { | |
| 149 | 新增: cancel() | |
| 150 | 新增: } | |
| 151 | 新增: }() | |
| 152 | 新增: defer func() { _ = input.Close(); <-sent }() | |
| 153 | 新增: } | |
| 154 | 新增: var result Result | |
| 155 | 新增: if err == nil { | |
| 156 | 新增: result, err = readResult(reader, turn.SessionID, onText, approvals, r.OnTools) | |
| 157 | 新增: } | |
| 158 | 新增: if err != nil { | |
| 159 | 新增: cancel() | |
| 160 | 新增: } | |
| 161 | 新增: _ = reader.Close() | |
| 162 | 新增: processErr := <-done | |
| 163 | 新增: // There may still be a pending phone decision when the child exits or | |
| 164 | 新增: // closes its output unexpectedly. Stop it before returning the turn. | |
| 165 | 新增: cancel() | |
| 166 | 新增: if approvals != nil { | |
| 167 | 新增: approvals.workers.Wait() | |
| 168 | 新增: } | |
| 169 | 新增: if err := ctx.Err(); err != nil { | |
| 170 | 新增: return result, err | |
| 171 | 新增: } | |
| 172 | 新增: if approvals != nil { | |
| 173 | 新增: if transportErr := approvals.failure(); transportErr != nil { | |
| 174 | 新增: return result, transportErr | |
| 175 | 新增: } | |
| 176 | 新增: } | |
| 177 | 新增: if err != nil { | |
| 178 | 新增: return result, err | |
| 179 | 新增: } | |
| 180 | 新增: if processErr != nil { | |
| 181 | 新增: return result, errors.New("Claude Code 进程退出异常,请检查客机连接、CLI 版本和登录状态") | |
| 182 | 新增: } | |
| 183 | 新增: return result, nil | |
| 184 | 新增:} | |
| 185 | 新增: | |
| 186 | 新增:type cliEvent struct { | |
| 187 | 新增: Type string `json:"type"` | |
| 188 | 新增: Subtype string `json:"subtype"` | |
| 189 | 新增: SessionID string `json:"session_id"` | |
| 190 | 新增: ParentToolUseID *string `json:"parent_tool_use_id"` | |
| 191 | 新增:} | |
| 192 | 新增: | |
| 193 | 新增:type resultEvent struct { | |
| 194 | 新增: IsError bool `json:"is_error"` | |
| 195 | 新增: Result string `json:"result"` | |
| 196 | 新增: PermissionDenials []struct { | |
| 197 | 新增: ToolName string `json:"tool_name"` | |
| 198 | 新增: } `json:"permission_denials"` | |
| 199 | 新增:} | |
| 200 | 新增: | |
| 201 | 新增:type streamEvent struct { | |
| 202 | 新增: Event struct { | |
| 203 | 新增: Type string `json:"type"` | |
| 204 | 新增: Delta struct { | |
| 205 | 新增: Type string `json:"type"` | |
| 206 | 新增: Text string `json:"text"` | |
| 207 | 新增: } `json:"delta"` | |
| 208 | 新增: } `json:"event"` | |
| 209 | 新增:} | |
| 210 | 新增: | |
| 211 | 新增:func readResult(reader io.Reader, sessionID string, onText func(string), approvals *approvalStream, onTools func([]ToolActivity)) (Result, error) { | |
| 212 | 新增: var result Result | |
| 213 | 新增: var finished bool | |
| 214 | 新增: var emitted int | |
| 215 | 新增: var tools []ToolActivity | |
| 216 | 新增: scan := bufio.NewScanner(reader) | |
| 217 | 新增: scan.Buffer(make([]byte, 32<<10), maxEventBytes) | |
| 218 | 新增: for scan.Scan() { | |
| 219 | 新增: line := bytes.TrimSpace(scan.Bytes()) | |
| 220 | 新增: if len(line) == 0 { | |
| 221 | 新增: continue | |
| 222 | 新增: } | |
| 223 | 新增: var e cliEvent | |
| 224 | 新增: if err := json.Unmarshal(line, &e); err != nil || e.Type == "" { | |
| 225 | 新增: if approvals != nil && !approvals.ready { | |
| 226 | 新增: return result, errors.New("客机 Claude Code 未返回逐次审批初始化消息,请检查 CLI 版本") | |
| 227 | 新增: } | |
| 228 | 新增: return result, errors.New("Claude Code 返回了无效的消息格式") | |
| 229 | 新增: } | |
| 230 | 新增: if e.Type == "control_request" || e.Type == "control_cancel_request" || e.Type == "control_response" { | |
| 231 | 新增: if approvals == nil { | |
| 232 | 新增: return result, errors.New("Claude Code 需要未配置的交互式审批") | |
| 233 | 新增: } | |
| 234 | 新增: if e.SessionID != "" && !strings.EqualFold(e.SessionID, sessionID) { | |
| 235 | 新增: return result, errors.New("Claude Code 审批会话不匹配") | |
| 236 | 新增: } | |
| 237 | 新增: if err := approvals.control(e.Type, line); err != nil { | |
| 238 | 新增: return result, err | |
| 239 | 新增: } | |
| 240 | 新增: continue | |
| 241 | 新增: } | |
| 242 | 新增: if e.ParentToolUseID != nil { | |
| 243 | 新增: continue | |
| 244 | 新增: } | |
| 245 | 新增: if e.Type == "system" && e.Subtype == "cage_identity_changed" { | |
| 246 | 新增: return result, errors.New("会话使用的账号、凭据或上游已变化,请恢复原配置或新建会话") | |
| 247 | 新增: } | |
| 248 | 新增: if e.Type == "system" && e.Subtype == "cage_identity_single_turn" { | |
| 249 | 新增: result.SingleTurn = true | |
| 250 | 新增: continue | |
| 251 | 新增: } | |
| 252 | 新增: if e.Type == "system" && e.Subtype == "cage_identity_unverified" { | |
| 253 | 新增: return result, errors.New("无法验证本会话原先使用的上游,请检查主机配置或新建会话") | |
| 254 | 新增: } | |
| 255 | 新增: if e.Type == "system" && e.Subtype == "cage_identity_unverified_start" { | |
| 256 | 新增: return result, errors.New("无法验证当前 Claude 账号或上游配置,请在电脑 Cage 检查账号和环境配置") | |
| 257 | 新增: } | |
| 258 | 新增: if e.Type == "system" && e.Subtype == "init" { | |
| 259 | 新增: if !strings.EqualFold(e.SessionID, sessionID) || finished { | |
| 260 | 新增: return result, errors.New("Claude Code 初始化了其他会话") | |
| 261 | 新增: } | |
| 262 | 新增: result.Started = true | |
| 263 | 新增: continue | |
| 264 | 新增: } | |
| 265 | 新增: if (e.Type == "assistant" || e.Type == "user") && onTools != nil && !finished && strings.EqualFold(e.SessionID, sessionID) { | |
| 266 | 新增: var changed bool | |
| 267 | 新增: tools, changed = updateTools(tools, e.Type, line) | |
| 268 | 新增: if changed { | |
| 269 | 新增: onTools(slices.Clone(tools)) | |
| 270 | 新增: } | |
| 271 | 新增: } | |
| 272 | 新增: if e.Type != "stream_event" && e.Type != "result" { | |
| 273 | 新增: continue | |
| 274 | 新增: } | |
| 275 | 新增: if !strings.EqualFold(e.SessionID, sessionID) || finished { | |
| 276 | 新增: return result, errors.New("Claude Code 会话标识或结果顺序不匹配") | |
| 277 | 新增: } | |
| 278 | 新增: if e.Type == "stream_event" { | |
| 279 | 新增: var stream streamEvent | |
| 280 | 新增: if err := json.Unmarshal(line, &stream); err != nil { | |
| 281 | 新增: return result, errors.New("Claude Code 文本事件无效") | |
| 282 | 新增: } | |
| 283 | 新增: if stream.Event.Type == "content_block_delta" && stream.Event.Delta.Type == "text_delta" { | |
| 284 | 新增: text := stream.Event.Delta.Text | |
| 285 | 新增: emitted += len(text) | |
| 286 | 新增: if emitted > maxTextBytes { | |
| 287 | 新增: return result, errors.New("Claude Code 回复超过 1 MiB") | |
| 288 | 新增: } | |
| 289 | 新增: if onText != nil && text != "" { | |
| 290 | 新增: onText(text) | |
| 291 | 新增: } | |
| 292 | 新增: } | |
| 293 | 新增: continue | |
| 294 | 新增: } | |
| 295 | 新增: finished = true | |
| 296 | 新增: if approvals != nil { | |
| 297 | 新增: if err := approvals.finish(); err != nil { | |
| 298 | 新增: return result, err | |
| 299 | 新增: } | |
| 300 | 新增: } | |
| 301 | 新增: var final resultEvent | |
| 302 | 新增: if err := json.Unmarshal(line, &final); err != nil { | |
| 303 | 新增: return result, errors.New("Claude Code 返回了无效的最终结果") | |
| 304 | 新增: } | |
| 305 | 新增: for _, denial := range final.PermissionDenials { | |
| 306 | 新增: name := denial.ToolName | |
| 307 | 新增: if !toolNamePattern.MatchString(name) { | |
| 308 | 新增: name = "未知工具" | |
| 309 | 新增: } | |
| 310 | 新增: if !slices.Contains(result.DeniedTools, name) { | |
| 311 | 新增: result.DeniedTools = append(result.DeniedTools, name) | |
| 312 | 新增: } | |
| 313 | 新增: if len(result.DeniedTools) == 64 { | |
| 314 | 新增: break | |
| 315 | 新增: } | |
| 316 | 新增: } | |
| 317 | 新增: if final.IsError || e.Subtype != "success" { | |
| 318 | 新增: return result, errors.New("Claude Code 未完成本轮,请检查客机登录、网络和工具权限") | |
| 319 | 新增: } | |
| 320 | 新增: if !result.Started { | |
| 321 | 新增: return result, errors.New("Claude Code 返回结果前未确认会话") | |
| 322 | 新增: } | |
| 323 | 新增: if len(final.Result) > maxTextBytes { | |
| 324 | 新增: return result, errors.New("Claude Code 回复超过 1 MiB") | |
| 325 | 新增: } | |
| 326 | 新增: result.Text = final.Result | |
| 327 | 新增: } | |
| 328 | 新增: if scan.Err() != nil { | |
| 329 | 新增: return result, errors.New("Claude Code 消息流中断或单条事件过大") | |
| 330 | 新增: } | |
| 331 | 新增: if !finished { | |
| 332 | 新增: if approvals != nil && !approvals.ready { | |
| 333 | 新增: return result, errors.New("客机 Claude Code 未确认逐次审批协议,请检查 CLI 版本") | |
| 334 | 新增: } | |
| 335 | 新增: return result, errors.New("Claude Code 未返回本轮结果,请检查客机连接、CLI 版本和登录状态") | |
| 336 | 新增: } | |
| 337 | 新增: return result, nil | |
| 338 | 新增:} | |
| @@ -0,0 +1,189 @@ | ||
| 1 | 新增:package cliconversation | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "io" | |
| 8 | 新增: "sync" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:// Input is the complete proposed tool input. Approve receives a copy so its | |
| 12 | 新增:// decision cannot change the arguments which are sent back to Claude Code. | |
| 13 | 新增:type PermissionRequest struct { | |
| 14 | 新增: Tool string | |
| 15 | 新增: Input json.RawMessage | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:const maxApprovalBytes = 8 << 10 | |
| 19 | 新增:const initRequestID = "cage-cli-initialize" | |
| 20 | 新增: | |
| 21 | 新增:// Claude Code uses the same bidirectional JSONL control protocol as its Agent | |
| 22 | 新增:// SDK. In supervised mode a second framing layer keeps the guest process lease | |
| 23 | 新增:// open after the CLI's input is closed at the end of a successful turn. | |
| 24 | 新增:type approvalStream struct { | |
| 25 | 新增: ctx context.Context | |
| 26 | 新增: cancel context.CancelFunc | |
| 27 | 新增: input io.WriteCloser | |
| 28 | 新增: supervised bool | |
| 29 | 新增: approve func(context.Context, PermissionRequest) bool | |
| 30 | 新增: turn Turn | |
| 31 | 新增: | |
| 32 | 新增: mu sync.Mutex // Serializes control frames, answers, and end-of-input. | |
| 33 | 新增: ready bool | |
| 34 | 新增: ended bool | |
| 35 | 新增: pending map[string]context.CancelFunc | |
| 36 | 新增: seen map[string]bool | |
| 37 | 新增: workers sync.WaitGroup | |
| 38 | 新增: writeErr error | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:func (p *approvalStream) expireInitialization() { | |
| 42 | 新增: p.mu.Lock() | |
| 43 | 新增: defer p.mu.Unlock() | |
| 44 | 新增: if !p.ready && p.ctx.Err() == nil { | |
| 45 | 新增: p.writeErr = errors.New("客机 Claude Code 未在一分钟内确认逐次审批,请检查 CLI 版本") | |
| 46 | 新增: p.cancel() | |
| 47 | 新增: } | |
| 48 | 新增:} | |
| 49 | 新增: | |
| 50 | 新增:func (p *approvalStream) failure() error { | |
| 51 | 新增: p.mu.Lock() | |
| 52 | 新增: defer p.mu.Unlock() | |
| 53 | 新增: return p.writeErr | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 56 | 新增:func (p *approvalStream) begin() error { | |
| 57 | 新增: p.mu.Lock() | |
| 58 | 新增: defer p.mu.Unlock() | |
| 59 | 新增: if p.supervised { | |
| 60 | 新增: if err := json.NewEncoder(p.input).Encode(map[string]bool{"stream": true}); err != nil { | |
| 61 | 新增: return errors.New("无法开始客机审批通道") | |
| 62 | 新增: } | |
| 63 | 新增: } | |
| 64 | 新增: return p.sendLocked(map[string]any{"type": "control_request", "request_id": initRequestID, | |
| 65 | 新增: "request": map[string]any{"subtype": "initialize", "hooks": map[string]any{}}}) | |
| 66 | 新增:} | |
| 67 | 新增: | |
| 68 | 新增:func (p *approvalStream) sendLocked(frame any) error { | |
| 69 | 新增: if p.supervised { | |
| 70 | 新增: frame = map[string]any{"input": frame} | |
| 71 | 新增: } | |
| 72 | 新增: if err := json.NewEncoder(p.input).Encode(frame); err != nil { | |
| 73 | 新增: p.writeErr = errors.New("Claude Code 审批通道已断开") | |
| 74 | 新增: p.cancel() | |
| 75 | 新增: return p.writeErr | |
| 76 | 新增: } | |
| 77 | 新增: return nil | |
| 78 | 新增:} | |
| 79 | 新增: | |
| 80 | 新增:type controlFrame struct { | |
| 81 | 新增: RequestID string `json:"request_id"` | |
| 82 | 新增: Request struct { | |
| 83 | 新增: Subtype string `json:"subtype"` | |
| 84 | 新增: Tool string `json:"tool_name"` | |
| 85 | 新增: Input json.RawMessage `json:"input"` | |
| 86 | 新增: } `json:"request"` | |
| 87 | 新增: Response struct { | |
| 88 | 新增: Subtype string `json:"subtype"` | |
| 89 | 新增: RequestID string `json:"request_id"` | |
| 90 | 新增: } `json:"response"` | |
| 91 | 新增:} | |
| 92 | 新增: | |
| 93 | 新增:func (p *approvalStream) control(kind string, line []byte) error { | |
| 94 | 新增: var frame controlFrame | |
| 95 | 新增: if err := json.Unmarshal(line, &frame); err != nil { | |
| 96 | 新增: return errors.New("Claude Code 审批消息格式无效") | |
| 97 | 新增: } | |
| 98 | 新增: p.mu.Lock() | |
| 99 | 新增: defer p.mu.Unlock() | |
| 100 | 新增: if p.ended { | |
| 101 | 新增: return nil | |
| 102 | 新增: } | |
| 103 | 新增: if kind == "control_response" { | |
| 104 | 新增: if p.ready || frame.Response.RequestID != initRequestID || frame.Response.Subtype != "success" { | |
| 105 | 新增: return errors.New("客机 Claude Code 无法初始化逐次审批,请检查 CLI 版本") | |
| 106 | 新增: } | |
| 107 | 新增: p.ready = true | |
| 108 | 新增: return p.sendLocked(map[string]any{"type": "user", "session_id": p.turn.SessionID, "parent_tool_use_id": nil, | |
| 109 | 新增: "message": map[string]string{"role": "user", "content": p.turn.Prompt}}) | |
| 110 | 新增: } | |
| 111 | 新增: id := frame.RequestID | |
| 112 | 新增: if id == "" || len(id) > 256 { | |
| 113 | 新增: return errors.New("Claude Code 审批请求标识无效") | |
| 114 | 新增: } | |
| 115 | 新增: if kind == "control_cancel_request" { | |
| 116 | 新增: if cancel := p.pending[id]; cancel != nil { | |
| 117 | 新增: delete(p.pending, id) | |
| 118 | 新增: cancel() | |
| 119 | 新增: } | |
| 120 | 新增: return nil | |
| 121 | 新增: } | |
| 122 | 新增: if !p.ready || p.seen[id] { | |
| 123 | 新增: return errors.New("Claude Code 审批请求重复或未初始化") | |
| 124 | 新增: } | |
| 125 | 新增: if len(p.seen) >= 1024 || len(p.pending) >= 16 { | |
| 126 | 新增: return errors.New("本轮工具请求超出容量,已停止执行") | |
| 127 | 新增: } | |
| 128 | 新增: p.seen[id] = true | |
| 129 | 新增: if frame.Request.Subtype != "can_use_tool" { | |
| 130 | 新增: return p.sendLocked(map[string]any{"type": "control_response", "response": map[string]string{ | |
| 131 | 新增: "subtype": "error", "request_id": id, "error": "Unsupported control request"}}) | |
| 132 | 新增: } | |
| 133 | 新增: request := PermissionRequest{Tool: frame.Request.Tool, Input: frame.Request.Input} | |
| 134 | 新增: // json.Unmarshal validated the complete frame; individual tool inputs must | |
| 135 | 新增: // be objects. An oversized input must never become a truncated approval. | |
| 136 | 新增: if !toolNamePattern.MatchString(request.Tool) || len(request.Input) == 0 || len(request.Input) > maxApprovalBytes || request.Input[0] != '{' { | |
| 137 | 新增: return p.answerLocked(id, false, nil) | |
| 138 | 新增: } | |
| 139 | 新增: ctx, cancel := context.WithCancel(p.ctx) | |
| 140 | 新增: p.pending[id] = cancel | |
| 141 | 新增: p.workers.Add(1) | |
| 142 | 新增: go func() { | |
| 143 | 新增: defer p.workers.Done() | |
| 144 | 新增: defer cancel() | |
| 145 | 新增: allowed := p.approve(ctx, PermissionRequest{Tool: request.Tool, Input: append(json.RawMessage(nil), request.Input...)}) | |
| 146 | 新增: p.mu.Lock() | |
| 147 | 新增: defer p.mu.Unlock() | |
| 148 | 新增: if p.pending[id] == nil || ctx.Err() != nil || p.ended { | |
| 149 | 新增: return | |
| 150 | 新增: } | |
| 151 | 新增: delete(p.pending, id) | |
| 152 | 新增: _ = p.answerLocked(id, allowed, request.Input) | |
| 153 | 新增: }() | |
| 154 | 新增: return nil | |
| 155 | 新增:} | |
| 156 | 新增: | |
| 157 | 新增:func (p *approvalStream) answerLocked(id string, allowed bool, input json.RawMessage) error { | |
| 158 | 新增: answer := map[string]any{"behavior": "deny", "message": "Cage did not approve this tool call."} | |
| 159 | 新增: if allowed { | |
| 160 | 新增: answer = map[string]any{"behavior": "allow", "updatedInput": input} | |
| 161 | 新增: } | |
| 162 | 新增: return p.sendLocked(map[string]any{"type": "control_response", "response": map[string]any{ | |
| 163 | 新增: "subtype": "success", "request_id": id, "response": answer}}) | |
| 164 | 新增:} | |
| 165 | 新增: | |
| 166 | 新增:func (p *approvalStream) finish() error { | |
| 167 | 新增: p.mu.Lock() | |
| 168 | 新增: defer p.mu.Unlock() | |
| 169 | 新增: p.ended = true | |
| 170 | 新增: for _, cancel := range p.pending { | |
| 171 | 新增: cancel() | |
| 172 | 新增: } | |
| 173 | 新增: if !p.ready { | |
| 174 | 新增: return errors.New("客机 Claude Code 未确认逐次审批协议") | |
| 175 | 新增: } | |
| 176 | 新增: if p.writeErr != nil { | |
| 177 | 新增: return p.writeErr | |
| 178 | 新增: } | |
| 179 | 新增: if p.supervised { | |
| 180 | 新增: if err := json.NewEncoder(p.input).Encode(map[string]bool{"finish": true}); err != nil { | |
| 181 | 新增: return errors.New("无法结束 Claude Code 客机输入") | |
| 182 | 新增: } | |
| 183 | 新增: return nil | |
| 184 | 新增: } | |
| 185 | 新增: if err := p.input.Close(); err != nil { | |
| 186 | 新增: return errors.New("无法结束 Claude Code 输入") | |
| 187 | 新增: } | |
| 188 | 新增: return nil | |
| 189 | 新增:} | |
| @@ -0,0 +1,108 @@ | ||
| 1 | 新增:package cliconversation | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "testing" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:type approvalCapture struct{ bytes.Buffer } | |
| 12 | 新增: | |
| 13 | 新增:func (*approvalCapture) Close() error { return nil } | |
| 14 | 新增: | |
| 15 | 新增:func TestDecisionsFollowTheOriginalRequestThroughSupervisor(t *testing.T) { | |
| 16 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 17 | 新增: defer cancel() | |
| 18 | 新增: wire := new(approvalCapture) | |
| 19 | 新增: release := make(chan struct{}) | |
| 20 | 新增: p := &approvalStream{ | |
| 21 | 新增: ctx: ctx, cancel: cancel, input: wire, supervised: true, turn: Turn{SessionID: testSessionID, Prompt: "fixture"}, | |
| 22 | 新增: pending: make(map[string]context.CancelFunc), seen: make(map[string]bool), | |
| 23 | 新增: approve: func(ctx context.Context, r PermissionRequest) bool { | |
| 24 | 新增: var args struct{ Command string } | |
| 25 | 新增: if err := json.Unmarshal(r.Input, &args); err != nil { | |
| 26 | 新增: t.Error(err) | |
| 27 | 新增: return false | |
| 28 | 新增: } | |
| 29 | 新增: switch args.Command { | |
| 30 | 新增: case "first": | |
| 31 | 新增: <-release // A second decision may arrive first. | |
| 32 | 新增: clear(r.Input) | |
| 33 | 新增: return true | |
| 34 | 新增: case "second": | |
| 35 | 新增: return false | |
| 36 | 新增: case "revoked": | |
| 37 | 新增: <-ctx.Done() | |
| 38 | 新增: return true // A late allow after CLI cancellation must have no effect. | |
| 39 | 新增: default: | |
| 40 | 新增: t.Error("oversized input reached the approval UI") | |
| 41 | 新增: return false | |
| 42 | 新增: } | |
| 43 | 新增: }, | |
| 44 | 新增: } | |
| 45 | 新增: if err := p.begin(); err != nil { | |
| 46 | 新增: t.Fatal(err) | |
| 47 | 新增: } | |
| 48 | 新增: if err := p.control("control_response", []byte(`{"response":{"subtype":"success","request_id":"wrong-init"}}`)); err == nil { | |
| 49 | 新增: t.Fatal("accepted an unrelated initialization reply") | |
| 50 | 新增: } | |
| 51 | 新增: if err := p.control("control_response", []byte(`{"response":{"subtype":"success","request_id":"cage-cli-initialize"}}`)); err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: request := func(id, command string) error { | |
| 55 | 新增: line, _ := json.Marshal(map[string]any{"request_id": id, "request": map[string]any{ | |
| 56 | 新增: "subtype": "can_use_tool", "tool_name": "Bash", "input": map[string]string{"command": command}, | |
| 57 | 新增: }}) | |
| 58 | 新增: return p.control("control_request", line) | |
| 59 | 新增: } | |
| 60 | 新增: for id, command := range map[string]string{"one": "first", "two": "second", "old": "revoked", "large": strings.Repeat("x", maxApprovalBytes)} { | |
| 61 | 新增: if err := request(id, command); err != nil { | |
| 62 | 新增: t.Fatal(err) | |
| 63 | 新增: } | |
| 64 | 新增: } | |
| 65 | 新增: if err := request("one", "first"); err == nil { | |
| 66 | 新增: t.Fatal("accepted a duplicate approval ID") | |
| 67 | 新增: } | |
| 68 | 新增: if err := p.control("control_cancel_request", []byte(`{"request_id":"old"}`)); err != nil { | |
| 69 | 新增: t.Fatal(err) | |
| 70 | 新增: } | |
| 71 | 新增: close(release) | |
| 72 | 新增: p.workers.Wait() | |
| 73 | 新增: if err := p.finish(); err != nil { | |
| 74 | 新增: t.Fatal(err) | |
| 75 | 新增: } | |
| 76 | 新增: lines := bytes.Split(bytes.TrimSpace(wire.Bytes()), []byte("\n")) | |
| 77 | 新增: if string(lines[0]) != `{"stream":true}` || string(lines[len(lines)-1]) != `{"finish":true}` { | |
| 78 | 新增: t.Fatal("supervisor did not get explicit stream start and finish") | |
| 79 | 新增: } | |
| 80 | 新增: decisions := map[string]string{} | |
| 81 | 新增: for _, line := range lines[1 : len(lines)-1] { | |
| 82 | 新增: var packet struct { | |
| 83 | 新增: Input struct { | |
| 84 | 新增: Type string `json:"type"` | |
| 85 | 新增: Response struct { | |
| 86 | 新增: ID string `json:"request_id"` | |
| 87 | 新增: Answer struct { | |
| 88 | 新增: Behavior string `json:"behavior"` | |
| 89 | 新增: Updated struct{ Command string } `json:"updatedInput"` | |
| 90 | 新增: } `json:"response"` | |
| 91 | 新增: } `json:"response"` | |
| 92 | 新增: } `json:"input"` | |
| 93 | 新增: } | |
| 94 | 新增: if err := json.Unmarshal(line, &packet); err != nil || packet.Input.Type == "" { | |
| 95 | 新增: t.Fatalf("invalid supervisor input: %s", line) | |
| 96 | 新增: } | |
| 97 | 新增: if packet.Input.Type == "control_response" { | |
| 98 | 新增: response := packet.Input.Response | |
| 99 | 新增: if _, duplicate := decisions[response.ID]; duplicate { | |
| 100 | 新增: t.Fatal("sent two answers for one request") | |
| 101 | 新增: } | |
| 102 | 新增: decisions[response.ID] = response.Answer.Behavior + ":" + response.Answer.Updated.Command | |
| 103 | 新增: } | |
| 104 | 新增: } | |
| 105 | 新增: if len(decisions) != 3 || decisions["one"] != "allow:first" || decisions["two"] != "deny:" || decisions["large"] != "deny:" { | |
| 106 | 新增: t.Errorf("approval crossed requests, accepted a late decision, or changed input: %#v", decisions) | |
| 107 | 新增: } | |
| 108 | 新增:} | |
| @@ -0,0 +1,270 @@ | ||
| 1 | 新增:package cliconversation | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bufio" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "net/http/httptest" | |
| 10 | 新增: "os" | |
| 11 | 新增: "os/exec" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "slices" | |
| 14 | 新增: "strings" | |
| 15 | 新增: "sync/atomic" | |
| 16 | 新增: "testing" | |
| 17 | 新增: "time" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:const testSessionID = "de3ac0b3-1bad-43da-88ab-d86b7af32210" | |
| 21 | 新增: | |
| 22 | 新增:func TestResultRequiresMatchingCompletedSession(t *testing.T) { | |
| 23 | 新增: init := `{"type":"system","subtype":"init","session_id":"` + testSessionID + `"}` + "\n" | |
| 24 | 新增: final := `{"type":"result","subtype":"success","session_id":"` + testSessionID + `","result":"done"}` | |
| 25 | 新增: for _, events := range []string{ | |
| 26 | 新增: `{"type":"assistant","message":{"content":[{"type":"text","text":"partial"}]}}`, | |
| 27 | 新增: strings.Replace(final, testSessionID, "1d2f57e6-64f9-44df-b0b4-43381e33a317", 1), | |
| 28 | 新增: init + final + "\n" + final, | |
| 29 | 新增: `{"type":"result","session_id":"` + testSessionID + `","is_error":true,"result":"private upstream diagnostic"}`, | |
| 30 | 新增: } { | |
| 31 | 新增: _, err := readResult(strings.NewReader(events), testSessionID, nil, nil, nil) | |
| 32 | 新增: if err == nil || strings.Contains(err.Error(), "private") { | |
| 33 | 新增: t.Fatalf("expected a sanitized failure, got %v", err) | |
| 34 | 新增: } | |
| 35 | 新增: } | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func TestIdentityFailureExplainsFirstLaunch(t *testing.T) { | |
| 39 | 新增: result, err := readResult(strings.NewReader(`{"type":"system","subtype":"cage_identity_unverified_start"}`), testSessionID, nil, nil, nil) | |
| 40 | 新增: if result.Started || err == nil || !strings.Contains(err.Error(), "当前 Claude 账号") || strings.Contains(err.Error(), "新建会话") { | |
| 41 | 新增: t.Fatalf("unexpected first-launch failure: %#v %v", result, err) | |
| 42 | 新增: } | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:func TestSupervisedInputKeepsConnectionOpenAfterPrompt(t *testing.T) { | |
| 46 | 新增: const prompt = "a quoted \"argument\"\non another line" | |
| 47 | 新增: if os.Getenv("CAGE_CLI_SUPERVISOR_FIXTURE") == "1" { | |
| 48 | 新增: input := bufio.NewReader(os.Stdin) | |
| 49 | 新增: line, err := input.ReadBytes('\n') | |
| 50 | 新增: var received string | |
| 51 | 新增: if err != nil || json.Unmarshal(line, &received) != nil || received != prompt { | |
| 52 | 新增: os.Exit(2) | |
| 53 | 新增: } | |
| 54 | 新增: closed := make(chan struct{}) | |
| 55 | 新增: go func() { _, _ = input.ReadByte(); close(closed) }() | |
| 56 | 新增: select { | |
| 57 | 新增: case <-closed: | |
| 58 | 新增: os.Exit(3) | |
| 59 | 新增: case <-time.After(70 * time.Millisecond): | |
| 60 | 新增: } | |
| 61 | 新增: fmt.Printf("{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":%q}\n", testSessionID) | |
| 62 | 新增: fmt.Printf("{\"type\":\"result\",\"subtype\":\"success\",\"session_id\":%q,\"result\":\"ok\"}\n", testSessionID) | |
| 63 | 新增: os.Exit(0) | |
| 64 | 新增: } | |
| 65 | 新增: runner := Runner{SupervisedStdin: true, Command: func(ctx context.Context, _ string, _ []string) (*exec.Cmd, error) { | |
| 66 | 新增: cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSupervisedInputKeepsConnectionOpenAfterPrompt$") | |
| 67 | 新增: cmd.Env = append(os.Environ(), "CAGE_CLI_SUPERVISOR_FIXTURE=1") | |
| 68 | 新增: return cmd, nil | |
| 69 | 新增: }} | |
| 70 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) | |
| 71 | 新增: defer cancel() | |
| 72 | 新增: result, err := runner.Run(ctx, Turn{Workspace: t.TempDir(), SessionID: testSessionID, Prompt: prompt}, nil) | |
| 73 | 新增: if err != nil || !result.Started || result.Text != "ok" { | |
| 74 | 新增: t.Fatalf("supervised turn: %#v, %v", result, err) | |
| 75 | 新增: } | |
| 76 | 新增:} | |
| 77 | 新增: | |
| 78 | 新增:func TestCancelStopsRunningProcess(t *testing.T) { | |
| 79 | 新增: if os.Getenv("CAGE_CLI_CANCEL_FIXTURE") == "1" { | |
| 80 | 新增: fmt.Printf("{\"type\":\"stream_event\",\"session_id\":%q,\"event\":{\"type\":\"content_block_delta\",\"delta\":{\"type\":\"text_delta\",\"text\":\"started\"}}}\n", testSessionID) | |
| 81 | 新增: time.Sleep(30 * time.Second) | |
| 82 | 新增: os.Exit(0) | |
| 83 | 新增: } | |
| 84 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) | |
| 85 | 新增: defer cancel() | |
| 86 | 新增: runner := Runner{Command: func(ctx context.Context, _ string, _ []string) (*exec.Cmd, error) { | |
| 87 | 新增: cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestCancelStopsRunningProcess$") | |
| 88 | 新增: cmd.Env = append(os.Environ(), "CAGE_CLI_CANCEL_FIXTURE=1") | |
| 89 | 新增: return cmd, nil | |
| 90 | 新增: }} | |
| 91 | 新增: _, err := runner.Run(ctx, Turn{Workspace: t.TempDir(), SessionID: testSessionID, Prompt: "synthetic"}, func(string) { cancel() }) | |
| 92 | 新增: if err != context.Canceled { | |
| 93 | 新增: t.Fatalf("cancelling a streaming turn returned %v", err) | |
| 94 | 新增: } | |
| 95 | 新增:} | |
| 96 | 新增: | |
| 97 | 新增:// CAGE_TEST_CLAUDE_CLI points to an installed official executable. This test | |
| 98 | 新增:// drives that actual process and its real session files; only its model is a | |
| 99 | 新增:// fixture. Bare mode and an isolated environment keep personal credentials out. | |
| 100 | 新增:func TestRealClaudeCodeWithLocalUpstream(t *testing.T) { | |
| 101 | 新增: binary := os.Getenv("CAGE_TEST_CLAUDE_CLI") | |
| 102 | 新增: if binary == "" { | |
| 103 | 新增: t.Skip("set CAGE_TEST_CLAUDE_CLI to an absolute official Claude Code executable") | |
| 104 | 新增: } | |
| 105 | 新增: if !filepath.IsAbs(binary) { | |
| 106 | 新增: t.Fatal("use an absolute executable path") | |
| 107 | 新增: } | |
| 108 | 新增: home := t.TempDir() | |
| 109 | 新增: project := t.TempDir() | |
| 110 | 新增: forbidden := filepath.Join(project, "would-write.txt") | |
| 111 | 新增: var resumed, denied atomic.Bool | |
| 112 | 新增: upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { | |
| 113 | 新增: if req.URL.Path == "/v1/messages/count_tokens" { | |
| 114 | 新增: w.Header().Set("Content-Type", "application/json") | |
| 115 | 新增: fmt.Fprint(w, `{"input_tokens":64}`) | |
| 116 | 新增: return | |
| 117 | 新增: } | |
| 118 | 新增: if req.URL.Path != "/v1/messages" { | |
| 119 | 新增: http.NotFound(w, req) | |
| 120 | 新增: return | |
| 121 | 新增: } | |
| 122 | 新增: var payload struct { | |
| 123 | 新增: Model string `json:"model"` | |
| 124 | 新增: Messages json.RawMessage `json:"messages"` | |
| 125 | 新增: Stream bool `json:"stream"` | |
| 126 | 新增: } | |
| 127 | 新增: if err := json.NewDecoder(req.Body).Decode(&payload); err != nil || !payload.Stream { | |
| 128 | 新增: http.Error(w, "expected a streaming Messages API request", http.StatusBadRequest) | |
| 129 | 新增: return | |
| 130 | 新增: } | |
| 131 | 新增: history := string(payload.Messages) | |
| 132 | 新增: w.Header().Set("Content-Type", "text/event-stream") | |
| 133 | 新增: event := func(kind string, data any) { | |
| 134 | 新增: body, err := json.Marshal(data) | |
| 135 | 新增: if err != nil { | |
| 136 | 新增: t.Errorf("fixture event: %v", err) | |
| 137 | 新增: return | |
| 138 | 新增: } | |
| 139 | 新增: fmt.Fprintf(w, "event: %s\ndata: %s\n\n", kind, body) | |
| 140 | 新增: w.(http.Flusher).Flush() | |
| 141 | 新增: } | |
| 142 | 新增: event("message_start", map[string]any{"type": "message_start", "message": map[string]any{ | |
| 143 | 新增: "id": "msg_synthetic_cage", "type": "message", "role": "assistant", "model": payload.Model, | |
| 144 | 新增: "content": []any{}, "stop_reason": nil, "stop_sequence": nil, | |
| 145 | 新增: "usage": map[string]int{"input_tokens": 64, "output_tokens": 1}, | |
| 146 | 新增: }}) | |
| 147 | 新增: stop := "end_turn" | |
| 148 | 新增: if strings.Contains(history, "write-fixture") && !strings.Contains(history, `"tool_result"`) { | |
| 149 | 新增: stop = "tool_use" | |
| 150 | 新增: event("content_block_start", map[string]any{"type": "content_block_start", "index": 0, | |
| 151 | 新增: "content_block": map[string]any{"type": "tool_use", "id": "toolu_cage", "name": "Bash", "input": map[string]any{}}}) | |
| 152 | 新增: input, _ := json.Marshal(map[string]string{"command": "printf synthetic > would-write.txt", "description": "Create a synthetic test file"}) | |
| 153 | 新增: event("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, | |
| 154 | 新增: "delta": map[string]string{"type": "input_json_delta", "partial_json": string(input)}}) | |
| 155 | 新增: } else { | |
| 156 | 新增: reply := "first simulated reply" | |
| 157 | 新增: if strings.Contains(history, "resume-fixture") { | |
| 158 | 新增: resumed.Store(strings.Contains(history, "first-fixture") && strings.Contains(history, "first simulated reply")) | |
| 159 | 新增: reply = "second simulated reply" | |
| 160 | 新增: } | |
| 161 | 新增: if strings.Contains(history, "write-fixture") { | |
| 162 | 新增: denied.Store(strings.Contains(history, `"is_error":true`)) | |
| 163 | 新增: if denied.Load() { | |
| 164 | 新增: reply = "simulated denial received" | |
| 165 | 新增: } else { | |
| 166 | 新增: reply = "simulated write completed" | |
| 167 | 新增: } | |
| 168 | 新增: } | |
| 169 | 新增: event("content_block_start", map[string]any{"type": "content_block_start", "index": 0, | |
| 170 | 新增: "content_block": map[string]string{"type": "text", "text": ""}}) | |
| 171 | 新增: event("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, | |
| 172 | 新增: "delta": map[string]string{"type": "text_delta", "text": reply}}) | |
| 173 | 新增: } | |
| 174 | 新增: event("content_block_stop", map[string]any{"type": "content_block_stop", "index": 0}) | |
| 175 | 新增: event("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": stop, "stop_sequence": nil}, | |
| 176 | 新增: "usage": map[string]int{"output_tokens": 5}}) | |
| 177 | 新增: event("message_stop", map[string]string{"type": "message_stop"}) | |
| 178 | 新增: })) | |
| 179 | 新增: defer upstream.Close() | |
| 180 | 新增: supervisor := os.Getenv("CAGE_TEST_CLI_SUPERVISOR") | |
| 181 | 新增: runner := Runner{SupervisedStdin: supervisor != "", Command: func(ctx context.Context, workspace string, args []string) (*exec.Cmd, error) { | |
| 182 | 新增: command := append([]string{binary, "--bare"}, args...) | |
| 183 | 新增: if supervisor != "" { | |
| 184 | 新增: python, err := exec.LookPath("python3") | |
| 185 | 新增: if err != nil { | |
| 186 | 新增: return nil, err | |
| 187 | 新增: } | |
| 188 | 新增: command = append([]string{python, "-I", supervisor, workspace}, command...) | |
| 189 | 新增: } | |
| 190 | 新增: cmd := exec.CommandContext(ctx, command[0], command[1:]...) | |
| 191 | 新增: if supervisor != "" { | |
| 192 | 新增: // Simulate SSH disconnect locally: EOF reaches the real supervisor. | |
| 193 | 新增: // WaitDelay remains a final bound if the supervisor cannot exit. | |
| 194 | 新增: cmd.Cancel = func() error { return nil } | |
| 195 | 新增: } | |
| 196 | 新增: cmd.Dir = workspace | |
| 197 | 新增: cmd.Env = []string{ | |
| 198 | 新增: "HOME=" + home, "USERPROFILE=" + home, "CLAUDE_CONFIG_DIR=" + filepath.Join(home, "config"), | |
| 199 | 新增: "PATH=" + filepath.Dir(binary) + string(os.PathListSeparator) + "/usr/bin" + string(os.PathListSeparator) + "/bin", | |
| 200 | 新增: "ANTHROPIC_BASE_URL=" + upstream.URL, "ANTHROPIC_API_KEY=sk-ant-fixture-only", | |
| 201 | 新增: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", "DISABLE_AUTOUPDATER=1", | |
| 202 | 新增: "HTTPS_PROXY=http://127.0.0.1:1", "HTTP_PROXY=http://127.0.0.1:1", "NO_PROXY=127.0.0.1,localhost", | |
| 203 | 新增: } | |
| 204 | 新增: if systemRoot := os.Getenv("SystemRoot"); systemRoot != "" { | |
| 205 | 新增: cmd.Env = append(cmd.Env, "SystemRoot="+systemRoot) | |
| 206 | 新增: } | |
| 207 | 新增: return cmd, nil | |
| 208 | 新增: }} | |
| 209 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) | |
| 210 | 新增: defer cancel() | |
| 211 | 新增: run := func(id, prompt, want string, resume bool) Result { | |
| 212 | 新增: t.Helper() | |
| 213 | 新增: var live strings.Builder | |
| 214 | 新增: result, err := runner.Run(ctx, Turn{project, id, prompt, resume}, func(delta string) { live.WriteString(delta) }) | |
| 215 | 新增: if err != nil || !result.Started || result.Text != want || live.String() != want { | |
| 216 | 新增: t.Fatalf("turn %s: result=%q live=%q err=%v", prompt, result.Text, live.String(), err) | |
| 217 | 新增: } | |
| 218 | 新增: return result | |
| 219 | 新增: } | |
| 220 | 新增: run(testSessionID, "first-fixture", "first simulated reply", false) | |
| 221 | 新增: run(testSessionID, "resume-fixture", "second simulated reply", true) | |
| 222 | 新增: if !resumed.Load() { | |
| 223 | 新增: t.Fatal("resumed CLI did not send the first exchange to the local provider") | |
| 224 | 新增: } | |
| 225 | 新增: result := run("93b18ece-8eab-4c7e-b970-c3652252b7c4", "write-fixture", "simulated denial received", false) | |
| 226 | 新增: if !denied.Load() || !slices.Contains(result.DeniedTools, "Bash") { | |
| 227 | 新增: t.Fatalf("missing permission denial: upstream observed denial=%t, result=%#v", denied.Load(), result) | |
| 228 | 新增: } | |
| 229 | 新增: if _, err := os.Stat(forbidden); !os.IsNotExist(err) { | |
| 230 | 新增: t.Fatalf("denied tool changed the workspace: %v", err) | |
| 231 | 新增: } | |
| 232 | 新增: var approvals atomic.Int32 | |
| 233 | 新增: answer := func(allow bool) func(context.Context, PermissionRequest) bool { | |
| 234 | 新增: return func(_ context.Context, request PermissionRequest) bool { | |
| 235 | 新增: approvals.Add(1) | |
| 236 | 新增: var proposed struct{ Command string } | |
| 237 | 新增: if request.Tool != "Bash" || json.Unmarshal(request.Input, &proposed) != nil || proposed.Command != "printf synthetic > would-write.txt" { | |
| 238 | 新增: t.Errorf("unexpected approval request: %s, %s", request.Tool, request.Input) | |
| 239 | 新增: return false | |
| 240 | 新增: } | |
| 241 | 新增: if _, err := os.Stat(forbidden); !os.IsNotExist(err) { | |
| 242 | 新增: t.Errorf("command ran before the decision: %v", err) | |
| 243 | 新增: return false | |
| 244 | 新增: } | |
| 245 | 新增: // The approval UI cannot substitute different arguments, even if it | |
| 246 | 新增: // accidentally mutates its raw JSON while preparing a preview. | |
| 247 | 新增: clear(request.Input) | |
| 248 | 新增: return allow | |
| 249 | 新增: } | |
| 250 | 新增: } | |
| 251 | 新增: runner.Approve = answer(false) | |
| 252 | 新增: run("24816c82-cf57-4ec3-b8c0-05dc70614440", "write-fixture", "simulated denial received", false) | |
| 253 | 新增: pending, stop := context.WithCancel(ctx) | |
| 254 | 新增: defer stop() | |
| 255 | 新增: runner.Approve = func(approvalCtx context.Context, _ PermissionRequest) bool { | |
| 256 | 新增: stop() | |
| 257 | 新增: <-approvalCtx.Done() | |
| 258 | 新增: return true | |
| 259 | 新增: } | |
| 260 | 新增: result, err := runner.Run(pending, Turn{project, "0ca69e7b-2661-4b81-b966-f2589547933c", "write-fixture", false}, nil) | |
| 261 | 新增: if err != context.Canceled || !result.Started { | |
| 262 | 新增: t.Fatalf("cancel during pending tool approval: %#v, %v", result, err) | |
| 263 | 新增: } | |
| 264 | 新增: runner.Approve = answer(true) | |
| 265 | 新增: run("8c0d77d3-cb3e-43b2-9114-62cb05c5ebc4", "write-fixture", "simulated write completed", false) | |
| 266 | 新增: bytes, err := os.ReadFile(forbidden) | |
| 267 | 新增: if err != nil || string(bytes) != "synthetic" || approvals.Load() != 2 { | |
| 268 | 新增: t.Fatalf("expected one approved write after exactly two decisions: %q, %v, decisions=%d", bytes, err, approvals.Load()) | |
| 269 | 新增: } | |
| 270 | 新增:} | |
| @@ -0,0 +1,222 @@ | ||
| 1 | 新增:// Package clipboardfiles streams selected ordinary files between guest systems. | |
| 2 | 新增:// It has no host/guest process or authentication policy; callers own the selection. | |
| 3 | 新增:package clipboardfiles | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "archive/tar" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "strings" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:const FileLimit int64 = 2 << 30 | |
| 15 | 新增:const SelectionLimit = 100 | |
| 16 | 新增: | |
| 17 | 新增:// LinkCachedFiles groups already frozen guest-cache files for one native file | |
| 18 | 新增:// chooser without copying every attachment again. GUI callers validate ownership. | |
| 19 | 新增:func LinkCachedFiles(paths []string) (result []string, err error) { | |
| 20 | 新增: if len(paths) == 0 || len(paths) > SelectionLimit { | |
| 21 | 新增: return nil, errors.New("请选择 1 至 100 个文件") | |
| 22 | 新增: } | |
| 23 | 新增: root, err := os.MkdirTemp("", "cage-clipboard-") | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: return nil, err | |
| 26 | 新增: } | |
| 27 | 新增: defer func() { | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: _ = os.RemoveAll(root) | |
| 30 | 新增: } | |
| 31 | 新增: }() | |
| 32 | 新增: for _, source := range paths { | |
| 33 | 新增: name := filepath.Base(source) | |
| 34 | 新增: info, err := os.Lstat(source) | |
| 35 | 新增: if err != nil || !filepath.IsAbs(source) || !strings.HasPrefix(filepath.Base(filepath.Dir(source)), "cage-clipboard-") || !validName(name) || !info.Mode().IsRegular() || info.Size() > FileLimit { | |
| 36 | 新增: return nil, errors.New("附件缓存文件无效") | |
| 37 | 新增: } | |
| 38 | 新增: target := filepath.Join(root, name) | |
| 39 | 新增: if err := os.Link(source, target); err != nil { | |
| 40 | 新增: return nil, errors.New("无法准备附件选择,请核对文件名是否重复") | |
| 41 | 新增: } | |
| 42 | 新增: linked, err := os.Lstat(target) | |
| 43 | 新增: if err != nil || !linked.Mode().IsRegular() || !os.SameFile(info, linked) { | |
| 44 | 新增: return nil, errors.New("附件缓存已变化,请重新选择文件") | |
| 45 | 新增: } | |
| 46 | 新增: result = append(result, target) | |
| 47 | 新增: } | |
| 48 | 新增: return result, nil | |
| 49 | 新增:} | |
| 50 | 新增: | |
| 51 | 新增:// Save receives one file into a newly owned cache directory. The caller can | |
| 52 | 新增:// publish the returned path only after the complete bounded write succeeds. | |
| 53 | 新增:func Save(input io.Reader, name string) (path string, err error) { | |
| 54 | 新增: if !validName(name) || strings.Contains(name, ":") { | |
| 55 | 新增: return "", errors.New("剪贴板文件名称无效") | |
| 56 | 新增: } | |
| 57 | 新增: root, err := os.MkdirTemp("", "cage-clipboard-") | |
| 58 | 新增: if err != nil { | |
| 59 | 新增: return "", err | |
| 60 | 新增: } | |
| 61 | 新增: defer func() { | |
| 62 | 新增: if err != nil { | |
| 63 | 新增: _ = os.RemoveAll(root) | |
| 64 | 新增: } | |
| 65 | 新增: }() | |
| 66 | 新增: path = filepath.Join(root, name) | |
| 67 | 新增: file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) | |
| 68 | 新增: if err != nil { | |
| 69 | 新增: return "", err | |
| 70 | 新增: } | |
| 71 | 新增: count, writeErr := io.Copy(file, io.LimitReader(input, FileLimit+1)) | |
| 72 | 新增: if count > FileLimit { | |
| 73 | 新增: writeErr = errors.New("每个文件不能超过 2 GB") | |
| 74 | 新增: } | |
| 75 | 新增: if writeErr == nil { | |
| 76 | 新增: writeErr = file.Sync() | |
| 77 | 新增: } | |
| 78 | 新增: if err = errors.Join(writeErr, file.Close()); err != nil { | |
| 79 | 新增: return "", err | |
| 80 | 新增: } | |
| 81 | 新增: return path, nil | |
| 82 | 新增:} | |
| 83 | 新增: | |
| 84 | 新增:func validName(name string) bool { | |
| 85 | 新增: return name != "" && len(name) <= 255 && name != "." && name != ".." && !strings.ContainsAny(name, "/\\\x00") && | |
| 86 | 新增: !strings.ContainsFunc(name, func(r rune) bool { return r < 32 || r == 127 }) | |
| 87 | 新增:} | |
| 88 | 新增: | |
| 89 | 新增:func Write(output io.Writer, paths []string) error { | |
| 90 | 新增: if len(paths) == 0 || len(paths) > SelectionLimit { | |
| 91 | 新增: return errors.New("请选择 1 至 100 个文件或文件夹") | |
| 92 | 新增: } | |
| 93 | 新增: writer := tar.NewWriter(output) | |
| 94 | 新增: names := map[string]bool{} | |
| 95 | 新增: for _, selected := range paths { | |
| 96 | 新增: name := filepath.Base(selected) | |
| 97 | 新增: if !filepath.IsAbs(selected) || !validName(name) || names[name] { | |
| 98 | 新增: return errors.New("剪贴板文件名称无效或重复") | |
| 99 | 新增: } | |
| 100 | 新增: names[name] = true | |
| 101 | 新增: err := filepath.Walk(selected, func(path string, info os.FileInfo, err error) error { | |
| 102 | 新增: if err != nil { | |
| 103 | 新增: return errors.New("无法读取所选剪贴板文件") | |
| 104 | 新增: } | |
| 105 | 新增: if !(info.Mode().IsRegular() || info.IsDir()) || info.Size() > FileLimit { | |
| 106 | 新增: return errors.New("剪贴板支持普通文件和文件夹,每个文件最多 2 GB") | |
| 107 | 新增: } | |
| 108 | 新增: relative, err := filepath.Rel(filepath.Dir(selected), path) | |
| 109 | 新增: if err != nil { | |
| 110 | 新增: return err | |
| 111 | 新增: } | |
| 112 | 新增: header, err := tar.FileInfoHeader(info, "") | |
| 113 | 新增: if err != nil { | |
| 114 | 新增: return err | |
| 115 | 新增: } | |
| 116 | 新增: header.Name = filepath.ToSlash(relative) | |
| 117 | 新增: if err := writer.WriteHeader(header); err != nil { | |
| 118 | 新增: return err | |
| 119 | 新增: } | |
| 120 | 新增: if !info.Mode().IsRegular() { | |
| 121 | 新增: return nil | |
| 122 | 新增: } | |
| 123 | 新增: file, err := os.Open(path) | |
| 124 | 新增: if err != nil { | |
| 125 | 新增: return errors.New("无法读取所选剪贴板文件") | |
| 126 | 新增: } | |
| 127 | 新增: defer file.Close() | |
| 128 | 新增: after, err := file.Stat() | |
| 129 | 新增: if err != nil || !os.SameFile(info, after) || after.Size() != info.Size() { | |
| 130 | 新增: return errors.New("文件已变化,请重新复制") | |
| 131 | 新增: } | |
| 132 | 新增: _, err = io.CopyN(writer, file, info.Size()) | |
| 133 | 新增: return err | |
| 134 | 新增: }) | |
| 135 | 新增: if err != nil { | |
| 136 | 新增: return err | |
| 137 | 新增: } | |
| 138 | 新增: } | |
| 139 | 新增: return writer.Close() | |
| 140 | 新增:} | |
| 141 | 新增: | |
| 142 | 新增:func Read(input io.Reader) (paths []string, err error) { | |
| 143 | 新增: root, err := os.MkdirTemp("", "cage-clipboard-") | |
| 144 | 新增: if err != nil { | |
| 145 | 新增: return nil, err | |
| 146 | 新增: } | |
| 147 | 新增: defer func() { | |
| 148 | 新增: if err != nil { | |
| 149 | 新增: _ = os.RemoveAll(root) | |
| 150 | 新增: } | |
| 151 | 新增: }() | |
| 152 | 新增: reader := tar.NewReader(input) | |
| 153 | 新增: names := map[string]bool{} | |
| 154 | 新增: for { | |
| 155 | 新增: header, readErr := reader.Next() | |
| 156 | 新增: if readErr == io.EOF { | |
| 157 | 新增: break | |
| 158 | 新增: } | |
| 159 | 新增: if readErr != nil { | |
| 160 | 新增: return nil, readErr | |
| 161 | 新增: } | |
| 162 | 新增: name := strings.TrimSuffix(header.Name, "/") | |
| 163 | 新增: parts := strings.Split(name, "/") | |
| 164 | 新增: if !filepath.IsLocal(filepath.FromSlash(name)) || header.Size < 0 || header.Size > FileLimit { | |
| 165 | 新增: return nil, errors.New("剪贴板文件位置或大小无效") | |
| 166 | 新增: } | |
| 167 | 新增: for _, part := range parts { | |
| 168 | 新增: if !validName(part) || strings.Contains(part, ":") { | |
| 169 | 新增: return nil, errors.New("剪贴板文件名称无效") | |
| 170 | 新增: } | |
| 171 | 新增: } | |
| 172 | 新增: if !names[parts[0]] { | |
| 173 | 新增: names[parts[0]] = true | |
| 174 | 新增: paths = append(paths, filepath.Join(root, parts[0])) | |
| 175 | 新增: if len(paths) > SelectionLimit { | |
| 176 | 新增: return nil, errors.New("剪贴板文件数量超过 100 个") | |
| 177 | 新增: } | |
| 178 | 新增: } | |
| 179 | 新增: destination := filepath.Join(root, filepath.FromSlash(name)) | |
| 180 | 新增: if err = os.MkdirAll(filepath.Dir(destination), 0700); err != nil { | |
| 181 | 新增: return nil, err | |
| 182 | 新增: } | |
| 183 | 新增: switch header.Typeflag { | |
| 184 | 新增: case tar.TypeDir: | |
| 185 | 新增: if err = os.MkdirAll(destination, 0700); err != nil { | |
| 186 | 新增: return nil, err | |
| 187 | 新增: } | |
| 188 | 新增: case tar.TypeReg, tar.TypeRegA: | |
| 189 | 新增: file, createErr := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_EXCL, os.FileMode(header.Mode)&0700|0600) | |
| 190 | 新增: if createErr != nil { | |
| 191 | 新增: return nil, createErr | |
| 192 | 新增: } | |
| 193 | 新增: _, copyErr := io.CopyN(file, reader, header.Size) | |
| 194 | 新增: closeErr := file.Close() | |
| 195 | 新增: if copyErr != nil || closeErr != nil { | |
| 196 | 新增: return nil, errors.Join(copyErr, closeErr) | |
| 197 | 新增: } | |
| 198 | 新增: default: | |
| 199 | 新增: return nil, errors.New("剪贴板不支持链接或特殊文件") | |
| 200 | 新增: } | |
| 201 | 新增: } | |
| 202 | 新增: if len(paths) == 0 { | |
| 203 | 新增: return nil, errors.New("剪贴板文件为空") | |
| 204 | 新增: } | |
| 205 | 新增: return paths, nil | |
| 206 | 新增:} | |
| 207 | 新增: | |
| 208 | 新增:func Copy(paths []string) ([]string, error) { | |
| 209 | 新增: reader, writer := io.Pipe() | |
| 210 | 新增: defer reader.Close() | |
| 211 | 新增: done := make(chan error, 1) | |
| 212 | 新增: go func() { err := Write(writer, paths); writer.CloseWithError(err); done <- err }() | |
| 213 | 新增: copied, err := Read(reader) | |
| 214 | 新增: reader.Close() | |
| 215 | 新增: if writeErr := <-done; writeErr != nil { | |
| 216 | 新增: if len(copied) > 0 { | |
| 217 | 新增: _ = os.RemoveAll(filepath.Dir(copied[0])) | |
| 218 | 新增: } | |
| 219 | 新增: return nil, writeErr | |
| 220 | 新增: } | |
| 221 | 新增: return copied, err | |
| 222 | 新增:} | |
| @@ -0,0 +1,230 @@ | ||
| 1 | 新增:package clipboardfiles | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/rand" | |
| 5 | 新增: "encoding/hex" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "strings" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:// CachedSelection records a directory created by a successful receive or copy. | |
| 16 | 新增:// The identifier is private to the native clipboard owner. | |
| 17 | 新增:type CachedSelection struct { | |
| 18 | 新增: ID string `json:"cache_id"` | |
| 19 | 新增: Paths []string `json:"paths"` | |
| 20 | 新增:} | |
| 21 | 新增: | |
| 22 | 新增:type cacheRecord struct { | |
| 23 | 新增: CachedSelection | |
| 24 | 新增: Directory string `json:"directory"` | |
| 25 | 新增: Marker string `json:"marker"` | |
| 26 | 新增: Owner int `json:"owner"` | |
| 27 | 新增: Published bool `json:"published"` | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:type CacheStore struct{ Directory string } | |
| 31 | 新增: | |
| 32 | 新增:type CacheRequest struct { | |
| 33 | 新增: Action string `json:"action"` | |
| 34 | 新增: ID string `json:"cache_id,omitempty"` | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:func (store CacheStore) Control(request CacheRequest) (map[string]any, error) { | |
| 38 | 新增: if request.Action == "list" { | |
| 39 | 新增: selections, err := store.List() | |
| 40 | 新增: return map[string]any{"selections": selections}, err | |
| 41 | 新增: } | |
| 42 | 新增: var err error | |
| 43 | 新增: switch request.Action { | |
| 44 | 新增: case "publish": | |
| 45 | 新增: err = store.Publish(request.ID) | |
| 46 | 新增: case "release": | |
| 47 | 新增: err = store.Release(request.ID) | |
| 48 | 新增: default: | |
| 49 | 新增: err = errors.New("invalid clipboard cache operation") | |
| 50 | 新增: } | |
| 51 | 新增: return map[string]any{"ok": err == nil}, err | |
| 52 | 新增:} | |
| 53 | 新增: | |
| 54 | 新增:func (store CacheStore) recordPath(id string) (string, error) { | |
| 55 | 新增: if decoded, err := hex.DecodeString(id); err != nil || len(decoded) != 16 { | |
| 56 | 新增: return "", errors.New("invalid clipboard cache identity") | |
| 57 | 新增: } | |
| 58 | 新增: return filepath.Join(store.Directory, id+".json"), nil | |
| 59 | 新增:} | |
| 60 | 新增: | |
| 61 | 新增:// Register takes ownership only of a directory just returned by Read, Copy, | |
| 62 | 新增:// Save or LinkCachedFiles. Existing user selections never enter this method. | |
| 63 | 新增:func (store CacheStore) Register(paths []string) (CachedSelection, error) { | |
| 64 | 新增: var empty CachedSelection | |
| 65 | 新增: if len(paths) == 0 || len(paths) > SelectionLimit { | |
| 66 | 新增: return empty, errors.New("invalid clipboard cache selection") | |
| 67 | 新增: } | |
| 68 | 新增: directory := filepath.Dir(paths[0]) | |
| 69 | 新增: for _, path := range paths { | |
| 70 | 新增: if !filepath.IsAbs(path) || filepath.Clean(path) != path || filepath.Dir(path) != directory { | |
| 71 | 新增: return empty, errors.New("invalid clipboard cache directory") | |
| 72 | 新增: } | |
| 73 | 新增: } | |
| 74 | 新增: if err := host.EnsurePrivateDir(store.Directory); err != nil { | |
| 75 | 新增: return empty, err | |
| 76 | 新增: } | |
| 77 | 新增: var token [16]byte | |
| 78 | 新增: if _, err := rand.Read(token[:]); err != nil { | |
| 79 | 新增: return empty, err | |
| 80 | 新增: } | |
| 81 | 新增: selection := CachedSelection{ID: hex.EncodeToString(token[:]), Paths: append([]string(nil), paths...)} | |
| 82 | 新增: marker, err := os.CreateTemp(directory, ".cage-clipboard-owner-") | |
| 83 | 新增: if err != nil { | |
| 84 | 新增: return empty, err | |
| 85 | 新增: } | |
| 86 | 新增: _, writeErr := marker.WriteString(selection.ID) | |
| 87 | 新增: err = errors.Join(writeErr, marker.Close()) | |
| 88 | 新增: if err != nil { | |
| 89 | 新增: _ = os.Remove(marker.Name()) | |
| 90 | 新增: return empty, err | |
| 91 | 新增: } | |
| 92 | 新增: record := cacheRecord{CachedSelection: selection, Directory: directory, Marker: filepath.Base(marker.Name()), Owner: os.Getppid()} | |
| 93 | 新增: if err := store.save(record); err != nil { | |
| 94 | 新增: _ = os.Remove(marker.Name()) | |
| 95 | 新增: return empty, err | |
| 96 | 新增: } | |
| 97 | 新增: return selection, nil | |
| 98 | 新增:} | |
| 99 | 新增: | |
| 100 | 新增:func (store CacheStore) save(record cacheRecord) error { | |
| 101 | 新增: path, err := store.recordPath(record.ID) | |
| 102 | 新增: if err != nil { | |
| 103 | 新增: return err | |
| 104 | 新增: } | |
| 105 | 新增: file, err := os.CreateTemp(store.Directory, ".clipboard-record-") | |
| 106 | 新增: if err != nil { | |
| 107 | 新增: return err | |
| 108 | 新增: } | |
| 109 | 新增: defer os.Remove(file.Name()) | |
| 110 | 新增: if err := json.NewEncoder(file).Encode(record); err != nil { | |
| 111 | 新增: _ = file.Close() | |
| 112 | 新增: return err | |
| 113 | 新增: } | |
| 114 | 新增: if err := file.Close(); err != nil { | |
| 115 | 新增: return err | |
| 116 | 新增: } | |
| 117 | 新增: return os.Rename(file.Name(), path) | |
| 118 | 新增:} | |
| 119 | 新增: | |
| 120 | 新增:func (store CacheStore) load(id string) (cacheRecord, error) { | |
| 121 | 新增: var record cacheRecord | |
| 122 | 新增: path, err := store.recordPath(id) | |
| 123 | 新增: if err != nil { | |
| 124 | 新增: return record, err | |
| 125 | 新增: } | |
| 126 | 新增: data, err := os.ReadFile(path) | |
| 127 | 新增: if err != nil { | |
| 128 | 新增: return record, err | |
| 129 | 新增: } | |
| 130 | 新增: if json.Unmarshal(data, &record) != nil || record.ID != id || len(record.Paths) == 0 || | |
| 131 | 新增: !filepath.IsAbs(record.Directory) || filepath.Clean(record.Directory) != record.Directory || | |
| 132 | 新增: !validName(record.Marker) || record.Owner < 1 { | |
| 133 | 新增: return record, errors.New("invalid clipboard cache record") | |
| 134 | 新增: } | |
| 135 | 新增: for _, path := range record.Paths { | |
| 136 | 新增: if filepath.Dir(path) != record.Directory || filepath.Clean(path) != path { | |
| 137 | 新增: return record, errors.New("invalid clipboard cache paths") | |
| 138 | 新增: } | |
| 139 | 新增: } | |
| 140 | 新增: return record, nil | |
| 141 | 新增:} | |
| 142 | 新增: | |
| 143 | 新增:func (store CacheStore) Publish(id string) error { | |
| 144 | 新增: record, err := store.load(id) | |
| 145 | 新增: if err != nil { | |
| 146 | 新增: return err | |
| 147 | 新增: } | |
| 148 | 新增: record.Published = true | |
| 149 | 新增: return store.save(record) | |
| 150 | 新增:} | |
| 151 | 新增: | |
| 152 | 新增:// List recovers published copies and abandoned receives from their creation | |
| 153 | 新增:// records. A live native owner retains admission for its unpublished transfers. | |
| 154 | 新增:func (store CacheStore) List() ([]CachedSelection, error) { | |
| 155 | 新增: entries, err := os.ReadDir(store.Directory) | |
| 156 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 157 | 新增: return []CachedSelection{}, nil | |
| 158 | 新增: } | |
| 159 | 新增: if err != nil { | |
| 160 | 新增: return nil, err | |
| 161 | 新增: } | |
| 162 | 新增: selections := []CachedSelection{} | |
| 163 | 新增: for _, entry := range entries { | |
| 164 | 新增: if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") { | |
| 165 | 新增: continue | |
| 166 | 新增: } | |
| 167 | 新增: record, err := store.load(strings.TrimSuffix(entry.Name(), ".json")) | |
| 168 | 新增: if err != nil { | |
| 169 | 新增: return nil, err | |
| 170 | 新增: } | |
| 171 | 新增: if record.Published || !cacheOwnerAlive(record.Owner) { | |
| 172 | 新增: selections = append(selections, record.CachedSelection) | |
| 173 | 新增: } | |
| 174 | 新增: } | |
| 175 | 新增: return selections, nil | |
| 176 | 新增:} | |
| 177 | 新增: | |
| 178 | 新增:// Release runs after the native owner has checked the current OS selection and | |
| 179 | 新增:// its in-flight readers. A Windows sharing violation keeps the receipt for retry. | |
| 180 | 新增:func (store CacheStore) Release(id string) error { | |
| 181 | 新增: record, err := store.load(id) | |
| 182 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 183 | 新增: return nil | |
| 184 | 新增: } | |
| 185 | 新增: if err != nil { | |
| 186 | 新增: return err | |
| 187 | 新增: } | |
| 188 | 新增: path, _ := store.recordPath(id) | |
| 189 | 新增: root, err := os.OpenRoot(record.Directory) | |
| 190 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 191 | 新增: return os.Remove(path) | |
| 192 | 新增: } | |
| 193 | 新增: if err != nil { | |
| 194 | 新增: return err | |
| 195 | 新增: } | |
| 196 | 新增: defer root.Close() | |
| 197 | 新增: marker, err := root.ReadFile(record.Marker) | |
| 198 | 新增: if err != nil || string(marker) != id { | |
| 199 | 新增: return errors.New("clipboard cache creation record no longer matches") | |
| 200 | 新增: } | |
| 201 | 新增: directory, err := root.Open(".") | |
| 202 | 新增: if err != nil { | |
| 203 | 新增: return err | |
| 204 | 新增: } | |
| 205 | 新增: entries, readErr := directory.ReadDir(-1) | |
| 206 | 新增: err = errors.Join(readErr, directory.Close()) | |
| 207 | 新增: if err != nil { | |
| 208 | 新增: return err | |
| 209 | 新增: } | |
| 210 | 新增: for _, entry := range entries { | |
| 211 | 新增: if entry.Name() != record.Marker { | |
| 212 | 新增: if err := root.RemoveAll(entry.Name()); err != nil { | |
| 213 | 新增: return err | |
| 214 | 新增: } | |
| 215 | 新增: } | |
| 216 | 新增: } | |
| 217 | 新增: if err := root.Remove(record.Marker); err != nil { | |
| 218 | 新增: return err | |
| 219 | 新增: } | |
| 220 | 新增: if err := os.Remove(record.Directory); err != nil { | |
| 221 | 新增: // A busy directory must retain its proof of ownership for a later retry. | |
| 222 | 新增: return errors.Join(err, root.WriteFile(record.Marker, []byte(id), 0600)) | |
| 223 | 新增: } | |
| 224 | 新增: return os.Remove(path) | |
| 225 | 新增:} | |
| 226 | 新增: | |
| 227 | 新增:func UserCacheStore() (CacheStore, error) { | |
| 228 | 新增: directory, err := os.UserCacheDir() | |
| 229 | 新增: return CacheStore{Directory: filepath.Join(directory, "cage", "clipboard-ownership")}, err | |
| 230 | 新增:} | |
| @@ -0,0 +1,101 @@ | ||
| 1 | 新增:package clipboardfiles | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "strings" | |
| 7 | 新增: "testing" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func cacheFixture(t *testing.T) (CacheStore, CachedSelection) { | |
| 11 | 新增: t.Helper() | |
| 12 | 新增: directory := t.TempDir() | |
| 13 | 新增: created, err := os.MkdirTemp(directory, "created-") | |
| 14 | 新增: if err != nil { | |
| 15 | 新增: t.Fatal(err) | |
| 16 | 新增: } | |
| 17 | 新增: path := filepath.Join(created, "fixture.txt") | |
| 18 | 新增: if err := os.WriteFile(path, []byte("complete copied bytes"), 0600); err != nil { | |
| 19 | 新增: t.Fatal(err) | |
| 20 | 新增: } | |
| 21 | 新增: store := CacheStore{Directory: filepath.Join(directory, "records")} | |
| 22 | 新增: selection, err := store.Register([]string{path}) | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: t.Fatal(err) | |
| 25 | 新增: } | |
| 26 | 新增: return store, selection | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:func TestCacheReleaseUsesItsCreationRecord(t *testing.T) { | |
| 30 | 新增: store, selection := cacheFixture(t) | |
| 31 | 新增: unrelated := filepath.Join(t.TempDir(), "cage-clipboard-unrelated") | |
| 32 | 新增: if err := os.Mkdir(unrelated, 0700); err != nil { | |
| 33 | 新增: t.Fatal(err) | |
| 34 | 新增: } | |
| 35 | 新增: if err := store.Release(selection.ID); err != nil { | |
| 36 | 新增: t.Fatal(err) | |
| 37 | 新增: } | |
| 38 | 新增: if _, err := os.Stat(filepath.Dir(selection.Paths[0])); !os.IsNotExist(err) { | |
| 39 | 新增: t.Fatal("owned copy remained") | |
| 40 | 新增: } | |
| 41 | 新增: if _, err := os.Stat(unrelated); err != nil { | |
| 42 | 新增: t.Fatal("unrelated directory changed") | |
| 43 | 新增: } | |
| 44 | 新增: if err := store.Release(selection.ID); err != nil { | |
| 45 | 新增: t.Fatal("release was not idempotent", err) | |
| 46 | 新增: } | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:func TestCacheReleaseRejectsChangedCreationMarker(t *testing.T) { | |
| 50 | 新增: store, selection := cacheFixture(t) | |
| 51 | 新增: record, err := store.load(selection.ID) | |
| 52 | 新增: if err != nil { | |
| 53 | 新增: t.Fatal(err) | |
| 54 | 新增: } | |
| 55 | 新增: if err := os.WriteFile(filepath.Join(record.Directory, record.Marker), []byte("changed"), 0600); err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: if err := store.Release(selection.ID); err == nil { | |
| 59 | 新增: t.Fatal("changed directory ownership was accepted") | |
| 60 | 新增: } | |
| 61 | 新增: if data, err := os.ReadFile(selection.Paths[0]); err != nil || string(data) != "complete copied bytes" { | |
| 62 | 新增: t.Fatal("unverified files were removed") | |
| 63 | 新增: } | |
| 64 | 新增:} | |
| 65 | 新增: | |
| 66 | 新增:func TestCacheRecoveryKeepsUnpublishedLiveTransfers(t *testing.T) { | |
| 67 | 新增: store, selection := cacheFixture(t) | |
| 68 | 新增: listed, err := store.List() | |
| 69 | 新增: if err != nil || len(listed) != 0 { | |
| 70 | 新增: t.Fatal("an active unpublished transfer was collected", err) | |
| 71 | 新增: } | |
| 72 | 新增: if err := store.Publish(selection.ID); err != nil { | |
| 73 | 新增: t.Fatal(err) | |
| 74 | 新增: } | |
| 75 | 新增: listed, err = store.List() | |
| 76 | 新增: if err != nil || len(listed) != 1 || listed[0].ID != selection.ID { | |
| 77 | 新增: t.Fatal("published ownership could not be restored", err) | |
| 78 | 新增: } | |
| 79 | 新增: record, _ := store.load(selection.ID) | |
| 80 | 新增: record.Published = false | |
| 81 | 新增: record.Owner = 2147483647 | |
| 82 | 新增: if err := store.save(record); err != nil { | |
| 83 | 新增: t.Fatal(err) | |
| 84 | 新增: } | |
| 85 | 新增: listed, err = store.List() | |
| 86 | 新增: if err != nil || len(listed) != 1 { | |
| 87 | 新增: t.Fatal("abandoned receive ownership was lost", err) | |
| 88 | 新增: } | |
| 89 | 新增:} | |
| 90 | 新增: | |
| 91 | 新增:func TestCacheRejectsForeignOrMalformedIdentifiers(t *testing.T) { | |
| 92 | 新增: store, selection := cacheFixture(t) | |
| 93 | 新增: for _, id := range []string{"../outside", "", strings.Repeat("g", 32)} { | |
| 94 | 新增: if err := store.Release(id); err == nil { | |
| 95 | 新增: t.Fatal("invalid cache identifier admitted") | |
| 96 | 新增: } | |
| 97 | 新增: } | |
| 98 | 新增: if _, err := os.Stat(selection.Paths[0]); err != nil { | |
| 99 | 新增: t.Fatal(err) | |
| 100 | 新增: } | |
| 101 | 新增:} | |
| @@ -0,0 +1,10 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package clipboardfiles | |
| 4 | 新增: | |
| 5 | 新增:import "syscall" | |
| 6 | 新增: | |
| 7 | 新增:func cacheOwnerAlive(pid int) bool { | |
| 8 | 新增: err := syscall.Kill(pid, 0) | |
| 9 | 新增: return err == nil || err == syscall.EPERM | |
| 10 | 新增:} | |
| @@ -0,0 +1,50 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package clipboardfiles | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "io" | |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "testing" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func TestCacheReleasePreservesAnAlreadyOpenExternalReader(t *testing.T) { | |
| 13 | 新增: store, selection := cacheFixture(t) | |
| 14 | 新增: reader, err := os.Open(selection.Paths[0]) | |
| 15 | 新增: if err != nil { | |
| 16 | 新增: t.Fatal(err) | |
| 17 | 新增: } | |
| 18 | 新增: defer reader.Close() | |
| 19 | 新增: if err := store.Release(selection.ID); err != nil { | |
| 20 | 新增: t.Fatal(err) | |
| 21 | 新增: } | |
| 22 | 新增: data, err := io.ReadAll(reader) | |
| 23 | 新增: if err != nil || string(data) != "complete copied bytes" { | |
| 24 | 新增: t.Fatal("the open external reader lost its bytes", err) | |
| 25 | 新增: } | |
| 26 | 新增: if _, err := os.Open(selection.Paths[0]); !os.IsNotExist(err) { | |
| 27 | 新增: t.Fatal("a retired path remained available to a new reader") | |
| 28 | 新增: } | |
| 29 | 新增:} | |
| 30 | 新增: | |
| 31 | 新增:func TestCacheReleaseRetainsMarkerAfterDirectoryRemovalFailure(t *testing.T) { | |
| 32 | 新增: if os.Geteuid() == 0 { | |
| 33 | 新增: t.Skip("root can remove the protected test directory") | |
| 34 | 新增: } | |
| 35 | 新增: store, selection := cacheFixture(t) | |
| 36 | 新增: parent := filepath.Dir(filepath.Dir(selection.Paths[0])) | |
| 37 | 新增: if err := os.Chmod(parent, 0500); err != nil { | |
| 38 | 新增: t.Fatal(err) | |
| 39 | 新增: } | |
| 40 | 新增: defer os.Chmod(parent, 0700) | |
| 41 | 新增: if err := store.Release(selection.ID); err == nil { | |
| 42 | 新增: t.Fatal("a protected directory was removed") | |
| 43 | 新增: } | |
| 44 | 新增: if err := os.Chmod(parent, 0700); err != nil { | |
| 45 | 新增: t.Fatal(err) | |
| 46 | 新增: } | |
| 47 | 新增: if err := store.Release(selection.ID); err != nil { | |
| 48 | 新增: t.Fatal("the failed removal lost its creation proof", err) | |
| 49 | 新增: } | |
| 50 | 新增:} | |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增:package clipboardfiles | |
| 2 | 新增: | |
| 3 | 新增:import "golang.org/x/sys/windows" | |
| 4 | 新增: | |
| 5 | 新增:func cacheOwnerAlive(pid int) bool { | |
| 6 | 新增: handle, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid)) | |
| 7 | 新增: if err != nil { | |
| 8 | 新增: return err == windows.ERROR_ACCESS_DENIED | |
| 9 | 新增: } | |
| 10 | 新增: defer windows.CloseHandle(handle) | |
| 11 | 新增: status, err := windows.WaitForSingleObject(handle, 0) | |
| 12 | 新增: return err != nil || status == uint32(windows.WAIT_TIMEOUT) | |
| 13 | 新增:} | |
| @@ -0,0 +1,43 @@ | ||
| 1 | 新增:package clipboardfiles | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "testing" | |
| 6 | 新增: | |
| 7 | 新增: "golang.org/x/sys/windows" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func TestCacheReleaseRetriesAfterExternalWindowsReaderCloses(t *testing.T) { | |
| 11 | 新增: store, selection := cacheFixture(t) | |
| 12 | 新增: name, err := windows.UTF16PtrFromString(selection.Paths[0]) | |
| 13 | 新增: if err != nil { | |
| 14 | 新增: t.Fatal(err) | |
| 15 | 新增: } | |
| 16 | 新增: reader, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ, nil, windows.OPEN_EXISTING, 0, 0) | |
| 17 | 新增: if err != nil { | |
| 18 | 新增: t.Fatal(err) | |
| 19 | 新增: } | |
| 20 | 新增: defer func() { | |
| 21 | 新增: if reader != 0 { | |
| 22 | 新增: windows.CloseHandle(reader) | |
| 23 | 新增: } | |
| 24 | 新增: }() | |
| 25 | 新增: if err := store.Release(selection.ID); err == nil { | |
| 26 | 新增: t.Fatal("a file opened without delete sharing was removed") | |
| 27 | 新增: } | |
| 28 | 新增: buffer := make([]byte, 64) | |
| 29 | 新增: var count uint32 | |
| 30 | 新增: if err := windows.ReadFile(reader, buffer, &count, nil); err != nil || string(buffer[:count]) != "complete copied bytes" { | |
| 31 | 新增: t.Fatal("the external reader lost its file", err) | |
| 32 | 新增: } | |
| 33 | 新增: if err := windows.CloseHandle(reader); err != nil { | |
| 34 | 新增: t.Fatal(err) | |
| 35 | 新增: } | |
| 36 | 新增: reader = 0 | |
| 37 | 新增: if err := store.Release(selection.ID); err != nil { | |
| 38 | 新增: t.Fatal("release could not retry", err) | |
| 39 | 新增: } | |
| 40 | 新增: if _, err := os.Stat(selection.Paths[0]); !os.IsNotExist(err) { | |
| 41 | 新增: t.Fatal("released cache remained") | |
| 42 | 新增: } | |
| 43 | 新增:} | |
| @@ -0,0 +1,224 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "crypto/sha256" | |
| 6 | 新增: "encoding/hex" | |
| 7 | 新增: "encoding/json" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "fmt" | |
| 10 | 新增: "io" | |
| 11 | 新增: "io/fs" | |
| 12 | 新增: "os" | |
| 13 | 新增: "path" | |
| 14 | 新增: "path/filepath" | |
| 15 | 新增: "sort" | |
| 16 | 新增: "strings" | |
| 17 | 新增: | |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/version" | |
| 20 | 新增:) | |
| 21 | 新增: | |
| 22 | 新增:const MacOSBrowserTools = "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0" | |
| 23 | 新增:const MacOSCLIRuntime = "/usr/local/libexec/cage-cli-runtime-2.1.311-py3.13.18-git2.56.0" | |
| 24 | 新增: | |
| 25 | 新增:type NativeComponentFile struct { | |
| 26 | 新增: Source string `json:"source"` | |
| 27 | 新增: Target string `json:"target,omitempty"` | |
| 28 | 新增: SHA256 string `json:"sha256"` | |
| 29 | 新增: InstalledSHA256 string `json:"installed_sha256"` | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 32 | 新增:type NativeComponentManifest struct { | |
| 33 | 新增: cage.GuestManifest | |
| 34 | 新增: System string `json:"system"` | |
| 35 | 新增: Files []NativeComponentFile `json:"files"` | |
| 36 | 新增: Tools map[string]string `json:"tools"` | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:// The installed application bundle is the required component source. Walking | |
| 40 | 新增:// its actual contents includes newly added helper resources and browser modules. | |
| 41 | 新增:func RequiredNativeComponents(kit, system string) (NativeComponentManifest, error) { | |
| 42 | 新增: manifest := NativeComponentManifest{GuestManifest: cage.GuestManifest{Protocol: 1, AppVersion: version.Version}, System: system} | |
| 43 | 新增: if system != MacOS && system != Windows11 { | |
| 44 | 新增: return manifest, errors.New("原生客机系统无效") | |
| 45 | 新增: } | |
| 46 | 新增: essential := []string{"payload/Cage.GuestClipboard.exe", "payload/cage-guest-files.exe", "payload/cage-guest-boot.exe", "payload/Cage.HyperVManager.exe", "payload/windows-browser.mjs"} | |
| 47 | 新增: if system == MacOS { | |
| 48 | 新增: essential = []string{"Cage Guest Window.app/Contents/MacOS/CageGuestWindow", "Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard", "project/cage-sshfs", "project/cage-macos-terminal", "native-browser/macos-native-browser.mjs", "native-browser/macos-browser-service.mjs", "register-macos-browser.sh", "macos-cli.py", "cli_channel.py"} | |
| 49 | 新增: } | |
| 50 | 新增: for _, relative := range essential { | |
| 51 | 新增: info, err := os.Lstat(filepath.Join(kit, filepath.FromSlash(relative))) | |
| 52 | 新增: if err != nil || !info.Mode().IsRegular() { | |
| 53 | 新增: return manifest, fmt.Errorf("原生组件包缺少 %s", relative) | |
| 54 | 新增: } | |
| 55 | 新增: } | |
| 56 | 新增: err := filepath.WalkDir(kit, func(filename string, entry fs.DirEntry, walkErr error) error { | |
| 57 | 新增: if walkErr != nil { | |
| 58 | 新增: return walkErr | |
| 59 | 新增: } | |
| 60 | 新增: if entry.IsDir() { | |
| 61 | 新增: return nil | |
| 62 | 新增: } | |
| 63 | 新增: if entry.Type()&os.ModeSymlink != 0 { | |
| 64 | 新增: return errors.New("原生组件目录不能包含文件链接") | |
| 65 | 新增: } | |
| 66 | 新增: info, err := entry.Info() | |
| 67 | 新增: if err != nil { | |
| 68 | 新增: return err | |
| 69 | 新增: } | |
| 70 | 新增: if !info.Mode().IsRegular() { | |
| 71 | 新增: return errors.New("原生组件目录包含特殊文件") | |
| 72 | 新增: } | |
| 73 | 新增: relative, err := filepath.Rel(kit, filename) | |
| 74 | 新增: if err != nil { | |
| 75 | 新增: return err | |
| 76 | 新增: } | |
| 77 | 新增: relative = filepath.ToSlash(relative) | |
| 78 | 新增: if relative == "native-components.json" { | |
| 79 | 新增: return nil | |
| 80 | 新增: } | |
| 81 | 新增: file, err := os.Open(filename) | |
| 82 | 新增: if err != nil { | |
| 83 | 新增: return err | |
| 84 | 新增: } | |
| 85 | 新增: hash := sha256.New() | |
| 86 | 新增: _, readErr := io.Copy(hash, file) | |
| 87 | 新增: if err = errors.Join(readErr, file.Close()); err != nil { | |
| 88 | 新增: return err | |
| 89 | 新增: } | |
| 90 | 新增: digest := hex.EncodeToString(hash.Sum(nil)) | |
| 91 | 新增: target := nativeComponentTarget(relative, system) | |
| 92 | 新增: installed := digest | |
| 93 | 新增: if system == MacOS && relative == "claude-account.py" { | |
| 94 | 新增: data, err := os.ReadFile(filename) | |
| 95 | 新增: if err != nil { | |
| 96 | 新增: return err | |
| 97 | 新增: } | |
| 98 | 新增: _, body, found := bytes.Cut(data, []byte("\n")) | |
| 99 | 新增: if !found { | |
| 100 | 新增: return errors.New("账号组件缺少程序正文") | |
| 101 | 新增: } | |
| 102 | 新增: rewritten := sha256.Sum256(append([]byte("#!"+MacOSCLIRuntime+"/bin/python3 -I\n"), body...)) | |
| 103 | 新增: installed = hex.EncodeToString(rewritten[:]) | |
| 104 | 新增: } | |
| 105 | 新增: manifest.Files = append(manifest.Files, NativeComponentFile{Source: relative, Target: target, SHA256: digest, InstalledSHA256: installed}) | |
| 106 | 新增: if system == Windows11 && relative == "payload/Cage.GuestClipboard.exe" { | |
| 107 | 新增: manifest.Files = append(manifest.Files, NativeComponentFile{Source: relative, Target: "network/Cage.GuestNetwork.exe", SHA256: digest, InstalledSHA256: installed}) | |
| 108 | 新增: } | |
| 109 | 新增: return nil | |
| 110 | 新增: }) | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: return manifest, err | |
| 113 | 新增: } | |
| 114 | 新增: if len(manifest.Files) == 0 { | |
| 115 | 新增: return manifest, errors.New("此应用缺少原生客机组件") | |
| 116 | 新增: } | |
| 117 | 新增: sort.Slice(manifest.Files, func(i, j int) bool { | |
| 118 | 新增: if manifest.Files[i].Source != manifest.Files[j].Source { | |
| 119 | 新增: return manifest.Files[i].Source < manifest.Files[j].Source | |
| 120 | 新增: } | |
| 121 | 新增: return manifest.Files[i].Target < manifest.Files[j].Target | |
| 122 | 新增: }) | |
| 123 | 新增: digest := sha256.New() | |
| 124 | 新增: fmt.Fprintf(digest, "cage-native-components-1\x00%s\x00", system) | |
| 125 | 新增: for _, file := range manifest.Files { | |
| 126 | 新增: fmt.Fprintf(digest, "%s\x00%s\x00%s\x00%s\x00", file.Source, file.Target, file.SHA256, file.InstalledSHA256) | |
| 127 | 新增: } | |
| 128 | 新增: manifest.Revision = hex.EncodeToString(digest.Sum(nil)) | |
| 129 | 新增: manifest.Tools = map[string]string{"chromium": "系统维护的 Chrome / Edge", "code_server": "261c84cb1eddf11235f9e2c921425e9663fbe556"} | |
| 130 | 新增: if system == MacOS { | |
| 131 | 新增: manifest.Tools = map[string]string{"chromium": "Google Chrome 稳定版", "code_server": "4.145.0", "claude": "2.1.311", "node": "24.22.2", "python": "3.13.18", "git": "2.56.0"} | |
| 132 | 新增: } else { | |
| 133 | 新增: var dependencies map[string]struct { | |
| 134 | 新增: Version string `json:"version"` | |
| 135 | 新增: } | |
| 136 | 新增: if data, err := os.ReadFile(filepath.Join(kit, "payload", "cli-dependencies.json")); err != nil { | |
| 137 | 新增: return manifest, err | |
| 138 | 新增: } else if err = json.Unmarshal(data, &dependencies); err != nil { | |
| 139 | 新增: return manifest, err | |
| 140 | 新增: } | |
| 141 | 新增: for _, name := range []string{"claude", "python", "git"} { | |
| 142 | 新增: manifest.Tools[name] = dependencies[name].Version | |
| 143 | 新增: } | |
| 144 | 新增: manifest.Tools["node"] = "24.22.2" | |
| 145 | 新增: } | |
| 146 | 新增: return manifest, manifest.Validate() | |
| 147 | 新增:} | |
| 148 | 新增: | |
| 149 | 新增:func nativeComponentTarget(source, system string) string { | |
| 150 | 新增: if system == Windows11 { | |
| 151 | 新增: if !strings.HasPrefix(source, "payload/") { | |
| 152 | 新增: return "" | |
| 153 | 新增: } | |
| 154 | 新增: name := strings.TrimPrefix(source, "payload/") | |
| 155 | 新增: if name == "Cage.HyperVManager.exe" || name == "windows-workbench-packages.json" { | |
| 156 | 新增: return "" | |
| 157 | 新增: } | |
| 158 | 新增: return "bridge/" + name | |
| 159 | 新增: } | |
| 160 | 新增: switch { | |
| 161 | 新增: case strings.HasPrefix(source, "Cage ") && strings.Contains(source, ".app/"): | |
| 162 | 新增: return "/Applications/" + source | |
| 163 | 新增: case strings.HasPrefix(source, "project/CageProjectAccess.app/"): | |
| 164 | 新增: return "/Applications/" + strings.TrimPrefix(source, "project/") | |
| 165 | 新增: case strings.HasPrefix(source, "native-browser/"): | |
| 166 | 新增: return MacOSBrowserTools + "/controller/" + strings.TrimPrefix(source, "native-browser/") | |
| 167 | 新增: } | |
| 168 | 新增: targets := map[string]string{ | |
| 169 | 新增: "project/cage-sshfs": "/usr/local/libexec/cage-sshfs", | |
| 170 | 新增: "project/cage-macos-terminal": "/usr/local/libexec/cage-macos-terminal", | |
| 171 | 新增: "cage-finish-initial-setup": "/usr/local/libexec/cage-finish-initial-setup", | |
| 172 | 新增: "cage-macos-ipv6-check": "/usr/local/libexec/cage-macos-ipv6-check", | |
| 173 | 新增: "macos-browser.mjs": "/usr/local/libexec/cage-macos-browser.mjs", | |
| 174 | 新增: "cage-macos-editor": "/usr/local/libexec/cage-macos-editor", | |
| 175 | 新增: "register-macos-claude-window.sh": "/usr/local/libexec/cage-register-claude-window", | |
| 176 | 新增: "register-macos-clipboard.sh": "/usr/local/libexec/cage-register-clipboard", | |
| 177 | 新增: "register-macos-browser.sh": "/usr/local/libexec/cage-register-browser", | |
| 178 | 新增: "macos-cli.py": "/usr/local/libexec/cage-cli/macos-cli.py", | |
| 179 | 新增: "cli_channel.py": "/usr/local/libexec/cage-cli/cli_channel.py", | |
| 180 | 新增: "cli_channel.resume.md": "/usr/local/libexec/cage-cli/cli_channel.resume.md", | |
| 181 | 新增: "claude_account_resume.md": "/usr/local/libexec/cage-cli/cli_channel.account-resume.md", | |
| 182 | 新增: "claude-account.py": "/usr/local/libexec/cage-cli/bin/cage-claude-account", | |
| 183 | 新增: } | |
| 184 | 新增: return targets[source] | |
| 185 | 新增:} | |
| 186 | 新增: | |
| 187 | 新增:func (m NativeComponentManifest) Validate() error { | |
| 188 | 新增: if m.Protocol != 1 || (m.System != MacOS && m.System != Windows11) || len(m.Revision) != 64 || len(m.Files) == 0 || len(m.Files) > 10000 { | |
| 189 | 新增: return errors.New("原生组件清单无效") | |
| 190 | 新增: } | |
| 191 | 新增: if _, err := hex.DecodeString(m.Revision); err != nil { | |
| 192 | 新增: return errors.New("原生组件版本摘要无效") | |
| 193 | 新增: } | |
| 194 | 新增: seen := map[string]bool{} | |
| 195 | 新增: for _, file := range m.Files { | |
| 196 | 新增: key := file.Source + "\x00" + file.Target | |
| 197 | 新增: if !fs.ValidPath(file.Source) || strings.ContainsAny(file.Source+file.Target, "\x00\r\n") || seen[key] || len(file.SHA256) != 64 || len(file.InstalledSHA256) != 64 { | |
| 198 | 新增: return errors.New("原生组件文件记录无效") | |
| 199 | 新增: } | |
| 200 | 新增: if _, err := hex.DecodeString(file.SHA256 + file.InstalledSHA256); err != nil { | |
| 201 | 新增: return errors.New("原生组件摘要无效") | |
| 202 | 新增: } | |
| 203 | 新增: if file.Target != "" && (path.Clean(file.Target) != file.Target || strings.Contains(file.Target, "\\")) { | |
| 204 | 新增: return errors.New("原生组件安装位置无效") | |
| 205 | 新增: } | |
| 206 | 新增: if file.Target != "" && seen["\x00"+file.Target] { | |
| 207 | 新增: return errors.New("原生组件安装位置重复") | |
| 208 | 新增: } | |
| 209 | 新增: if file.Target != "" && m.System == MacOS && !strings.HasPrefix(file.Target, "/Applications/Cage") && !strings.HasPrefix(file.Target, "/usr/local/libexec/cage-") { | |
| 210 | 新增: return errors.New("macOS 组件安装位置无效") | |
| 211 | 新增: } | |
| 212 | 新增: if file.Target != "" && m.System == Windows11 && !strings.HasPrefix(file.Target, "bridge/") && !strings.HasPrefix(file.Target, "network/") { | |
| 213 | 新增: return errors.New("Windows 组件安装位置无效") | |
| 214 | 新增: } | |
| 215 | 新增: if m.System == Windows11 && strings.ContainsAny(file.Source+file.Target, ":\\") { | |
| 216 | 新增: return errors.New("Windows 组件文件名无效") | |
| 217 | 新增: } | |
| 218 | 新增: seen[key] = true | |
| 219 | 新增: if file.Target != "" { | |
| 220 | 新增: seen["\x00"+file.Target] = true | |
| 221 | 新增: } | |
| 222 | 新增: } | |
| 223 | 新增: return nil | |
| 224 | 新增:} | |
| @@ -0,0 +1,96 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/sha256" | |
| 5 | 新增: "encoding/hex" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "testing" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func nativeManifestKit(t *testing.T, system string) string { | |
| 12 | 新增: t.Helper() | |
| 13 | 新增: kit := t.TempDir() | |
| 14 | 新增: names := []string{"payload/Cage.GuestClipboard.exe", "payload/cage-guest-files.exe", "payload/cage-guest-boot.exe", "payload/Cage.HyperVManager.exe", "payload/windows-browser.mjs", "payload/cli-dependencies.json"} | |
| 15 | 新增: if system == MacOS { | |
| 16 | 新增: names = []string{"Cage Guest Window.app/Contents/MacOS/CageGuestWindow", "Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard", "project/cage-sshfs", "project/cage-macos-terminal", "native-browser/macos-native-browser.mjs", "native-browser/macos-browser-service.mjs", "register-macos-browser.sh", "macos-cli.py", "cli_channel.py", "claude-account.py"} | |
| 17 | 新增: } | |
| 18 | 新增: for _, name := range names { | |
| 19 | 新增: filename := filepath.Join(kit, filepath.FromSlash(name)) | |
| 20 | 新增: if err := os.MkdirAll(filepath.Dir(filename), 0700); err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: data := []byte("#!fixture\n{}") | |
| 24 | 新增: if name == "payload/cli-dependencies.json" { | |
| 25 | 新增: data = []byte(`{"claude":{"version":"2.1.311"},"python":{"version":"3.13.18"},"git":{"version":"2.56.0"}}`) | |
| 26 | 新增: } | |
| 27 | 新增: if err := os.WriteFile(filename, data, 0600); err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: } | |
| 31 | 新增: return kit | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:func TestNativeManifestTracksInstalledComponents(t *testing.T) { | |
| 35 | 新增: for _, system := range []string{MacOS, Windows11} { | |
| 36 | 新增: t.Run(system, func(t *testing.T) { | |
| 37 | 新增: kit := nativeManifestKit(t, system) | |
| 38 | 新增: first, err := RequiredNativeComponents(kit, system) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: t.Fatal(err) | |
| 41 | 新增: } | |
| 42 | 新增: again, err := RequiredNativeComponents(kit, system) | |
| 43 | 新增: if err != nil || first.Revision != again.Revision { | |
| 44 | 新增: t.Fatalf("manifest is unstable: %v", err) | |
| 45 | 新增: } | |
| 46 | 新增: source := "payload/new-phone-browser.mjs" | |
| 47 | 新增: if system == MacOS { | |
| 48 | 新增: source = "native-browser/macos-phone-browser.mjs" | |
| 49 | 新增: } | |
| 50 | 新增: if err = os.WriteFile(filepath.Join(kit, filepath.FromSlash(source)), []byte("phone-browser"), 0600); err != nil { | |
| 51 | 新增: t.Fatal(err) | |
| 52 | 新增: } | |
| 53 | 新增: next, err := RequiredNativeComponents(kit, system) | |
| 54 | 新增: if err != nil || next.Revision == first.Revision { | |
| 55 | 新增: t.Fatalf("new component was omitted: %v", err) | |
| 56 | 新增: } | |
| 57 | 新增: found, packet := false, false | |
| 58 | 新增: for _, item := range next.Files { | |
| 59 | 新增: if item.Source == source { | |
| 60 | 新增: found = item.Target != "" && item.SHA256 == item.InstalledSHA256 | |
| 61 | 新增: } | |
| 62 | 新增: if item.Target == "network/Cage.GuestNetwork.exe" { | |
| 63 | 新增: packet = item.Source == "payload/Cage.GuestClipboard.exe" | |
| 64 | 新增: } | |
| 65 | 新增: if item.Source == "claude-account.py" { | |
| 66 | 新增: expected := sha256.Sum256([]byte("#!" + MacOSCLIRuntime + "/bin/python3 -I\n{}")) | |
| 67 | 新增: if item.InstalledSHA256 != hex.EncodeToString(expected[:]) { | |
| 68 | 新增: t.Fatal("installed Python entry point digest differs from installer") | |
| 69 | 新增: } | |
| 70 | 新增: } | |
| 71 | 新增: } | |
| 72 | 新增: if !found || (system == Windows11 && !packet) { | |
| 73 | 新增: t.Fatal("manifest did not include installed guest capabilities") | |
| 74 | 新增: } | |
| 75 | 新增: if err = os.Symlink(source, filepath.Join(kit, "unexpected-link")); err != nil { | |
| 76 | 新增: t.Skipf("symlinks unavailable: %v", err) | |
| 77 | 新增: } | |
| 78 | 新增: if _, err = RequiredNativeComponents(kit, system); err == nil { | |
| 79 | 新增: t.Fatal("linked payload was accepted") | |
| 80 | 新增: } | |
| 81 | 新增: }) | |
| 82 | 新增: } | |
| 83 | 新增:} | |
| 84 | 新增: | |
| 85 | 新增:func TestNativeManifestRejectsEscapedTargets(t *testing.T) { | |
| 86 | 新增: manifest, err := RequiredNativeComponents(nativeManifestKit(t, MacOS), MacOS) | |
| 87 | 新增: if err != nil { | |
| 88 | 新增: t.Fatal(err) | |
| 89 | 新增: } | |
| 90 | 新增: for _, target := range []string{"/usr/local/libexec/cage-cli/../../private", "/etc/passwd", "network/Cage.GuestNetwork.exe"} { | |
| 91 | 新增: manifest.Files[0].Target = target | |
| 92 | 新增: if manifest.Validate() == nil { | |
| 93 | 新增: t.Fatalf("accepted target %q", target) | |
| 94 | 新增: } | |
| 95 | 新增: } | |
| 96 | 新增:} | |
| @@ -0,0 +1,137 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "strings" | |
| 7 | 新增: "testing" | |
| 8 | 新增: | |
| 9 | 新增: "github.com/google/uuid" | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/hostimage" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func TestHostSourcePublishesOneVerifiedMediaReceipt(t *testing.T) { | |
| 14 | 新增: profile := t.TempDir() | |
| 15 | 新增: source := hostimage.Plan{Host: hostimage.Identity{System: Windows11, Version: "25H2", Build: "26200.9", Edition: "Professional", Language: "zh-CN", Arch: "amd64"}, Version: "25H2", Build: "26200.8", Format: "esd", URL: "http://dl.delivery.mp.microsoft.com/example.esd", Digest: "sha256:" + strings.Repeat("a", 64), Bytes: 10} | |
| 16 | 新增: install := Installation{Version: 1, ID: uuid.New(), System: Windows11, EditorTerms: true, Source: source} | |
| 17 | 新增: if err := SaveInstallation(profile, install); err != nil { | |
| 18 | 新增: t.Fatal(err) | |
| 19 | 新增: } | |
| 20 | 新增: original, _ := os.ReadFile(filepath.Join(profile, installRecord)) | |
| 21 | 新增: ready := source | |
| 22 | 新增: ready.Path = filepath.Join(profile, "system.esd") | |
| 23 | 新增: ready.Modified = 123 | |
| 24 | 新增: if err := RecordPreparedMedia(profile, install.ID, ready); err != nil { | |
| 25 | 新增: t.Fatal(err) | |
| 26 | 新增: } | |
| 27 | 新增: loaded, err := LoadInstallation(profile) | |
| 28 | 新增: if err != nil || loaded.Media != ready.Path || loaded.Source != ready { | |
| 29 | 新增: t.Fatalf("loaded: %+v %v", loaded, err) | |
| 30 | 新增: } | |
| 31 | 新增: if err := SaveInstallation(profile, *loaded); err != nil { | |
| 32 | 新增: t.Fatal(err) | |
| 33 | 新增: } | |
| 34 | 新增: if err := RecordPreparedMedia(profile, install.ID, ready); err != nil { | |
| 35 | 新增: t.Fatal(err) | |
| 36 | 新增: } | |
| 37 | 新增: after, _ := os.ReadFile(filepath.Join(profile, installRecord)) | |
| 38 | 新增: if string(original) != string(after) { | |
| 39 | 新增: t.Fatal("changed original installation choice") | |
| 40 | 新增: } | |
| 41 | 新增: changed := ready | |
| 42 | 新增: changed.Host.Edition = "Enterprise" | |
| 43 | 新增: if err := RecordPreparedMedia(profile, install.ID, changed); err == nil { | |
| 44 | 新增: t.Fatal("accepted another edition") | |
| 45 | 新增: } | |
| 46 | 新增: if err := RecordPreparedMedia(profile, uuid.New(), ready); err == nil { | |
| 47 | 新增: t.Fatal("accepted another installation") | |
| 48 | 新增: } | |
| 49 | 新增: changed = ready | |
| 50 | 新增: changed.Path = filepath.Join(profile, "other.esd") | |
| 51 | 新增: if err := RecordPreparedMedia(profile, install.ID, changed); err == nil { | |
| 52 | 新增: t.Fatal("replaced published media") | |
| 53 | 新增: } | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 56 | 新增:func TestLegacyInstallationOmitsSource(t *testing.T) { | |
| 57 | 新增: profile := t.TempDir() | |
| 58 | 新增: if err := SaveInstallation(profile, Installation{Version: 1, ID: uuid.New(), System: MacOS}); err != nil { | |
| 59 | 新增: t.Fatal(err) | |
| 60 | 新增: } | |
| 61 | 新增: data, _ := os.ReadFile(filepath.Join(profile, installRecord)) | |
| 62 | 新增: if strings.Contains(string(data), `"source"`) { | |
| 63 | 新增: t.Fatal("legacy choice acquired source metadata") | |
| 64 | 新增: } | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:func TestWindowsCloneCleanupTracksRetainedCredential(t *testing.T) { | |
| 68 | 新增: profile := t.TempDir() | |
| 69 | 新增: source := hostimage.Plan{ | |
| 70 | 新增: Host: hostimage.Identity{System: Windows11, Version: "25H2", Edition: "Professional", Language: "zh-CN", Arch: "amd64"}, | |
| 71 | 新增: Version: "25H2", Build: "26200.8", Format: "esd", Path: filepath.Join(profile, "system.esd"), | |
| 72 | 新增: } | |
| 73 | 新增: install := Installation{Version: 1, ID: uuid.New(), System: Windows11, EditorTerms: true, Source: source} | |
| 74 | 新增: if err := SaveInstallation(profile, install); err != nil { | |
| 75 | 新增: t.Fatal(err) | |
| 76 | 新增: } | |
| 77 | 新增: path := filepath.Join(profile, "windows-setup-"+strings.ReplaceAll(install.ID.String(), "-", "")+".dpapi") | |
| 78 | 新增: if err := os.WriteFile(path, []byte("encrypted-fixture"), 0600); err != nil { | |
| 79 | 新增: t.Fatal(err) | |
| 80 | 新增: } | |
| 81 | 新增: pending, err := WindowsCloneCleanupPending(profile) | |
| 82 | 新增: if err != nil || !pending { | |
| 83 | 新增: t.Fatalf("retained credential bypassed cleanup: %v %v", pending, err) | |
| 84 | 新增: } | |
| 85 | 新增: if err := os.Remove(path); err != nil { | |
| 86 | 新增: t.Fatal(err) | |
| 87 | 新增: } | |
| 88 | 新增: pending, err = WindowsCloneCleanupPending(profile) | |
| 89 | 新增: if err != nil || pending { | |
| 90 | 新增: t.Fatalf("completed cleanup still blocks activation: %v %v", pending, err) | |
| 91 | 新增: } | |
| 92 | 新增:} | |
| 93 | 新增: | |
| 94 | 新增:func TestLinuxCloneKeepsItsChoiceAfterBaseInstallation(t *testing.T) { | |
| 95 | 新增: for _, name := range []string{"base-building", "base"} { | |
| 96 | 新增: t.Run(name, func(t *testing.T) { | |
| 97 | 新增: profile := t.TempDir() | |
| 98 | 新增: install := Installation{ | |
| 99 | 新增: Version: 1, ID: uuid.New(), System: "ubuntu-22.04", | |
| 100 | 新增: Source: hostimage.Plan{ | |
| 101 | 新增: Host: hostimage.Identity{System: "ubuntu-22.04", Version: "22.04", Arch: "amd64"}, | |
| 102 | 新增: Version: "22.04", Format: "qcow2", Path: filepath.Join(profile, "ubuntu.img"), | |
| 103 | 新增: Digest: "sha256:" + strings.Repeat("a", 64), | |
| 104 | 新增: }, | |
| 105 | 新增: } | |
| 106 | 新增: if err := SaveInstallation(profile, install); err != nil { | |
| 107 | 新增: t.Fatal(err) | |
| 108 | 新增: } | |
| 109 | 新增: disk := filepath.Join(profile, "state", "lima", name) | |
| 110 | 新增: if err := os.MkdirAll(disk, 0700); err != nil { | |
| 111 | 新增: t.Fatal(err) | |
| 112 | 新增: } | |
| 113 | 新增: unstarted, err := UnstartedInstallation(profile, install) | |
| 114 | 新增: if err != nil || unstarted { | |
| 115 | 新增: t.Fatalf("existing base was treated as an unstarted choice: %v %v", unstarted, err) | |
| 116 | 新增: } | |
| 117 | 新增: if err := ClearUnstartedInstallation(profile, install.ID); err == nil { | |
| 118 | 新增: t.Fatal("cleared a choice that already produced a base disk") | |
| 119 | 新增: } | |
| 120 | 新增: if err := FinishLinuxInstallation(profile, install.ID); err == nil { | |
| 121 | 新增: t.Fatal("finished without a durable Linux choice") | |
| 122 | 新增: } | |
| 123 | 新增: if pending, err := LoadInstallation(profile); err != nil || pending == nil { | |
| 124 | 新增: t.Fatal("lost installation recovery information", err) | |
| 125 | 新增: } | |
| 126 | 新增: if err := hostimage.WriteLinuxTemplate(filepath.Join(profile, "state"), install.Source); err != nil { | |
| 127 | 新增: t.Fatal(err) | |
| 128 | 新增: } | |
| 129 | 新增: if err := FinishLinuxInstallation(profile, install.ID); err != nil { | |
| 130 | 新增: t.Fatal(err) | |
| 131 | 新增: } | |
| 132 | 新增: if _, err := os.Stat(disk); err != nil { | |
| 133 | 新增: t.Fatal("finishing the installation affected its disk", err) | |
| 134 | 新增: } | |
| 135 | 新增: }) | |
| 136 | 新增: } | |
| 137 | 新增:} | |
| @@ -0,0 +1,23 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:// HyperVInspection describes only the VM explicitly requested by its caller. | |
| 4 | 新增:// A matched VM is not automatically owned by the current Cage profile. | |
| 5 | 新增:type HyperVInspection struct { | |
| 6 | 新增: Inspection | |
| 7 | 新增: VMID string `json:"vmId"` | |
| 8 | 新增: Lookup string `json:"lookup"` // found, not-found (for this user), or unavailable | |
| 9 | 新增: LookupDetail string `json:"lookupDetail,omitempty"` | |
| 10 | 新增: VM *HyperVConfiguration `json:"vm,omitempty"` | |
| 11 | 新增:} | |
| 12 | 新增: | |
| 13 | 新增:type HyperVConfiguration struct { | |
| 14 | 新增: State string `json:"state"` | |
| 15 | 新增: Generation int `json:"generation"` | |
| 16 | 新增: DiskCount int `json:"diskCount"` | |
| 17 | 新增: SingleLocalVHDX *bool `json:"singleLocalVhdx"` // null if local disk metadata was unreadable | |
| 18 | 新增: DiskType string `json:"diskType,omitempty"` | |
| 19 | 新增: SecureBoot bool `json:"secureBoot"` | |
| 20 | 新增: SecureBootTemplate string `json:"secureBootTemplate,omitempty"` | |
| 21 | 新增: VirtualTPM bool `json:"virtualTpm"` | |
| 22 | 新增: NetworkAdapterCount int `json:"networkAdapterCount"` | |
| 23 | 新增:} | |
| @@ -0,0 +1,49 @@ | ||
| 1 | 新增:$ErrorActionPreference = 'Stop' | |
| 2 | 新增:$ProgressPreference = 'SilentlyContinue' | |
| 3 | 新增:$WarningPreference = 'SilentlyContinue' | |
| 4 | 新增:[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) | |
| 5 | 新增:# An exact CIM query can return zero matches without conflating a failed or | |
| 6 | 新增:# unauthorized management request with a nonexistent VM. | |
| 7 | 新增:$systems = @(Get-CimInstance -Namespace root/virtualization/v2 -ClassName Msvm_ComputerSystem -Filter "Name='$targetId'") | |
| 8 | 新增:if ($systems.Count -eq 0) { Write-Output 'null'; return } | |
| 9 | 新增:if ($systems.Count -ne 1) { throw 'Unexpected Hyper-V management result.' } | |
| 10 | 新增:$vm = Hyper-V\Get-VM -Id $targetId | |
| 11 | 新增:if ($vm.Id -ne $targetId -or [string]::IsNullOrWhiteSpace([string]$vm.State) -or $vm.Generation -notin 1,2) { | |
| 12 | 新增: throw 'Hyper-V instance changed.' | |
| 13 | 新增:} | |
| 14 | 新增:$disks = @(Hyper-V\Get-VMHardDiskDrive -VM $vm) | |
| 15 | 新增:$adapters = @(Hyper-V\Get-VMNetworkAdapter -VM $vm) | |
| 16 | 新增:$singleLocalVHDX = $false | |
| 17 | 新增:$diskType = '' | |
| 18 | 新增:if ($disks.Count -eq 1 -and $disks[0].Path) { | |
| 19 | 新增: $path = [string]$disks[0].Path | |
| 20 | 新增: if ($path -match '^[A-Za-z]:[\\/]') { | |
| 21 | 新增: try { | |
| 22 | 新增: if ([IO.DriveInfo]::new($path.Substring(0,3)).DriveType -ne 'Network') { | |
| 23 | 新增: $disk = Hyper-V\Get-VHD -Path $path | |
| 24 | 新增: if (!$disk -or !$disk.VhdFormat) { throw 'No local VHD metadata.' } | |
| 25 | 新增: $singleLocalVHDX = [string]$disk.VhdFormat -eq 'VHDX' | |
| 26 | 新增: $diskType = [string]$disk.VhdType | |
| 27 | 新增: } | |
| 28 | 新增: } catch { | |
| 29 | 新增: $singleLocalVHDX = $null | |
| 30 | 新增: } | |
| 31 | 新增: } | |
| 32 | 新增:} | |
| 33 | 新增:$secureBoot = $false | |
| 34 | 新增:$template = '' | |
| 35 | 新增:$virtualTPM = $false | |
| 36 | 新增:if ($vm.Generation -eq 2) { | |
| 37 | 新增: $firmware = Hyper-V\Get-VMFirmware -VM $vm | |
| 38 | 新增: $security = Hyper-V\Get-VMSecurity -VM $vm | |
| 39 | 新增: if ($null -eq $security.TpmEnabled -or [string]$firmware.SecureBoot -notin 'On','Off') { throw 'Incomplete security configuration.' } | |
| 40 | 新增: $secureBoot = [string]$firmware.SecureBoot -eq 'On' | |
| 41 | 新增: $template = [string]$firmware.SecureBootTemplate | |
| 42 | 新增: $virtualTPM = [bool]$security.TpmEnabled | |
| 43 | 新增:} | |
| 44 | 新增:[ordered]@{ | |
| 45 | 新增: state=[string]$vm.State; generation=[int]$vm.Generation | |
| 46 | 新增: diskCount=$disks.Count; singleLocalVhdx=$singleLocalVHDX; diskType=$diskType | |
| 47 | 新增: secureBoot=$secureBoot; secureBootTemplate=$template; virtualTpm=$virtualTPM | |
| 48 | 新增: networkAdapterCount=$adapters.Count | |
| 49 | 新增:} | ConvertTo-Json -Compress | |
| @@ -0,0 +1,14 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: | |
| 9 | 新增: "github.com/google/uuid" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func InspectHyperV(context.Context, uuid.UUID) (HyperVInspection, error) { | |
| 13 | 新增: return HyperVInspection{}, errors.New("--vm-id 只支持查询本机 Windows Hyper-V 虚拟机") | |
| 14 | 新增:} | |
| @@ -0,0 +1,27 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os/exec" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "runtime" | |
| 7 | 新增: "testing" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func TestHyperVReadOnlyQuery(t *testing.T) { | |
| 11 | 新增: shell := "pwsh" | |
| 12 | 新增: if runtime.GOOS == "windows" { | |
| 13 | 新增: shell = "powershell.exe" | |
| 14 | 新增: } | |
| 15 | 新增: binary, err := exec.LookPath(shell) | |
| 16 | 新增: if err != nil { | |
| 17 | 新增: t.Skipf("%s is not installed", shell) | |
| 18 | 新增: } | |
| 19 | 新增: query, err := filepath.Abs("hyperv_instance.ps1") | |
| 20 | 新增: if err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: cmd := exec.CommandContext(t.Context(), binary, "-NoProfile", "-NonInteractive", "-File", filepath.Join("testdata", "hyperv_instance.ps1"), "-Query", query) | |
| 24 | 新增: if output, err := cmd.CombinedOutput(); err != nil { | |
| 25 | 新增: t.Fatalf("Hyper-V query: %v\n%s", err, output) | |
| 26 | 新增: } | |
| 27 | 新增:} | |
| @@ -0,0 +1,70 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: _ "embed" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: | |
| 10 | 新增: "github.com/google/uuid" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增://go:embed hyperv_instance.ps1 | |
| 14 | 新增:var hyperVInstanceQuery string | |
| 15 | 新增: | |
| 16 | 新增:// InspectHyperV reads Hyper-V configuration without starting the VM, opening a | |
| 17 | 新增:// guest session, enumerating unrelated VMs, or binding this VM to Cage. | |
| 18 | 新增:func InspectHyperV(ctx context.Context, id uuid.UUID) (HyperVInspection, error) { | |
| 19 | 新增: if id == uuid.Nil { | |
| 20 | 新增: return HyperVInspection{}, errors.New("expected a non-empty Hyper-V VM GUID") | |
| 21 | 新增: } | |
| 22 | 新增: report := HyperVInspection{Inspection: Inspect(ctx), VMID: id.String(), Lookup: "unavailable"} | |
| 23 | 新增: if !report.HostCheckPassed { | |
| 24 | 新增: return report, nil | |
| 25 | 新增: } | |
| 26 | 新增: var actual HyperVInspection | |
| 27 | 新增: if err := windowsHostManagerCall(ctx, id, "inspect", 0, 0, &actual); err != nil { | |
| 28 | 新增: if ctx.Err() != nil { | |
| 29 | 新增: return report, ctx.Err() | |
| 30 | 新增: } | |
| 31 | 新增: report.LookupDetail = err.Error() | |
| 32 | 新增: return report, nil | |
| 33 | 新增: } | |
| 34 | 新增: if actual.VMID != id.String() || actual.Lookup != "found" || actual.VM == nil { | |
| 35 | 新增: return report, errors.New("Windows 系统管理助手返回的虚拟机身份无效") | |
| 36 | 新增: } | |
| 37 | 新增: actual.Inspection = report.Inspection | |
| 38 | 新增: return actual, nil | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:func inspectHyperVNative(ctx context.Context, id uuid.UUID) (HyperVInspection, error) { | |
| 42 | 新增: if id == uuid.Nil { | |
| 43 | 新增: return HyperVInspection{}, errors.New("expected a non-empty Hyper-V VM GUID") | |
| 44 | 新增: } | |
| 45 | 新增: report := HyperVInspection{Inspection: Inspection{Guest: Windows11, HostCheckPassed: true, WorkbenchSupport: nativeWorkbenchSupport(Windows11, true)}, VMID: id.String(), Lookup: "unavailable"} | |
| 46 | 新增: // UUID.String supplies only hexadecimal digits and dashes. | |
| 47 | 新增: query := fmt.Sprintf("$targetId = [guid]'%s'\n", id.String()) + hyperVInstanceQuery | |
| 48 | 新增: cmd, err := systemPowerShellQuery(ctx, query) | |
| 49 | 新增: if err != nil { | |
| 50 | 新增: return report, err | |
| 51 | 新增: } | |
| 52 | 新增: output, err := cmd.Output() | |
| 53 | 新增: if ctx.Err() != nil { | |
| 54 | 新增: return report, ctx.Err() | |
| 55 | 新增: } | |
| 56 | 新增: if err != nil { | |
| 57 | 新增: report.LookupDetail = "无法读取该虚拟机的 Hyper-V 配置,请核对当前用户权限与虚拟机状态。" | |
| 58 | 新增: return report, nil | |
| 59 | 新增: } | |
| 60 | 新增: if err := json.Unmarshal(output, &report.VM); err != nil { | |
| 61 | 新增: return report, errors.New("Hyper-V 返回了无法识别的虚拟机配置") | |
| 62 | 新增: } | |
| 63 | 新增: if report.VM == nil { | |
| 64 | 新增: report.Lookup = "not-found" | |
| 65 | 新增: report.LookupDetail = "当前用户未查询到此标识的本机 Hyper-V 虚拟机。" | |
| 66 | 新增: } else { | |
| 67 | 新增: report.Lookup = "found" | |
| 68 | 新增: } | |
| 69 | 新增: return report, nil | |
| 70 | 新增:} | |
| @@ -0,0 +1,64 @@ | ||
| 1 | 新增:// Package guestos checks host prerequisites for a local guest system. | |
| 2 | 新增:package guestos | |
| 3 | 新增: | |
| 4 | 新增:import ( | |
| 5 | 新增: "os" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:// Guest system IDs are shared with the workbench installer. | |
| 10 | 新增:const ( | |
| 11 | 新增: Debian13 = "debian-13" | |
| 12 | 新增: MacOS = "macos" | |
| 13 | 新增: Windows11 = "windows-11" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:// MacRestore comes from Apple's compatibility catalog for this particular host. | |
| 17 | 新增:type MacRestore struct { | |
| 18 | 新增: Version string `json:"version"` | |
| 19 | 新增: Build string `json:"build"` | |
| 20 | 新增: URL string `json:"url"` | |
| 21 | 新增: MinimumCPUs int `json:"minimumCPUs"` | |
| 22 | 新增: MinimumMemoryBytes uint64 `json:"minimumMemoryBytes"` | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:// Inspection keeps host capability separate from availability in the workbench. | |
| 26 | 新增:type Inspection struct { | |
| 27 | 新增: Guest string `json:"guest"` | |
| 28 | 新增: HostCheckPassed bool `json:"hostCheckPassed"` | |
| 29 | 新增: WorkbenchSupport string `json:"workbenchSupport"` | |
| 30 | 新增: Detail string `json:"detail"` | |
| 31 | 新增: Restore *MacRestore `json:"restore,omitempty"` | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:// HasNativeWorkbenchKit checks the resources shipped alongside this backend. | |
| 35 | 新增:// A standalone diagnostic binary can inspect a host without the desktop kit. | |
| 36 | 新增:func HasNativeWorkbenchKit(executable, system string) bool { | |
| 37 | 新增: var files []string | |
| 38 | 新增: switch system { | |
| 39 | 新增: case MacOS: | |
| 40 | 新增: files = []string{"prepare-macos-media.sh", "provision-macos-workbench.sh", "project/cage-sshfs", "native-browser/macos-native-browser.mjs", "cage-finish-initial-setup"} | |
| 41 | 新增: case Windows11: | |
| 42 | 新增: files = []string{"new-windows-guest.ps1", "setup-windows-guest.ps1", "windows-host-image.ps1", "complete-windows-guest.ps1", "install-windows-host-manager.ps1", "payload/Cage.HyperVManager.exe", "payload/Cage.GuestClipboard.exe"} | |
| 43 | 新增: default: | |
| 44 | 新增: return false | |
| 45 | 新增: } | |
| 46 | 新增: for _, name := range files { | |
| 47 | 新增: info, err := os.Stat(filepath.Join(filepath.Dir(executable), "guest-os", name)) | |
| 48 | 新增: if err != nil || !info.Mode().IsRegular() { | |
| 49 | 新增: return false | |
| 50 | 新增: } | |
| 51 | 新增: } | |
| 52 | 新增: return true | |
| 53 | 新增:} | |
| 54 | 新增: | |
| 55 | 新增:func nativeWorkbenchSupport(system string, hostReady bool) string { | |
| 56 | 新增: if !hostReady { | |
| 57 | 新增: return "host-not-ready" | |
| 58 | 新增: } | |
| 59 | 新增: exe, err := os.Executable() | |
| 60 | 新增: if err != nil || !HasNativeWorkbenchKit(exe, system) { | |
| 61 | 新增: return "installation-kit-missing" | |
| 62 | 新增: } | |
| 63 | 新增: return "desktop-installer" | |
| 64 | 新增:} | |
| @@ -0,0 +1,17 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import "context" | |
| 4 | 新增: | |
| 5 | 新增:func Inspect(ctx context.Context) Inspection { | |
| 6 | 新增: r := Inspection{Guest: MacOS, WorkbenchSupport: nativeWorkbenchSupport(MacOS, false)} | |
| 7 | 新增: image, err := probeMacHost(ctx) | |
| 8 | 新增: if err != nil { | |
| 9 | 新增: r.Detail = "无法查询本机兼容的 Apple 恢复镜像:" + err.Error() | |
| 10 | 新增: return r | |
| 11 | 新增: } | |
| 12 | 新增: r.HostCheckPassed = true | |
| 13 | 新增: r.WorkbenchSupport = nativeWorkbenchSupport(MacOS, true) | |
| 14 | 新增: r.Restore = &image | |
| 15 | 新增: r.Detail = "Apple 提供与此主机兼容的 macOS 恢复镜像。" | |
| 16 | 新增: return r | |
| 17 | 新增:} | |
| @@ -0,0 +1,26 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "runtime" | |
| 7 | 新增: "strings" | |
| 8 | 新增: | |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func Inspect(_ context.Context) Inspection { | |
| 13 | 新增: r := Inspection{Guest: Debian13, WorkbenchSupport: "supported"} | |
| 14 | 新增: if runtime.GOARCH != "amd64" { | |
| 15 | 新增: r.WorkbenchSupport = "unsupported-host" | |
| 16 | 新增: r.Detail = "Linux 桌面发行包面向 x86_64 主机。" | |
| 17 | 新增: return r | |
| 18 | 新增: } | |
| 19 | 新增: var details bytes.Buffer | |
| 20 | 新增: r.HostCheckPassed = host.LinuxPrereqs(&details) | |
| 21 | 新增: r.Detail = strings.TrimSpace(details.String()) | |
| 22 | 新增: if r.HostCheckPassed { | |
| 23 | 新增: r.Detail = "已检测到 Debian 工作台所需的 Linux 虚拟化组件。" | |
| 24 | 新增: } | |
| 25 | 新增: return r | |
| 26 | 新增:} | |
| @@ -0,0 +1,9 @@ | ||
| 1 | 新增://go:build !darwin && !linux && !windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import "context" | |
| 6 | 新增: | |
| 7 | 新增:func Inspect(_ context.Context) Inspection { | |
| 8 | 新增: return Inspection{WorkbenchSupport: "unsupported-host", Detail: "此平台没有 Cage 本机工作台。"} | |
| 9 | 新增:} | |
| @@ -0,0 +1,8 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import "context" | |
| 4 | 新增: | |
| 5 | 新增:func Inspect(ctx context.Context) Inspection { | |
| 6 | 新增: ok, reason := probeWindowsHost(ctx) | |
| 7 | 新增: return Inspection{Guest: Windows11, HostCheckPassed: ok, WorkbenchSupport: nativeWorkbenchSupport(Windows11, ok), Detail: reason} | |
| 8 | 新增:} | |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "os/exec" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func WindowsInstallCommand(context.Context, string, string, Installation) (*exec.Cmd, error) { | |
| 12 | 新增: return nil, errors.New("Windows 客机需要 Windows 11 x64 Hyper-V 主机") | |
| 13 | 新增:} | |
| @@ -0,0 +1,40 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "crypto/sha256" | |
| 6 | 新增: "fmt" | |
| 7 | 新增: "os" | |
| 8 | 新增: | |
| 9 | 新增: "os/exec" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 13 | 新增: "golang.org/x/sys/windows" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:func WindowsInstallCommand(ctx context.Context, profile, kit string, install Installation) (*exec.Cmd, error) { | |
| 17 | 新增: system, err := windows.GetSystemDirectory() | |
| 18 | 新增: if err != nil { | |
| 19 | 新增: return nil, err | |
| 20 | 新增: } | |
| 21 | 新增: state, err := cage.StoragePhysicalPath(filepath.Join(profile, "state")) | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: return nil, err | |
| 24 | 新增: } | |
| 25 | 新增: manifest, err := RequiredNativeComponents(kit, Windows11) | |
| 26 | 新增: if err != nil { | |
| 27 | 新增: return nil, err | |
| 28 | 新增: } | |
| 29 | 新增: manifestPath := filepath.Join(profile, "windows-components-required.json") | |
| 30 | 新增: if err = WriteNativeComponentManifest(manifestPath, manifest); err != nil { | |
| 31 | 新增: return nil, err | |
| 32 | 新增: } | |
| 33 | 新增: data, err := os.ReadFile(manifestPath) | |
| 34 | 新增: if err != nil { | |
| 35 | 新增: return nil, err | |
| 36 | 新增: } | |
| 37 | 新增: digest := fmt.Sprintf("%x", sha256.Sum256(data)) | |
| 38 | 新增: cmd := exec.CommandContext(ctx, filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe"), "-NoLogo", "-NoProfile", "-ExecutionPolicy", "RemoteSigned", "-File", filepath.Join(kit, "setup-windows-guest.ps1"), "-Profile", profile, "-State", state, "-InstallationID", install.ID.String(), "-IsoPath", install.Media, "-ExpectedIsoSha256", install.SHA256, "-ManifestPath", manifestPath, "-ManifestSHA256", digest) | |
| 39 | 新增: return cmd, nil | |
| 40 | 新增:} | |
| @@ -0,0 +1,254 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "encoding/hex" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "strings" | |
| 12 | 新增: | |
| 13 | 新增: "github.com/google/uuid" | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/hostimage" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:// Installation persists only the media choice and private instance identity. | |
| 18 | 新增:// macOS secrets live separately in the Cage account's encrypted vault. | |
| 19 | 新增:type Installation struct { | |
| 20 | 新增: Version int `json:"version"` | |
| 21 | 新增: System string `json:"system"` | |
| 22 | 新增: Media string `json:"media,omitempty"` | |
| 23 | 新增: SHA256 string `json:"sha256,omitempty"` | |
| 24 | 新增: EditorTerms bool `json:"editor_terms,omitempty"` | |
| 25 | 新增: ID uuid.UUID `json:"id"` | |
| 26 | 新增: Source hostimage.Plan `json:"source,omitzero"` | |
| 27 | 新增: // Empty preserves legacy host-clone records. LinuxImageSource selects a | |
| 28 | 新增: // catalog image independently of the physical host OS. | |
| 29 | 新增: SourceKind string `json:"source_kind,omitempty"` | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 32 | 新增:const installRecord = "guest-install.json" | |
| 33 | 新增:const LinuxImageSource = "linux-image" | |
| 34 | 新增:const Ubuntu2204 = "ubuntu-22.04" | |
| 35 | 新增: | |
| 36 | 新增:// Older installers could publish the binding before removing the temporary | |
| 37 | 新增:// credential. Keep those profiles in setup until their original cleanup runs. | |
| 38 | 新增:func WindowsCloneCleanupPending(profile string) (bool, error) { | |
| 39 | 新增: install, err := LoadInstallation(profile) | |
| 40 | 新增: if err != nil || install == nil || install.Source.Host.System != Windows11 { | |
| 41 | 新增: return false, err | |
| 42 | 新增: } | |
| 43 | 新增: path := filepath.Join(profile, "windows-setup-"+strings.ReplaceAll(install.ID.String(), "-", "")+".dpapi") | |
| 44 | 新增: _, err = os.Lstat(path) | |
| 45 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 46 | 新增: return false, nil | |
| 47 | 新增: } | |
| 48 | 新增: return err == nil, err | |
| 49 | 新增:} | |
| 50 | 新增: | |
| 51 | 新增:func (i Installation) Validate() error { | |
| 52 | 新增: if i.Version != 1 || i.ID == uuid.Nil || (i.System != MacOS && i.System != Windows11 && !hostimage.IsLinux(i.System)) { | |
| 53 | 新增: return errors.New("客户机安装记录无效") | |
| 54 | 新增: } | |
| 55 | 新增: if i.SourceKind != "" && (i.SourceKind != LinuxImageSource || i.System != Ubuntu2204 || i.Source.Host.System != i.System) { | |
| 56 | 新增: return errors.New("客户机镜像选择方式无效") | |
| 57 | 新增: } | |
| 58 | 新增: if i.Media != "" && (!filepath.IsAbs(i.Media) || strings.ContainsAny(i.Media, "\r\n\x00") || filepath.Clean(i.Media) != i.Media) { | |
| 59 | 新增: return errors.New("请选择本机的安装镜像") | |
| 60 | 新增: } | |
| 61 | 新增: if i.Source.Host.System != "" { | |
| 62 | 新增: if i.System != i.Source.Host.System || (i.System == Windows11 && !i.EditorTerms) { | |
| 63 | 新增: return errors.New("本机系统安装选择无效,请重新检查") | |
| 64 | 新增: } | |
| 65 | 新增: if i.Media != "" && i.Media != i.Source.Path { | |
| 66 | 新增: return errors.New("安装介质与已选择的本机系统来源不一致") | |
| 67 | 新增: } | |
| 68 | 新增: return i.Source.Validate() | |
| 69 | 新增: } | |
| 70 | 新增: if hostimage.IsLinux(i.System) { | |
| 71 | 新增: return errors.New("缺少 Linux 本机系统安装来源") | |
| 72 | 新增: } | |
| 73 | 新增: if i.System == MacOS { | |
| 74 | 新增: if i.SHA256 != "" || (i.Media != "" && !strings.EqualFold(filepath.Ext(i.Media), ".ipsw")) { | |
| 75 | 新增: return errors.New("请选择 Apple 的 .ipsw 恢复镜像") | |
| 76 | 新增: } | |
| 77 | 新增: } else if hash, err := hex.DecodeString(i.SHA256); i.Media == "" || !i.EditorTerms || err != nil || len(hash) != 32 || !strings.EqualFold(filepath.Ext(i.Media), ".iso") { | |
| 78 | 新增: return errors.New("请选择 Windows 11 x64 ISO,并填写这份镜像的完整 SHA-256") | |
| 79 | 新增: } | |
| 80 | 新增: return nil | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:func LoadInstallation(profile string) (*Installation, error) { | |
| 84 | 新增: path := filepath.Join(profile, installRecord) | |
| 85 | 新增: info, err := os.Lstat(path) | |
| 86 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 87 | 新增: return nil, nil | |
| 88 | 新增: } | |
| 89 | 新增: if err != nil { | |
| 90 | 新增: return nil, err | |
| 91 | 新增: } | |
| 92 | 新增: if !info.Mode().IsRegular() || info.Size() > 32<<10 { | |
| 93 | 新增: return nil, errors.New("客户机安装记录无法读取") | |
| 94 | 新增: } | |
| 95 | 新增: data, err := os.ReadFile(path) | |
| 96 | 新增: if err != nil { | |
| 97 | 新增: return nil, err | |
| 98 | 新增: } | |
| 99 | 新增: var i Installation | |
| 100 | 新增: decoder := json.NewDecoder(bytes.NewReader(data)) | |
| 101 | 新增: decoder.DisallowUnknownFields() | |
| 102 | 新增: if decoder.Decode(&i) != nil || decoder.Decode(new(any)) != io.EOF { | |
| 103 | 新增: return nil, errors.New("客户机安装记录格式无效") | |
| 104 | 新增: } | |
| 105 | 新增: if err := i.Validate(); err != nil { | |
| 106 | 新增: return nil, err | |
| 107 | 新增: } | |
| 108 | 新增: if i.Source.Host.System != "" { | |
| 109 | 新增: var ready struct { | |
| 110 | 新增: ID uuid.UUID `json:"id"` | |
| 111 | 新增: Source hostimage.Plan `json:"source"` | |
| 112 | 新增: } | |
| 113 | 新增: mediaPath := filepath.Join(profile, "guest-install-media-"+i.ID.String()+".json") | |
| 114 | 新增: info, err := os.Lstat(mediaPath) | |
| 115 | 新增: if err == nil { | |
| 116 | 新增: if !info.Mode().IsRegular() || info.Size() > 32<<10 { | |
| 117 | 新增: return nil, errors.New("已校验的安装材料记录无效") | |
| 118 | 新增: } | |
| 119 | 新增: data, readErr := os.ReadFile(mediaPath) | |
| 120 | 新增: if readErr != nil || json.Unmarshal(data, &ready) != nil || ready.ID != i.ID { | |
| 121 | 新增: return nil, errors.New("无法读取已校验的安装材料") | |
| 122 | 新增: } | |
| 123 | 新增: if err := matchPreparedMedia(i.Source, ready.Source); err != nil { | |
| 124 | 新增: return nil, err | |
| 125 | 新增: } | |
| 126 | 新增: i.Source, i.Media = ready.Source, ready.Source.Path | |
| 127 | 新增: i.SHA256 = strings.TrimPrefix(ready.Source.Digest, "sha256:") | |
| 128 | 新增: } else if !errors.Is(err, os.ErrNotExist) { | |
| 129 | 新增: return nil, err | |
| 130 | 新增: } | |
| 131 | 新增: } | |
| 132 | 新增: return &i, i.Validate() | |
| 133 | 新增:} | |
| 134 | 新增: | |
| 135 | 新增:func SaveInstallation(profile string, i Installation) error { | |
| 136 | 新增: if err := i.Validate(); err != nil { | |
| 137 | 新增: return err | |
| 138 | 新增: } | |
| 139 | 新增: if current, err := LoadInstallation(profile); err != nil { | |
| 140 | 新增: return err | |
| 141 | 新增: } else if current != nil { | |
| 142 | 新增: if *current == i { | |
| 143 | 新增: return nil | |
| 144 | 新增: } | |
| 145 | 新增: return errors.New("已有其他安装选择,请继续原安装") | |
| 146 | 新增: } | |
| 147 | 新增: data, err := json.Marshal(i) | |
| 148 | 新增: if err != nil { | |
| 149 | 新增: return err | |
| 150 | 新增: } | |
| 151 | 新增: return publishBinding(profile, installRecord, append(data, '\n')) | |
| 152 | 新增:} | |
| 153 | 新增: | |
| 154 | 新增:func matchPreparedMedia(chosen, ready hostimage.Plan) error { | |
| 155 | 新增: if err := ready.Validate(); err != nil { | |
| 156 | 新增: return err | |
| 157 | 新增: } | |
| 158 | 新增: if ready.Path == "" || ready.Digest == "" || ready.Host != chosen.Host || ready.Version != chosen.Version || ready.Build != chosen.Build || | |
| 159 | 新增: ready.Format != chosen.Format || ready.URL != chosen.URL || (chosen.Digest != "" && ready.Digest != chosen.Digest) || | |
| 160 | 新增: (chosen.Bytes != 0 && ready.Bytes != chosen.Bytes) || (chosen.Path != "" && ready.Path != chosen.Path) || | |
| 161 | 新增: (chosen.Modified != 0 && ready.Modified != chosen.Modified) { | |
| 162 | 新增: return errors.New("已校验的系统材料与原安装选择不一致") | |
| 163 | 新增: } | |
| 164 | 新增: return nil | |
| 165 | 新增:} | |
| 166 | 新增: | |
| 167 | 新增:// RecordPreparedMedia publishes a create-only receipt. The original choice | |
| 168 | 新增:// remains immutable throughout downloading, installation and concurrent retries. | |
| 169 | 新增:func RecordPreparedMedia(profile string, id uuid.UUID, ready hostimage.Plan) error { | |
| 170 | 新增: current, err := LoadInstallation(profile) | |
| 171 | 新增: if err != nil { | |
| 172 | 新增: return err | |
| 173 | 新增: } | |
| 174 | 新增: if current == nil || current.ID != id { | |
| 175 | 新增: return errors.New("安装选择已变化") | |
| 176 | 新增: } | |
| 177 | 新增: if err := matchPreparedMedia(current.Source, ready); err != nil { | |
| 178 | 新增: return err | |
| 179 | 新增: } | |
| 180 | 新增: data, err := json.Marshal(struct { | |
| 181 | 新增: ID uuid.UUID `json:"id"` | |
| 182 | 新增: Source hostimage.Plan `json:"source"` | |
| 183 | 新增: }{id, ready}) | |
| 184 | 新增: if err != nil { | |
| 185 | 新增: return err | |
| 186 | 新增: } | |
| 187 | 新增: return publishBinding(profile, "guest-install-media-"+id.String()+".json", data) | |
| 188 | 新增:} | |
| 189 | 新增: | |
| 190 | 新增:func FinishLinuxInstallation(profile string, id uuid.UUID) error { | |
| 191 | 新增: installed, err := LoadInstallation(profile) | |
| 192 | 新增: if err != nil { | |
| 193 | 新增: return err | |
| 194 | 新增: } | |
| 195 | 新增: if installed == nil || installed.ID != id || !hostimage.IsLinux(installed.System) { | |
| 196 | 新增: return errors.New("Linux 安装记录已变化") | |
| 197 | 新增: } | |
| 198 | 新增: // Keep recovery information until the persistent image choice can be read. | |
| 199 | 新增: system, err := hostimage.LinuxSystem(filepath.Join(profile, "state")) | |
| 200 | 新增: if err != nil { | |
| 201 | 新增: return err | |
| 202 | 新增: } | |
| 203 | 新增: if system != installed.System { | |
| 204 | 新增: return errors.New("Linux 安装尚未保存所选系统,保留安装记录以便继续") | |
| 205 | 新增: } | |
| 206 | 新增: return os.Remove(filepath.Join(profile, installRecord)) | |
| 207 | 新增:} | |
| 208 | 新增: | |
| 209 | 新增:// UnstartedInstallation reports whether the choice can be changed while | |
| 210 | 新增:// retaining every downloaded file and disk. A partial VM counts as started. | |
| 211 | 新增:func UnstartedInstallation(profile string, i Installation) (bool, error) { | |
| 212 | 新增: paths := []string{"macos-guest.json", "windows-guest.json", "windows-install-vm.txt", | |
| 213 | 新增: filepath.Join("state", "windows-"+strings.ReplaceAll(i.ID.String(), "-", "")), | |
| 214 | 新增: filepath.Join("state", "lima", "mac"), filepath.Join("state", "lima", "base-building"), filepath.Join("state", "lima", "base")} | |
| 215 | 新增: for _, rel := range paths { | |
| 216 | 新增: _, err := os.Lstat(filepath.Join(profile, rel)) | |
| 217 | 新增: if err == nil { | |
| 218 | 新增: return false, nil | |
| 219 | 新增: } | |
| 220 | 新增: if !errors.Is(err, os.ErrNotExist) { | |
| 221 | 新增: return false, err | |
| 222 | 新增: } | |
| 223 | 新增: } | |
| 224 | 新增: return true, nil | |
| 225 | 新增:} | |
| 226 | 新增: | |
| 227 | 新增:func ClearUnstartedInstallation(profile string, id uuid.UUID) error { | |
| 228 | 新增: pending, err := LoadInstallation(profile) | |
| 229 | 新增: if err != nil { | |
| 230 | 新增: return err | |
| 231 | 新增: } | |
| 232 | 新增: if pending == nil || pending.ID != id { | |
| 233 | 新增: return errors.New("客户机安装选择已改变") | |
| 234 | 新增: } | |
| 235 | 新增: canClear, err := UnstartedInstallation(profile, *pending) | |
| 236 | 新增: if err != nil { | |
| 237 | 新增: return err | |
| 238 | 新增: } | |
| 239 | 新增: if !canClear { | |
| 240 | 新增: return errors.New("已开始创建客户机,请继续原安装") | |
| 241 | 新增: } | |
| 242 | 新增: if hostimage.IsLinux(pending.System) { | |
| 243 | 新增: if err := hostimage.ClearLinuxTemplate(filepath.Join(profile, "state"), pending.Source); err != nil { | |
| 244 | 新增: return err | |
| 245 | 新增: } | |
| 246 | 新增: } | |
| 247 | 新增: return os.Remove(filepath.Join(profile, installRecord)) | |
| 248 | 新增:} | |
| 249 | 新增: | |
| 250 | 新增:// The Apple login surface accepts physical keys from the guest's initial US | |
| 251 | 新增:// layout. Check this before downloading media or creating the local account. | |
| 252 | 新增:func ValidMacOSInstallPassword(value string) bool { | |
| 253 | 新增: return len(value) >= 8 && len(value) <= 256 && strings.IndexFunc(value, func(r rune) bool { return r < ' ' || r > '~' }) < 0 | |
| 254 | 新增:} | |
| @@ -0,0 +1,107 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "crypto/ed25519" | |
| 6 | 新增: "crypto/rand" | |
| 7 | 新增: "github.com/google/uuid" | |
| 8 | 新增: "golang.org/x/crypto/ssh" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "testing" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:func TestInstallationKeepsChoiceAndRefusesToClearVM(t *testing.T) { | |
| 16 | 新增: p := t.TempDir() | |
| 17 | 新增: first := Installation{Version: 1, System: MacOS, ID: uuid.New()} | |
| 18 | 新增: if err := SaveInstallation(p, first); err != nil { | |
| 19 | 新增: t.Fatal(err) | |
| 20 | 新增: } | |
| 21 | 新增: if err := SaveInstallation(p, first); err != nil { | |
| 22 | 新增: t.Fatal(err) | |
| 23 | 新增: } | |
| 24 | 新增: other := first | |
| 25 | 新增: other.ID = uuid.New() | |
| 26 | 新增: if err := SaveInstallation(p, other); err == nil { | |
| 27 | 新增: t.Fatal("overwrote an active installation") | |
| 28 | 新增: } | |
| 29 | 新增: if err := ClearUnstartedInstallation(p, other.ID); err == nil { | |
| 30 | 新增: t.Fatal("stale reset changed selection") | |
| 31 | 新增: } | |
| 32 | 新增: disk := filepath.Join(p, "state", "lima", "mac") | |
| 33 | 新增: if err := os.MkdirAll(disk, 0700); err != nil { | |
| 34 | 新增: t.Fatal(err) | |
| 35 | 新增: } | |
| 36 | 新增: if err := ClearUnstartedInstallation(p, first.ID); err == nil { | |
| 37 | 新增: t.Fatal("forgot a partially installed VM") | |
| 38 | 新增: } | |
| 39 | 新增: got, err := LoadInstallation(p) | |
| 40 | 新增: if err != nil || got == nil || *got != first { | |
| 41 | 新增: t.Fatalf("changed original selection: %v %v", got, err) | |
| 42 | 新增: } | |
| 43 | 新增: if err := os.Remove(disk); err != nil { | |
| 44 | 新增: t.Fatal(err) | |
| 45 | 新增: } | |
| 46 | 新增: if err := ClearUnstartedInstallation(p, first.ID); err != nil { | |
| 47 | 新增: t.Fatal(err) | |
| 48 | 新增: } | |
| 49 | 新增: got, err = LoadInstallation(p) | |
| 50 | 新增: if err != nil || got != nil { | |
| 51 | 新增: t.Fatal("failed to clear media-only choice") | |
| 52 | 新增: } | |
| 53 | 新增:} | |
| 54 | 新增: | |
| 55 | 新增:func TestWindowsInstallRequiresMediaDigestAndEditorAgreement(t *testing.T) { | |
| 56 | 新增: i := Installation{Version: 1, System: Windows11, ID: uuid.New(), Media: filepath.Join(t.TempDir(), "system.iso"), SHA256: strings.Repeat("a", 64)} | |
| 57 | 新增: if err := i.Validate(); err == nil { | |
| 58 | 新增: t.Fatal("accepted without the editor agreement") | |
| 59 | 新增: } | |
| 60 | 新增: i.EditorTerms = true | |
| 61 | 新增: if err := i.Validate(); err != nil { | |
| 62 | 新增: t.Fatal(err) | |
| 63 | 新增: } | |
| 64 | 新增: i.SHA256 = "bad" | |
| 65 | 新增: if err := i.Validate(); err == nil { | |
| 66 | 新增: t.Fatal("accepted an incomplete ISO digest") | |
| 67 | 新增: } | |
| 68 | 新增:} | |
| 69 | 新增: | |
| 70 | 新增:func TestMacSerialIdentityIsUnambiguous(t *testing.T) { | |
| 71 | 新增: newKey := func() []byte { | |
| 72 | 新增: pub, _, err := ed25519.GenerateKey(rand.Reader) | |
| 73 | 新增: if err != nil { | |
| 74 | 新增: t.Fatal(err) | |
| 75 | 新增: } | |
| 76 | 新增: key, err := ssh.NewPublicKey(pub) | |
| 77 | 新增: if err != nil { | |
| 78 | 新增: t.Fatal(err) | |
| 79 | 新增: } | |
| 80 | 新增: return ssh.MarshalAuthorizedKey(key) | |
| 81 | 新增: } | |
| 82 | 新增: key := newKey() | |
| 83 | 新增: prefix := "CAGE-GUEST-HOST-KEY " | |
| 84 | 新增: line := prefix + strings.TrimSpace(string(key)) + " guest\r\n" | |
| 85 | 新增: got, err := parseInstallHostKey(strings.NewReader("startup\n" + line + line)) | |
| 86 | 新增: if err != nil || !bytes.Equal(key, got) { | |
| 87 | 新增: t.Fatalf("valid serial identity: %v", err) | |
| 88 | 新增: } | |
| 89 | 新增: for _, body := range []string{"", "other " + line, line + prefix + "bad", line + prefix + string(newKey())} { | |
| 90 | 新增: if _, err := parseInstallHostKey(strings.NewReader(body)); err == nil { | |
| 91 | 新增: t.Fatal("accepted missing or inconsistent identity") | |
| 92 | 新增: } | |
| 93 | 新增: } | |
| 94 | 新增:} | |
| 95 | 新增: | |
| 96 | 新增:func TestInitialMacPasswordCanBeEnteredAtTheLoginWindow(t *testing.T) { | |
| 97 | 新增: for _, value := range []string{"Mix @#?9", strings.Repeat("!", 256)} { | |
| 98 | 新增: if !ValidMacOSInstallPassword(value) { | |
| 99 | 新增: t.Fatal("rejected an enterable password") | |
| 100 | 新增: } | |
| 101 | 新增: } | |
| 102 | 新增: for _, value := range []string{"short", "中文输入示例密码", "abcde\tfgh", strings.Repeat("a", 257)} { | |
| 103 | 新增: if ValidMacOSInstallPassword(value) { | |
| 104 | 新增: t.Fatal("accepted an unsupported password") | |
| 105 | 新增: } | |
| 106 | 新增: } | |
| 107 | 新增:} | |
| @@ -0,0 +1,121 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:/* | |
| 6 | 新增:#cgo CFLAGS: -x objective-c -fno-objc-arc | |
| 7 | 新增:#cgo LDFLAGS: -framework Foundation -framework Security -framework Virtualization | |
| 8 | 新增:#import <Security/SecTask.h> | |
| 9 | 新增:#import <Virtualization/Virtualization.h> | |
| 10 | 新增:#include <stdint.h> | |
| 11 | 新增: | |
| 12 | 新增:typedef struct { | |
| 13 | 新增: const char *error; | |
| 14 | 新增: const char *version; | |
| 15 | 新增: const char *build; | |
| 16 | 新增: const char *url; | |
| 17 | 新增: uint64_t cpus; | |
| 18 | 新增: uint64_t memory; | |
| 19 | 新增:} cageMacRestore; | |
| 20 | 新增: | |
| 21 | 新增:extern void cageCompleteMacRestore(uintptr_t handle, cageMacRestore result); | |
| 22 | 新增: | |
| 23 | 新增:static bool cageHasVirtualizationEntitlement(void) { | |
| 24 | 新增: SecTaskRef task = SecTaskCreateFromSelf(NULL); | |
| 25 | 新增: if (!task) return false; | |
| 26 | 新增: CFTypeRef value = SecTaskCopyValueForEntitlement(task, CFSTR("com.apple.security.virtualization"), NULL); | |
| 27 | 新增: bool enabled = value && CFEqual(value, kCFBooleanTrue); | |
| 28 | 新增: if (value) CFRelease(value); | |
| 29 | 新增: CFRelease(task); | |
| 30 | 新增: return enabled; | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:// The Go binding's network lookup exposes only the URL. Apple's callback also | |
| 34 | 新增:// contains the compatible hardware requirements, without reading the IPSW. | |
| 35 | 新增:static void cageFetchMacRestore(uintptr_t handle) { | |
| 36 | 新增: @autoreleasepool { | |
| 37 | 新增: if (@available(macOS 12.0, *)) { | |
| 38 | 新增: if (!cageHasVirtualizationEntitlement()) { | |
| 39 | 新增: cageCompleteMacRestore(handle, (cageMacRestore){.error = "Cage must be signed with the com.apple.security.virtualization entitlement"}); | |
| 40 | 新增: return; | |
| 41 | 新增: } | |
| 42 | 新增: if (!VZVirtualMachine.supported) { | |
| 43 | 新增: cageCompleteMacRestore(handle, (cageMacRestore){.error = "virtualization is unavailable on this Mac"}); | |
| 44 | 新增: return; | |
| 45 | 新增: } | |
| 46 | 新增: [VZMacOSRestoreImage fetchLatestSupportedWithCompletionHandler:^(VZMacOSRestoreImage *image, NSError *error) { | |
| 47 | 新增: @autoreleasepool { | |
| 48 | 新增: if (error) { | |
| 49 | 新增: cageCompleteMacRestore(handle, (cageMacRestore){.error = error.localizedDescription.UTF8String}); | |
| 50 | 新增: return; | |
| 51 | 新增: } | |
| 52 | 新增: VZMacOSConfigurationRequirements *config = image.mostFeaturefulSupportedConfiguration; | |
| 53 | 新增: if (!config.hardwareModel.supported) { | |
| 54 | 新增: cageCompleteMacRestore(handle, (cageMacRestore){.error = "no macOS restore image supports this Mac"}); | |
| 55 | 新增: return; | |
| 56 | 新增: } | |
| 57 | 新增: NSOperatingSystemVersion os = image.operatingSystemVersion; | |
| 58 | 新增: NSString *version = [NSString stringWithFormat:@"%ld.%ld.%ld", | |
| 59 | 新增: (long)os.majorVersion, (long)os.minorVersion, (long)os.patchVersion]; | |
| 60 | 新增: cageCompleteMacRestore(handle, (cageMacRestore){ | |
| 61 | 新增: .version = version.UTF8String, | |
| 62 | 新增: .build = image.buildVersion.UTF8String, | |
| 63 | 新增: .url = image.URL.absoluteString.UTF8String, | |
| 64 | 新增: .cpus = config.minimumSupportedCPUCount, | |
| 65 | 新增: .memory = config.minimumSupportedMemorySize, | |
| 66 | 新增: }); | |
| 67 | 新增: } | |
| 68 | 新增: }]; | |
| 69 | 新增: } else { | |
| 70 | 新增: cageCompleteMacRestore(handle, (cageMacRestore){.error = "macOS restore images require macOS 12 or later"}); | |
| 71 | 新增: } | |
| 72 | 新增: } | |
| 73 | 新增:} | |
| 74 | 新增:*/ | |
| 75 | 新增:import "C" | |
| 76 | 新增: | |
| 77 | 新增:import ( | |
| 78 | 新增: "context" | |
| 79 | 新增: "errors" | |
| 80 | 新增: "runtime/cgo" | |
| 81 | 新增:) | |
| 82 | 新增: | |
| 83 | 新增:type macRestoreResult struct { | |
| 84 | 新增: image MacRestore | |
| 85 | 新增: err error | |
| 86 | 新增:} | |
| 87 | 新增: | |
| 88 | 新增:func probeMacHost(ctx context.Context) (MacRestore, error) { | |
| 89 | 新增: if err := ctx.Err(); err != nil { | |
| 90 | 新增: return MacRestore{}, err | |
| 91 | 新增: } | |
| 92 | 新增: done := make(chan macRestoreResult, 1) | |
| 93 | 新增: C.cageFetchMacRestore(C.uintptr_t(cgo.NewHandle(done))) | |
| 94 | 新增: select { | |
| 95 | 新增: case <-ctx.Done(): | |
| 96 | 新增: return MacRestore{}, ctx.Err() | |
| 97 | 新增: case result := <-done: | |
| 98 | 新增: return result.image, result.err | |
| 99 | 新增: } | |
| 100 | 新增:} | |
| 101 | 新增: | |
| 102 | 新增:// The framework owns the request until completion. A late callback releases | |
| 103 | 新增:// the handle and can finish even when its caller already timed out. | |
| 104 | 新增:// | |
| 105 | 新增://export cageCompleteMacRestore | |
| 106 | 新增:func cageCompleteMacRestore(handle C.uintptr_t, native C.cageMacRestore) { | |
| 107 | 新增: h := cgo.Handle(handle) | |
| 108 | 新增: done := h.Value().(chan macRestoreResult) | |
| 109 | 新增: defer h.Delete() | |
| 110 | 新增: if native.error != nil { | |
| 111 | 新增: done <- macRestoreResult{err: errors.New(C.GoString(native.error))} | |
| 112 | 新增: return | |
| 113 | 新增: } | |
| 114 | 新增: done <- macRestoreResult{image: MacRestore{ | |
| 115 | 新增: Version: C.GoString(native.version), | |
| 116 | 新增: Build: C.GoString(native.build), | |
| 117 | 新增: URL: C.GoString(native.url), | |
| 118 | 新增: MinimumCPUs: int(native.cpus), | |
| 119 | 新增: MinimumMemoryBytes: uint64(native.memory), | |
| 120 | 新增: }} | |
| 121 | 新增:} | |
| @@ -0,0 +1,15 @@ | ||
| 1 | 新增://go:build darwin && (!arm64 || !cgo || no_vz) | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func probeMacHost(ctx context.Context) (MacRestore, error) { | |
| 11 | 新增: if err := ctx.Err(); err != nil { | |
| 12 | 新增: return MacRestore{}, err | |
| 13 | 新增: } | |
| 14 | 新增: return MacRestore{}, errors.New("macOS guests require Apple silicon and a Cage build with native Virtualization support") | |
| 15 | 新增:} | |
| @@ -0,0 +1,24 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:// MacLoginRequest is the local one-instance login control protocol. No guest or | |
| 4 | 新增:// host file paths, clipboard contents, or global shortcuts are accepted. Only | |
| 5 | 新增:// the authenticated host may attach a stored password to fill-password. | |
| 6 | 新增:type MacLoginRequest struct { | |
| 7 | 新增: Action string `json:"action"` | |
| 8 | 新增: Session string `json:"session,omitempty"` | |
| 9 | 新增: Setup bool `json:"initial_setup,omitempty"` | |
| 10 | 新增: Code int `json:"code"` | |
| 11 | 新增: Shift bool `json:"shift"` | |
| 12 | 新增: X int `json:"x"` | |
| 13 | 新增: Y int `json:"y"` | |
| 14 | 新增: DeltaX int `json:"delta_x,omitempty"` | |
| 15 | 新增: DeltaY int `json:"delta_y,omitempty"` | |
| 16 | 新增: Password string `json:"password,omitempty"` | |
| 17 | 新增:} | |
| 18 | 新增:type MacLoginReply struct { | |
| 19 | 新增: MIME string `json:"mime,omitempty"` | |
| 20 | 新增: Session string `json:"session,omitempty"` | |
| 21 | 新增: Image []byte `json:"image,omitempty"` | |
| 22 | 新增: Error string `json:"error,omitempty"` | |
| 23 | 新增: Closed bool `json:"closed,omitempty"` | |
| 24 | 新增:} | |
| @@ -0,0 +1,200 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "crypto/sha256" | |
| 6 | 新增: "encoding/hex" | |
| 7 | 新增: "encoding/json" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "fmt" | |
| 10 | 新增: "github.com/google/uuid" | |
| 11 | 新增: "os" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "regexp" | |
| 14 | 新增: | |
| 15 | 新增: "golang.org/x/crypto/ssh" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:// MacOSProfile binds one prepared local VZ guest to its ordinary development account. | |
| 19 | 新增:type MacOSProfile struct { | |
| 20 | 新增: Version int `json:"version"` | |
| 21 | 新增: Instance string `json:"instance"` | |
| 22 | 新增: User string `json:"user"` | |
| 23 | 新增: MachineID string `json:"machineID"` | |
| 24 | 新增: SetupID string `json:"initial_setup,omitempty"` | |
| 25 | 新增:} | |
| 26 | 新增: | |
| 27 | 新增:var macUser = regexp.MustCompile(`^[a-z][a-z0-9_]{0,30}$`) | |
| 28 | 新增: | |
| 29 | 新增:func macMachineID(profile string) (string, error) { | |
| 30 | 新增: path := filepath.Join(profile, "state", "lima", "mac", "vz-identifier") | |
| 31 | 新增: info, err := os.Lstat(path) | |
| 32 | 新增: if err != nil { | |
| 33 | 新增: return "", err | |
| 34 | 新增: } | |
| 35 | 新增: if !info.Mode().IsRegular() || info.Size() == 0 || info.Size() > 4096 { | |
| 36 | 新增: return "", errors.New("invalid Apple virtual machine identifier") | |
| 37 | 新增: } | |
| 38 | 新增: data, err := os.ReadFile(path) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: return "", err | |
| 41 | 新增: } | |
| 42 | 新增: sum := sha256.Sum256(data) | |
| 43 | 新增: return hex.EncodeToString(sum[:]), nil | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:func LoadMacOSProfile(profile string) (*MacOSProfile, error) { | |
| 47 | 新增: path := filepath.Join(profile, "macos-guest.json") | |
| 48 | 新增: info, err := os.Lstat(path) | |
| 49 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 50 | 新增: return nil, nil | |
| 51 | 新增: } | |
| 52 | 新增: if err != nil { | |
| 53 | 新增: return nil, err | |
| 54 | 新增: } | |
| 55 | 新增: if !info.Mode().IsRegular() || info.Size() > 4096 { | |
| 56 | 新增: return nil, errors.New("invalid macOS guest profile") | |
| 57 | 新增: } | |
| 58 | 新增: data, err := os.ReadFile(path) | |
| 59 | 新增: if err != nil { | |
| 60 | 新增: return nil, err | |
| 61 | 新增: } | |
| 62 | 新增: var m MacOSProfile | |
| 63 | 新增: if err := json.Unmarshal(data, &m); err != nil { | |
| 64 | 新增: return nil, err | |
| 65 | 新增: } | |
| 66 | 新增: if m.Version != 1 || m.Instance != "mac" || !macUser.MatchString(m.User) || m.User == "root" { | |
| 67 | 新增: return nil, errors.New("invalid macOS guest profile or login") | |
| 68 | 新增: } | |
| 69 | 新增: if m.SetupID != "" && !validSetupID(m.SetupID) { | |
| 70 | 新增: return nil, errors.New("invalid first setup identity") | |
| 71 | 新增: } | |
| 72 | 新增: id, err := macMachineID(profile) | |
| 73 | 新增: if err != nil { | |
| 74 | 新增: return nil, err | |
| 75 | 新增: } | |
| 76 | 新增: if id != m.MachineID { | |
| 77 | 新增: return nil, errors.New("the macOS guest differs from the machine bound to this profile") | |
| 78 | 新增: } | |
| 79 | 新增: return &m, nil | |
| 80 | 新增:} | |
| 81 | 新增: | |
| 82 | 新增:// BindMacOSProfile takes an independently obtained guest host public key. Do | |
| 83 | 新增:// not discover this key by scanning an unverified localhost SSH port. | |
| 84 | 新增:func BindMacOSProfile(profile, user string, hostKey []byte) error { | |
| 85 | 新增: return bindMacOSProfile(profile, user, hostKey, "") | |
| 86 | 新增:} | |
| 87 | 新增: | |
| 88 | 新增:// BindNewMacOSProfile is called only by the fresh, resumable installer. | |
| 89 | 新增:func BindNewMacOSProfile(profile, user string, hostKey []byte, id uuid.UUID) error { | |
| 90 | 新增: install, err := LoadInstallation(profile) | |
| 91 | 新增: if err != nil { | |
| 92 | 新增: return err | |
| 93 | 新增: } | |
| 94 | 新增: if install == nil || id == uuid.Nil || install.ID != id || install.System != MacOS { | |
| 95 | 新增: return errors.New("首次设置与当前安装记录不匹配") | |
| 96 | 新增: } | |
| 97 | 新增: return bindMacOSProfile(profile, user, hostKey, id.String()) | |
| 98 | 新增:} | |
| 99 | 新增: | |
| 100 | 新增:func validSetupID(id string) bool { | |
| 101 | 新增: value, err := uuid.Parse(id) | |
| 102 | 新增: return err == nil && value != uuid.Nil && value.String() == id | |
| 103 | 新增:} | |
| 104 | 新增: | |
| 105 | 新增:func bindMacOSProfile(profile, user string, hostKey []byte, setupID string) error { | |
| 106 | 新增: if !macUser.MatchString(user) || user == "root" { | |
| 107 | 新增: return errors.New("supply the short name of the ordinary macOS guest account") | |
| 108 | 新增: } | |
| 109 | 新增: key, _, options, rest, err := ssh.ParseAuthorizedKey(hostKey) | |
| 110 | 新增: if err != nil || len(options) != 0 || len(bytes.TrimSpace(rest)) != 0 || key.Type() != ssh.KeyAlgoED25519 { | |
| 111 | 新增: return errors.New("expected one Ed25519 guest SSH host public key") | |
| 112 | 新增: } | |
| 113 | 新增: id, err := macMachineID(profile) | |
| 114 | 新增: if err != nil { | |
| 115 | 新增: return err | |
| 116 | 新增: } | |
| 117 | 新增: m := MacOSProfile{Version: 1, Instance: "mac", User: user, MachineID: id, SetupID: setupID} | |
| 118 | 新增: data, err := json.Marshal(m) | |
| 119 | 新增: if err != nil { | |
| 120 | 新增: return err | |
| 121 | 新增: } | |
| 122 | 新增: if current, err := LoadMacOSProfile(profile); err != nil { | |
| 123 | 新增: return err | |
| 124 | 新增: } else if current != nil && *current != m { | |
| 125 | 新增: return errors.New("this profile is already bound to another macOS guest account") | |
| 126 | 新增: } | |
| 127 | 新增: if err := publishBinding(profile, "macos-known-hosts", append([]byte("cage-macos "), ssh.MarshalAuthorizedKey(key)...)); err != nil { | |
| 128 | 新增: return err | |
| 129 | 新增: } | |
| 130 | 新增: return publishBinding(profile, "macos-guest.json", append(data, '\n')) | |
| 131 | 新增:} | |
| 132 | 新增: | |
| 133 | 新增:func publishBinding(profile, name string, data []byte) error { | |
| 134 | 新增: temp, err := os.CreateTemp(profile, ".guest-binding-*") | |
| 135 | 新增: if err != nil { | |
| 136 | 新增: return err | |
| 137 | 新增: } | |
| 138 | 新增: defer os.Remove(temp.Name()) | |
| 139 | 新增: _, writeErr := temp.Write(data) | |
| 140 | 新增: if err := errors.Join(writeErr, temp.Close()); err != nil { | |
| 141 | 新增: return err | |
| 142 | 新增: } | |
| 143 | 新增: path := filepath.Join(profile, name) | |
| 144 | 新增: if err := os.Link(temp.Name(), path); !errors.Is(err, os.ErrExist) { | |
| 145 | 新增: return err | |
| 146 | 新增: } | |
| 147 | 新增: info, err := os.Lstat(path) | |
| 148 | 新增: if err != nil || !info.Mode().IsRegular() || info.Size() != int64(len(data)) { | |
| 149 | 新增: return fmt.Errorf("unexpected existing %s", name) | |
| 150 | 新增: } | |
| 151 | 新增: prior, err := os.ReadFile(path) | |
| 152 | 新增: if err != nil || !bytes.Equal(data, prior) { | |
| 153 | 新增: return fmt.Errorf("refusing to replace existing %s", name) | |
| 154 | 新增: } | |
| 155 | 新增: return nil | |
| 156 | 新增:} | |
| 157 | 新增: | |
| 158 | 新增:// PinMacOSInstallHostKey persists only the host key, without enabling the workbench. | |
| 159 | 新增:func PinMacOSInstallHostKey(profile string) error { | |
| 160 | 新增: key, err := MacOSInstallHostKey(profile) | |
| 161 | 新增: if err != nil { | |
| 162 | 新增: return err | |
| 163 | 新增: } | |
| 164 | 新增: return publishBinding(profile, "macos-known-hosts", append([]byte("cage-macos "), key...)) | |
| 165 | 新增:} | |
| 166 | 新增: | |
| 167 | 新增:// FinishMacOSSetup removes the installation identity from the existing binding. | |
| 168 | 新增:// Binding publication is create-only, so retrying an installer cannot reopen it. | |
| 169 | 新增:func FinishMacOSSetup(profile, setupID string) error { | |
| 170 | 新增: bound, err := LoadMacOSProfile(profile) | |
| 171 | 新增: if err != nil { | |
| 172 | 新增: return err | |
| 173 | 新增: } | |
| 174 | 新增: if bound == nil || !validSetupID(setupID) || bound.SetupID != setupID { | |
| 175 | 新增: return errors.New("首次设置已关闭或安装实例已变更") | |
| 176 | 新增: } | |
| 177 | 新增: bound.SetupID = "" | |
| 178 | 新增: data, err := json.Marshal(bound) | |
| 179 | 新增: if err != nil { | |
| 180 | 新增: return err | |
| 181 | 新增: } | |
| 182 | 新增: f, err := os.CreateTemp(profile, ".finish-guest-setup-*") | |
| 183 | 新增: if err != nil { | |
| 184 | 新增: return err | |
| 185 | 新增: } | |
| 186 | 新增: defer os.Remove(f.Name()) | |
| 187 | 新增: _, writeErr := f.Write(append(data, '\n')) | |
| 188 | 新增: if err = errors.Join(writeErr, f.Sync(), f.Close()); err != nil { | |
| 189 | 新增: return err | |
| 190 | 新增: } | |
| 191 | 新增: if err = os.Rename(f.Name(), filepath.Join(profile, "macos-guest.json")); err != nil { | |
| 192 | 新增: return err | |
| 193 | 新增: } | |
| 194 | 新增: dir, err := os.Open(profile) | |
| 195 | 新增: if err != nil { | |
| 196 | 新增: return err | |
| 197 | 新增: } | |
| 198 | 新增: defer dir.Close() | |
| 199 | 新增: return dir.Sync() | |
| 200 | 新增:} | |
| @@ -0,0 +1,104 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/ed25519" | |
| 5 | 新增: "crypto/rand" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "testing" | |
| 9 | 新增: | |
| 10 | 新增: "github.com/google/uuid" | |
| 11 | 新增: "golang.org/x/crypto/ssh" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func TestPreparedMacOSBindingRejectsChangedKeyAndDisk(t *testing.T) { | |
| 15 | 新增: profile := t.TempDir() | |
| 16 | 新增: dir := filepath.Join(profile, "state", "lima", "mac") | |
| 17 | 新增: if err := os.MkdirAll(dir, 0700); err != nil { | |
| 18 | 新增: t.Fatal(err) | |
| 19 | 新增: } | |
| 20 | 新增: identifier := filepath.Join(dir, "vz-identifier") | |
| 21 | 新增: if err := os.WriteFile(identifier, []byte("one trial machine"), 0600); err != nil { | |
| 22 | 新增: t.Fatal(err) | |
| 23 | 新增: } | |
| 24 | 新增: key := func() []byte { | |
| 25 | 新增: pub, _, err := ed25519.GenerateKey(rand.Reader) | |
| 26 | 新增: if err != nil { | |
| 27 | 新增: t.Fatal(err) | |
| 28 | 新增: } | |
| 29 | 新增: p, err := ssh.NewPublicKey(pub) | |
| 30 | 新增: if err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: return ssh.MarshalAuthorizedKey(p) | |
| 34 | 新增: } | |
| 35 | 新增: pub := key() | |
| 36 | 新增: if err := BindMacOSProfile(profile, "dev", pub); err != nil { | |
| 37 | 新增: t.Fatal(err) | |
| 38 | 新增: } | |
| 39 | 新增: if err := BindMacOSProfile(profile, "dev", pub); err != nil { | |
| 40 | 新增: t.Fatal(err) | |
| 41 | 新增: } | |
| 42 | 新增: if err := BindMacOSProfile(profile, "dev", key()); err == nil { | |
| 43 | 新增: t.Error("changed host key accepted") | |
| 44 | 新增: } | |
| 45 | 新增: if err := BindMacOSProfile(profile, "root", pub); err == nil { | |
| 46 | 新增: t.Error("root login accepted") | |
| 47 | 新增: } | |
| 48 | 新增: if m, err := LoadMacOSProfile(profile); err != nil || m.User != "dev" { | |
| 49 | 新增: t.Fatal(m, err) | |
| 50 | 新增: } | |
| 51 | 新增: if err := os.WriteFile(identifier, []byte("replaced guest"), 0600); err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: if _, err := LoadMacOSProfile(profile); err == nil { | |
| 55 | 新增: t.Error("replacement machine accepted") | |
| 56 | 新增: } | |
| 57 | 新增:} | |
| 58 | 新增: | |
| 59 | 新增:func TestMacFirstSetupCanOnlySealItsNewGuest(t *testing.T) { | |
| 60 | 新增: profile := t.TempDir() | |
| 61 | 新增: dir := filepath.Join(profile, "state", "lima", "mac") | |
| 62 | 新增: if err := os.MkdirAll(dir, 0700); err != nil { | |
| 63 | 新增: t.Fatal(err) | |
| 64 | 新增: } | |
| 65 | 新增: if err := os.WriteFile(filepath.Join(dir, "vz-identifier"), []byte("new-mac"), 0600); err != nil { | |
| 66 | 新增: t.Fatal(err) | |
| 67 | 新增: } | |
| 68 | 新增: pub, _, err := ed25519.GenerateKey(rand.Reader) | |
| 69 | 新增: if err != nil { | |
| 70 | 新增: t.Fatal(err) | |
| 71 | 新增: } | |
| 72 | 新增: key, err := ssh.NewPublicKey(pub) | |
| 73 | 新增: if err != nil { | |
| 74 | 新增: t.Fatal(err) | |
| 75 | 新增: } | |
| 76 | 新增: hostKey := ssh.MarshalAuthorizedKey(key) | |
| 77 | 新增: id := uuid.New() | |
| 78 | 新增: if err = BindNewMacOSProfile(profile, "cageuser", hostKey, id); err == nil { | |
| 79 | 新增: t.Fatal("accepted missing install record") | |
| 80 | 新增: } | |
| 81 | 新增: if err = SaveInstallation(profile, Installation{Version: 1, System: MacOS, ID: id}); err != nil { | |
| 82 | 新增: t.Fatal(err) | |
| 83 | 新增: } | |
| 84 | 新增: if err = BindNewMacOSProfile(profile, "cageuser", hostKey, id); err != nil { | |
| 85 | 新增: t.Fatal(err) | |
| 86 | 新增: } | |
| 87 | 新增: if err = FinishMacOSSetup(profile, uuid.NewString()); err == nil { | |
| 88 | 新增: t.Fatal("sealed unrelated install") | |
| 89 | 新增: } | |
| 90 | 新增: bound, err := LoadMacOSProfile(profile) | |
| 91 | 新增: if err != nil || bound.SetupID != id.String() { | |
| 92 | 新增: t.Fatal("lost pending setup") | |
| 93 | 新增: } | |
| 94 | 新增: if err = FinishMacOSSetup(profile, id.String()); err != nil { | |
| 95 | 新增: t.Fatal(err) | |
| 96 | 新增: } | |
| 97 | 新增: if err = BindNewMacOSProfile(profile, "cageuser", hostKey, id); err == nil { | |
| 98 | 新增: t.Fatal("a retried installer reopened setup") | |
| 99 | 新增: } | |
| 100 | 新增: bound, err = LoadMacOSProfile(profile) | |
| 101 | 新增: if err != nil || bound.SetupID != "" { | |
| 102 | 新增: t.Fatal("setup still open") | |
| 103 | 新增: } | |
| 104 | 新增:} | |
| @@ -0,0 +1,29 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "testing" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestMacOSProvisionIdentity(t *testing.T) { | |
| 10 | 新增: profile := t.TempDir() | |
| 11 | 新增: dir := filepath.Join(profile, "state", "lima", "mac") | |
| 12 | 新增: if err := os.MkdirAll(dir, 0700); err != nil { | |
| 13 | 新增: t.Fatal(err) | |
| 14 | 新增: } | |
| 15 | 新增: for _, tc := range []struct{ config, want string }{ | |
| 16 | 新增: {"Host lima-mac\n User cage\n Port 12345\n", "cage"}, | |
| 17 | 新增: {"Host lima-mac\n User cageprovision\n Port 12345\n", "cageprovision"}, | |
| 18 | 新增: {"User cageuser\n", ""}, {"User root\n", ""}, {"Port 12345\n", ""}, | |
| 19 | 新增: {"User cage\nUser cageprovision\n", ""}, {"User cage extra\n", ""}, | |
| 20 | 新增: } { | |
| 21 | 新增: if err := os.WriteFile(filepath.Join(dir, "ssh.config"), []byte(tc.config), 0600); err != nil { | |
| 22 | 新增: t.Fatal(err) | |
| 23 | 新增: } | |
| 24 | 新增: got, err := MacOSProvisionUser(profile) | |
| 25 | 新增: if got != tc.want || (err == nil) != (tc.want != "") { | |
| 26 | 新增: t.Fatalf("%q: got %q, %v", tc.config, got, err) | |
| 27 | 新增: } | |
| 28 | 新增: } | |
| 29 | 新增:} | |
| @@ -0,0 +1,61 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bufio" | |
| 5 | 新增: "bytes" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "io" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "strings" | |
| 11 | 新增: | |
| 12 | 新增: "golang.org/x/crypto/ssh" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:// MacOSInstallHostKey reads the key written by the fresh guest's root-owned | |
| 16 | 新增:// first-boot script to its VZ serial attachment, independent of loopback SSH. | |
| 17 | 新增:func MacOSInstallHostKey(profile string) ([]byte, error) { | |
| 18 | 新增: path := filepath.Join(profile, "state", "lima", "mac", "serialv.log") | |
| 19 | 新增: info, err := os.Lstat(path) | |
| 20 | 新增: if err != nil { | |
| 21 | 新增: return nil, err | |
| 22 | 新增: } | |
| 23 | 新增: if !info.Mode().IsRegular() || info.Size() > 8<<20 { | |
| 24 | 新增: return nil, errors.New("无效的 macOS 客机首次启动串口记录") | |
| 25 | 新增: } | |
| 26 | 新增: file, err := os.Open(path) | |
| 27 | 新增: if err != nil { | |
| 28 | 新增: return nil, err | |
| 29 | 新增: } | |
| 30 | 新增: defer file.Close() | |
| 31 | 新增: return parseInstallHostKey(io.LimitReader(file, info.Size())) | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:func parseInstallHostKey(input io.Reader) ([]byte, error) { | |
| 35 | 新增: const prefix = "CAGE-GUEST-HOST-KEY " | |
| 36 | 新增: scanner := bufio.NewScanner(input) | |
| 37 | 新增: var found []byte | |
| 38 | 新增: for scanner.Scan() { | |
| 39 | 新增: line := strings.TrimSuffix(scanner.Text(), "\r") | |
| 40 | 新增: keyLine, ok := strings.CutPrefix(line, prefix) | |
| 41 | 新增: if !ok { | |
| 42 | 新增: continue | |
| 43 | 新增: } | |
| 44 | 新增: key, _, opts, rest, err := ssh.ParseAuthorizedKey([]byte(keyLine)) | |
| 45 | 新增: if err != nil || key.Type() != ssh.KeyAlgoED25519 || len(opts) != 0 || len(rest) != 0 { | |
| 46 | 新增: return nil, errors.New("虚拟 Mac 首次启动返回了无效的主机公钥") | |
| 47 | 新增: } | |
| 48 | 新增: candidate := ssh.MarshalAuthorizedKey(key) | |
| 49 | 新增: if found != nil && !bytes.Equal(found, candidate) { | |
| 50 | 新增: return nil, errors.New("虚拟 Mac 首次启动返回了不同的主机公钥") | |
| 51 | 新增: } | |
| 52 | 新增: found = candidate | |
| 53 | 新增: } | |
| 54 | 新增: if err := scanner.Err(); err != nil { | |
| 55 | 新增: return nil, err | |
| 56 | 新增: } | |
| 57 | 新增: if found == nil { | |
| 58 | 新增: return nil, errors.New("尚未从这台虚拟 Mac 的串口取得主机公钥") | |
| 59 | 新增: } | |
| 60 | 新增: return found, nil | |
| 61 | 新增:} | |
| @@ -0,0 +1,79 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "os" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: "strconv" | |
| 8 | 新增: "strings" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:// Lima chooses a new loopback port on each boot. Read only that number from | |
| 12 | 新增:// its generated config; use the provisioned VM key, user and identity file. | |
| 13 | 新增:func MacOSSSHPort(config []byte) (int, error) { | |
| 14 | 新增: var port int | |
| 15 | 新增: for _, line := range strings.Split(string(config), "\n") { | |
| 16 | 新增: fields := strings.Fields(line) | |
| 17 | 新增: if len(fields) == 0 || !strings.EqualFold(fields[0], "port") { | |
| 18 | 新增: continue | |
| 19 | 新增: } | |
| 20 | 新增: if len(fields) != 2 || port != 0 { | |
| 21 | 新增: return 0, errors.New("macOS 客机 SSH 端口配置无效") | |
| 22 | 新增: } | |
| 23 | 新增: value, err := strconv.Atoi(fields[1]) | |
| 24 | 新增: if err != nil || value < 1 || value > 65535 { | |
| 25 | 新增: return 0, errors.New("macOS 客机 SSH 端口配置无效") | |
| 26 | 新增: } | |
| 27 | 新增: port = value | |
| 28 | 新增: } | |
| 29 | 新增: if port == 0 { | |
| 30 | 新增: return 0, errors.New("macOS 客机 SSH 端口尚未就绪") | |
| 31 | 新增: } | |
| 32 | 新增: return port, nil | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:func MacOSSSHArgs(profile, user string) ([]string, error) { | |
| 36 | 新增: data, err := os.ReadFile(filepath.Join(profile, "state", "lima", "mac", "ssh.config")) | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: return nil, err | |
| 39 | 新增: } | |
| 40 | 新增: port, err := MacOSSSHPort(data) | |
| 41 | 新增: if err != nil { | |
| 42 | 新增: return nil, err | |
| 43 | 新增: } | |
| 44 | 新增: known := filepath.Join(profile, "macos-known-hosts") | |
| 45 | 新增: // ssh -o parses each option as a config line; quote paths with spaces. | |
| 46 | 新增: base := []string{"-q", "-e", "none", "-F", os.DevNull, "-p", strconv.Itoa(port), | |
| 47 | 新增: "-l", user, "-i", filepath.Join(profile, "state", "lima", "_config", "user"), | |
| 48 | 新增: "-o", "Hostname=127.0.0.1", "-o", "HostKeyAlias=cage-macos", | |
| 49 | 新增: "-o", "StrictHostKeyChecking=yes", "-o", "HostKeyAlgorithms=ssh-ed25519", | |
| 50 | 新增: "-o", "UserKnownHostsFile=" + strconv.Quote(known), "-o", "GlobalKnownHostsFile=" + os.DevNull, | |
| 51 | 新增: "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none", | |
| 52 | 新增: "-o", "ForwardAgent=no", "-o", "ClearAllForwardings=yes", "-o", "ControlPath=none", | |
| 53 | 新增: "-o", "ConnectTimeout=3", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=2"} | |
| 54 | 新增: return base, nil | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:// MacOSProvisionUser reads Lima's installation identity, including older VMs. | |
| 58 | 新增:// Only these two dedicated identities may run privileged maintenance. | |
| 59 | 新增:func MacOSProvisionUser(profile string) (string, error) { | |
| 60 | 新增: data, err := os.ReadFile(filepath.Join(profile, "state", "lima", "mac", "ssh.config")) | |
| 61 | 新增: if err != nil { | |
| 62 | 新增: return "", err | |
| 63 | 新增: } | |
| 64 | 新增: var user string | |
| 65 | 新增: for _, line := range strings.Split(string(data), "\n") { | |
| 66 | 新增: fields := strings.Fields(line) | |
| 67 | 新增: if len(fields) == 0 || !strings.EqualFold(fields[0], "User") { | |
| 68 | 新增: continue | |
| 69 | 新增: } | |
| 70 | 新增: if len(fields) != 2 || user != "" || (fields[1] != "cage" && fields[1] != "cageprovision") { | |
| 71 | 新增: return "", errors.New("macOS 客机安装账户配置无效") | |
| 72 | 新增: } | |
| 73 | 新增: user = fields[1] | |
| 74 | 新增: } | |
| 75 | 新增: if user == "" { | |
| 76 | 新增: return "", errors.New("macOS 客机安装账户尚未就绪") | |
| 77 | 新增: } | |
| 78 | 新增: return user, nil | |
| 79 | 新增:} | |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "os/exec" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func WindowsMaintenanceCommand(context.Context, string, string, string, bool) (*exec.Cmd, error) { | |
| 12 | 新增: return nil, errors.New("Windows 客机维护需要其 Windows Hyper-V 主机") | |
| 13 | 新增:} | |
| @@ -0,0 +1,39 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "crypto/sha256" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "fmt" | |
| 10 | 新增: "os" | |
| 11 | 新增: "os/exec" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: | |
| 14 | 新增: "golang.org/x/sys/windows" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func WindowsMaintenanceCommand(ctx context.Context, profile, kit, manifest string, tools bool) (*exec.Cmd, error) { | |
| 18 | 新增: binding, err := LoadWindowsProfile(profile) | |
| 19 | 新增: if err != nil { | |
| 20 | 新增: return nil, err | |
| 21 | 新增: } | |
| 22 | 新增: if binding == nil { | |
| 23 | 新增: return nil, errors.New("此配置尚未绑定 Windows 客机") | |
| 24 | 新增: } | |
| 25 | 新增: system, err := windows.GetSystemDirectory() | |
| 26 | 新增: if err != nil { | |
| 27 | 新增: return nil, err | |
| 28 | 新增: } | |
| 29 | 新增: data, err := os.ReadFile(manifest) | |
| 30 | 新增: if err != nil { | |
| 31 | 新增: return nil, err | |
| 32 | 新增: } | |
| 33 | 新增: hash := fmt.Sprintf("%x", sha256.Sum256(data)) | |
| 34 | 新增: args := []string{"-NoLogo", "-NoProfile", "-ExecutionPolicy", "RemoteSigned", "-File", filepath.Join(kit, "maintain-windows-workbench.ps1"), "-Profile", profile, "-ManifestPath", manifest, "-ManifestSHA256", hash} | |
| 35 | 新增: if tools { | |
| 36 | 新增: args = append(args, "-Tools") | |
| 37 | 新增: } | |
| 38 | 新增: return exec.CommandContext(ctx, filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe"), args...), nil | |
| 39 | 新增:} | |
| @@ -0,0 +1,55 @@ | ||
| 1 | 新增:# Exercise the bundled read-only query. No Hyper-V service or real VM is used. | |
| 2 | 新增:param([Parameter(Mandatory)][string]$Query) | |
| 3 | 新增:$ErrorActionPreference = 'Stop' | |
| 4 | 新增:$targetId = [Guid]::NewGuid() | |
| 5 | 新增:$global:hypervTestId = $targetId | |
| 6 | 新增:$global:hypervCase = 'single' | |
| 7 | 新增:function Get-CimInstance { | |
| 8 | 新增: param($Namespace,$ClassName,$Filter) | |
| 9 | 新增: if ($Namespace -ne 'root/virtualization/v2' -or $ClassName -ne 'Msvm_ComputerSystem' -or $Filter -ne "Name='$global:hypervTestId'") { throw 'Unscoped VM lookup.' } | |
| 10 | 新增: if ($global:hypervCase -eq 'denied') { throw 'test management access denied' } | |
| 11 | 新增: if ($global:hypervCase -ne 'absent') { [pscustomobject]@{Name=$global:hypervTestId} } | |
| 12 | 新增:} | |
| 13 | 新增:$fake = New-Module -Name Hyper-V -ScriptBlock { | |
| 14 | 新增: function Get-VM { | |
| 15 | 新增: param($Id) | |
| 16 | 新增: if ($id -ne $global:hypervTestId) { throw 'Unscoped management lookup' } | |
| 17 | 新增: $returned = if ($global:hypervCase -eq 'swapped') { [Guid]::NewGuid() } else { $id } | |
| 18 | 新增: $generation = if ($global:hypervCase -eq 'legacy') { 1 } else { 2 } | |
| 19 | 新增: $state = if ($global:hypervCase -eq 'connected') { 'Running' } else { 'Off' } | |
| 20 | 新增: [pscustomobject]@{Id=$returned; Generation=$generation; State=$state} | |
| 21 | 新增: } | |
| 22 | 新增: function Get-VMHardDiskDrive { | |
| 23 | 新增: param($VM) | |
| 24 | 新增: [pscustomobject]@{Path='C:\private-qa\system.vhdx'} | |
| 25 | 新增: if ($global:hypervCase -eq 'connected') { [pscustomobject]@{Path='C:\private-qa\second.vhdx'} } | |
| 26 | 新增: } | |
| 27 | 新增: function Get-VMNetworkAdapter { param($VM) if ($global:hypervCase -eq 'connected') { [pscustomobject]@{Name='adapter'} } } | |
| 28 | 新增: function Get-VHD { | |
| 29 | 新增: param($Path) | |
| 30 | 新增: if ($global:hypervCase -eq 'disk-denied') { throw 'test disk metadata unavailable' } | |
| 31 | 新增: if ($Path -cne 'C:\private-qa\system.vhdx') { throw 'Unexpected disk lookup' } | |
| 32 | 新增: [pscustomobject]@{VhdFormat='VHDX'; VhdType='Dynamic'} | |
| 33 | 新增: } | |
| 34 | 新增: function Get-VMFirmware {param($VM) if ($VM.Generation -ne 2) { throw 'Legacy VM firmware query' }; [pscustomobject]@{SecureBoot='On'; SecureBootTemplate='MicrosoftWindows'} } | |
| 35 | 新增: function Get-VMSecurity {param($VM) if ($VM.Generation -ne 2) { throw 'Legacy VM security query' }; [pscustomobject]@{TpmEnabled=$true} } | |
| 36 | 新增: Export-ModuleMember -Function 'Get-*' | |
| 37 | 新增:} | |
| 38 | 新增:Import-Module $fake -Force | |
| 39 | 新增:function Result { (& $Query) | ConvertFrom-Json } | |
| 40 | 新增:$found = Result | |
| 41 | 新增:if ($found.state -ne 'Off' -or $found.generation -ne 2 -or $found.diskCount -ne 1 -or !$found.singleLocalVhdx -or $found.diskType -ne 'Dynamic' -or !$found.secureBoot -or !$found.virtualTpm -or $found.networkAdapterCount -ne 0) { throw 'Invalid offline VM observation' } | |
| 42 | 新增:if (($found | ConvertTo-Json -Compress).Contains('private-qa')) { throw 'Host disk path exposed' } | |
| 43 | 新增:$global:hypervCase='connected'; $running=Result | |
| 44 | 新增:if ($running.state -ne 'Running' -or $running.networkAdapterCount -ne 1 -or $running.diskCount -ne 2 -or $running.singleLocalVhdx) { throw 'Connected or multiple-disk VM misreported' } | |
| 45 | 新增:$global:hypervCase='disk-denied' | |
| 46 | 新增:if ($null -ne (Result).singleLocalVhdx) { throw 'Denied disk metadata reported as verified' } | |
| 47 | 新增:$global:hypervCase='legacy'; $legacy = Result | |
| 48 | 新增:if ($legacy.secureBoot -or $legacy.virtualTpm) { throw 'Legacy VM reported as secure boot/vTPM capable' } | |
| 49 | 新增:$global:hypervCase='absent'; if ($null -ne (Result)) { throw 'Unexpected VM for missing ID' } | |
| 50 | 新增:foreach ($testCase in @('denied', 'swapped')) { | |
| 51 | 新增: $global:hypervCase = $testCase | |
| 52 | 新增: $rejected = $false | |
| 53 | 新增: try { $null = Result } catch { $rejected = $true } | |
| 54 | 新增: if (!$rejected) { throw 'Access failure or changed VM identity treated as a valid lookup' } | |
| 55 | 新增:} | |
| @@ -0,0 +1,29 @@ | ||
| 1 | 新增:param([Parameter(Mandatory)][string]$Query) | |
| 2 | 新增:$ErrorActionPreference='Stop' | |
| 3 | 新增:$script:targetId=[guid]'9e97dd9a-eb36-489a-bb1d-8d28a0d78682' | |
| 4 | 新增:$script:state='Off';$script:nics=0;$script:mutations=0;$script:generation=2;$script:secure='On' | |
| 5 | 新增:New-Module -Name Hyper-V -ScriptBlock { | |
| 6 | 新增: function Get-VM { param([Guid]$Id) if ($Id -ne $script:targetId) { throw 'Unscoped VM operation.' }; [pscustomobject]@{Id=$Id;State=$script:state;Generation=$script:generation} } | |
| 7 | 新增: function Get-VMFirmware { param($VM) if ($VM.Id -ne $script:targetId) { throw 'Wrong VM.' };[pscustomobject]@{SecureBoot=$script:secure;SecureBootTemplate='MicrosoftWindows'} } | |
| 8 | 新增: function Get-VMSecurity { param($VM) [pscustomobject]@{TpmEnabled=$true} } | |
| 9 | 新增: function Get-VMNetworkAdapter { param($VM) for($i=0;$i -lt $script:nics;$i++){[pscustomobject]@{Id=$i}} } | |
| 10 | 新增: function Start-VM { param($VM) if($VM.Id -ne $script:targetId){throw 'Wrong VM.'};$script:state='Running';$script:mutations++ } | |
| 11 | 新增: function Stop-VM { param($VM,[switch]$TurnOff,[switch]$Force) if($TurnOff -or $Force -or $VM.Id -ne $script:targetId){throw 'Unsafe stop.'};$script:state='Off';$script:mutations++ } | |
| 12 | 新增: Export-ModuleMember -Function * | |
| 13 | 新增:} | Import-Module -Force | |
| 14 | 新增:# Module state is independent: configure it deliberately for each case. | |
| 15 | 新增:$module=Get-Module Hyper-V | |
| 16 | 新增:& $module { $script:targetId=[guid]'9e97dd9a-eb36-489a-bb1d-8d28a0d78682';$script:state='Off';$script:nics=0;$script:mutations=0;$script:generation=2;$script:secure='On' } | |
| 17 | 新增:$action='start';$result=(& $Query)|ConvertFrom-Json | |
| 18 | 新增:if($result.state -ne 'Running'){throw 'Start failed.'} | |
| 19 | 新增:$action='stop';$result=(& $Query)|ConvertFrom-Json | |
| 20 | 新增:if($result.state -ne 'Off'){throw 'Stop failed.'} | |
| 21 | 新增:$action='stop';$result=(& $Query)|ConvertFrom-Json | |
| 22 | 新增:if((& $module {$script:mutations}) -ne 2){throw 'Non-idempotent stop.'} | |
| 23 | 新增:foreach($unsafe in 'nic','generation','secure'){ | |
| 24 | 新增: & $module { $script:nics=0;$script:generation=2;$script:secure='On' } | |
| 25 | 新增: switch($unsafe){'nic'{& $module {$script:nics=1}}'generation'{& $module {$script:generation=1}}'secure'{& $module {$script:secure='Off'}}} | |
| 26 | 新增: $action='start';$rejected=$false;try{& $Query | Out-Null}catch{$rejected=$true} | |
| 27 | 新增: if(!$rejected -or (& $module {$script:mutations}) -ne 2){throw "Unsafe $unsafe guest started."} | |
| 28 | 新增:} | |
| 29 | 新增:'Windows lifecycle exact VM and safe shutdown checks passed.' | |
| @@ -0,0 +1,26 @@ | ||
| 1 | 新增:param([Parameter(Mandatory)][string]$Query) | |
| 2 | 新增:$ErrorActionPreference='Stop' | |
| 3 | 新增:$targetId=[guid]'9e97dd9a-eb36-489a-bb1d-8d28a0d78682' | |
| 4 | 新增:$module=New-Module -Name Hyper-V -ScriptBlock { | |
| 5 | 新增: $script:id=[guid]'9e97dd9a-eb36-489a-bb1d-8d28a0d78682';$script:state='Off';$script:cpus=2;$script:start=5GB;$script:min=512MB;$script:max=1TB;$script:dynamic=$false;$script:mutations=0;$script:failMemory=$false | |
| 6 | 新增: function Get-VM {param([Guid]$Id) if($Id -ne $script:id){throw 'Unscoped VM'};[pscustomobject]@{Id=$Id;State=$script:state;MemoryAssigned=0}} | |
| 7 | 新增: function Get-VMProcessor {param($VM) if($VM.Id -ne $script:id){throw 'Wrong VM'};[pscustomobject]@{Count=$script:cpus}} | |
| 8 | 新增: function Get-VMMemory {param($VM) if($VM.Id -ne $script:id){throw 'Wrong VM'};[pscustomobject]@{Startup=$script:start;Minimum=$script:min;Maximum=$script:max;DynamicMemoryEnabled=$script:dynamic}} | |
| 9 | 新增: function Set-VMProcessor {param($VM,[int]$Count) if($VM.Id -ne $script:id -or $script:state -ne 'Off'){throw 'Unsafe apply'};$script:cpus=$Count;$script:mutations++} | |
| 10 | 新增: function Set-VMMemory {param($VM,[bool]$DynamicMemoryEnabled,[long]$MinimumBytes,[long]$StartupBytes,[long]$MaximumBytes) if($VM.Id -ne $script:id -or $script:state -ne 'Off'){throw 'Unsafe memory apply'};if($script:failMemory -and $MaximumBytes -eq 16GB){throw 'Synthetic memory failure'};$script:min=$MinimumBytes;$script:start=$StartupBytes;$script:max=$MaximumBytes;$script:dynamic=$DynamicMemoryEnabled;$script:mutations++} | |
| 11 | 新增: Export-ModuleMember -Function * | |
| 12 | 新增:};$module|Import-Module -Force | |
| 13 | 新增:$memoryGiB=0;$cpus=0;$read=(& $Query)|ConvertFrom-Json | |
| 14 | 新增:if($read.cpus -ne 2 -or $read.memory_startup_bytes -ne 5GB -or (& $module {$script:mutations}) -ne 0){throw 'Read mutated resource settings'} | |
| 15 | 新增:$memoryGiB=8;$cpus=4;$applied=(& $Query)|ConvertFrom-Json | |
| 16 | 新增:if($applied.cpus -ne 4 -or $applied.memory_maximum_bytes -ne 8GB -or !$applied.dynamic_memory){throw 'Apply mismatch'} | |
| 17 | 新增:& $module {$script:state='Running'} | |
| 18 | 新增:$blocked=$false;try{& $Query|Out-Null}catch{$blocked=$true} | |
| 19 | 新增:if(!$blocked -or (& $module {$script:mutations}) -ne 2){throw 'Running VM changed'} | |
| 20 | 新增:& $module {$script:state='Off'};$memoryGiB=2 | |
| 21 | 新增:$blocked=$false;try{& $Query|Out-Null}catch{$blocked=$true} | |
| 22 | 新增:if(!$blocked -or (& $module {$script:mutations}) -ne 2){throw 'Invalid memory changed VM'} | |
| 23 | 新增:& $module {$script:failMemory=$true};$memoryGiB=16;$cpus=6 | |
| 24 | 新增:$blocked=$false;try{& $Query|Out-Null}catch{$blocked=$true} | |
| 25 | 新增:if(!$blocked -or (& $module {$script:cpus}) -ne 4 -or (& $module {$script:max}) -ne 8GB){throw 'Failed apply did not restore prior resource settings'} | |
| 26 | 新增:'Windows resource exact VM, readback, stopped apply and rollback passed.' | |
| @@ -0,0 +1,70 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "github.com/google/uuid" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:// Options are captured by the original, unprivileged setup process. A pipe | |
| 9 | 新增:// client cannot replace these paths, identities, or installation choices. | |
| 10 | 新增:type WindowsHostEnrollmentOptions struct { | |
| 11 | 新增: VMID uuid.UUID | |
| 12 | 新增: InstallationID uuid.UUID | |
| 13 | 新增: HostSID string | |
| 14 | 新增: Profile string | |
| 15 | 新增: State string | |
| 16 | 新增: Pipe string | |
| 17 | 新增: ParentPID uint32 | |
| 18 | 新增:} | |
| 19 | 新增: | |
| 20 | 新增:type windowsHostEnrollmentRequest struct { | |
| 21 | 新增: Version int `json:"version"` | |
| 22 | 新增: Challenge string `json:"challenge"` | |
| 23 | 新增: Action string `json:"action"` | |
| 24 | 新增: VMID uuid.UUID `json:"vm_id"` | |
| 25 | 新增: GUIUserSID string `json:"gui_user_sid,omitempty"` | |
| 26 | 新增: PID uint32 `json:"pid,omitempty"` | |
| 27 | 新增: ProcessHandle uint64 `json:"process_handle,omitempty"` | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:type windowsHostEnrollmentReply struct { | |
| 31 | 新增: Version int `json:"version"` | |
| 32 | 新增: OK bool `json:"ok"` | |
| 33 | 新增: Challenge string `json:"challenge,omitempty"` | |
| 34 | 新增: Authorized bool `json:"authorized,omitempty"` | |
| 35 | 新增: Error string `json:"error,omitempty"` | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func (request windowsHostEnrollmentRequest) validate(vm uuid.UUID, owner bool, guestSID string) error { | |
| 39 | 新增: if request.Version != 1 || request.VMID != vm { | |
| 40 | 新增: return errors.New("enrollment_request_invalid") | |
| 41 | 新增: } | |
| 42 | 新增: if owner { | |
| 43 | 新增: switch request.Action { | |
| 44 | 新增: case "ready", "stop": | |
| 45 | 新增: if request.PID != 0 || request.ProcessHandle != 0 || request.GUIUserSID != "" { | |
| 46 | 新增: return errors.New("enrollment_request_invalid") | |
| 47 | 新增: } | |
| 48 | 新增: case "allow-admin": | |
| 49 | 新增: if request.PID == 0 || request.ProcessHandle == 0 || request.GUIUserSID != "" { | |
| 50 | 新增: return errors.New("enrollment_request_invalid") | |
| 51 | 新增: } | |
| 52 | 新增: default: | |
| 53 | 新增: return errors.New("enrollment_action_invalid") | |
| 54 | 新增: } | |
| 55 | 新增: } else { | |
| 56 | 新增: if request.PID != 0 || request.ProcessHandle != 0 || !windowsGUISID.MatchString(request.GUIUserSID) || guestSID != "" && request.GUIUserSID != guestSID { | |
| 57 | 新增: return errors.New("enrollment_request_invalid") | |
| 58 | 新增: } | |
| 59 | 新增: switch request.Action { | |
| 60 | 新增: case "deliver-gui", "deliver-packet": | |
| 61 | 新增: case "finalize": | |
| 62 | 新增: if guestSID == "" { | |
| 63 | 新增: return errors.New("enrollment_request_invalid") | |
| 64 | 新增: } | |
| 65 | 新增: default: | |
| 66 | 新增: return errors.New("enrollment_action_invalid") | |
| 67 | 新增: } | |
| 68 | 新增: } | |
| 69 | 新增: return nil | |
| 70 | 新增:} | |
| @@ -0,0 +1,42 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "github.com/google/uuid" | |
| 5 | 新增: "testing" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:func TestWindowsHostEnrollmentFixedAuthorityAndRole(t *testing.T) { | |
| 9 | 新增: vm := uuid.New() | |
| 10 | 新增: sid := "S-1-5-21-1-2-3-1001" | |
| 11 | 新增: valid := windowsHostEnrollmentRequest{Version: 1, VMID: vm, Action: "deliver-gui", GUIUserSID: sid} | |
| 12 | 新增: if err := valid.validate(vm, false, ""); err != nil { | |
| 13 | 新增: t.Fatal("authenticated initial GUI identity rejected", err) | |
| 14 | 新增: } | |
| 15 | 新增: if err := valid.validate(vm, true, ""); err == nil { | |
| 16 | 新增: t.Fatal("ordinary owner was allowed to act as the elevated sender") | |
| 17 | 新增: } | |
| 18 | 新增: if err := valid.validate(uuid.New(), false, ""); err == nil { | |
| 19 | 新增: t.Fatal("other VM could replace fixed enrollment scope") | |
| 20 | 新增: } | |
| 21 | 新增: if err := valid.validate(vm, false, "S-1-5-21-1-2-3-1002"); err == nil { | |
| 22 | 新增: t.Fatal("guest identity could change after first authenticated binding") | |
| 23 | 新增: } | |
| 24 | 新增: valid.Action = "finalize" | |
| 25 | 新增: if valid.validate(vm, false, "") == nil { | |
| 26 | 新增: t.Fatal("unbound guest could finalize") | |
| 27 | 新增: } | |
| 28 | 新增: if err := valid.validate(vm, false, sid); err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: valid.ProcessHandle = 99 | |
| 32 | 新增: if valid.validate(vm, false, sid) == nil { | |
| 33 | 新增: t.Fatal("admin delivery accepted owner control fields") | |
| 34 | 新增: } | |
| 35 | 新增: owner := windowsHostEnrollmentRequest{Version: 1, VMID: vm, Action: "allow-admin", PID: 12, ProcessHandle: 34} | |
| 36 | 新增: if err := owner.validate(vm, true, ""); err != nil { | |
| 37 | 新增: t.Fatal(err) | |
| 38 | 新增: } | |
| 39 | 新增: if owner.validate(vm, false, sid) == nil { | |
| 40 | 新增: t.Fatal("admin sender could replace original parent's authorization") | |
| 41 | 新增: } | |
| 42 | 新增:} | |
| @@ -0,0 +1,637 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bufio" | |
| 7 | 新增: "bytes" | |
| 8 | 新增: "context" | |
| 9 | 新增: "crypto/rand" | |
| 10 | 新增: "crypto/sha256" | |
| 11 | 新增: "crypto/subtle" | |
| 12 | 新增: "encoding/base64" | |
| 13 | 新增: "encoding/json" | |
| 14 | 新增: "errors" | |
| 15 | 新增: "io" | |
| 16 | 新增: "net" | |
| 17 | 新增: "os" | |
| 18 | 新增: "path/filepath" | |
| 19 | 新增: "runtime" | |
| 20 | 新增: "slices" | |
| 21 | 新增: "strings" | |
| 22 | 新增: "sync" | |
| 23 | 新增: "time" | |
| 24 | 新增: "unsafe" | |
| 25 | 新增: | |
| 26 | 新增: "github.com/Microsoft/go-winio" | |
| 27 | 新增: "github.com/google/uuid" | |
| 28 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 29 | 新增: "golang.org/x/sys/windows" | |
| 30 | 新增:) | |
| 31 | 新增: | |
| 32 | 新增:const enrollmentWireLimit = 16 << 10 | |
| 33 | 新增: | |
| 34 | 新增:type enrollmentProcess struct { | |
| 35 | 新增: handle windows.Handle | |
| 36 | 新增: pid uint32 | |
| 37 | 新增: started uint64 | |
| 38 | 新增: image string | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:func enrollmentProcessFromHandle(handle windows.Handle) (enrollmentProcess, error) { | |
| 42 | 新增: var value enrollmentProcess | |
| 43 | 新增: pid, err := windows.GetProcessId(handle) | |
| 44 | 新增: if err != nil || pid == 0 { | |
| 45 | 新增: return value, errors.New("enrollment_process_invalid") | |
| 46 | 新增: } | |
| 47 | 新增: var created, exited, kernel, user windows.Filetime | |
| 48 | 新增: if windows.GetProcessTimes(handle, &created, &exited, &kernel, &user) != nil { | |
| 49 | 新增: return value, errors.New("enrollment_process_invalid") | |
| 50 | 新增: } | |
| 51 | 新增: buffer := make([]uint16, 32768) | |
| 52 | 新增: size := uint32(len(buffer)) | |
| 53 | 新增: if windows.QueryFullProcessImageName(handle, 0, &buffer[0], &size) != nil || size == 0 || size >= uint32(len(buffer)) { | |
| 54 | 新增: return value, errors.New("enrollment_process_invalid") | |
| 55 | 新增: } | |
| 56 | 新增: value = enrollmentProcess{handle: handle, pid: pid, started: uint64(created.HighDateTime)<<32 | uint64(created.LowDateTime), image: windows.UTF16ToString(buffer[:size])} | |
| 57 | 新增: return value, nil | |
| 58 | 新增:} | |
| 59 | 新增: | |
| 60 | 新增:func (process enrollmentProcess) alive() bool { | |
| 61 | 新增: if process.handle == 0 { | |
| 62 | 新增: return false | |
| 63 | 新增: } | |
| 64 | 新增: state, err := windows.WaitForSingleObject(process.handle, 0) | |
| 65 | 新增: if err != nil || state != uint32(windows.WAIT_TIMEOUT) { | |
| 66 | 新增: return false | |
| 67 | 新增: } | |
| 68 | 新增: fresh, err := enrollmentProcessFromHandle(process.handle) | |
| 69 | 新增: return err == nil && fresh.pid == process.pid && fresh.started == process.started && strings.EqualFold(fresh.image, process.image) | |
| 70 | 新增:} | |
| 71 | 新增: | |
| 72 | 新增:type windowsHostEnrollment struct { | |
| 73 | 新增: options WindowsHostEnrollmentOptions | |
| 74 | 新增: installation Installation | |
| 75 | 新增: instance, stage string | |
| 76 | 新增: owner enrollmentProcess | |
| 77 | 新增: admin enrollmentProcess | |
| 78 | 新增: guestSID string | |
| 79 | 新增: finalized bool | |
| 80 | 新增: mu sync.Mutex | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:func newWindowsHostEnrollment(options WindowsHostEnrollmentOptions) (*windowsHostEnrollment, error) { | |
| 84 | 新增: token := windows.GetCurrentProcessToken() | |
| 85 | 新增: user, err := token.GetTokenUser() | |
| 86 | 新增: if err != nil || token.IsElevated() || user.User.Sid.String() != options.HostSID || options.ParentPID == 0 || options.VMID == uuid.Nil || options.InstallationID == uuid.Nil || | |
| 87 | 新增: !filepath.IsAbs(options.Profile) || !filepath.IsAbs(options.State) || strings.ContainsAny(options.Profile+options.State, "\x00\r\n") || | |
| 88 | 新增: !(strings.HasPrefix(options.HostSID, "S-1-5-21-") || strings.HasPrefix(options.HostSID, "S-1-12-1-")) || | |
| 89 | 新增: !strings.HasPrefix(options.Pipe, "Cage.Enroll.") || len(options.Pipe) > 180 || strings.ContainsAny(options.Pipe, "\\/:\x00\r\n") { | |
| 90 | 新增: return nil, errors.New("enrollment_original_user_required") | |
| 91 | 新增: } | |
| 92 | 新增: var basic struct{ ExitStatus, PEB, Affinity, Priority, PID, Parent uintptr } | |
| 93 | 新增: var returned uint32 | |
| 94 | 新增: if windows.NtQueryInformationProcess(windows.CurrentProcess(), windows.ProcessBasicInformation, unsafe.Pointer(&basic), uint32(unsafe.Sizeof(basic)), &returned) != nil || uint32(basic.Parent) != options.ParentPID { | |
| 95 | 新增: return nil, errors.New("enrollment_parent_invalid") | |
| 96 | 新增: } | |
| 97 | 新增: handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.SYNCHRONIZE, false, options.ParentPID) | |
| 98 | 新增: if err != nil { | |
| 99 | 新增: return nil, errors.New("enrollment_parent_invalid") | |
| 100 | 新增: } | |
| 101 | 新增: owner, err := enrollmentProcessFromHandle(handle) | |
| 102 | 新增: if err != nil { | |
| 103 | 新增: windows.CloseHandle(handle) | |
| 104 | 新增: return nil, err | |
| 105 | 新增: } | |
| 106 | 新增: var parentToken windows.Token | |
| 107 | 新增: if windows.OpenProcessToken(handle, windows.TOKEN_QUERY, &parentToken) != nil { | |
| 108 | 新增: windows.CloseHandle(handle) | |
| 109 | 新增: return nil, errors.New("enrollment_parent_invalid") | |
| 110 | 新增: } | |
| 111 | 新增: parentUser, err := parentToken.GetTokenUser() | |
| 112 | 新增: parentToken.Close() | |
| 113 | 新增: system, systemErr := windows.GetSystemDirectory() | |
| 114 | 新增: expected := filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe") | |
| 115 | 新增: if err != nil || parentUser.User.Sid.String() != options.HostSID || systemErr != nil || !strings.EqualFold(owner.image, expected) || !owner.alive() { | |
| 116 | 新增: windows.CloseHandle(handle) | |
| 117 | 新增: return nil, errors.New("enrollment_parent_invalid") | |
| 118 | 新增: } | |
| 119 | 新增: profile, err := paths.Resolve(options.Profile) | |
| 120 | 新增: if err != nil { | |
| 121 | 新增: windows.CloseHandle(handle) | |
| 122 | 新增: return nil, errors.New("enrollment_profile_invalid") | |
| 123 | 新增: } | |
| 124 | 新增: state, err := paths.Resolve(options.State) | |
| 125 | 新增: if err != nil { | |
| 126 | 新增: windows.CloseHandle(handle) | |
| 127 | 新增: return nil, errors.New("enrollment_profile_invalid") | |
| 128 | 新增: } | |
| 129 | 新增: anchor, err := paths.Resolve(filepath.Join(profile, "state")) | |
| 130 | 新增: if err != nil || !strings.EqualFold(anchor, state) { | |
| 131 | 新增: windows.CloseHandle(handle) | |
| 132 | 新增: return nil, errors.New("enrollment_profile_invalid") | |
| 133 | 新增: } | |
| 134 | 新增: options.Profile, options.State = profile, state | |
| 135 | 新增: installation, err := LoadInstallation(profile) | |
| 136 | 新增: if err != nil || installation == nil || installation.System != Windows11 || installation.ID != options.InstallationID { | |
| 137 | 新增: windows.CloseHandle(handle) | |
| 138 | 新增: return nil, errors.New("enrollment_installation_changed") | |
| 139 | 新增: } | |
| 140 | 新增: instance := filepath.Join(state, "windows-"+strings.ReplaceAll(options.InstallationID.String(), "-", "")) | |
| 141 | 新增: value := &windowsHostEnrollment{options: options, installation: *installation, instance: instance, stage: filepath.Join(instance, "cage-workbench", "pair"), owner: owner} | |
| 142 | 新增: if err = value.assertScope(); err != nil { | |
| 143 | 新增: windows.CloseHandle(handle) | |
| 144 | 新增: return nil, err | |
| 145 | 新增: } | |
| 146 | 新增: if _, err = os.Lstat(WindowsProfilePath(profile)); !errors.Is(err, os.ErrNotExist) { | |
| 147 | 新增: windows.CloseHandle(handle) | |
| 148 | 新增: return nil, errors.New("enrollment_existing_profile_preserved") | |
| 149 | 新增: } | |
| 150 | 新增: if binding, err := LoadWindowsProfile(value.stage); err != nil { | |
| 151 | 新增: windows.CloseHandle(handle) | |
| 152 | 新增: return nil, errors.New("enrollment_existing_pairing_preserved") | |
| 153 | 新增: } else if binding != nil { | |
| 154 | 新增: if err = value.bindingValid(*binding); err != nil { | |
| 155 | 新增: windows.CloseHandle(handle) | |
| 156 | 新增: return nil, err | |
| 157 | 新增: } | |
| 158 | 新增: value.guestSID = binding.GUIUserSID | |
| 159 | 新增: } | |
| 160 | 新增: return value, nil | |
| 161 | 新增:} | |
| 162 | 新增: | |
| 163 | 新增:func (value *windowsHostEnrollment) assertScope() error { | |
| 164 | 新增: if !value.owner.alive() { | |
| 165 | 新增: return errors.New("enrollment_parent_exited") | |
| 166 | 新增: } | |
| 167 | 新增: current, err := LoadInstallation(value.options.Profile) | |
| 168 | 新增: if err != nil || current == nil || *current != value.installation { | |
| 169 | 新增: return errors.New("enrollment_installation_changed") | |
| 170 | 新增: } | |
| 171 | 新增: receipt, err := os.ReadFile(filepath.Join(value.options.Profile, "windows-install-vm.txt")) | |
| 172 | 新增: if err == nil && len(receipt) > 80 { | |
| 173 | 新增: return errors.New("enrollment_vm_changed") | |
| 174 | 新增: } | |
| 175 | 新增: id, parse := uuid.Parse(strings.TrimSpace(string(receipt))) | |
| 176 | 新增: if err != nil || parse != nil || id != value.options.VMID { | |
| 177 | 新增: return errors.New("enrollment_vm_changed") | |
| 178 | 新增: } | |
| 179 | 新增: state, err := paths.Resolve(filepath.Join(value.options.Profile, "state")) | |
| 180 | 新增: if err != nil || !strings.EqualFold(state, value.options.State) { | |
| 181 | 新增: return errors.New("enrollment_profile_changed") | |
| 182 | 新增: } | |
| 183 | 新增: return nil | |
| 184 | 新增:} | |
| 185 | 新增: | |
| 186 | 新增:func (value *windowsHostEnrollment) bindingValid(binding WindowsProfile) error { | |
| 187 | 新增: if binding.VMID != value.options.VMID || !strings.EqualFold(filepath.Clean(binding.InstanceDirectory), value.instance) || | |
| 188 | 新增: !strings.EqualFold(filepath.Clean(binding.RelayExecutable), filepath.Join(value.stage, "Cage.GuestClipboard.exe")) || | |
| 189 | 新增: !strings.EqualFold(filepath.Clean(binding.PairingFile), filepath.Join(value.stage, "pairing.dpapi")) || | |
| 190 | 新增: binding.NetworkPairingFile != "" && !strings.EqualFold(filepath.Clean(binding.NetworkPairingFile), filepath.Join(value.stage, "packet.dpapi")) || | |
| 191 | 新增: value.guestSID != "" && binding.GUIUserSID != value.guestSID { | |
| 192 | 新增: return errors.New("enrollment_binding_changed") | |
| 193 | 新增: } | |
| 194 | 新增: return nil | |
| 195 | 新增:} | |
| 196 | 新增: | |
| 197 | 新增:func (value *windowsHostEnrollment) authorizeAdmin(request windowsHostEnrollmentRequest) error { | |
| 198 | 新增: if value.admin.handle != 0 || request.PID == 0 || request.ProcessHandle == 0 || request.ProcessHandle > 0x7fffffffffffffff { | |
| 199 | 新增: return errors.New("enrollment_admin_invalid") | |
| 200 | 新增: } | |
| 201 | 新增: handle := windows.Handle(request.ProcessHandle) | |
| 202 | 新增: process, err := enrollmentProcessFromHandle(handle) | |
| 203 | 新增: system, systemErr := windows.GetSystemDirectory() | |
| 204 | 新增: if err != nil || systemErr != nil || process.pid != request.PID || !strings.EqualFold(process.image, filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe")) || !process.alive() { | |
| 205 | 新增: windows.CloseHandle(handle) | |
| 206 | 新增: return errors.New("enrollment_admin_invalid") | |
| 207 | 新增: } | |
| 208 | 新增: value.admin = process | |
| 209 | 新增: return nil | |
| 210 | 新增:} | |
| 211 | 新增: | |
| 212 | 新增:func cryptHostEnrollment(data []byte, vm uuid.UUID, sid string, protect bool) ([]byte, error) { | |
| 213 | 新增: input := make([]byte, len(data)) | |
| 214 | 新增: copy(input, data) | |
| 215 | 新增: defer clear(input) | |
| 216 | 新增: entropy := sha256.Sum256([]byte("Cage.HyperV.v1:" + vm.String() + ":" + sid)) | |
| 217 | 新增: in := windows.DataBlob{Size: uint32(len(input)), Data: &input[0]} | |
| 218 | 新增: salt := windows.DataBlob{Size: 32, Data: &entropy[0]} | |
| 219 | 新增: var output windows.DataBlob | |
| 220 | 新增: var err error | |
| 221 | 新增: if protect { | |
| 222 | 新增: err = windows.CryptProtectData(&in, nil, &salt, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &output) | |
| 223 | 新增: } else { | |
| 224 | 新增: err = windows.CryptUnprotectData(&in, nil, &salt, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &output) | |
| 225 | 新增: } | |
| 226 | 新增: runtime.KeepAlive(input) | |
| 227 | 新增: runtime.KeepAlive(entropy) | |
| 228 | 新增: if output.Data != nil { | |
| 229 | 新增: defer func() { | |
| 230 | 新增: if output.Size <= enrollmentWireLimit { | |
| 231 | 新增: clear(unsafe.Slice(output.Data, int(output.Size))) | |
| 232 | 新增: } | |
| 233 | 新增: windows.LocalFree(windows.Handle(unsafe.Pointer(output.Data))) | |
| 234 | 新增: }() | |
| 235 | 新增: } | |
| 236 | 新增: if err != nil || output.Data == nil || output.Size == 0 || output.Size > enrollmentWireLimit { | |
| 237 | 新增: return nil, errors.New("enrollment_current_user_crypto_failed") | |
| 238 | 新增: } | |
| 239 | 新增: result := append([]byte(nil), unsafe.Slice(output.Data, int(output.Size))...) | |
| 240 | 新增: return result, nil | |
| 241 | 新增:} | |
| 242 | 新增: | |
| 243 | 新增:func (value *windowsHostEnrollment) privateKey(path string) ([]byte, error) { | |
| 244 | 新增: info, err := os.Lstat(path) | |
| 245 | 新增: if err != nil || !info.Mode().IsRegular() || info.Size() < 1 || info.Size() > enrollmentWireLimit { | |
| 246 | 新增: return nil, errors.New("enrollment_existing_pairing_preserved") | |
| 247 | 新增: } | |
| 248 | 新增: name, _ := windows.UTF16PtrFromString(path) | |
| 249 | 新增: attributes, err := windows.GetFileAttributes(name) | |
| 250 | 新增: if err != nil || attributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 { | |
| 251 | 新增: return nil, errors.New("enrollment_existing_pairing_preserved") | |
| 252 | 新增: } | |
| 253 | 新增: sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION) | |
| 254 | 新增: if err != nil { | |
| 255 | 新增: return nil, errors.New("enrollment_existing_pairing_preserved") | |
| 256 | 新增: } | |
| 257 | 新增: owner, _, err := sd.Owner() | |
| 258 | 新增: control, _, controlErr := sd.Control() | |
| 259 | 新增: acl, _, aclErr := sd.DACL() | |
| 260 | 新增: if err != nil || owner == nil || owner.String() != value.options.HostSID || controlErr != nil || control&windows.SE_DACL_PROTECTED == 0 || aclErr != nil || acl == nil { | |
| 261 | 新增: return nil, errors.New("enrollment_existing_pairing_preserved") | |
| 262 | 新增: } | |
| 263 | 新增: for i := uint32(0); i < uint32(acl.AceCount); i++ { | |
| 264 | 新增: var ace *windows.ACCESS_ALLOWED_ACE | |
| 265 | 新增: if windows.GetAce(acl, i, &ace) != nil || ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE { | |
| 266 | 新增: return nil, errors.New("enrollment_existing_pairing_preserved") | |
| 267 | 新增: } | |
| 268 | 新增: sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) | |
| 269 | 新增: if sid.String() != value.options.HostSID && !sid.IsWellKnown(windows.WinBuiltinAdministratorsSid) && !sid.IsWellKnown(windows.WinLocalSystemSid) { | |
| 270 | 新增: return nil, errors.New("enrollment_existing_pairing_preserved") | |
| 271 | 新增: } | |
| 272 | 新增: } | |
| 273 | 新增: data, err := os.ReadFile(path) | |
| 274 | 新增: if err != nil { | |
| 275 | 新增: return nil, errors.New("enrollment_existing_pairing_preserved") | |
| 276 | 新增: } | |
| 277 | 新增: return data, nil | |
| 278 | 新增:} | |
| 279 | 新增: | |
| 280 | 新增:func (value *windowsHostEnrollment) storeKey(ctx context.Context, kind, sid string, key []byte) error { | |
| 281 | 新增: if ctx.Err() != nil { | |
| 282 | 新增: return errors.New("enrollment_cancelled") | |
| 283 | 新增: } | |
| 284 | 新增: if len(key) != 32 || !windowsGUISID.MatchString(sid) || value.guestSID != "" && value.guestSID != sid { | |
| 285 | 新增: return errors.New("enrollment_guest_changed") | |
| 286 | 新增: } | |
| 287 | 新增: if err := value.assertScope(); err != nil { | |
| 288 | 新增: return err | |
| 289 | 新增: } | |
| 290 | 新增: if !value.admin.alive() { | |
| 291 | 新增: return errors.New("enrollment_admin_exited") | |
| 292 | 新增: } | |
| 293 | 新增: value.guestSID = sid | |
| 294 | 新增: name := "pairing.dpapi" | |
| 295 | 新增: if kind == "deliver-packet" { | |
| 296 | 新增: name = "packet.dpapi" | |
| 297 | 新增: } | |
| 298 | 新增: path := filepath.Join(value.stage, name) | |
| 299 | 新增: if _, err := os.Lstat(path); err == nil { | |
| 300 | 新增: data, err := value.privateKey(path) | |
| 301 | 新增: if err != nil { | |
| 302 | 新增: return err | |
| 303 | 新增: } | |
| 304 | 新增: old, err := cryptHostEnrollment(data, value.options.VMID, sid, false) | |
| 305 | 新增: if err != nil { | |
| 306 | 新增: return err | |
| 307 | 新增: } | |
| 308 | 新增: defer clear(old) | |
| 309 | 新增: if subtle.ConstantTimeCompare(old, key) != 1 { | |
| 310 | 新增: return errors.New("enrollment_existing_pairing_preserved") | |
| 311 | 新增: } | |
| 312 | 新增: return nil | |
| 313 | 新增: } else if !errors.Is(err, os.ErrNotExist) { | |
| 314 | 新增: return errors.New("enrollment_existing_pairing_preserved") | |
| 315 | 新增: } | |
| 316 | 新增: stage, err := paths.Resolve(value.stage) | |
| 317 | 新增: if err != nil || !strings.EqualFold(stage, value.stage) { | |
| 318 | 新增: return errors.New("enrollment_profile_changed") | |
| 319 | 新增: } | |
| 320 | 新增: data, err := cryptHostEnrollment(key, value.options.VMID, sid, true) | |
| 321 | 新增: if err != nil { | |
| 322 | 新增: return err | |
| 323 | 新增: } | |
| 324 | 新增: sd, err := windows.SecurityDescriptorFromString("O:" + value.options.HostSID + "D:P(A;;FA;;;" + value.options.HostSID + ")(A;;FA;;;SY)(A;;FA;;;BA)") | |
| 325 | 新增: if err != nil { | |
| 326 | 新增: return errors.New("enrollment_permissions_invalid") | |
| 327 | 新增: } | |
| 328 | 新增: attributes := windows.SecurityAttributes{Length: uint32(unsafe.Sizeof(windows.SecurityAttributes{})), SecurityDescriptor: sd} | |
| 329 | 新增: pathPtr, _ := windows.UTF16PtrFromString(path) | |
| 330 | 新增: if ctx.Err() != nil || !value.admin.alive() { | |
| 331 | 新增: return errors.New("enrollment_cancelled") | |
| 332 | 新增: } | |
| 333 | 新增: handle, err := windows.CreateFile(pathPtr, windows.FILE_WRITE_DATA|windows.READ_CONTROL|windows.WRITE_DAC|windows.DELETE, 0, &attributes, windows.CREATE_NEW, windows.FILE_ATTRIBUTE_NORMAL, 0) | |
| 334 | 新增: runtime.KeepAlive(sd) | |
| 335 | 新增: if err != nil { | |
| 336 | 新增: return errors.New("enrollment_pairing_not_saved") | |
| 337 | 新增: } | |
| 338 | 新增: file := os.NewFile(uintptr(handle), path) | |
| 339 | 新增: completed := false | |
| 340 | 新增: defer func() { | |
| 341 | 新增: if !completed { | |
| 342 | 新增: discard := byte(1) | |
| 343 | 新增: _ = windows.SetFileInformationByHandle(handle, windows.FileDispositionInfo, &discard, 1) | |
| 344 | 新增: } | |
| 345 | 新增: file.Close() | |
| 346 | 新增: }() | |
| 347 | 新增: if _, err = file.Write(data); err == nil { | |
| 348 | 新增: err = file.Sync() | |
| 349 | 新增: } | |
| 350 | 新增: if err != nil { | |
| 351 | 新增: return errors.New("enrollment_pairing_not_saved") | |
| 352 | 新增: } | |
| 353 | 新增: if err = value.assertScope(); err != nil { | |
| 354 | 新增: return err | |
| 355 | 新增: } | |
| 356 | 新增: if ctx.Err() != nil { | |
| 357 | 新增: return errors.New("enrollment_cancelled") | |
| 358 | 新增: } | |
| 359 | 新增: if !value.admin.alive() { | |
| 360 | 新增: return errors.New("enrollment_admin_exited") | |
| 361 | 新增: } | |
| 362 | 新增: completed = true | |
| 363 | 新增: return nil | |
| 364 | 新增:} | |
| 365 | 新增: | |
| 366 | 新增:func (value *windowsHostEnrollment) finalize(ctx context.Context) error { | |
| 367 | 新增: if value.finalized { | |
| 368 | 新增: return nil | |
| 369 | 新增: } | |
| 370 | 新增: ctx, cancel := context.WithTimeout(ctx, 35*time.Second) | |
| 371 | 新增: defer cancel() | |
| 372 | 新增: binding, err := LoadWindowsProfile(value.stage) | |
| 373 | 新增: if err != nil || binding == nil || value.bindingValid(*binding) != nil || binding.GUIUserSID != value.guestSID || binding.NetworkPairingFile == "" { | |
| 374 | 新增: return errors.New("enrollment_binding_not_ready") | |
| 375 | 新增: } | |
| 376 | 新增: for _, name := range []string{"pairing.dpapi", "packet.dpapi"} { | |
| 377 | 新增: data, err := value.privateKey(filepath.Join(value.stage, name)) | |
| 378 | 新增: if err != nil { | |
| 379 | 新增: return err | |
| 380 | 新增: } | |
| 381 | 新增: key, err := cryptHostEnrollment(data, value.options.VMID, value.guestSID, false) | |
| 382 | 新增: if err != nil { | |
| 383 | 新增: return err | |
| 384 | 新增: } | |
| 385 | 新增: valid := len(key) == 32 | |
| 386 | 新增: clear(key) | |
| 387 | 新增: if !valid { | |
| 388 | 新增: return errors.New("enrollment_binding_not_ready") | |
| 389 | 新增: } | |
| 390 | 新增: } | |
| 391 | 新增: var ready bool | |
| 392 | 新增: for ctx.Err() == nil { | |
| 393 | 新增: if !value.admin.alive() { | |
| 394 | 新增: return errors.New("enrollment_admin_exited") | |
| 395 | 新增: } | |
| 396 | 新增: if err = value.assertScope(); err != nil { | |
| 397 | 新增: return err | |
| 398 | 新增: } | |
| 399 | 新增: request, requestErr := WindowsRelayCommand(ctx, value.stage, "status") | |
| 400 | 新增: if requestErr != nil { | |
| 401 | 新增: return errors.New("enrollment_relay_not_ready") | |
| 402 | 新增: } | |
| 403 | 新增: var output boundedEnrollmentOutput | |
| 404 | 新增: request.Stdout = &output | |
| 405 | 新增: request.Stderr = io.Discard | |
| 406 | 新增: if request.Run() == nil { | |
| 407 | 新增: var report struct { | |
| 408 | 新增: Version int `json:"version"` | |
| 409 | 新增: OS string `json:"os"` | |
| 410 | 新增: VMID string `json:"vm_id"` | |
| 411 | 新增: SID string `json:"gui_user_sid"` | |
| 412 | 新增: Available bool `json:"available"` | |
| 413 | 新增: Capabilities []string `json:"capabilities"` | |
| 414 | 新增: Browser struct { | |
| 415 | 新增: Installed bool `json:"installed"` | |
| 416 | 新增: EditorInstalled bool `json:"editor_installed"` | |
| 417 | 新增: } `json:"browser"` | |
| 418 | 新增: Components map[string]struct { | |
| 419 | 新增: Installed bool `json:"installed"` | |
| 420 | 新增: Ready bool `json:"ready"` | |
| 421 | 新增: } `json:"components"` | |
| 422 | 新增: } | |
| 423 | 新增: if json.Unmarshal(output.Bytes(), &report) == nil && report.Version == 1 && report.OS == "windows" && report.VMID == value.options.VMID.String() && report.SID == value.guestSID && report.Available && report.Browser.Installed && report.Browser.EditorInstalled { | |
| 424 | 新增: ready = true | |
| 425 | 新增: for _, name := range []string{"cli", "terminal", "project-mount", "desktop"} { | |
| 426 | 新增: component := report.Components[name] | |
| 427 | 新增: ready = ready && slices.Contains(report.Capabilities, name) && component.Installed && component.Ready | |
| 428 | 新增: } | |
| 429 | 新增: if ready { | |
| 430 | 新增: break | |
| 431 | 新增: } | |
| 432 | 新增: } | |
| 433 | 新增: } | |
| 434 | 新增: select { | |
| 435 | 新增: case <-ctx.Done(): | |
| 436 | 新增: case <-time.After(time.Second): | |
| 437 | 新增: } | |
| 438 | 新增: } | |
| 439 | 新增: if !ready || ctx.Err() != nil || !value.admin.alive() { | |
| 440 | 新增: return errors.New("enrollment_components_not_ready") | |
| 441 | 新增: } | |
| 442 | 新增: if err = value.assertScope(); err != nil { | |
| 443 | 新增: return err | |
| 444 | 新增: } | |
| 445 | 新增: var state WindowsVMResourceState | |
| 446 | 新增: if err = windowsHostManagerCall(ctx, value.options.VMID, "resources", 0, 0, &state); err != nil || state.State != "Running" { | |
| 447 | 新增: return errors.New("enrollment_manager_not_ready") | |
| 448 | 新增: } | |
| 449 | 新增: if err = value.assertScope(); err != nil { | |
| 450 | 新增: return err | |
| 451 | 新增: } | |
| 452 | 新增: if !value.admin.alive() || ctx.Err() != nil { | |
| 453 | 新增: return errors.New("enrollment_cancelled") | |
| 454 | 新增: } | |
| 455 | 新增: if err = BindWindowsProfile(value.options.Profile, *binding); err != nil { | |
| 456 | 新增: return errors.New("enrollment_profile_not_published") | |
| 457 | 新增: } | |
| 458 | 新增: value.finalized = true | |
| 459 | 新增: return nil | |
| 460 | 新增:} | |
| 461 | 新增: | |
| 462 | 新增:type boundedEnrollmentOutput struct{ bytes.Buffer } | |
| 463 | 新增: | |
| 464 | 新增:func (value *boundedEnrollmentOutput) Write(data []byte) (int, error) { | |
| 465 | 新增: if value.Len()+len(data) > 64<<10 { | |
| 466 | 新增: return 0, errors.New("enrollment_response_limit") | |
| 467 | 新增: } | |
| 468 | 新增: return value.Buffer.Write(data) | |
| 469 | 新增:} | |
| 470 | 新增: | |
| 471 | 新增:func (value *windowsHostEnrollment) connection(ctx context.Context, conn net.Conn, cancel context.CancelFunc) { | |
| 472 | 新增: defer conn.Close() | |
| 473 | 新增: _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) | |
| 474 | 新增: fd, ok := conn.(interface{ Fd() uintptr }) | |
| 475 | 新增: var pid uint32 | |
| 476 | 新增: if !ok || windows.GetNamedPipeClientProcessId(windows.Handle(fd.Fd()), &pid) != nil { | |
| 477 | 新增: return | |
| 478 | 新增: } | |
| 479 | 新增: value.mu.Lock() | |
| 480 | 新增: owner := pid == value.owner.pid && value.owner.alive() | |
| 481 | 新增: admin := pid == value.admin.pid && value.admin.alive() | |
| 482 | 新增: value.mu.Unlock() | |
| 483 | 新增: challenge := make([]byte, 32) | |
| 484 | 新增: if _, err := rand.Read(challenge); err != nil { | |
| 485 | 新增: return | |
| 486 | 新增: } | |
| 487 | 新增: defer clear(challenge) | |
| 488 | 新增: write := func(reply windowsHostEnrollmentReply) { reply.Version = 1; _ = json.NewEncoder(conn).Encode(reply) } | |
| 489 | 新增: write(windowsHostEnrollmentReply{OK: owner || admin, Authorized: owner || admin, Challenge: base64.StdEncoding.EncodeToString(challenge)}) | |
| 490 | 新增: if !owner && !admin { | |
| 491 | 新增: return | |
| 492 | 新增: } | |
| 493 | 新增: reader := bufio.NewReaderSize(conn, enrollmentWireLimit+1) | |
| 494 | 新增: line, err := reader.ReadSlice('\n') | |
| 495 | 新增: if err != nil || len(line) > enrollmentWireLimit { | |
| 496 | 新增: return | |
| 497 | 新增: } | |
| 498 | 新增: var request windowsHostEnrollmentRequest | |
| 499 | 新增: decoder := json.NewDecoder(bytes.NewReader(line)) | |
| 500 | 新增: decoder.DisallowUnknownFields() | |
| 501 | 新增: if decoder.Decode(&request) != nil || decoder.Decode(new(any)) != io.EOF { | |
| 502 | 新增: return | |
| 503 | 新增: } | |
| 504 | 新增: decoded, err := base64.StdEncoding.DecodeString(request.Challenge) | |
| 505 | 新增: if err != nil || request.Version != 1 || request.VMID != value.options.VMID || subtle.ConstantTimeCompare(decoded, challenge) != 1 { | |
| 506 | 新增: return | |
| 507 | 新增: } | |
| 508 | 新增: value.mu.Lock() | |
| 509 | 新增: requestErr := request.validate(value.options.VMID, owner, value.guestSID) | |
| 510 | 新增: value.mu.Unlock() | |
| 511 | 新增: if requestErr != nil { | |
| 512 | 新增: return | |
| 513 | 新增: } | |
| 514 | 新增: key := make([]byte, 32) | |
| 515 | 新增: defer clear(key) | |
| 516 | 新增: if request.Action == "deliver-gui" || request.Action == "deliver-packet" { | |
| 517 | 新增: if !admin { | |
| 518 | 新增: return | |
| 519 | 新增: } | |
| 520 | 新增: if _, err = io.ReadFull(reader, key); err != nil { | |
| 521 | 新增: return | |
| 522 | 新增: } | |
| 523 | 新增: } | |
| 524 | 新增: if reader.Buffered() != 0 { | |
| 525 | 新增: return | |
| 526 | 新增: } | |
| 527 | 新增: _ = conn.SetDeadline(time.Now().Add(45 * time.Second)) | |
| 528 | 新增: operation, finish := context.WithCancel(ctx) | |
| 529 | 新增: defer finish() | |
| 530 | 新增: disconnected := make(chan struct{}) | |
| 531 | 新增: go func() { defer close(disconnected); var extra [1]byte; _, _ = conn.Read(extra[:]); finish() }() | |
| 532 | 新增: defer func() { conn.Close(); <-disconnected }() | |
| 533 | 新增: value.mu.Lock() | |
| 534 | 新增: defer value.mu.Unlock() | |
| 535 | 新增: if err = value.assertScope(); err != nil { | |
| 536 | 新增: write(windowsHostEnrollmentReply{Error: err.Error()}) | |
| 537 | 新增: return | |
| 538 | 新增: } | |
| 539 | 新增: if owner { | |
| 540 | 新增: switch request.Action { | |
| 541 | 新增: case "ready": | |
| 542 | 新增: case "allow-admin": | |
| 543 | 新增: err = value.authorizeAdmin(request) | |
| 544 | 新增: case "stop": | |
| 545 | 新增: cancel() | |
| 546 | 新增: default: | |
| 547 | 新增: err = errors.New("enrollment_action_invalid") | |
| 548 | 新增: } | |
| 549 | 新增: } else if !value.admin.alive() { | |
| 550 | 新增: err = errors.New("enrollment_admin_exited") | |
| 551 | 新增: } else { | |
| 552 | 新增: switch request.Action { | |
| 553 | 新增: case "deliver-gui", "deliver-packet": | |
| 554 | 新增: err = value.storeKey(operation, request.Action, request.GUIUserSID, key) | |
| 555 | 新增: case "finalize": | |
| 556 | 新增: if request.GUIUserSID != value.guestSID { | |
| 557 | 新增: err = errors.New("enrollment_guest_changed") | |
| 558 | 新增: } else { | |
| 559 | 新增: err = value.finalize(operation) | |
| 560 | 新增: } | |
| 561 | 新增: default: | |
| 562 | 新增: err = errors.New("enrollment_action_invalid") | |
| 563 | 新增: } | |
| 564 | 新增: } | |
| 565 | 新增: if err != nil { | |
| 566 | 新增: write(windowsHostEnrollmentReply{Error: "enrollment_not_completed"}) | |
| 567 | 新增: return | |
| 568 | 新增: } | |
| 569 | 新增: write(windowsHostEnrollmentReply{OK: true}) | |
| 570 | 新增:} | |
| 571 | 新增: | |
| 572 | 新增:func RunWindowsHostEnrollment(parent context.Context, options WindowsHostEnrollmentOptions) error { | |
| 573 | 新增: value, err := newWindowsHostEnrollment(options) | |
| 574 | 新增: if err != nil { | |
| 575 | 新增: return err | |
| 576 | 新增: } | |
| 577 | 新增: defer windows.CloseHandle(value.owner.handle) | |
| 578 | 新增: defer func() { | |
| 579 | 新增: if value.admin.handle != 0 { | |
| 580 | 新增: windows.CloseHandle(value.admin.handle) | |
| 581 | 新增: } | |
| 582 | 新增: }() | |
| 583 | 新增: ctx, cancel := context.WithCancel(parent) | |
| 584 | 新增: defer cancel() | |
| 585 | 新增: listener, err := winio.ListenPipe(`\\.\pipe\`+options.Pipe, &winio.PipeConfig{SecurityDescriptor: "O:" + options.HostSID + "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12019b;;;" + options.HostSID + ")", InputBufferSize: enrollmentWireLimit, OutputBufferSize: enrollmentWireLimit}) | |
| 586 | 新增: if err != nil { | |
| 587 | 新增: return errors.New("enrollment_pipe_unavailable") | |
| 588 | 新增: } | |
| 589 | 新增: defer listener.Close() | |
| 590 | 新增: var active sync.WaitGroup | |
| 591 | 新增: var connections sync.Map | |
| 592 | 新增: go func() { | |
| 593 | 新增: ticker := time.NewTicker(200 * time.Millisecond) | |
| 594 | 新增: defer ticker.Stop() | |
| 595 | 新增: for { | |
| 596 | 新增: select { | |
| 597 | 新增: case <-ctx.Done(): | |
| 598 | 新增: listener.Close() | |
| 599 | 新增: connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true }) | |
| 600 | 新增: return | |
| 601 | 新增: case <-ticker.C: | |
| 602 | 新增: if !value.owner.alive() { | |
| 603 | 新增: cancel() | |
| 604 | 新增: } | |
| 605 | 新增: } | |
| 606 | 新增: } | |
| 607 | 新增: }() | |
| 608 | 新增: defer func() { | |
| 609 | 新增: cancel() | |
| 610 | 新增: listener.Close() | |
| 611 | 新增: connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true }) | |
| 612 | 新增: active.Wait() | |
| 613 | 新增: }() | |
| 614 | 新增: slots := make(chan struct{}, 4) | |
| 615 | 新增: for { | |
| 616 | 新增: conn, err := listener.Accept() | |
| 617 | 新增: if err != nil { | |
| 618 | 新增: if ctx.Err() != nil { | |
| 619 | 新增: return nil | |
| 620 | 新增: } | |
| 621 | 新增: return errors.New("enrollment_pipe_unavailable") | |
| 622 | 新增: } | |
| 623 | 新增: select { | |
| 624 | 新增: case slots <- struct{}{}: | |
| 625 | 新增: default: | |
| 626 | 新增: conn.Close() | |
| 627 | 新增: continue | |
| 628 | 新增: } | |
| 629 | 新增: connections.Store(conn, struct{}{}) | |
| 630 | 新增: active.Add(1) | |
| 631 | 新增: go func() { | |
| 632 | 新增: defer active.Done() | |
| 633 | 新增: defer func() { <-slots; connections.Delete(conn) }() | |
| 634 | 新增: value.connection(ctx, conn, cancel) | |
| 635 | 新增: }() | |
| 636 | 新增: } | |
| 637 | 新增:} | |
| @@ -0,0 +1,61 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "os" | |
| 7 | 新增: "testing" | |
| 8 | 新增: | |
| 9 | 新增: "golang.org/x/sys/windows" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:// Native ACL fixtures contain only this test's temporary directory. They never | |
| 13 | 新增:// change a real manager, VM, account, user group or installation directory. | |
| 14 | 新增:func TestWindowsHostManagerProtectedDirectoryACL(t *testing.T) { | |
| 15 | 新增: if os.Getenv("CAGE_TEST_WINDOWS_MANAGER_ACL") != "1" { | |
| 16 | 新增: t.Skip("requires explicitly enabled administrator-owned ACL fixtures") | |
| 17 | 新增: } | |
| 18 | 新增: if !windows.GetCurrentProcessToken().IsElevated() { | |
| 19 | 新增: t.Fatal("creating administrator-owned ACL fixtures requires an elevated test process") | |
| 20 | 新增: } | |
| 21 | 新增: user, err := windows.GetCurrentProcessToken().GetTokenUser() | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: t.Fatal(err) | |
| 24 | 新增: } | |
| 25 | 新增: sid := user.User.Sid.String() | |
| 26 | 新增: set := func(path, reader, mask string) { | |
| 27 | 新增: t.Helper() | |
| 28 | 新增: sd, err := windows.SecurityDescriptorFromString("O:BAG:SYD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;" + mask + ";;;" + reader + ")") | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: t.Fatal(err) | |
| 31 | 新增: } | |
| 32 | 新增: owner, _, _ := sd.Owner() | |
| 33 | 新增: dacl, _, _ := sd.DACL() | |
| 34 | 新增: if err := windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, owner, nil, dacl, nil); err != nil { | |
| 35 | 新增: t.Fatal(err) | |
| 36 | 新增: } | |
| 37 | 新增: } | |
| 38 | 新增: t.Run("shared_readers", func(t *testing.T) { | |
| 39 | 新增: path := t.TempDir() | |
| 40 | 新增: set(path, "S-1-5-32-545", "FRFX") | |
| 41 | 新增: if err := managerSharedProtected(path, sid); err != nil { | |
| 42 | 新增: t.Fatal("safe shared parent rejected", err) | |
| 43 | 新增: } | |
| 44 | 新增: if err := managerProtected(path, sid); err == nil { | |
| 45 | 新增: t.Fatal("private per-VM authority permits unrelated readers") | |
| 46 | 新增: } | |
| 47 | 新增: }) | |
| 48 | 新增: t.Run("delete_child", func(t *testing.T) { | |
| 49 | 新增: path := t.TempDir() | |
| 50 | 新增: set(path, sid, "0x120040") // READ_CONTROL, SYNCHRONIZE, FILE_DELETE_CHILD. | |
| 51 | 新增: if err := managerSharedProtected(path, sid); err == nil { | |
| 52 | 新增: t.Fatal("shared parent accepts ordinary-user child replacement") | |
| 53 | 新增: } | |
| 54 | 新增: if err := managerProtected(path, sid); err == nil { | |
| 55 | 新增: t.Fatal("private parent accepts ordinary-user child replacement") | |
| 56 | 新增: } | |
| 57 | 新增: if err := checkWindowsSystemOwnedObject(path); err == nil { | |
| 58 | 新增: t.Fatal("client accepts ordinary-user child replacement") | |
| 59 | 新增: } | |
| 60 | 新增: }) | |
| 61 | 新增:} | |
| @@ -0,0 +1,232 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bufio" | |
| 7 | 新增: "bytes" | |
| 8 | 新增: "context" | |
| 9 | 新增: "encoding/json" | |
| 10 | 新增: "errors" | |
| 11 | 新增: "fmt" | |
| 12 | 新增: "io" | |
| 13 | 新增: "net" | |
| 14 | 新增: "os" | |
| 15 | 新增: "path/filepath" | |
| 16 | 新增: "runtime" | |
| 17 | 新增: "strings" | |
| 18 | 新增: "time" | |
| 19 | 新增: "unsafe" | |
| 20 | 新增: | |
| 21 | 新增: "github.com/Microsoft/go-winio" | |
| 22 | 新增: "github.com/google/uuid" | |
| 23 | 新增: "golang.org/x/sys/windows" | |
| 24 | 新增:) | |
| 25 | 新增: | |
| 26 | 新增:func windowsHostManagerCall(ctx context.Context, id uuid.UUID, operation string, memory, cpus int, result any) error { | |
| 27 | 新增: request := windowsHostManagerRequest{Version: windowsHostManagerVersion, VMID: id, Operation: operation, MemoryGiB: memory, CPUs: cpus} | |
| 28 | 新增: return windowsHostManagerRequestCall(ctx, request, result) | |
| 29 | 新增:} | |
| 30 | 新增: | |
| 31 | 新增:func windowsHostManagerRequestCall(ctx context.Context, request windowsHostManagerRequest, result any) error { | |
| 32 | 新增: id := request.VMID | |
| 33 | 新增: if err := request.validate(); err != nil { | |
| 34 | 新增: return errors.New("Windows 客机管理参数无效") | |
| 35 | 新增: } | |
| 36 | 新增: ctx, cancel := context.WithTimeout(ctx, 3*time.Minute) | |
| 37 | 新增: defer cancel() | |
| 38 | 新增: connect, finish := context.WithTimeout(ctx, 10*time.Second) | |
| 39 | 新增: level := winio.PipeImpLevelIdentification | |
| 40 | 新增: if request.Storage != nil && request.Storage.Action == "attach" { | |
| 41 | 新增: // The verified service opens the destination using this caller's rights. | |
| 42 | 新增: level = winio.PipeImpLevelImpersonation | |
| 43 | 新增: } | |
| 44 | 新增: connection, err := winio.DialPipeAccessImpLevel(connect, `\\.\pipe\Cage.HyperV.`+id.String(), 0x120003, level) | |
| 45 | 新增: finish() | |
| 46 | 新增: if err != nil { | |
| 47 | 新增: if ctx.Err() != nil { | |
| 48 | 新增: return ctx.Err() | |
| 49 | 新增: } | |
| 50 | 新增: return errors.New("Windows 系统管理助手尚未连接,请在 Cage 安装流程中完成系统授权或恢复助手;原虚拟机和数据已保留") | |
| 51 | 新增: } | |
| 52 | 新增: defer connection.Close() | |
| 53 | 新增: stop := context.AfterFunc(ctx, func() { _ = connection.Close() }) | |
| 54 | 新增: defer stop() | |
| 55 | 新增: if deadline, ok := ctx.Deadline(); ok { | |
| 56 | 新增: _ = connection.SetDeadline(deadline) | |
| 57 | 新增: } | |
| 58 | 新增: if err := verifyWindowsHostManagerPeer(connection, id); err != nil { | |
| 59 | 新增: return err | |
| 60 | 新增: } | |
| 61 | 新增: if err := json.NewEncoder(connection).Encode(request); err != nil { | |
| 62 | 新增: return errors.New("Windows 系统管理请求没有完整送达") | |
| 63 | 新增: } | |
| 64 | 新增: line, err := bufio.NewReaderSize(connection, windowsHostManagerWireLimit).ReadSlice('\n') | |
| 65 | 新增: if err != nil { | |
| 66 | 新增: if ctx.Err() != nil { | |
| 67 | 新增: return ctx.Err() | |
| 68 | 新增: } | |
| 69 | 新增: return errors.New("Windows 系统管理结果没有完整返回,现有环境已保留") | |
| 70 | 新增: } | |
| 71 | 新增: var response windowsHostManagerResponse | |
| 72 | 新增: decoder := json.NewDecoder(bytes.NewReader(line)) | |
| 73 | 新增: decoder.DisallowUnknownFields() | |
| 74 | 新增: if decoder.Decode(&response) != nil || decoder.Decode(new(any)) != io.EOF || response.Version != windowsHostManagerVersion || response.VMID != id { | |
| 75 | 新增: return errors.New("Windows 系统管理响应身份或格式不匹配") | |
| 76 | 新增: } | |
| 77 | 新增: if err := verifyWindowsHostManagerPeer(connection, id); err != nil { | |
| 78 | 新增: return err | |
| 79 | 新增: } | |
| 80 | 新增: if !response.OK || response.Error != "" { | |
| 81 | 新增: if response.Error == "storage_pending" { | |
| 82 | 新增: return errors.New("Windows 客机有待恢复的存储迁移,请重新打开原工作台完成恢复") | |
| 83 | 新增: } | |
| 84 | 新增: if response.Error == "vm_running" { | |
| 85 | 新增: return errors.New("请等待 Windows 客机完整关机,再迁移环境存储") | |
| 86 | 新增: } | |
| 87 | 新增: if response.Error == "unauthorized" || response.Error == "permission_denied" { | |
| 88 | 新增: return errors.New("当前系统用户没有这台 Cage 客机的管理授权") | |
| 89 | 新增: } | |
| 90 | 新增: if response.Error == "binding_mismatch" || response.Error == "layout_mismatch" || response.Error == "binding_invalid" { | |
| 91 | 新增: return errors.New("Windows 客机的登记配置已变化,请核对原虚拟机;现有数据已保留") | |
| 92 | 新增: } | |
| 93 | 新增: return errors.New("Windows 系统管理操作未完成,请重试或在设置中导出诊断包;现有环境已保留") | |
| 94 | 新增: } | |
| 95 | 新增: if len(response.Result) == 0 || bytes.Equal(bytes.TrimSpace(response.Result), []byte("null")) || result == nil || json.Unmarshal(response.Result, result) != nil { | |
| 96 | 新增: return errors.New("Windows 系统管理响应缺少实际读回结果") | |
| 97 | 新增: } | |
| 98 | 新增: return nil | |
| 99 | 新增:} | |
| 100 | 新增: | |
| 101 | 新增:func verifyWindowsHostManagerPeer(connection net.Conn, id uuid.UUID) error { | |
| 102 | 新增: f, ok := connection.(interface{ Fd() uintptr }) | |
| 103 | 新增: if !ok { | |
| 104 | 新增: return errors.New("Windows 系统管理通道无法核验") | |
| 105 | 新增: } | |
| 106 | 新增: var pid uint32 | |
| 107 | 新增: if windows.GetNamedPipeServerProcessId(windows.Handle(f.Fd()), &pid) != nil || pid == 0 { | |
| 108 | 新增: return errors.New("Windows 系统管理进程无法核验") | |
| 109 | 新增: } | |
| 110 | 新增: // Query the SCM with read-only rights. A normal user cannot open the | |
| 111 | 新增: // LocalSystem process token; the protected service account and live PID | |
| 112 | 新增: // provide the corresponding identity without requesting that privilege. | |
| 113 | 新增: manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT) | |
| 114 | 新增: if err != nil { | |
| 115 | 新增: return errors.New("Windows 系统管理服务身份无法读取") | |
| 116 | 新增: } | |
| 117 | 新增: defer windows.CloseServiceHandle(manager) | |
| 118 | 新增: name, _ := windows.UTF16PtrFromString("CageHV-" + id.String()) | |
| 119 | 新增: service, err := windows.OpenService(manager, name, windows.SERVICE_QUERY_CONFIG|windows.SERVICE_QUERY_STATUS) | |
| 120 | 新增: if err != nil { | |
| 121 | 新增: return errors.New("Windows 系统管理服务未登记或当前用户不可读取") | |
| 122 | 新增: } | |
| 123 | 新增: defer windows.CloseServiceHandle(service) | |
| 124 | 新增: var status windows.SERVICE_STATUS_PROCESS | |
| 125 | 新增: var needed uint32 | |
| 126 | 新增: if windows.QueryServiceStatusEx(service, windows.SC_STATUS_PROCESS_INFO, (*byte)(unsafe.Pointer(&status)), uint32(unsafe.Sizeof(status)), &needed) != nil || status.ProcessId != pid || status.CurrentState != windows.SERVICE_RUNNING { | |
| 127 | 新增: return errors.New("Windows 系统管理通道不属于当前已登记服务") | |
| 128 | 新增: } | |
| 129 | 新增: binaryPath, account, err := windowsHostServiceConfig(service) | |
| 130 | 新增: if err != nil { | |
| 131 | 新增: return errors.New("Windows 系统管理服务配置无法核验") | |
| 132 | 新增: } | |
| 133 | 新增: if !strings.EqualFold(account, "LocalSystem") && !strings.EqualFold(account, `NT AUTHORITY\SYSTEM`) { | |
| 134 | 新增: return errors.New("Windows 系统管理服务未使用受限系统入口") | |
| 135 | 新增: } | |
| 136 | 新增: program, err := windows.KnownFolderPath(windows.FOLDERID_ProgramFiles, 0) | |
| 137 | 新增: if err != nil { | |
| 138 | 新增: return err | |
| 139 | 新增: } | |
| 140 | 新增: expected := filepath.Join(program, "Cage Host Manager", id.String(), "Cage.HyperVManager.exe") | |
| 141 | 新增: data, err := windows.KnownFolderPath(windows.FOLDERID_ProgramData, 0) | |
| 142 | 新增: if err != nil { | |
| 143 | 新增: return err | |
| 144 | 新增: } | |
| 145 | 新增: binding := filepath.Join(data, "Cage", "HyperVManager", id.String(), "binding.json") | |
| 146 | 新增: arguments, err := windows.DecomposeCommandLine(binaryPath) | |
| 147 | 新增: if err != nil || len(arguments) != 4 || !strings.EqualFold(filepath.Clean(arguments[0]), filepath.Clean(expected)) || arguments[1] != "service" || arguments[2] != "--binding" || !strings.EqualFold(filepath.Clean(arguments[3]), filepath.Clean(binding)) { | |
| 148 | 新增: return errors.New("Windows 系统管理程序不属于已登记的安装位置") | |
| 149 | 新增: } | |
| 150 | 新增: if err := checkWindowsSystemOwnedObject(binding); err != nil { | |
| 151 | 新增: return err | |
| 152 | 新增: } | |
| 153 | 新增: for current := expected; !strings.EqualFold(current, program); current = filepath.Dir(current) { | |
| 154 | 新增: if current == filepath.Dir(current) { | |
| 155 | 新增: return fmt.Errorf("Windows 系统管理程序路径无效") | |
| 156 | 新增: } | |
| 157 | 新增: if err := checkWindowsSystemOwnedObject(current); err != nil { | |
| 158 | 新增: return err | |
| 159 | 新增: } | |
| 160 | 新增: } | |
| 161 | 新增: return nil | |
| 162 | 新增:} | |
| 163 | 新增: | |
| 164 | 新增:func windowsHostServiceConfig(service windows.Handle) (string, string, error) { | |
| 165 | 新增: // QUERY_SERVICE_CONFIG contains pointers into this native output buffer. | |
| 166 | 新增: // A variable-sized allocation stays on the heap when later Go calls grow | |
| 167 | 新增: // the stack; copy its strings before releasing the retained buffer. | |
| 168 | 新增: size := uint32(1024) | |
| 169 | 新增: for size <= windowsHostManagerWireLimit { | |
| 170 | 新增: buffer := make([]byte, size) | |
| 171 | 新增: config := (*windows.QUERY_SERVICE_CONFIG)(unsafe.Pointer(&buffer[0])) | |
| 172 | 新增: var needed uint32 | |
| 173 | 新增: err := windows.QueryServiceConfig(service, config, size, &needed) | |
| 174 | 新增: if err == nil { | |
| 175 | 新增: binaryPath, account := windows.UTF16PtrToString(config.BinaryPathName), windows.UTF16PtrToString(config.ServiceStartName) | |
| 176 | 新增: runtime.KeepAlive(buffer) | |
| 177 | 新增: return binaryPath, account, nil | |
| 178 | 新增: } | |
| 179 | 新增: runtime.KeepAlive(buffer) | |
| 180 | 新增: if !errors.Is(err, windows.ERROR_INSUFFICIENT_BUFFER) || needed <= size { | |
| 181 | 新增: return "", "", err | |
| 182 | 新增: } | |
| 183 | 新增: size = needed | |
| 184 | 新增: } | |
| 185 | 新增: return "", "", errors.New("Windows service configuration exceeds limit") | |
| 186 | 新增:} | |
| 187 | 新增: | |
| 188 | 新增:func checkWindowsSystemOwnedObject(path string) error { | |
| 189 | 新增: info, err := os.Lstat(path) | |
| 190 | 新增: if err != nil { | |
| 191 | 新增: return errors.New("Windows 系统管理程序或目录不可读") | |
| 192 | 新增: } | |
| 193 | 新增: ptr, err := windows.UTF16PtrFromString(path) | |
| 194 | 新增: if err != nil { | |
| 195 | 新增: return err | |
| 196 | 新增: } | |
| 197 | 新增: attributes, err := windows.GetFileAttributes(ptr) | |
| 198 | 新增: if err != nil || attributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 || !info.Mode().IsRegular() && !info.IsDir() { | |
| 199 | 新增: return errors.New("Windows 系统管理程序不能经过目录链接") | |
| 200 | 新增: } | |
| 201 | 新增: sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION) | |
| 202 | 新增: if err != nil { | |
| 203 | 新增: return errors.New("Windows 系统管理程序权限不可读") | |
| 204 | 新增: } | |
| 205 | 新增: owner, _, err := sd.Owner() | |
| 206 | 新增: if err != nil || owner == nil || !owner.IsWellKnown(windows.WinLocalSystemSid) && !owner.IsWellKnown(windows.WinBuiltinAdministratorsSid) { | |
| 207 | 新增: return errors.New("Windows 系统管理程序未受系统权限保护") | |
| 208 | 新增: } | |
| 209 | 新增: acl, _, err := sd.DACL() | |
| 210 | 新增: if err != nil || acl == nil || acl.AceCount == 0 { | |
| 211 | 新增: return errors.New("Windows 系统管理程序没有访问限制") | |
| 212 | 新增: } | |
| 213 | 新增: const fileDeleteChild = 0x40 // FILE_DELETE_CHILD is absent from x/sys/windows. | |
| 214 | 新增: const writes = windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA | windows.FILE_WRITE_EA | windows.FILE_WRITE_ATTRIBUTES | fileDeleteChild | windows.DELETE | windows.WRITE_DAC | windows.WRITE_OWNER | windows.GENERIC_WRITE | windows.GENERIC_ALL | |
| 215 | 新增: for i := uint32(0); i < uint32(acl.AceCount); i++ { | |
| 216 | 新增: var ace *windows.ACCESS_ALLOWED_ACE | |
| 217 | 新增: if windows.GetAce(acl, i, &ace) != nil { | |
| 218 | 新增: return errors.New("Windows 系统管理程序权限无法核验") | |
| 219 | 新增: } | |
| 220 | 新增: if ace.Header.AceType == windows.ACCESS_DENIED_ACE_TYPE { | |
| 221 | 新增: continue | |
| 222 | 新增: } | |
| 223 | 新增: if ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE { | |
| 224 | 新增: return errors.New("Windows 系统管理程序含未支持的权限规则") | |
| 225 | 新增: } | |
| 226 | 新增: principal := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) | |
| 227 | 新增: if ace.Mask&writes != 0 && !principal.IsWellKnown(windows.WinLocalSystemSid) && !principal.IsWellKnown(windows.WinBuiltinAdministratorsSid) { | |
| 228 | 新增: return errors.New("Windows 系统管理程序可被普通用户修改") | |
| 229 | 新增: } | |
| 230 | 新增: } | |
| 231 | 新增: return nil | |
| 232 | 新增:} | |
| @@ -0,0 +1,138 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bufio" | |
| 7 | 新增: "context" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "os" | |
| 10 | 新增: "strings" | |
| 11 | 新增: "testing" | |
| 12 | 新增: "time" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/Microsoft/go-winio" | |
| 15 | 新增: "github.com/google/uuid" | |
| 16 | 新增: "golang.org/x/sys/windows" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:// This test only reads the already registered VM. It must run in the ordinary | |
| 20 | 新增:// desktop user's token so direct Hyper-V administrator access cannot mask a | |
| 21 | 新增:// broken manager boundary. | |
| 22 | 新增:func TestWindowsHostManagerOrdinaryRead(t *testing.T) { | |
| 23 | 新增: idText := os.Getenv("CAGE_TEST_WINDOWS_MANAGER_VM") | |
| 24 | 新增: if idText == "" { | |
| 25 | 新增: t.Skip("requires the installed fixed-VM manager and ordinary host session") | |
| 26 | 新增: } | |
| 27 | 新增: id, err := uuid.Parse(idText) | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: t.Fatal("invalid test VM") | |
| 30 | 新增: } | |
| 31 | 新增: token := windows.GetCurrentProcessToken() | |
| 32 | 新增: if token.IsElevated() { | |
| 33 | 新增: t.Fatal("this acceptance test must use the ordinary desktop token") | |
| 34 | 新增: } | |
| 35 | 新增: admins, _ := windows.StringToSid("S-1-5-32-578") | |
| 36 | 新增: member, err := token.IsMember(admins) | |
| 37 | 新增: if err != nil || member { | |
| 38 | 新增: t.Fatal("ordinary host must not receive Hyper-V Administrators membership") | |
| 39 | 新增: } | |
| 40 | 新增: binding, err := LoadWindowsHostManagerBinding(WindowsHostManagerBindingPath(id)) | |
| 41 | 新增: if err != nil { | |
| 42 | 新增: t.Fatal(err) | |
| 43 | 新增: } | |
| 44 | 新增: user, err := token.GetTokenUser() | |
| 45 | 新增: if err != nil || user.User.Sid.String() != binding.HostSID { | |
| 46 | 新增: t.Fatal("acceptance token differs from protected manager host identity") | |
| 47 | 新增: } | |
| 48 | 新增: for _, path := range []string{WindowsHostManagerBindingPath(id), WindowsHostManagerExecutablePath(id)} { | |
| 49 | 新增: name, _ := windows.UTF16PtrFromString(path) | |
| 50 | 新增: handle, err := windows.CreateFile(name, windows.FILE_WRITE_DATA|windows.WRITE_DAC, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, 0, 0) | |
| 51 | 新增: if err == nil { | |
| 52 | 新增: windows.CloseHandle(handle) | |
| 53 | 新增: t.Fatal("ordinary caller can alter manager code or authority") | |
| 54 | 新增: } | |
| 55 | 新增: if err != windows.ERROR_ACCESS_DENIED { | |
| 56 | 新增: t.Fatal("manager write protection was not proven by access denial", err) | |
| 57 | 新增: } | |
| 58 | 新增: } | |
| 59 | 新增: scm, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT) | |
| 60 | 新增: if err != nil { | |
| 61 | 新增: t.Fatal(err) | |
| 62 | 新增: } | |
| 63 | 新增: defer windows.CloseServiceHandle(scm) | |
| 64 | 新增: serviceName, _ := windows.UTF16PtrFromString(WindowsHostManagerServiceName(id)) | |
| 65 | 新增: service, err := windows.OpenService(scm, serviceName, windows.SERVICE_QUERY_CONFIG|windows.SERVICE_QUERY_STATUS|windows.SERVICE_START) | |
| 66 | 新增: if err != nil { | |
| 67 | 新增: t.Fatal("ordinary host cannot query or restore its fixed helper", err) | |
| 68 | 新增: } | |
| 69 | 新增: windows.CloseServiceHandle(service) | |
| 70 | 新增: service, err = windows.OpenService(scm, serviceName, windows.SERVICE_CHANGE_CONFIG|windows.WRITE_DAC) | |
| 71 | 新增: if err == nil { | |
| 72 | 新增: windows.CloseServiceHandle(service) | |
| 73 | 新增: t.Fatal("ordinary host can replace its SYSTEM service configuration") | |
| 74 | 新增: } | |
| 75 | 新增: if err != windows.ERROR_ACCESS_DENIED { | |
| 76 | 新增: t.Fatal("service configuration write denial was not proven", err) | |
| 77 | 新增: } | |
| 78 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) | |
| 79 | 新增: defer cancel() | |
| 80 | 新增: var inspected HyperVInspection | |
| 81 | 新增: if err := windowsHostManagerCall(ctx, id, "inspect", 0, 0, &inspected); err != nil { | |
| 82 | 新增: t.Fatal(err) | |
| 83 | 新增: } | |
| 84 | 新增: if inspected.Lookup != "found" || inspected.VMID != id.String() || inspected.VM == nil || inspected.VM.NetworkAdapterCount != 0 || inspected.VM.Generation != 2 || !inspected.VM.SecureBoot || !inspected.VM.VirtualTPM { | |
| 85 | 新增: t.Fatal("manager did not return the registered offline-network VM layout") | |
| 86 | 新增: } | |
| 87 | 新增: public, err := InspectHyperV(ctx, id) | |
| 88 | 新增: if err != nil || public.Lookup != "found" || public.VMID != id.String() || public.VM == nil || public.VM.State != inspected.VM.State { | |
| 89 | 新增: t.Fatal("ordinary public inspection did not reach the authenticated fixed-VM manager", err) | |
| 90 | 新增: } | |
| 91 | 新增: var resources WindowsVMResourceState | |
| 92 | 新增: if err := windowsHostManagerCall(ctx, id, "resources", 0, 0, &resources); err != nil { | |
| 93 | 新增: t.Fatal(err) | |
| 94 | 新增: } | |
| 95 | 新增: if resources.State != inspected.VM.State || resources.CPUs <= 0 || resources.MemoryStartup < 4<<30 { | |
| 96 | 新增: t.Fatal("manager did not return actual fixed-VM resources") | |
| 97 | 新增: } | |
| 98 | 新增: t.Logf("ordinary token accepted; VM state=%s, no NIC, CPU=%d, memory=%d GiB", inspected.VM.State, resources.CPUs, resources.MemoryStartup>>30) | |
| 99 | 新增: | |
| 100 | 新增: request := func(t *testing.T, body string, expected string) { | |
| 101 | 新增: t.Helper() | |
| 102 | 新增: conn, err := winio.DialPipeAccessImpLevel(ctx, `\\.\pipe\Cage.HyperV.`+id.String(), 0x120003, winio.PipeImpLevelIdentification) | |
| 103 | 新增: if err != nil { | |
| 104 | 新增: t.Fatal(err) | |
| 105 | 新增: } | |
| 106 | 新增: defer conn.Close() | |
| 107 | 新增: _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) | |
| 108 | 新增: if err := verifyWindowsHostManagerPeer(conn, id); err != nil { | |
| 109 | 新增: t.Fatal(err) | |
| 110 | 新增: } | |
| 111 | 新增: if _, err := conn.Write([]byte(body)); err != nil { | |
| 112 | 新增: t.Fatal(err) | |
| 113 | 新增: } | |
| 114 | 新增: line, err := bufio.NewReader(conn).ReadBytes('\n') | |
| 115 | 新增: if err != nil { | |
| 116 | 新增: t.Fatal(err) | |
| 117 | 新增: } | |
| 118 | 新增: var response windowsHostManagerResponse | |
| 119 | 新增: if json.Unmarshal(line, &response) != nil || response.OK || response.Error != expected || response.VMID != id || response.Version != windowsHostManagerVersion || len(response.Result) != 0 { | |
| 120 | 新增: t.Fatalf("unsafe or unexpected rejection: %s", line) | |
| 121 | 新增: } | |
| 122 | 新增: } | |
| 123 | 新增: for _, item := range []struct{ name, body, code string }{ | |
| 124 | 新增: {"wrong_vm", `{"version":1,"vm_id":"` + uuid.NewString() + `","operation":"inspect"}` + "\n", "invalid_request"}, | |
| 125 | 新增: {"unknown_operation", `{"version":1,"vm_id":"` + id.String() + `","operation":"execute"}` + "\n", "invalid_request"}, | |
| 126 | 新增: {"unknown_field", `{"version":1,"vm_id":"` + id.String() + `","operation":"inspect","command":"noop"}` + "\n", "invalid_request"}, | |
| 127 | 新增: {"resource_bounds", `{"version":1,"vm_id":"` + id.String() + `","operation":"resources","memory_gib":1025,"cpus":1}` + "\n", "invalid_request"}, | |
| 128 | 新增: {"oversize", strings.Repeat("x", windowsHostManagerWireLimit+1) + "\n", "invalid_request"}, | |
| 129 | 新增: {"extra_json", `{"version":1,"vm_id":"` + id.String() + `","operation":"inspect"} {}` + "\n", "invalid_request"}, | |
| 130 | 新增: } { | |
| 131 | 新增: t.Run(item.name, func(t *testing.T) { request(t, item.body, item.code) }) | |
| 132 | 新增: } | |
| 133 | 新增: // Invalid clients must not poison later reads or stop the existing VM. | |
| 134 | 新增: var after HyperVInspection | |
| 135 | 新增: if err := windowsHostManagerCall(ctx, id, "inspect", 0, 0, &after); err != nil || after.VM == nil || after.VM.State != inspected.VM.State { | |
| 136 | 新增: t.Fatal("rejected requests damaged the manager or VM state", err) | |
| 137 | 新增: } | |
| 138 | 新增:} | |
| @@ -0,0 +1,474 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bufio" | |
| 7 | 新增: "bytes" | |
| 8 | 新增: "context" | |
| 9 | 新增: "encoding/json" | |
| 10 | 新增: "errors" | |
| 11 | 新增: "fmt" | |
| 12 | 新增: "io" | |
| 13 | 新增: "net" | |
| 14 | 新增: "os" | |
| 15 | 新增: "path/filepath" | |
| 16 | 新增: "runtime" | |
| 17 | 新增: "strings" | |
| 18 | 新增: "sync" | |
| 19 | 新增: "time" | |
| 20 | 新增: "unsafe" | |
| 21 | 新增: | |
| 22 | 新增: "github.com/Microsoft/go-winio" | |
| 23 | 新增: "github.com/google/uuid" | |
| 24 | 新增: "golang.org/x/sys/windows" | |
| 25 | 新增: | |
| 26 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 27 | 新增:) | |
| 28 | 新增: | |
| 29 | 新增:// WindowsHostManagerBinding is installed by an administrator. The service never | |
| 30 | 新增:// takes its authority from a user's workbench profile or a pipe request. | |
| 31 | 新增:type WindowsHostManagerBinding struct { | |
| 32 | 新增: Version int `json:"version"` | |
| 33 | 新增: VMID uuid.UUID `json:"vm_id"` | |
| 34 | 新增: HostSID string `json:"host_sid"` | |
| 35 | 新增: DiskPath string `json:"disk_path"` | |
| 36 | 新增: DiskVolume uint32 `json:"disk_volume"` | |
| 37 | 新增: DiskFileID uint64 `json:"disk_file_id"` | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:func WindowsHostManagerServiceName(id uuid.UUID) string { return "CageHV-" + id.String() } | |
| 41 | 新增: | |
| 42 | 新增:func managerKnownFolder(id *windows.KNOWNFOLDERID) string { | |
| 43 | 新增: p, err := windows.KnownFolderPath(id, 0) | |
| 44 | 新增: if err != nil { | |
| 45 | 新增: return "" | |
| 46 | 新增: } | |
| 47 | 新增: return p | |
| 48 | 新增:} | |
| 49 | 新增: | |
| 50 | 新增:func WindowsHostManagerBindingPath(id uuid.UUID) string { | |
| 51 | 新增: return filepath.Join(managerKnownFolder(windows.FOLDERID_ProgramData), "Cage", "HyperVManager", id.String(), "binding.json") | |
| 52 | 新增:} | |
| 53 | 新增: | |
| 54 | 新增:func WindowsHostManagerExecutablePath(id uuid.UUID) string { | |
| 55 | 新增: return filepath.Join(managerKnownFolder(windows.FOLDERID_ProgramFiles), "Cage Host Manager", id.String(), "Cage.HyperVManager.exe") | |
| 56 | 新增:} | |
| 57 | 新增: | |
| 58 | 新增:func managerProtected(path, hostSID string) error { | |
| 59 | 新增: return managerProtectedAccess(path, hostSID, false) | |
| 60 | 新增:} | |
| 61 | 新增: | |
| 62 | 新增:func managerSharedProtected(path, hostSID string) error { | |
| 63 | 新增: return managerProtectedAccess(path, hostSID, true) | |
| 64 | 新增:} | |
| 65 | 新增: | |
| 66 | 新增:func managerProtectedAccess(path, hostSID string, shared bool) error { | |
| 67 | 新增: for p := path; p != filepath.Dir(p); p = filepath.Dir(p) { | |
| 68 | 新增: name, err := windows.UTF16PtrFromString(p) | |
| 69 | 新增: if err != nil { | |
| 70 | 新增: return errors.New("binding_invalid") | |
| 71 | 新增: } | |
| 72 | 新增: attributes, err := windows.GetFileAttributes(name) | |
| 73 | 新增: if err != nil || attributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 { | |
| 74 | 新增: return errors.New("binding_invalid") | |
| 75 | 新增: } | |
| 76 | 新增: } | |
| 77 | 新增: sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION) | |
| 78 | 新增: if err != nil { | |
| 79 | 新增: return errors.New("binding_invalid") | |
| 80 | 新增: } | |
| 81 | 新增: owner, _, err := sd.Owner() | |
| 82 | 新增: if err != nil || owner == nil || !(owner.IsWellKnown(windows.WinLocalSystemSid) || owner.IsWellKnown(windows.WinBuiltinAdministratorsSid)) { | |
| 83 | 新增: return errors.New("binding_invalid") | |
| 84 | 新增: } | |
| 85 | 新增: control, _, err := sd.Control() | |
| 86 | 新增: if err != nil || control&windows.SE_DACL_PROTECTED == 0 { | |
| 87 | 新增: return errors.New("binding_invalid") | |
| 88 | 新增: } | |
| 89 | 新增: acl, _, err := sd.DACL() | |
| 90 | 新增: if err != nil || acl == nil || acl.AceCount == 0 { | |
| 91 | 新增: return errors.New("binding_invalid") | |
| 92 | 新增: } | |
| 93 | 新增: for index := uint32(0); index < uint32(acl.AceCount); index++ { | |
| 94 | 新增: var ace *windows.ACCESS_ALLOWED_ACE | |
| 95 | 新增: if windows.GetAce(acl, index, &ace) != nil || ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE { | |
| 96 | 新增: return errors.New("binding_invalid") | |
| 97 | 新增: } | |
| 98 | 新增: sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) | |
| 99 | 新增: if sid.IsWellKnown(windows.WinLocalSystemSid) || sid.IsWellKnown(windows.WinBuiltinAdministratorsSid) { | |
| 100 | 新增: continue | |
| 101 | 新增: } | |
| 102 | 新增: const deleteChild = 0x40 // FILE_DELETE_CHILD is absent from x/sys/windows. | |
| 103 | 新增: const modify = windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA | windows.FILE_WRITE_EA | windows.FILE_WRITE_ATTRIBUTES | deleteChild | windows.DELETE | windows.WRITE_DAC | windows.WRITE_OWNER | windows.GENERIC_WRITE | windows.GENERIC_ALL | |
| 104 | 新增: if (!shared && sid.String() != hostSID) || ace.Mask&modify != 0 { | |
| 105 | 新增: return errors.New("binding_invalid") | |
| 106 | 新增: } | |
| 107 | 新增: } | |
| 108 | 新增: return nil | |
| 109 | 新增:} | |
| 110 | 新增: | |
| 111 | 新增:func LoadWindowsHostManagerBinding(path string) (WindowsHostManagerBinding, error) { | |
| 112 | 新增: var binding WindowsHostManagerBinding | |
| 113 | 新增: file, err := os.Open(path) | |
| 114 | 新增: if err != nil { | |
| 115 | 新增: return binding, errors.New("binding_invalid") | |
| 116 | 新增: } | |
| 117 | 新增: defer file.Close() | |
| 118 | 新增: info, err := file.Stat() | |
| 119 | 新增: if err != nil || !info.Mode().IsRegular() || info.Size() > windowsHostManagerWireLimit { | |
| 120 | 新增: return binding, errors.New("binding_invalid") | |
| 121 | 新增: } | |
| 122 | 新增: decoder := json.NewDecoder(io.LimitReader(file, windowsHostManagerWireLimit+1)) | |
| 123 | 新增: decoder.DisallowUnknownFields() | |
| 124 | 新增: if decoder.Decode(&binding) != nil || decoder.Decode(new(any)) != io.EOF || binding.Version != windowsHostManagerVersion || binding.VMID == uuid.Nil || binding.DiskFileID == 0 || binding.DiskVolume == 0 || !filepath.IsAbs(binding.DiskPath) || strings.HasPrefix(binding.DiskPath, `\\`) || !strings.EqualFold(filepath.Ext(binding.DiskPath), ".vhdx") { | |
| 125 | 新增: return binding, errors.New("binding_invalid") | |
| 126 | 新增: } | |
| 127 | 新增: sid, err := windows.StringToSid(binding.HostSID) | |
| 128 | 新增: if err != nil || !(strings.HasPrefix(sid.String(), "S-1-5-21-") || strings.HasPrefix(sid.String(), "S-1-12-1-")) || !strings.EqualFold(filepath.Clean(path), WindowsHostManagerBindingPath(binding.VMID)) { | |
| 129 | 新增: return binding, errors.New("binding_invalid") | |
| 130 | 新增: } | |
| 131 | 新增: if err = managerProtected(path, binding.HostSID); err != nil { | |
| 132 | 新增: return binding, err | |
| 133 | 新增: } | |
| 134 | 新增: if err = managerProtected(filepath.Dir(path), binding.HostSID); err != nil { | |
| 135 | 新增: return binding, err | |
| 136 | 新增: } | |
| 137 | 新增: if err = managerSharedProtected(filepath.Dir(filepath.Dir(path)), binding.HostSID); err != nil { | |
| 138 | 新增: return binding, err | |
| 139 | 新增: } | |
| 140 | 新增: if err = managerSharedProtected(filepath.Dir(filepath.Dir(filepath.Dir(path))), binding.HostSID); err != nil { | |
| 141 | 新增: return binding, err | |
| 142 | 新增: } | |
| 143 | 新增: return binding, nil | |
| 144 | 新增:} | |
| 145 | 新增: | |
| 146 | 新增:func managerDiskIdentity(path string) (uint32, uint64, error) { | |
| 147 | 新增: name, err := windows.UTF16PtrFromString(path) | |
| 148 | 新增: if err != nil { | |
| 149 | 新增: return 0, 0, errors.New("vm_changed") | |
| 150 | 新增: } | |
| 151 | 新增: handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) | |
| 152 | 新增: if err != nil { | |
| 153 | 新增: return 0, 0, errors.New("vm_changed") | |
| 154 | 新增: } | |
| 155 | 新增: defer windows.CloseHandle(handle) | |
| 156 | 新增: var info windows.ByHandleFileInformation | |
| 157 | 新增: if windows.GetFileInformationByHandle(handle, &info) != nil || info.FileAttributes&(windows.FILE_ATTRIBUTE_DIRECTORY|windows.FILE_ATTRIBUTE_REPARSE_POINT) != 0 { | |
| 158 | 新增: return 0, 0, errors.New("vm_changed") | |
| 159 | 新增: } | |
| 160 | 新增: return info.VolumeSerialNumber, uint64(info.FileIndexHigh)<<32 | uint64(info.FileIndexLow), nil | |
| 161 | 新增:} | |
| 162 | 新增: | |
| 163 | 新增:func managerVMDisk(ctx context.Context, id uuid.UUID) (string, error) { | |
| 164 | 新增: script := fmt.Sprintf("$ErrorActionPreference='Stop';$v=Get-VM -Id ([guid]'%s');$d=@(Get-VMHardDiskDrive -VM $v);if($d.Count -ne 1){throw 'bound_disk_invalid'};[pscustomobject]@{path=$d[0].Path}|ConvertTo-Json -Compress", id.String()) | |
| 165 | 新增: cmd, err := systemPowerShellQuery(ctx, script) | |
| 166 | 新增: if err != nil { | |
| 167 | 新增: return "", errors.New("vm_changed") | |
| 168 | 新增: } | |
| 169 | 新增: data, err := cmd.Output() | |
| 170 | 新增: if err != nil || len(data) > 16384 { | |
| 171 | 新增: return "", errors.New("vm_changed") | |
| 172 | 新增: } | |
| 173 | 新增: var disk struct { | |
| 174 | 新增: Path string `json:"path"` | |
| 175 | 新增: } | |
| 176 | 新增: if json.Unmarshal(data, &disk) != nil { | |
| 177 | 新增: return "", errors.New("vm_changed") | |
| 178 | 新增: } | |
| 179 | 新增: return disk.Path, nil | |
| 180 | 新增:} | |
| 181 | 新增: | |
| 182 | 新增:func managerValidateVM(ctx context.Context, binding WindowsHostManagerBinding) (HyperVInspection, error) { | |
| 183 | 新增: state, err := inspectHyperVNative(ctx, binding.VMID) | |
| 184 | 新增: if err != nil || state.Lookup != "found" || state.VM == nil || state.VM.Generation != 2 || !state.VM.SecureBoot || !state.VM.VirtualTPM || state.VM.NetworkAdapterCount != 0 || state.VM.DiskCount != 1 || state.VM.SingleLocalVHDX == nil || !*state.VM.SingleLocalVHDX { | |
| 185 | 新增: return state, errors.New("vm_changed") | |
| 186 | 新增: } | |
| 187 | 新增: disk, err := managerVMDisk(ctx, binding.VMID) | |
| 188 | 新增: if err != nil { | |
| 189 | 新增: return state, err | |
| 190 | 新增: } | |
| 191 | 新增: real, err := paths.Resolve(disk) | |
| 192 | 新增: if err != nil || !strings.EqualFold(real, binding.DiskPath) { | |
| 193 | 新增: return state, errors.New("vm_changed") | |
| 194 | 新增: } | |
| 195 | 新增: volume, id, err := managerDiskIdentity(real) | |
| 196 | 新增: if err != nil || volume != binding.DiskVolume || id != binding.DiskFileID { | |
| 197 | 新增: return state, errors.New("vm_changed") | |
| 198 | 新增: } | |
| 199 | 新增: return state, nil | |
| 200 | 新增:} | |
| 201 | 新增: | |
| 202 | 新增:func PrepareWindowsHostManagerBinding(ctx context.Context, id uuid.UUID, hostSID string) (WindowsHostManagerBinding, error) { | |
| 203 | 新增: var binding WindowsHostManagerBinding | |
| 204 | 新增: token := windows.GetCurrentProcessToken() | |
| 205 | 新增: host, err := windows.StringToSid(hostSID) | |
| 206 | 新增: if err != nil || !token.IsElevated() || !(strings.HasPrefix(host.String(), "S-1-5-21-") || strings.HasPrefix(host.String(), "S-1-12-1-")) { | |
| 207 | 新增: return binding, errors.New("installation_requires_administrator") | |
| 208 | 新增: } | |
| 209 | 新增: state, err := inspectHyperVNative(ctx, id) | |
| 210 | 新增: if err != nil || state.Lookup != "found" || state.VM == nil || state.VM.Generation != 2 || !state.VM.SecureBoot || !state.VM.VirtualTPM || state.VM.NetworkAdapterCount != 0 || state.VM.DiskCount != 1 { | |
| 211 | 新增: return binding, errors.New("vm_changed") | |
| 212 | 新增: } | |
| 213 | 新增: disk, err := managerVMDisk(ctx, id) | |
| 214 | 新增: if err != nil { | |
| 215 | 新增: return binding, err | |
| 216 | 新增: } | |
| 217 | 新增: real, err := paths.Resolve(disk) | |
| 218 | 新增: if err != nil || strings.HasPrefix(real, `\\`) || !strings.EqualFold(filepath.Ext(real), ".vhdx") { | |
| 219 | 新增: return binding, errors.New("vm_changed") | |
| 220 | 新增: } | |
| 221 | 新增: volume, fileID, err := managerDiskIdentity(real) | |
| 222 | 新增: if err != nil { | |
| 223 | 新增: return binding, err | |
| 224 | 新增: } | |
| 225 | 新增: return WindowsHostManagerBinding{Version: windowsHostManagerVersion, VMID: id, HostSID: hostSID, DiskPath: real, DiskVolume: volume, DiskFileID: fileID}, nil | |
| 226 | 新增:} | |
| 227 | 新增: | |
| 228 | 新增:func managerClientSID(conn net.Conn) (string, error) { | |
| 229 | 新增: file, ok := conn.(interface{ Fd() uintptr }) | |
| 230 | 新增: if !ok { | |
| 231 | 新增: return "", errors.New("unauthorized") | |
| 232 | 新增: } | |
| 233 | 新增: var pid uint32 | |
| 234 | 新增: if windows.GetNamedPipeClientProcessId(windows.Handle(file.Fd()), &pid) != nil || pid == 0 { | |
| 235 | 新增: return "", errors.New("unauthorized") | |
| 236 | 新增: } | |
| 237 | 新增: process, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid) | |
| 238 | 新增: if err != nil { | |
| 239 | 新增: return "", errors.New("unauthorized") | |
| 240 | 新增: } | |
| 241 | 新增: defer windows.CloseHandle(process) | |
| 242 | 新增: var token windows.Token | |
| 243 | 新增: if windows.OpenProcessToken(process, windows.TOKEN_QUERY, &token) != nil { | |
| 244 | 新增: return "", errors.New("unauthorized") | |
| 245 | 新增: } | |
| 246 | 新增: defer token.Close() | |
| 247 | 新增: user, err := token.GetTokenUser() | |
| 248 | 新增: if err != nil { | |
| 249 | 新增: return "", errors.New("unauthorized") | |
| 250 | 新增: } | |
| 251 | 新增: return user.User.Sid.String(), nil | |
| 252 | 新增:} | |
| 253 | 新增: | |
| 254 | 新增:type windowsHostManagerServer struct { | |
| 255 | 新增: binding WindowsHostManagerBinding | |
| 256 | 新增: mutate sync.RWMutex | |
| 257 | 新增:} | |
| 258 | 新增: | |
| 259 | 新增:func managerHostMemoryGiB() int { | |
| 260 | 新增: var memory struct { | |
| 261 | 新增: Length, Load uint32 | |
| 262 | 新增: TotalPhysical, AvailablePhysical, TotalPage, AvailablePage, TotalVirtual, AvailableVirtual, AvailableExtended uint64 | |
| 263 | 新增: } | |
| 264 | 新增: memory.Length = uint32(unsafe.Sizeof(memory)) | |
| 265 | 新增: result, _, _ := windows.NewLazySystemDLL("kernel32.dll").NewProc("GlobalMemoryStatusEx").Call(uintptr(unsafe.Pointer(&memory))) | |
| 266 | 新增: if result == 0 { | |
| 267 | 新增: return 0 | |
| 268 | 新增: } | |
| 269 | 新增: return int(memory.TotalPhysical >> 30) | |
| 270 | 新增:} | |
| 271 | 新增: | |
| 272 | 新增:func (server *windowsHostManagerServer) request(ctx context.Context, request windowsHostManagerRequest, conn net.Conn) (any, error) { | |
| 273 | 新增: if request.validate() != nil || request.VMID != server.binding.VMID { | |
| 274 | 新增: return nil, errors.New("invalid_request") | |
| 275 | 新增: } | |
| 276 | 新增: if request.Operation == "storage" || request.Operation == "start" || request.Operation == "shutdown" || request.Operation == "resources" && request.CPUs != 0 { | |
| 277 | 新增: server.mutate.Lock() | |
| 278 | 新增: defer server.mutate.Unlock() | |
| 279 | 新增: } else { | |
| 280 | 新增: server.mutate.RLock() | |
| 281 | 新增: defer server.mutate.RUnlock() | |
| 282 | 新增: } | |
| 283 | 新增: journal, err := server.loadStorageJournal() | |
| 284 | 新增: if err != nil { | |
| 285 | 新增: return nil, err | |
| 286 | 新增: } | |
| 287 | 新增: if request.Storage != nil { | |
| 288 | 新增: return server.storageRequest(ctx, *request.Storage, journal, conn) | |
| 289 | 新增: } | |
| 290 | 新增: if journal != nil && journal.Phase == "pending" { | |
| 291 | 新增: return nil, errors.New("storage_pending") | |
| 292 | 新增: } | |
| 293 | 新增: state, err := managerValidateVM(ctx, server.binding) | |
| 294 | 新增: if err != nil { | |
| 295 | 新增: return nil, err | |
| 296 | 新增: } | |
| 297 | 新增: name, err := windows.UTF16PtrFromString(server.binding.DiskPath) | |
| 298 | 新增: if err != nil { | |
| 299 | 新增: return nil, errors.New("vm_changed") | |
| 300 | 新增: } | |
| 301 | 新增: // Hold the verified inode across the operation. A same-user caller cannot | |
| 302 | 新增: // replace the VHDX path after validation while the SYSTEM operation runs. | |
| 303 | 新增: lockedDisk, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) | |
| 304 | 新增: if err != nil { | |
| 305 | 新增: return nil, errors.New("vm_changed") | |
| 306 | 新增: } | |
| 307 | 新增: defer windows.CloseHandle(lockedDisk) | |
| 308 | 新增: var pinned windows.ByHandleFileInformation | |
| 309 | 新增: if windows.GetFileInformationByHandle(lockedDisk, &pinned) != nil || pinned.VolumeSerialNumber != server.binding.DiskVolume || uint64(pinned.FileIndexHigh)<<32|uint64(pinned.FileIndexLow) != server.binding.DiskFileID { | |
| 310 | 新增: return nil, errors.New("vm_changed") | |
| 311 | 新增: } | |
| 312 | 新增: switch request.Operation { | |
| 313 | 新增: case "inspect": | |
| 314 | 新增: return state, nil | |
| 315 | 新增: case "resources": | |
| 316 | 新增: if request.CPUs != 0 { | |
| 317 | 新增: maxMemory, maxCPUs := WindowsVMResourceCeiling(managerHostMemoryGiB(), runtime.NumCPU()) | |
| 318 | 新增: if request.CPUs > maxCPUs || request.MemoryGiB > maxMemory { | |
| 319 | 新增: return nil, errors.New("resources_out_of_bounds") | |
| 320 | 新增: } | |
| 321 | 新增: } | |
| 322 | 新增: return windowsVMResourcesNative(ctx, server.binding.VMID, request.MemoryGiB, request.CPUs) | |
| 323 | 新增: case "start", "shutdown": | |
| 324 | 新增: action := "start" | |
| 325 | 新增: if request.Operation == "shutdown" { | |
| 326 | 新增: action = "stop" | |
| 327 | 新增: } | |
| 328 | 新增: if err := windowsVMActionNative(ctx, server.binding.VMID, action); err != nil { | |
| 329 | 新增: return nil, errors.New("operation_failed") | |
| 330 | 新增: } | |
| 331 | 新增: if _, err = managerValidateVM(ctx, server.binding); err != nil { | |
| 332 | 新增: return nil, err | |
| 333 | 新增: } | |
| 334 | 新增: return windowsVMResourcesNative(ctx, server.binding.VMID, 0, 0) | |
| 335 | 新增: } | |
| 336 | 新增: return nil, errors.New("invalid_operation") | |
| 337 | 新增:} | |
| 338 | 新增: | |
| 339 | 新增:func (server *windowsHostManagerServer) connection(ctx context.Context, conn net.Conn) { | |
| 340 | 新增: defer conn.Close() | |
| 341 | 新增: response := windowsHostManagerResponse{Version: windowsHostManagerVersion, VMID: server.binding.VMID} | |
| 342 | 新增: write := func() { | |
| 343 | 新增: conn.SetWriteDeadline(time.Now().Add(10 * time.Second)) | |
| 344 | 新增: _ = json.NewEncoder(conn).Encode(response) | |
| 345 | 新增: } | |
| 346 | 新增: sid, err := managerClientSID(conn) | |
| 347 | 新增: if err != nil || sid != server.binding.HostSID { | |
| 348 | 新增: response.Error = "unauthorized" | |
| 349 | 新增: write() | |
| 350 | 新增: return | |
| 351 | 新增: } | |
| 352 | 新增: conn.SetReadDeadline(time.Now().Add(10 * time.Second)) | |
| 353 | 新增: reader := bufio.NewReaderSize(conn, windowsHostManagerWireLimit+1) | |
| 354 | 新增: line, err := reader.ReadSlice('\n') | |
| 355 | 新增: if err != nil || len(line) > windowsHostManagerWireLimit || reader.Buffered() != 0 { | |
| 356 | 新增: response.Error = "invalid_request" | |
| 357 | 新增: write() | |
| 358 | 新增: return | |
| 359 | 新增: } | |
| 360 | 新增: var request windowsHostManagerRequest | |
| 361 | 新增: decoder := json.NewDecoder(bytes.NewReader(line)) | |
| 362 | 新增: decoder.DisallowUnknownFields() | |
| 363 | 新增: if decoder.Decode(&request) != nil || decoder.Decode(new(any)) != io.EOF { | |
| 364 | 新增: response.Error = "invalid_request" | |
| 365 | 新增: write() | |
| 366 | 新增: return | |
| 367 | 新增: } | |
| 368 | 新增: conn.SetReadDeadline(time.Time{}) | |
| 369 | 新增: deadline := time.Minute | |
| 370 | 新增: if request.Storage != nil { | |
| 371 | 新增: deadline = 3 * time.Minute | |
| 372 | 新增: } | |
| 373 | 新增: operation, cancel := context.WithTimeout(ctx, deadline) | |
| 374 | 新增: defer cancel() | |
| 375 | 新增: // One request per pipe. A client disconnect or extra command cancels work. | |
| 376 | 新增: disconnected := make(chan struct{}) | |
| 377 | 新增: go func() { defer close(disconnected); var extra [1]byte; _, _ = conn.Read(extra[:]); cancel() }() | |
| 378 | 新增: result, err := server.request(operation, request, conn) | |
| 379 | 新增: if err != nil { | |
| 380 | 新增: response.Error = "operation_failed" | |
| 381 | 新增: for _, code := range []string{"invalid_request", "invalid_operation", "vm_changed", "resources_out_of_bounds", "storage_pending", "vm_running"} { | |
| 382 | 新增: if err.Error() == code { | |
| 383 | 新增: response.Error = code | |
| 384 | 新增: } | |
| 385 | 新增: } | |
| 386 | 新增: if operation.Err() != nil { | |
| 387 | 新增: response.Error = "cancelled" | |
| 388 | 新增: } | |
| 389 | 新增: } else { | |
| 390 | 新增: response.Result, err = json.Marshal(result) | |
| 391 | 新增: response.OK = err == nil | |
| 392 | 新增: if err != nil { | |
| 393 | 新增: response.Error = "operation_failed" | |
| 394 | 新增: } | |
| 395 | 新增: } | |
| 396 | 新增: write() | |
| 397 | 新增: conn.Close() | |
| 398 | 新增: <-disconnected | |
| 399 | 新增:} | |
| 400 | 新增: | |
| 401 | 新增:func ServeWindowsHostManager(parent context.Context, path string) error { | |
| 402 | 新增: return serveWindowsHostManager(parent, path, nil) | |
| 403 | 新增:} | |
| 404 | 新增: | |
| 405 | 新增:func serveWindowsHostManager(parent context.Context, path string, ready chan<- struct{}) error { | |
| 406 | 新增: ctx, cancel := context.WithCancel(parent) | |
| 407 | 新增: defer cancel() | |
| 408 | 新增: user, err := windows.GetCurrentProcessToken().GetTokenUser() | |
| 409 | 新增: if err != nil || !user.User.Sid.IsWellKnown(windows.WinLocalSystemSid) { | |
| 410 | 新增: return errors.New("service_requires_system") | |
| 411 | 新增: } | |
| 412 | 新增: binding, err := LoadWindowsHostManagerBinding(path) | |
| 413 | 新增: if err != nil { | |
| 414 | 新增: return err | |
| 415 | 新增: } | |
| 416 | 新增: exe, err := os.Executable() | |
| 417 | 新增: if err != nil || !strings.EqualFold(exe, WindowsHostManagerExecutablePath(binding.VMID)) { | |
| 418 | 新增: return errors.New("binding_invalid") | |
| 419 | 新增: } | |
| 420 | 新增: if err = managerProtected(exe, binding.HostSID); err != nil { | |
| 421 | 新增: return err | |
| 422 | 新增: } | |
| 423 | 新增: if err = managerProtected(filepath.Dir(exe), binding.HostSID); err != nil { | |
| 424 | 新增: return err | |
| 425 | 新增: } | |
| 426 | 新增: if err = managerSharedProtected(filepath.Dir(filepath.Dir(exe)), binding.HostSID); err != nil { | |
| 427 | 新增: return err | |
| 428 | 新增: } | |
| 429 | 新增: server := windowsHostManagerServer{binding: binding} | |
| 430 | 新增: listener, err := winio.ListenPipe(`\\.\pipe\Cage.HyperV.`+binding.VMID.String(), &winio.PipeConfig{SecurityDescriptor: "O:SYG:SYD:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12019b;;;" + binding.HostSID + ")", InputBufferSize: windowsHostManagerWireLimit, OutputBufferSize: windowsHostManagerWireLimit}) | |
| 431 | 新增: if err != nil { | |
| 432 | 新增: return errors.New("service_pipe_unavailable") | |
| 433 | 新增: } | |
| 434 | 新增: defer listener.Close() | |
| 435 | 新增: if ready != nil { | |
| 436 | 新增: close(ready) | |
| 437 | 新增: } | |
| 438 | 新增: var active sync.WaitGroup | |
| 439 | 新增: var connections sync.Map | |
| 440 | 新增: go func() { | |
| 441 | 新增: <-ctx.Done() | |
| 442 | 新增: listener.Close() | |
| 443 | 新增: connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true }) | |
| 444 | 新增: }() | |
| 445 | 新增: slots := make(chan struct{}, 16) | |
| 446 | 新增: defer func() { | |
| 447 | 新增: cancel() | |
| 448 | 新增: listener.Close() | |
| 449 | 新增: connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true }) | |
| 450 | 新增: active.Wait() | |
| 451 | 新增: }() | |
| 452 | 新增: for { | |
| 453 | 新增: conn, err := listener.Accept() | |
| 454 | 新增: if err != nil { | |
| 455 | 新增: if ctx.Err() != nil { | |
| 456 | 新增: return nil | |
| 457 | 新增: } | |
| 458 | 新增: return errors.New("service_pipe_unavailable") | |
| 459 | 新增: } | |
| 460 | 新增: select { | |
| 461 | 新增: case slots <- struct{}{}: | |
| 462 | 新增: default: | |
| 463 | 新增: conn.Close() | |
| 464 | 新增: continue | |
| 465 | 新增: } | |
| 466 | 新增: connections.Store(conn, struct{}{}) | |
| 467 | 新增: active.Add(1) | |
| 468 | 新增: go func() { | |
| 469 | 新增: defer active.Done() | |
| 470 | 新增: defer func() { <-slots; connections.Delete(conn) }() | |
| 471 | 新增: server.connection(ctx, conn) | |
| 472 | 新增: }() | |
| 473 | 新增: } | |
| 474 | 新增:} | |
| @@ -0,0 +1,60 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "golang.org/x/sys/windows/svc" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:type windowsHostManagerHandler struct{ bindingPath string } | |
| 12 | 新增: | |
| 13 | 新增:func (handler windowsHostManagerHandler) Execute(_ []string, requests <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) { | |
| 14 | 新增: status <- svc.Status{State: svc.StartPending, WaitHint: 30000} | |
| 15 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 16 | 新增: defer cancel() | |
| 17 | 新增: done := make(chan error, 1) | |
| 18 | 新增: ready := make(chan struct{}) | |
| 19 | 新增: go func() { done <- serveWindowsHostManager(ctx, handler.bindingPath, ready) }() | |
| 20 | 新增: select { | |
| 21 | 新增: case <-ready: | |
| 22 | 新增: case <-done: | |
| 23 | 新增: return true, 1 | |
| 24 | 新增: } | |
| 25 | 新增: status <- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown} | |
| 26 | 新增: for { | |
| 27 | 新增: select { | |
| 28 | 新增: case err := <-done: | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: return true, 1 | |
| 31 | 新增: } | |
| 32 | 新增: return false, 0 | |
| 33 | 新增: case request := <-requests: | |
| 34 | 新增: switch request.Cmd { | |
| 35 | 新增: case svc.Interrogate: | |
| 36 | 新增: status <- request.CurrentStatus | |
| 37 | 新增: case svc.Stop, svc.Shutdown: | |
| 38 | 新增: status <- svc.Status{State: svc.StopPending} | |
| 39 | 新增: cancel() | |
| 40 | 新增: err := <-done | |
| 41 | 新增: if err != nil { | |
| 42 | 新增: return true, 1 | |
| 43 | 新增: } | |
| 44 | 新增: return false, 0 | |
| 45 | 新增: } | |
| 46 | 新增: } | |
| 47 | 新增: } | |
| 48 | 新增:} | |
| 49 | 新增: | |
| 50 | 新增:func RunWindowsHostManagerService(path string) error { | |
| 51 | 新增: service, err := svc.IsWindowsService() | |
| 52 | 新增: if err != nil || !service { | |
| 53 | 新增: return errors.New("manager_requires_scm") | |
| 54 | 新增: } | |
| 55 | 新增: binding, err := LoadWindowsHostManagerBinding(path) | |
| 56 | 新增: if err != nil { | |
| 57 | 新增: return err | |
| 58 | 新增: } | |
| 59 | 新增: return svc.Run(WindowsHostManagerServiceName(binding.VMID), windowsHostManagerHandler{bindingPath: path}) | |
| 60 | 新增:} | |
| @@ -0,0 +1,117 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "strings" | |
| 7 | 新增: | |
| 8 | 新增: "github.com/google/uuid" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:const windowsHostManagerVersion = 1 | |
| 12 | 新增:const windowsHostManagerWireLimit = 64 << 10 | |
| 13 | 新增: | |
| 14 | 新增:type windowsHostManagerRequest struct { | |
| 15 | 新增: Version int `json:"version"` | |
| 16 | 新增: VMID uuid.UUID `json:"vm_id"` | |
| 17 | 新增: Operation string `json:"operation"` | |
| 18 | 新增: MemoryGiB int `json:"memory_gib,omitempty"` | |
| 19 | 新增: CPUs int `json:"cpus,omitempty"` | |
| 20 | 新增: Storage *windowsHostStorageRequest `json:"storage,omitempty"` | |
| 21 | 新增:} | |
| 22 | 新增: | |
| 23 | 新增:type windowsStorageDisk struct { | |
| 24 | 新增: Path string `json:"path"` | |
| 25 | 新增: Volume uint32 `json:"volume"` | |
| 26 | 新增: FileID uint64 `json:"file_id"` | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:type windowsVMStorageLayout struct { | |
| 30 | 新增: Configuration string `json:"configuration"` | |
| 31 | 新增: Snapshots string `json:"snapshots"` | |
| 32 | 新增: Paging string `json:"paging"` | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:type windowsHostStorageRequest struct { | |
| 36 | 新增: Action string `json:"action"` | |
| 37 | 新增: ID string `json:"id,omitempty"` | |
| 38 | 新增: SourceVolume uint32 `json:"source_volume,omitempty"` | |
| 39 | 新增: SourceFileID uint64 `json:"source_file_id,omitempty"` | |
| 40 | 新增: Disk string `json:"disk,omitempty"` | |
| 41 | 新增: Directory string `json:"directory,omitempty"` | |
| 42 | 新增:} | |
| 43 | 新增: | |
| 44 | 新增:type windowsHostStorageState struct { | |
| 45 | 新增: Disk windowsStorageDisk `json:"disk"` | |
| 46 | 新增: Layout *windowsVMStorageLayout `json:"layout,omitempty"` | |
| 47 | 新增: Pending string `json:"pending,omitempty"` | |
| 48 | 新增: Outcome string `json:"outcome,omitempty"` | |
| 49 | 新增:} | |
| 50 | 新增: | |
| 51 | 新增:func validWindowsStorageID(id string) bool { | |
| 52 | 新增: return len(id) == 32 && strings.Trim(id, "0123456789abcdef") == "" | |
| 53 | 新增:} | |
| 54 | 新增: | |
| 55 | 新增:func (r windowsHostStorageRequest) validate() error { | |
| 56 | 新增: if r.Action == "status" { | |
| 57 | 新增: if r.ID == "" && r.SourceVolume == 0 && r.SourceFileID == 0 && r.Disk == "" && r.Directory == "" { | |
| 58 | 新增: return nil | |
| 59 | 新增: } | |
| 60 | 新增: return errors.New("invalid_request") | |
| 61 | 新增: } | |
| 62 | 新增: if !validWindowsStorageID(r.ID) || r.SourceVolume == 0 || r.SourceFileID == 0 { | |
| 63 | 新增: return errors.New("invalid_request") | |
| 64 | 新增: } | |
| 65 | 新增: switch r.Action { | |
| 66 | 新增: case "begin", "commit", "rollback": | |
| 67 | 新增: if r.Disk != "" || r.Directory != "" { | |
| 68 | 新增: return errors.New("invalid_request") | |
| 69 | 新增: } | |
| 70 | 新增: case "attach": | |
| 71 | 新增: if r.Disk == "" || r.Directory == "" || len(r.Disk) > 32700 || len(r.Directory) > 32700 || strings.ContainsAny(r.Disk+r.Directory, "\x00\r\n") { | |
| 72 | 新增: return errors.New("invalid_request") | |
| 73 | 新增: } | |
| 74 | 新增: default: | |
| 75 | 新增: return errors.New("invalid_request") | |
| 76 | 新增: } | |
| 77 | 新增: return nil | |
| 78 | 新增:} | |
| 79 | 新增: | |
| 80 | 新增:type windowsHostManagerResponse struct { | |
| 81 | 新增: Version int `json:"version"` | |
| 82 | 新增: VMID uuid.UUID `json:"vm_id"` | |
| 83 | 新增: OK bool `json:"ok"` | |
| 84 | 新增: Result json.RawMessage `json:"result,omitempty"` | |
| 85 | 新增: Error string `json:"error,omitempty"` | |
| 86 | 新增:} | |
| 87 | 新增: | |
| 88 | 新增:func (r windowsHostManagerRequest) validate() error { | |
| 89 | 新增: if r.Version != windowsHostManagerVersion || r.VMID == uuid.Nil { | |
| 90 | 新增: return errors.New("invalid_request") | |
| 91 | 新增: } | |
| 92 | 新增: if r.Operation == "storage" { | |
| 93 | 新增: if r.Storage == nil || r.MemoryGiB != 0 || r.CPUs != 0 { | |
| 94 | 新增: return errors.New("invalid_request") | |
| 95 | 新增: } | |
| 96 | 新增: return r.Storage.validate() | |
| 97 | 新增: } | |
| 98 | 新增: if r.Storage != nil { | |
| 99 | 新增: return errors.New("invalid_request") | |
| 100 | 新增: } | |
| 101 | 新增: switch r.Operation { | |
| 102 | 新增: case "inspect", "start", "shutdown": | |
| 103 | 新增: if r.MemoryGiB != 0 || r.CPUs != 0 { | |
| 104 | 新增: return errors.New("invalid_request") | |
| 105 | 新增: } | |
| 106 | 新增: case "resources": | |
| 107 | 新增: if r.MemoryGiB == 0 && r.CPUs == 0 { | |
| 108 | 新增: return nil | |
| 109 | 新增: } | |
| 110 | 新增: if r.MemoryGiB < 4 || r.MemoryGiB > 1024 || r.CPUs < 2 || r.CPUs > 1024 { | |
| 111 | 新增: return errors.New("invalid_request") | |
| 112 | 新增: } | |
| 113 | 新增: default: | |
| 114 | 新增: return errors.New("invalid_operation") | |
| 115 | 新增: } | |
| 116 | 新增: return nil | |
| 117 | 新增:} | |
| @@ -0,0 +1,22 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "testing" | |
| 5 | 新增: | |
| 6 | 新增: "github.com/google/uuid" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestWindowsHostManagerRequiresTwoCPUs(t *testing.T) { | |
| 10 | 新增: request := windowsHostManagerRequest{Version: 1, VMID: uuid.New(), Operation: "resources", MemoryGiB: 4, CPUs: 1} | |
| 11 | 新增: if request.validate() == nil { | |
| 12 | 新增: t.Fatal("privileged Windows resource request accepted one CPU below the supported guest minimum") | |
| 13 | 新增: } | |
| 14 | 新增: request.CPUs = 2 | |
| 15 | 新增: if err := request.validate(); err != nil { | |
| 16 | 新增: t.Fatal("supported Windows CPU minimum rejected", err) | |
| 17 | 新增: } | |
| 18 | 新增: request.MemoryGiB, request.CPUs = 0, 0 | |
| 19 | 新增: if err := request.validate(); err != nil { | |
| 20 | 新增: t.Fatal("read-only resource request rejected", err) | |
| 21 | 新增: } | |
| 22 | 新增:} | |
| @@ -0,0 +1,579 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bytes" | |
| 7 | 新增: "context" | |
| 8 | 新增: _ "embed" | |
| 9 | 新增: "encoding/base64" | |
| 10 | 新增: "encoding/json" | |
| 11 | 新增: "errors" | |
| 12 | 新增: "io" | |
| 13 | 新增: "net" | |
| 14 | 新增: "os" | |
| 15 | 新增: "path/filepath" | |
| 16 | 新增: "runtime" | |
| 17 | 新增: "strings" | |
| 18 | 新增: | |
| 19 | 新增: "github.com/google/uuid" | |
| 20 | 新增: "golang.org/x/sys/windows" | |
| 21 | 新增: | |
| 22 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 23 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 24 | 新增:) | |
| 25 | 新增: | |
| 26 | 新增://go:embed windows_storage.ps1 | |
| 27 | 新增:var windowsStorageScript string | |
| 28 | 新增: | |
| 29 | 新增:type windowsHostStorageJournal struct { | |
| 30 | 新增: ID string `json:"id"` | |
| 31 | 新增: Phase string `json:"phase"` | |
| 32 | 新增: Before WindowsHostManagerBinding `json:"before"` | |
| 33 | 新增: OldDisk string `json:"old_disk"` | |
| 34 | 新增: OldLayout windowsVMStorageLayout `json:"old_layout"` | |
| 35 | 新增: After *WindowsHostManagerBinding `json:"after,omitempty"` | |
| 36 | 新增: NewLayout *windowsVMStorageLayout `json:"new_layout,omitempty"` | |
| 37 | 新增: Directory windowsStorageDisk `json:"directory"` | |
| 38 | 新增: Backup string `json:"backup"` | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:func (server *windowsHostManagerServer) storageJournalPath() string { | |
| 42 | 新增: return filepath.Join(filepath.Dir(WindowsHostManagerBindingPath(server.binding.VMID)), "storage.json") | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:func (server *windowsHostManagerServer) loadStorageJournal() (*windowsHostStorageJournal, error) { | |
| 46 | 新增: path := server.storageJournalPath() | |
| 47 | 新增: file, err := os.Open(path) | |
| 48 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 49 | 新增: return nil, nil | |
| 50 | 新增: } | |
| 51 | 新增: if err != nil { | |
| 52 | 新增: return nil, errors.New("binding_invalid") | |
| 53 | 新增: } | |
| 54 | 新增: defer file.Close() | |
| 55 | 新增: if err = managerProtected(path, server.binding.HostSID); err != nil { | |
| 56 | 新增: return nil, err | |
| 57 | 新增: } | |
| 58 | 新增: var journal windowsHostStorageJournal | |
| 59 | 新增: decoder := json.NewDecoder(io.LimitReader(file, windowsHostManagerWireLimit+1)) | |
| 60 | 新增: decoder.DisallowUnknownFields() | |
| 61 | 新增: if decoder.Decode(&journal) != nil || decoder.Decode(new(any)) != io.EOF || !validWindowsStorageID(journal.ID) || | |
| 62 | 新增: journal.Before.VMID != server.binding.VMID || journal.Before.HostSID != server.binding.HostSID || | |
| 63 | 新增: journal.Phase != "pending" && journal.Phase != "commit" && journal.Phase != "rollback" || | |
| 64 | 新增: (journal.After == nil) != (journal.NewLayout == nil) { | |
| 65 | 新增: return nil, errors.New("binding_invalid") | |
| 66 | 新增: } | |
| 67 | 新增: return &journal, nil | |
| 68 | 新增:} | |
| 69 | 新增: | |
| 70 | 新增:func managerProtectStoragePath(path, sid string) error { | |
| 71 | 新增: info, err := os.Lstat(path) | |
| 72 | 新增: if err != nil || info.Mode()&os.ModeSymlink != 0 { | |
| 73 | 新增: return errors.New("binding_invalid") | |
| 74 | 新增: } | |
| 75 | 新增: inherit := "" | |
| 76 | 新增: if info.IsDir() { | |
| 77 | 新增: inherit = "OICI" | |
| 78 | 新增: } | |
| 79 | 新增: sd, err := windows.SecurityDescriptorFromString("O:SYG:SYD:P(A;" + inherit + ";FA;;;SY)(A;" + inherit + ";FA;;;BA)(A;" + inherit + ";FRFX;;;" + sid + ")") | |
| 80 | 新增: if err != nil { | |
| 81 | 新增: return err | |
| 82 | 新增: } | |
| 83 | 新增: owner, _, err := sd.Owner() | |
| 84 | 新增: if err != nil { | |
| 85 | 新增: return err | |
| 86 | 新增: } | |
| 87 | 新增: acl, _, err := sd.DACL() | |
| 88 | 新增: if err != nil { | |
| 89 | 新增: return err | |
| 90 | 新增: } | |
| 91 | 新增: return windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, owner, nil, acl, nil) | |
| 92 | 新增:} | |
| 93 | 新增: | |
| 94 | 新增:func managerWriteStorageJSON(path, sid string, value any) error { | |
| 95 | 新增: data, err := json.Marshal(value) | |
| 96 | 新增: if err != nil { | |
| 97 | 新增: return err | |
| 98 | 新增: } | |
| 99 | 新增: file, err := os.CreateTemp(filepath.Dir(path), ".storage-*") | |
| 100 | 新增: if err != nil { | |
| 101 | 新增: return err | |
| 102 | 新增: } | |
| 103 | 新增: defer os.Remove(file.Name()) | |
| 104 | 新增: if err = managerProtectStoragePath(file.Name(), sid); err != nil { | |
| 105 | 新增: file.Close() | |
| 106 | 新增: return err | |
| 107 | 新增: } | |
| 108 | 新增: _, err = file.Write(data) | |
| 109 | 新增: if err == nil { | |
| 110 | 新增: err = file.Sync() | |
| 111 | 新增: } | |
| 112 | 新增: if err = errors.Join(err, file.Close()); err != nil { | |
| 113 | 新增: return err | |
| 114 | 新增: } | |
| 115 | 新增: from, _ := windows.UTF16PtrFromString(file.Name()) | |
| 116 | 新增: to, err := windows.UTF16PtrFromString(path) | |
| 117 | 新增: if err != nil { | |
| 118 | 新增: return err | |
| 119 | 新增: } | |
| 120 | 新增: return windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH) | |
| 121 | 新增:} | |
| 122 | 新增: | |
| 123 | 新增:func managerStorageCommand(ctx context.Context, id uuid.UUID, action string, input map[string]any, result any) error { | |
| 124 | 新增: if input == nil { | |
| 125 | 新增: input = make(map[string]any) | |
| 126 | 新增: } | |
| 127 | 新增: input["vm_id"], input["action"] = id.String(), action | |
| 128 | 新增: data, err := json.Marshal(input) | |
| 129 | 新增: if err != nil { | |
| 130 | 新增: return err | |
| 131 | 新增: } | |
| 132 | 新增: script := "$inputData = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('" + base64.StdEncoding.EncodeToString(data) + "')) | ConvertFrom-Json\n" + windowsStorageScript | |
| 133 | 新增: command, err := systemPowerShellQuery(ctx, script) | |
| 134 | 新增: if err != nil { | |
| 135 | 新增: return err | |
| 136 | 新增: } | |
| 137 | 新增: output, err := command.Output() | |
| 138 | 新增: if ctx.Err() != nil { | |
| 139 | 新增: return ctx.Err() | |
| 140 | 新增: } | |
| 141 | 新增: if err != nil || len(output) > windowsHostManagerWireLimit || json.Unmarshal(output, result) != nil { | |
| 142 | 新增: return errors.New("storage_operation_failed") | |
| 143 | 新增: } | |
| 144 | 新增: return nil | |
| 145 | 新增:} | |
| 146 | 新增: | |
| 147 | 新增:func (server *windowsHostManagerServer) storageState(journal *windowsHostStorageJournal, outcome string) windowsHostStorageState { | |
| 148 | 新增: state := windowsHostStorageState{Disk: windowsStorageDisk{Path: server.binding.DiskPath, Volume: server.binding.DiskVolume, FileID: server.binding.DiskFileID}, Outcome: outcome} | |
| 149 | 新增: if journal != nil && journal.Phase == "pending" { | |
| 150 | 新增: state.Pending = journal.ID | |
| 151 | 新增: } | |
| 152 | 新增: return state | |
| 153 | 新增:} | |
| 154 | 新增: | |
| 155 | 新增:func managerRequireStopped(ctx context.Context, binding WindowsHostManagerBinding) error { | |
| 156 | 新增: state, err := managerValidateVM(ctx, binding) | |
| 157 | 新增: if err != nil { | |
| 158 | 新增: return err | |
| 159 | 新增: } | |
| 160 | 新增: if state.VM.State != "Off" { | |
| 161 | 新增: return errors.New("vm_running") | |
| 162 | 新增: } | |
| 163 | 新增: return nil | |
| 164 | 新增:} | |
| 165 | 新增: | |
| 166 | 新增:func (server *windowsHostManagerServer) storageRequest(ctx context.Context, input windowsHostStorageRequest, journal *windowsHostStorageJournal, conn net.Conn) (any, error) { | |
| 167 | 新增: if input.Action == "status" { | |
| 168 | 新增: state := server.storageState(journal, "") | |
| 169 | 新增: if journal == nil || journal.Phase != "pending" { | |
| 170 | 新增: if err := managerRequireStopped(ctx, server.binding); err != nil { | |
| 171 | 新增: return nil, err | |
| 172 | 新增: } | |
| 173 | 新增: var layout windowsVMStorageLayout | |
| 174 | 新增: if err := managerStorageCommand(ctx, server.binding.VMID, "inspect", nil, &layout); err != nil { | |
| 175 | 新增: return nil, err | |
| 176 | 新增: } | |
| 177 | 新增: state.Layout = &layout | |
| 178 | 新增: } | |
| 179 | 新增: return state, nil | |
| 180 | 新增: } | |
| 181 | 新增: if journal != nil && journal.Phase == "pending" && journal.ID != input.ID { | |
| 182 | 新增: return nil, errors.New("storage_pending") | |
| 183 | 新增: } | |
| 184 | 新增: if journal == nil || journal.Phase != "pending" { | |
| 185 | 新增: if journal != nil && journal.ID == input.ID && journal.Phase == input.Action { | |
| 186 | 新增: if _, err := managerValidateVM(ctx, server.binding); err != nil { | |
| 187 | 新增: return nil, err | |
| 188 | 新增: } | |
| 189 | 新增: return server.storageState(journal, input.Action), nil | |
| 190 | 新增: } | |
| 191 | 新增: if server.binding.DiskVolume != input.SourceVolume || server.binding.DiskFileID != input.SourceFileID { | |
| 192 | 新增: return nil, errors.New("vm_changed") | |
| 193 | 新增: } | |
| 194 | 新增: if input.Action == "rollback" { | |
| 195 | 新增: if _, err := managerValidateVM(ctx, server.binding); err != nil { | |
| 196 | 新增: return nil, err | |
| 197 | 新增: } | |
| 198 | 新增: return server.storageState(nil, "rollback"), nil | |
| 199 | 新增: } | |
| 200 | 新增: if input.Action != "begin" { | |
| 201 | 新增: return nil, errors.New("invalid_request") | |
| 202 | 新增: } | |
| 203 | 新增: if err := managerRequireStopped(ctx, server.binding); err != nil { | |
| 204 | 新增: return nil, err | |
| 205 | 新增: } | |
| 206 | 新增: oldDisk, err := managerVMDisk(ctx, server.binding.VMID) | |
| 207 | 新增: if err != nil { | |
| 208 | 新增: return nil, err | |
| 209 | 新增: } | |
| 210 | 新增: var layout windowsVMStorageLayout | |
| 211 | 新增: if err = managerStorageCommand(ctx, server.binding.VMID, "inspect", nil, &layout); err != nil { | |
| 212 | 新增: return nil, err | |
| 213 | 新增: } | |
| 214 | 新增: backup := filepath.Join(filepath.Dir(server.storageJournalPath()), "storage-backup-"+input.ID) | |
| 215 | 新增: journal = &windowsHostStorageJournal{ID: input.ID, Phase: "pending", Before: server.binding, OldDisk: oldDisk, OldLayout: layout, Backup: backup} | |
| 216 | 新增: if err = managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal); err != nil { | |
| 217 | 新增: return nil, err | |
| 218 | 新增: } | |
| 219 | 新增: } | |
| 220 | 新增: if journal.Before.DiskVolume != input.SourceVolume || journal.Before.DiskFileID != input.SourceFileID { | |
| 221 | 新增: return nil, errors.New("vm_changed") | |
| 222 | 新增: } | |
| 223 | 新增: switch input.Action { | |
| 224 | 新增: case "begin": | |
| 225 | 新增: if err := server.ensureStorageBackup(ctx, journal); err != nil { | |
| 226 | 新增: return nil, err | |
| 227 | 新增: } | |
| 228 | 新增: case "attach": | |
| 229 | 新增: if err := server.attachStorage(ctx, journal, input, conn); err != nil { | |
| 230 | 新增: return nil, err | |
| 231 | 新增: } | |
| 232 | 新增: case "commit", "rollback": | |
| 233 | 新增: if err := server.finishStorage(ctx, journal, input.Action); err != nil { | |
| 234 | 新增: return nil, err | |
| 235 | 新增: } | |
| 236 | 新增: } | |
| 237 | 新增: return server.storageState(journal, input.Action), nil | |
| 238 | 新增:} | |
| 239 | 新增: | |
| 240 | 新增:func (server *windowsHostManagerServer) ensureStorageBackup(ctx context.Context, journal *windowsHostStorageJournal) error { | |
| 241 | 新增: complete := filepath.Join(journal.Backup, "cage-export-complete.json") | |
| 242 | 新增: if data, err := os.ReadFile(complete); err == nil && bytes.Equal(data, []byte(`{"id":"`+journal.ID+`"}`)) { | |
| 243 | 新增: return managerProtected(complete, server.binding.HostSID) | |
| 244 | 新增: } | |
| 245 | 新增: if journal.After != nil { | |
| 246 | 新增: return errors.New("binding_invalid") | |
| 247 | 新增: } | |
| 248 | 新增: if err := managerRequireStopped(ctx, journal.Before); err != nil { | |
| 249 | 新增: return err | |
| 250 | 新增: } | |
| 251 | 新增: // This directory is created only below the protected fixed-VM registration. | |
| 252 | 新增: // Retry a partial metadata export without touching the original VHDX. | |
| 253 | 新增: if err := os.RemoveAll(journal.Backup); err != nil { | |
| 254 | 新增: return err | |
| 255 | 新增: } | |
| 256 | 新增: if err := os.Mkdir(journal.Backup, 0700); err != nil { | |
| 257 | 新增: return err | |
| 258 | 新增: } | |
| 259 | 新增: if err := managerProtectStoragePath(journal.Backup, server.binding.HostSID); err != nil { | |
| 260 | 新增: return err | |
| 261 | 新增: } | |
| 262 | 新增: var result struct { | |
| 263 | 新增: Exported bool `json:"exported"` | |
| 264 | 新增: } | |
| 265 | 新增: if err := managerStorageCommand(ctx, server.binding.VMID, "export", map[string]any{"backup": journal.Backup}, &result); err != nil || !result.Exported { | |
| 266 | 新增: return errors.Join(err, errors.New("storage_export_failed")) | |
| 267 | 新增: } | |
| 268 | 新增: return managerWriteStorageJSON(complete, server.binding.HostSID, map[string]string{"id": journal.ID}) | |
| 269 | 新增:} | |
| 270 | 新增: | |
| 271 | 新增:// Open the requested object while impersonating the authenticated pipe caller. | |
| 272 | 新增:// The resulting handle proves the caller can read, write and manage its ACL. | |
| 273 | 新增:// No privileged open is used as a fallback for a denied destination. | |
| 274 | 新增:func managerOpenStorageDestination(conn net.Conn, path, hostSID string, directory bool) (windows.Handle, windowsStorageDisk, error) { | |
| 275 | 新增: var value windowsStorageDisk | |
| 276 | 新增: if !filepath.IsAbs(path) || strings.HasPrefix(path, `\\`) || (!directory && !strings.EqualFold(filepath.Ext(path), ".vhdx")) { | |
| 277 | 新增: return 0, value, errors.New("invalid_request") | |
| 278 | 新增: } | |
| 279 | 新增: file, ok := conn.(interface{ Fd() uintptr }) | |
| 280 | 新增: if !ok { | |
| 281 | 新增: return 0, value, errors.New("unauthorized") | |
| 282 | 新增: } | |
| 283 | 新增: name, err := windows.UTF16PtrFromString(path) | |
| 284 | 新增: if err != nil { | |
| 285 | 新增: return 0, value, err | |
| 286 | 新增: } | |
| 287 | 新增: runtime.LockOSThread() | |
| 288 | 新增: defer runtime.UnlockOSThread() | |
| 289 | 新增: impersonate := windows.NewLazySystemDLL("advapi32.dll").NewProc("ImpersonateNamedPipeClient") | |
| 290 | 新增: okValue, _, callErr := impersonate.Call(file.Fd()) | |
| 291 | 新增: if okValue == 0 { | |
| 292 | 新增: return 0, value, callErr | |
| 293 | 新增: } | |
| 294 | 新增: flags := uint32(windows.FILE_FLAG_OPEN_REPARSE_POINT) | |
| 295 | 新增: if directory { | |
| 296 | 新增: flags |= windows.FILE_FLAG_BACKUP_SEMANTICS | |
| 297 | 新增: } | |
| 298 | 新增: var token windows.Token | |
| 299 | 新增: identityErr := windows.OpenThreadToken(windows.CurrentThread(), windows.TOKEN_QUERY, true, &token) | |
| 300 | 新增: if identityErr == nil { | |
| 301 | 新增: user, err := token.GetTokenUser() | |
| 302 | 新增: token.Close() | |
| 303 | 新增: if err != nil || user.User.Sid.String() != hostSID { | |
| 304 | 新增: identityErr = errors.New("unauthorized") | |
| 305 | 新增: } | |
| 306 | 新增: } | |
| 307 | 新增: var handle windows.Handle | |
| 308 | 新增: openErr := identityErr | |
| 309 | 新增: if identityErr == nil { | |
| 310 | 新增: handle, openErr = windows.CreateFile(name, windows.GENERIC_READ|windows.GENERIC_WRITE|windows.WRITE_DAC|windows.WRITE_OWNER, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, flags, 0) | |
| 311 | 新增: } | |
| 312 | 新增: if revertErr := windows.RevertToSelf(); revertErr != nil { | |
| 313 | 新增: if openErr == nil { | |
| 314 | 新增: windows.CloseHandle(handle) | |
| 315 | 新增: } | |
| 316 | 新增: // Continuing this OS thread with a client's token is unsafe. | |
| 317 | 新增: panic("Windows storage impersonation could not be reverted") | |
| 318 | 新增: } | |
| 319 | 新增: if openErr != nil { | |
| 320 | 新增: return 0, value, errors.New("destination_access_denied") | |
| 321 | 新增: } | |
| 322 | 新增: value, err = managerStorageObject(handle, directory) | |
| 323 | 新增: if err != nil { | |
| 324 | 新增: windows.CloseHandle(handle) | |
| 325 | 新增: return 0, value, err | |
| 326 | 新增: } | |
| 327 | 新增: return handle, value, nil | |
| 328 | 新增:} | |
| 329 | 新增: | |
| 330 | 新增:// Pin each canonical directory until the privileged operation finishes. A | |
| 331 | 新增:// caller may rename a parent between requests, but cannot retarget this request | |
| 332 | 新增:// through a replaced directory or an NTFS junction after its access check. | |
| 333 | 新增:func managerPinStorageParents(path string) (func(), error) { | |
| 334 | 新增: var handles []windows.Handle | |
| 335 | 新增: closeAll := func() { | |
| 336 | 新增: for _, handle := range handles { | |
| 337 | 新增: windows.CloseHandle(handle) | |
| 338 | 新增: } | |
| 339 | 新增: } | |
| 340 | 新增: var parents []string | |
| 341 | 新增: for parent := filepath.Dir(path); ; parent = filepath.Dir(parent) { | |
| 342 | 新增: parents = append(parents, parent) | |
| 343 | 新增: if parent == filepath.Dir(parent) { | |
| 344 | 新增: break | |
| 345 | 新增: } | |
| 346 | 新增: } | |
| 347 | 新增: for index := len(parents) - 1; index >= 0; index-- { | |
| 348 | 新增: parent := parents[index] | |
| 349 | 新增: name, err := windows.UTF16PtrFromString(parent) | |
| 350 | 新增: if err != nil { | |
| 351 | 新增: closeAll() | |
| 352 | 新增: return nil, err | |
| 353 | 新增: } | |
| 354 | 新增: handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0) | |
| 355 | 新增: if err != nil { | |
| 356 | 新增: closeAll() | |
| 357 | 新增: return nil, err | |
| 358 | 新增: } | |
| 359 | 新增: handles = append(handles, handle) | |
| 360 | 新增: actual, err := managerStorageObject(handle, true) | |
| 361 | 新增: if err != nil || !strings.EqualFold(filepath.Clean(actual.Path), filepath.Clean(parent)) { | |
| 362 | 新增: closeAll() | |
| 363 | 新增: return nil, errors.New("vm_changed") | |
| 364 | 新增: } | |
| 365 | 新增: } | |
| 366 | 新增: return closeAll, nil | |
| 367 | 新增:} | |
| 368 | 新增: | |
| 369 | 新增:func managerProtectVMMetadata(handle windows.Handle, sid string, release bool) error { | |
| 370 | 新增: owner, access := "SY", "FRFX" | |
| 371 | 新增: if release { | |
| 372 | 新增: owner, access = sid, "FA" | |
| 373 | 新增: } | |
| 374 | 新增: sd, err := windows.SecurityDescriptorFromString("O:" + owner + "G:SYD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;" + access + ";;;" + sid + ")") | |
| 375 | 新增: if err != nil { | |
| 376 | 新增: return err | |
| 377 | 新增: } | |
| 378 | 新增: ownerSID, _, err := sd.Owner() | |
| 379 | 新增: if err != nil { | |
| 380 | 新增: return err | |
| 381 | 新增: } | |
| 382 | 新增: acl, _, err := sd.DACL() | |
| 383 | 新增: if err != nil { | |
| 384 | 新增: return err | |
| 385 | 新增: } | |
| 386 | 新增: return windows.SetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, ownerSID, nil, acl, nil) | |
| 387 | 新增:} | |
| 388 | 新增: | |
| 389 | 新增:func managerStorageObject(handle windows.Handle, directory bool) (windowsStorageDisk, error) { | |
| 390 | 新增: var value windowsStorageDisk | |
| 391 | 新增: var info windows.ByHandleFileInformation | |
| 392 | 新增: if windows.GetFileInformationByHandle(handle, &info) != nil || info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 || (info.FileAttributes&windows.FILE_ATTRIBUTE_DIRECTORY != 0) != directory { | |
| 393 | 新增: return value, errors.New("vm_changed") | |
| 394 | 新增: } | |
| 395 | 新增: name := make([]uint16, 32768) | |
| 396 | 新增: size, err := windows.GetFinalPathNameByHandle(handle, &name[0], uint32(len(name)), 0) | |
| 397 | 新增: if err != nil || size == 0 || size >= uint32(len(name)) { | |
| 398 | 新增: return value, errors.New("vm_changed") | |
| 399 | 新增: } | |
| 400 | 新增: path := strings.TrimPrefix(windows.UTF16ToString(name[:size]), `\\?\`) | |
| 401 | 新增: if len(filepath.VolumeName(path)) != 2 || strings.HasPrefix(path, `\\`) { | |
| 402 | 新增: return value, errors.New("vm_changed") | |
| 403 | 新增: } | |
| 404 | 新增: return windowsStorageDisk{Path: path, Volume: info.VolumeSerialNumber, FileID: uint64(info.FileIndexHigh)<<32 | uint64(info.FileIndexLow)}, nil | |
| 405 | 新增:} | |
| 406 | 新增: | |
| 407 | 新增:func managerGrantVMDisk(handle windows.Handle, id uuid.UUID) error { | |
| 408 | 新增: sid, _, _, err := windows.LookupSID("", `NT VIRTUAL MACHINE\`+id.String()) | |
| 409 | 新增: if err != nil { | |
| 410 | 新增: return err | |
| 411 | 新增: } | |
| 412 | 新增: sd, err := windows.GetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION) | |
| 413 | 新增: if err != nil { | |
| 414 | 新增: return err | |
| 415 | 新增: } | |
| 416 | 新增: acl, _, err := sd.DACL() | |
| 417 | 新增: if err != nil { | |
| 418 | 新增: return err | |
| 419 | 新增: } | |
| 420 | 新增: var pin runtime.Pinner | |
| 421 | 新增: pin.Pin(sid) | |
| 422 | 新增: defer pin.Unpin() | |
| 423 | 新增: // FILE_ALL_ACCESS from the Windows SDK; x/sys/windows does not export it. | |
| 424 | 新增: const fileAllAccess = windows.STANDARD_RIGHTS_REQUIRED | windows.SYNCHRONIZE | 0x1ff | |
| 425 | 新增: merged, err := windows.ACLFromEntries([]windows.EXPLICIT_ACCESS{{AccessPermissions: fileAllAccess, AccessMode: windows.GRANT_ACCESS, Trustee: windows.TRUSTEE{TrusteeForm: windows.TRUSTEE_IS_SID, TrusteeType: windows.TRUSTEE_IS_USER, TrusteeValue: windows.TrusteeValueFromSID(sid)}}}, acl) | |
| 426 | 新增: if err != nil { | |
| 427 | 新增: return err | |
| 428 | 新增: } | |
| 429 | 新增: return windows.SetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION, nil, nil, merged, nil) | |
| 430 | 新增:} | |
| 431 | 新增: | |
| 432 | 新增:func (server *windowsHostManagerServer) attachStorage(ctx context.Context, journal *windowsHostStorageJournal, input windowsHostStorageRequest, conn net.Conn) error { | |
| 433 | 新增: if err := server.ensureStorageBackup(ctx, journal); err != nil { | |
| 434 | 新增: return err | |
| 435 | 新增: } | |
| 436 | 新增: diskHandle, disk, err := managerOpenStorageDestination(conn, input.Disk, server.binding.HostSID, false) | |
| 437 | 新增: if err != nil { | |
| 438 | 新增: return err | |
| 439 | 新增: } | |
| 440 | 新增: defer windows.CloseHandle(diskHandle) | |
| 441 | 新增: diskParents, err := managerPinStorageParents(disk.Path) | |
| 442 | 新增: if err != nil { | |
| 443 | 新增: return err | |
| 444 | 新增: } | |
| 445 | 新增: defer diskParents() | |
| 446 | 新增: dirHandle, directory, err := managerOpenStorageDestination(conn, input.Directory, server.binding.HostSID, true) | |
| 447 | 新增: if err != nil { | |
| 448 | 新增: return err | |
| 449 | 新增: } | |
| 450 | 新增: defer windows.CloseHandle(dirHandle) | |
| 451 | 新增: directoryParents, err := managerPinStorageParents(directory.Path) | |
| 452 | 新增: if err != nil { | |
| 453 | 新增: return err | |
| 454 | 新增: } | |
| 455 | 新增: defer directoryParents() | |
| 456 | 新增: if cage.StoragePathsOverlap(directory.Path, disk.Path) || disk.Volume == journal.Before.DiskVolume && disk.FileID == journal.Before.DiskFileID { | |
| 457 | 新增: return errors.New("invalid_request") | |
| 458 | 新增: } | |
| 459 | 新增: if journal.After == nil { | |
| 460 | 新增: entries, err := os.ReadDir(directory.Path) | |
| 461 | 新增: if err != nil || len(entries) != 0 { | |
| 462 | 新增: return errors.New("destination_not_empty") | |
| 463 | 新增: } | |
| 464 | 新增: after := journal.Before | |
| 465 | 新增: after.DiskPath, after.DiskVolume, after.DiskFileID = disk.Path, disk.Volume, disk.FileID | |
| 466 | 新增: layout := windowsVMStorageLayout{Configuration: filepath.Join(directory.Path, "configuration"), Snapshots: filepath.Join(directory.Path, "snapshots"), Paging: filepath.Join(directory.Path, "paging")} | |
| 467 | 新增: journal.After, journal.NewLayout, journal.Directory = &after, &layout, directory | |
| 468 | 新增: if err = managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal); err != nil { | |
| 469 | 新增: return err | |
| 470 | 新增: } | |
| 471 | 新增: } else if journal.After.DiskPath != disk.Path || journal.After.DiskVolume != disk.Volume || journal.After.DiskFileID != disk.FileID || journal.Directory != directory { | |
| 472 | 新增: return errors.New("vm_changed") | |
| 473 | 新增: } | |
| 474 | 新增: if err = managerGrantVMDisk(diskHandle, server.binding.VMID); err != nil { | |
| 475 | 新增: return err | |
| 476 | 新增: } | |
| 477 | 新增: if err = managerProtectVMMetadata(dirHandle, server.binding.HostSID, false); err != nil { | |
| 478 | 新增: return err | |
| 479 | 新增: } | |
| 480 | 新增: if err = server.applyStorage(ctx, journal, *journal.After, *journal.NewLayout); err != nil { | |
| 481 | 新增: return err | |
| 482 | 新增: } | |
| 483 | 新增: return server.saveStorageBinding(*journal.After) | |
| 484 | 新增:} | |
| 485 | 新增: | |
| 486 | 新增:func (server *windowsHostManagerServer) applyStorage(ctx context.Context, journal *windowsHostStorageJournal, binding WindowsHostManagerBinding, layout windowsVMStorageLayout) error { | |
| 487 | 新增: name, err := windows.UTF16PtrFromString(binding.DiskPath) | |
| 488 | 新增: if err != nil { | |
| 489 | 新增: return err | |
| 490 | 新增: } | |
| 491 | 新增: handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) | |
| 492 | 新增: if err != nil { | |
| 493 | 新增: return err | |
| 494 | 新增: } | |
| 495 | 新增: defer windows.CloseHandle(handle) | |
| 496 | 新增: disk, err := managerStorageObject(handle, false) | |
| 497 | 新增: if err != nil || !strings.EqualFold(disk.Path, binding.DiskPath) || disk.Volume != binding.DiskVolume || disk.FileID != binding.DiskFileID { | |
| 498 | 新增: return errors.New("vm_changed") | |
| 499 | 新增: } | |
| 500 | 新增: parents, err := managerPinStorageParents(binding.DiskPath) | |
| 501 | 新增: if err != nil { | |
| 502 | 新增: return err | |
| 503 | 新增: } | |
| 504 | 新增: defer parents() | |
| 505 | 新增: for _, path := range []string{layout.Configuration, layout.Snapshots, layout.Paging} { | |
| 506 | 新增: real, err := cage.StoragePhysicalPath(path) | |
| 507 | 新增: if err != nil || !filepath.IsAbs(path) || !strings.EqualFold(real, filepath.Clean(path)) { | |
| 508 | 新增: return errors.New("vm_changed") | |
| 509 | 新增: } | |
| 510 | 新增: } | |
| 511 | 新增: var result struct { | |
| 512 | 新增: Applied bool `json:"applied"` | |
| 513 | 新增: } | |
| 514 | 新增: if err = managerStorageCommand(ctx, server.binding.VMID, "apply", map[string]any{"old": journal.OldLayout, "next": journal.NewLayout, "target": layout, "old_disk": journal.OldDisk, "source_disk": journal.Before.DiskPath, "new_disk": journal.After.DiskPath, "disk": binding.DiskPath}, &result); err != nil || !result.Applied { | |
| 515 | 新增: return errors.Join(err, errors.New("storage_operation_failed")) | |
| 516 | 新增: } | |
| 517 | 新增: return managerRequireStopped(ctx, binding) | |
| 518 | 新增:} | |
| 519 | 新增: | |
| 520 | 新增:func (server *windowsHostManagerServer) saveStorageBinding(binding WindowsHostManagerBinding) error { | |
| 521 | 新增: if err := managerWriteStorageJSON(WindowsHostManagerBindingPath(binding.VMID), binding.HostSID, binding); err != nil { | |
| 522 | 新增: return err | |
| 523 | 新增: } | |
| 524 | 新增: server.binding.DiskPath, server.binding.DiskVolume, server.binding.DiskFileID = binding.DiskPath, binding.DiskVolume, binding.DiskFileID | |
| 525 | 新增: return nil | |
| 526 | 新增:} | |
| 527 | 新增: | |
| 528 | 新增:func (server *windowsHostManagerServer) finishStorage(ctx context.Context, journal *windowsHostStorageJournal, action string) error { | |
| 529 | 新增: if action == "commit" { | |
| 530 | 新增: if journal.After == nil { | |
| 531 | 新增: return errors.New("invalid_request") | |
| 532 | 新增: } | |
| 533 | 新增: if err := managerRequireStopped(ctx, *journal.After); err != nil { | |
| 534 | 新增: return err | |
| 535 | 新增: } | |
| 536 | 新增: var actual windowsVMStorageLayout | |
| 537 | 新增: if err := managerStorageCommand(ctx, server.binding.VMID, "inspect", nil, &actual); err != nil || actual != *journal.NewLayout { | |
| 538 | 新增: return errors.Join(err, errors.New("vm_changed")) | |
| 539 | 新增: } | |
| 540 | 新增: if err := server.saveStorageBinding(*journal.After); err != nil { | |
| 541 | 新增: return err | |
| 542 | 新增: } | |
| 543 | 新增: } else { | |
| 544 | 新增: if journal.After != nil { | |
| 545 | 新增: if err := server.applyStorage(ctx, journal, journal.Before, journal.OldLayout); err != nil { | |
| 546 | 新增: return err | |
| 547 | 新增: } | |
| 548 | 新增: } else if err := managerRequireStopped(ctx, journal.Before); err != nil { | |
| 549 | 新增: return err | |
| 550 | 新增: } | |
| 551 | 新增: if err := server.saveStorageBinding(journal.Before); err != nil { | |
| 552 | 新增: return err | |
| 553 | 新增: } | |
| 554 | 新增: if journal.After != nil { | |
| 555 | 新增: // Return the verified metadata directory to its original owner after | |
| 556 | 新增: // Hyper-V moves back. Cleanup then runs with that user's permissions. | |
| 557 | 新增: real, err := paths.Resolve(journal.Directory.Path) | |
| 558 | 新增: if err == nil && strings.EqualFold(real, journal.Directory.Path) { | |
| 559 | 新增: name, _ := windows.UTF16PtrFromString(real) | |
| 560 | 新增: handle, openErr := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES|windows.WRITE_DAC|windows.WRITE_OWNER, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0) | |
| 561 | 新增: if openErr != nil { | |
| 562 | 新增: return openErr | |
| 563 | 新增: } | |
| 564 | 新增: defer windows.CloseHandle(handle) | |
| 565 | 新增: identity, identityErr := managerStorageObject(handle, true) | |
| 566 | 新增: if identityErr != nil || identity != journal.Directory { | |
| 567 | 新增: return errors.New("vm_changed") | |
| 568 | 新增: } | |
| 569 | 新增: if err := managerProtectVMMetadata(handle, server.binding.HostSID, true); err != nil { | |
| 570 | 新增: return err | |
| 571 | 新增: } | |
| 572 | 新增: } else if !errors.Is(err, os.ErrNotExist) { | |
| 573 | 新增: return errors.New("vm_changed") | |
| 574 | 新增: } | |
| 575 | 新增: } | |
| 576 | 新增: } | |
| 577 | 新增: journal.Phase = action | |
| 578 | 新增: return managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal) | |
| 579 | 新增:} | |
| @@ -0,0 +1,96 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "debug/pe" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "os/exec" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "runtime" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "syscall" | |
| 14 | 新增: "time" | |
| 15 | 新增: | |
| 16 | 新增: "golang.org/x/sys/windows" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:// probeWindowsHost checks the local platform without requiring VM-wide privileges. | |
| 20 | 新增:// It doesn't create a VM or test whether a guest image can be installed. | |
| 21 | 新增:func probeWindowsHost(ctx context.Context) (bool, string) { | |
| 22 | 新增: version := windows.RtlGetVersion() | |
| 23 | 新增: const workstation = 1 // VER_NT_WORKSTATION | |
| 24 | 新增: if version.ProductType != workstation || version.MajorVersion < 10 || version.BuildNumber < 22000 { | |
| 25 | 新增: return false, "Windows 原生客机需要 Windows 11 桌面版宿主。" | |
| 26 | 新增: } | |
| 27 | 新增: var processMachine, nativeMachine uint16 | |
| 28 | 新增: if err := windows.IsWow64Process2(windows.CurrentProcess(), &processMachine, &nativeMachine); err != nil { | |
| 29 | 新增: return false, "无法读取 Windows 主机的原生处理器架构。" | |
| 30 | 新增: } | |
| 31 | 新增: if runtime.GOARCH != "amd64" || nativeMachine != pe.IMAGE_FILE_MACHINE_AMD64 { | |
| 32 | 新增: return false, "Windows 原生客机需要 Intel 或 AMD x64 主机及 x64 版 Cage。" | |
| 33 | 新增: } | |
| 34 | 新增: ctx, cancel := context.WithTimeout(ctx, 12*time.Second) | |
| 35 | 新增: defer cancel() | |
| 36 | 新增: cmd, err := systemPowerShellQuery(ctx, hyperVHostProbe) | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: return false, "无法定位系统自带的 Windows PowerShell。" | |
| 39 | 新增: } | |
| 40 | 新增: output, err := cmd.Output() | |
| 41 | 新增: if errors.Is(ctx.Err(), context.DeadlineExceeded) { | |
| 42 | 新增: return false, "查询 Hyper-V 超时,请检查本机虚拟机管理服务后重试。" | |
| 43 | 新增: } | |
| 44 | 新增: if ctx.Err() != nil { | |
| 45 | 新增: return false, "已取消 Windows 主机预检。" | |
| 46 | 新增: } | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: var exit *exec.ExitError | |
| 49 | 新增: if errors.As(err, &exit) && exit.ExitCode() == 2 { | |
| 50 | 新增: if reason := strings.TrimSpace(string(output)); reason != "" { | |
| 51 | 新增: return false, reason | |
| 52 | 新增: } | |
| 53 | 新增: } | |
| 54 | 新增: return false, "无法通过系统 PowerShell 查询 Hyper-V,请检查 PowerShell 和 Windows 管理服务。" | |
| 55 | 新增: } | |
| 56 | 新增: if strings.TrimSpace(string(output)) != "ready" { | |
| 57 | 新增: return false, "Hyper-V 预检返回了无法识别的结果。" | |
| 58 | 新增: } | |
| 59 | 新增: return true, "Hyper-V 平台已就绪;首次安装确认系统授权后,Cage 管理助手仅操作已绑定客机。" | |
| 60 | 新增:} | |
| 61 | 新增: | |
| 62 | 新增:func systemPowerShellQuery(ctx context.Context, script string) (*exec.Cmd, error) { | |
| 63 | 新增: systemDir, err := windows.GetSystemDirectory() | |
| 64 | 新增: if err != nil { | |
| 65 | 新增: return nil, err | |
| 66 | 新增: } | |
| 67 | 新增: shell := filepath.Join(systemDir, "WindowsPowerShell", "v1.0", "powershell.exe") | |
| 68 | 新增: cmd := exec.CommandContext(ctx, shell, "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script) | |
| 69 | 新增: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} | |
| 70 | 新增: return cmd, nil | |
| 71 | 新增:} | |
| 72 | 新增: | |
| 73 | 新增:const hyperVHostProbe = ` | |
| 74 | 新增:$ErrorActionPreference = 'Stop' | |
| 75 | 新增:[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) | |
| 76 | 新增:function Unavailable([string]$reason) { Write-Output $reason; exit 2 } | |
| 77 | 新增: | |
| 78 | 新增:$edition = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name EditionID).EditionID | |
| 79 | 新增:if ($edition -like 'Core*') { | |
| 80 | 新增: Unavailable 'Windows 家庭版未提供完整的 Hyper-V 角色。此原型支持专业版、企业版和教育版。' | |
| 81 | 新增:} | |
| 82 | 新增:$service = Get-Service -Name vmms -ErrorAction SilentlyContinue | |
| 83 | 新增:if (!$service) { | |
| 84 | 新增: Unavailable '未检测到 Hyper-V 虚拟机管理服务(vmms),请检查 Windows 功能中的 Hyper-V 平台。' | |
| 85 | 新增:} | |
| 86 | 新增:if ($service.Status -ne 'Running') { | |
| 87 | 新增: Unavailable 'Hyper-V 虚拟机管理服务(vmms)当前未运行。' | |
| 88 | 新增:} | |
| 89 | 新增:if ((Get-CimInstance Win32_ComputerSystem).HypervisorPresent -ne $true) { | |
| 90 | 新增: Unavailable 'Windows 未检测到正在运行的虚拟机监控程序,请检查固件虚拟化设置和 Hyper-V 启动状态。' | |
| 91 | 新增:} | |
| 92 | 新增:if (!(Get-Command 'Hyper-V\Get-VMHost' -ErrorAction SilentlyContinue)) { | |
| 93 | 新增: Unavailable '缺少 Hyper-V PowerShell 管理模块,请检查 Windows 功能中的 Hyper-V 管理工具。' | |
| 94 | 新增:} | |
| 95 | 新增:Write-Output 'ready' | |
| 96 | 新增:` | |
| @@ -0,0 +1,6 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import _ "embed" | |
| 4 | 新增: | |
| 5 | 新增://go:embed windows_lifecycle.ps1 | |
| 6 | 新增:var windowsVMLifecycleScript string | |
| @@ -0,0 +1,23 @@ | ||
| 1 | 新增:$ErrorActionPreference = 'Stop' | |
| 2 | 新增:$ProgressPreference = 'SilentlyContinue' | |
| 3 | 新增:[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) | |
| 4 | 新增:$vm = Hyper-V\Get-VM -Id $targetId | |
| 5 | 新增:if (!$vm -or $vm.Id -ne $targetId) { throw 'Binding unavailable.' } | |
| 6 | 新增:if ($action -eq 'start') { | |
| 7 | 新增: if ($vm.Generation -ne 2) { throw 'Guest generation unavailable.' } | |
| 8 | 新增: $firmware = Hyper-V\Get-VMFirmware -VM $vm | |
| 9 | 新增: $security = Hyper-V\Get-VMSecurity -VM $vm | |
| 10 | 新增: if ([string]$firmware.SecureBoot -ne 'On' -or [string]$firmware.SecureBootTemplate -ne 'MicrosoftWindows' -or $security.TpmEnabled -ne $true) { throw 'Guest security unavailable.' } | |
| 11 | 新增: # Until Cage's managed exit has a Windows adapter, this guest remains offline. | |
| 12 | 新增: if (@(Hyper-V\Get-VMNetworkAdapter -VM $vm).Count -ne 0) { throw 'Controlled exit unavailable.' } | |
| 13 | 新增: if ([string]$vm.State -eq 'Off') { Hyper-V\Start-VM -VM $vm | Out-Null } | |
| 14 | 新增: elseif ([string]$vm.State -ne 'Running') { throw 'Guest cannot be started from this state.' } | |
| 15 | 新增:} elseif ($action -eq 'stop') { | |
| 16 | 新增: if ([string]$vm.State -eq 'Running') { | |
| 17 | 新增: # Stop-VM without TurnOff/Force requests the guest shutdown integration service. | |
| 18 | 新增: Hyper-V\Stop-VM -VM $vm -ErrorAction Stop | Out-Null | |
| 19 | 新增: } elseif ([string]$vm.State -ne 'Off') { throw 'Guest cannot be stopped safely from this state.' } | |
| 20 | 新增:} else { throw 'Invalid operation.' } | |
| 21 | 新增:$vm = Hyper-V\Get-VM -Id $targetId | |
| 22 | 新增:if (!$vm -or $vm.Id -ne $targetId) { throw 'Binding changed.' } | |
| 23 | 新增:[ordered]@{state=[string]$vm.State} | ConvertTo-Json -Compress | |
| @@ -0,0 +1,12 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func WindowsVMAction(context.Context, string, string) error { | |
| 11 | 新增: return errors.New("Windows 客机生命周期需要 Windows Hyper-V 主机") | |
| 12 | 新增:} | |
| @@ -0,0 +1,22 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os/exec" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "testing" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestWindowsLifecycleExactVMAndSafeShutdown(t *testing.T) { | |
| 10 | 新增: shell, err := exec.LookPath("pwsh") | |
| 11 | 新增: if err != nil { | |
| 12 | 新增: t.Skip("PowerShell not installed") | |
| 13 | 新增: } | |
| 14 | 新增: query, err := filepath.Abs("windows_lifecycle.ps1") | |
| 15 | 新增: if err != nil { | |
| 16 | 新增: t.Fatal(err) | |
| 17 | 新增: } | |
| 18 | 新增: cmd := exec.CommandContext(t.Context(), shell, "-NoLogo", "-NoProfile", "-NonInteractive", "-File", filepath.Join("testdata", "windows_lifecycle.ps1"), "-Query", query) | |
| 19 | 新增: if output, err := cmd.CombinedOutput(); err != nil { | |
| 20 | 新增: t.Fatalf("lifecycle mock failed: %v\n%s", err, output) | |
| 21 | 新增: } | |
| 22 | 新增:} | |
| @@ -0,0 +1,64 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "encoding/json" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "fmt" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/google/uuid" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:// WindowsVMAction controls only the already paired VM. It never creates, | |
| 15 | 新增:// discovers, force-powers-off, removes, or changes a guest's network adapters. | |
| 16 | 新增:func WindowsVMAction(ctx context.Context, root, action string) error { | |
| 17 | 新增: if action != "start" && action != "stop" { | |
| 18 | 新增: return errors.New("Windows 客机操作无效") | |
| 19 | 新增: } | |
| 20 | 新增: binding, err := LoadWindowsProfile(root) | |
| 21 | 新增: if err != nil { | |
| 22 | 新增: return err | |
| 23 | 新增: } | |
| 24 | 新增: if binding == nil { | |
| 25 | 新增: return errors.New("此配置尚未绑定 Windows 客机") | |
| 26 | 新增: } | |
| 27 | 新增: operation := action | |
| 28 | 新增: if operation == "stop" { | |
| 29 | 新增: operation = "shutdown" | |
| 30 | 新增: } | |
| 31 | 新增: var result WindowsVMResourceState | |
| 32 | 新增: if err := windowsHostManagerCall(ctx, binding.VMID, operation, 0, 0, &result); err != nil { | |
| 33 | 新增: return err | |
| 34 | 新增: } | |
| 35 | 新增: if action == "start" && result.State != "Running" || action == "stop" && result.State != "Off" { | |
| 36 | 新增: return errors.New("Windows 客机未到达预期状态") | |
| 37 | 新增: } | |
| 38 | 新增: return nil | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:func windowsVMActionNative(ctx context.Context, id uuid.UUID, action string) error { | |
| 42 | 新增: if id == uuid.Nil || action != "start" && action != "stop" { | |
| 43 | 新增: return errors.New("Windows 客机操作无效") | |
| 44 | 新增: } | |
| 45 | 新增: script := fmt.Sprintf("$targetId = [guid]'%s'\n$action = '%s'\n", id.String(), action) + windowsVMLifecycleScript | |
| 46 | 新增: cmd, err := systemPowerShellQuery(ctx, script) | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: return err | |
| 49 | 新增: } | |
| 50 | 新增: data, err := cmd.Output() | |
| 51 | 新增: if ctx.Err() != nil { | |
| 52 | 新增: return ctx.Err() | |
| 53 | 新增: } | |
| 54 | 新增: if err != nil { | |
| 55 | 新增: return errors.New("Windows 客机操作未完成,请检查绑定虚拟机的状态与管理权限") | |
| 56 | 新增: } | |
| 57 | 新增: var result struct { | |
| 58 | 新增: State string `json:"state"` | |
| 59 | 新增: } | |
| 60 | 新增: if json.Unmarshal(data, &result) != nil || (action == "start" && result.State != "Running") || (action == "stop" && result.State != "Off") { | |
| 61 | 新增: return errors.New("Windows 客机未到达预期状态") | |
| 62 | 新增: } | |
| 63 | 新增: return nil | |
| 64 | 新增:} | |
| @@ -0,0 +1,117 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "regexp" | |
| 13 | 新增: "strings" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/google/uuid" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:// WindowsProfile binds one Hyper-V guest to its ordinary GUI user and the | |
| 19 | 新增:// current host user's protected pairing. It contains no authentication secret. | |
| 20 | 新增:type WindowsProfile struct { | |
| 21 | 新增: Version int `json:"version"` | |
| 22 | 新增: VMID uuid.UUID `json:"vm_id"` | |
| 23 | 新增: GUIUserSID string `json:"gui_user_sid"` | |
| 24 | 新增: GUIUser string `json:"gui_user,omitempty"` | |
| 25 | 新增: InstanceDirectory string `json:"instance_directory"` | |
| 26 | 新增: RelayExecutable string `json:"relay_executable"` | |
| 27 | 新增: PairingFile string `json:"pairing_file"` | |
| 28 | 新增: NetworkPairingFile string `json:"network_pairing_file,omitempty"` | |
| 29 | 新增:} | |
| 30 | 新增: | |
| 31 | 新增:var windowsGUISID = regexp.MustCompile(`^S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+$`) | |
| 32 | 新增: | |
| 33 | 新增:func WindowsProfilePath(root string) string { return filepath.Join(root, "windows-guest.json") } | |
| 34 | 新增: | |
| 35 | 新增:func (p WindowsProfile) validate() error { | |
| 36 | 新增: if p.Version != 1 || p.VMID == uuid.Nil || !windowsGUISID.MatchString(p.GUIUserSID) || | |
| 37 | 新增: len(p.GUIUser) > 256 || strings.ContainsAny(p.GUIUser, "\x00\r\n") { | |
| 38 | 新增: return errors.New("Windows 客机标识或图形用户无效") | |
| 39 | 新增: } | |
| 40 | 新增: for _, path := range []string{p.InstanceDirectory, p.RelayExecutable, p.PairingFile} { | |
| 41 | 新增: if !filepath.IsAbs(path) || strings.ContainsAny(path, "\x00\r\n") { | |
| 42 | 新增: return errors.New("Windows 客机配置需要绝对本机路径") | |
| 43 | 新增: } | |
| 44 | 新增: } | |
| 45 | 新增: if p.NetworkPairingFile != "" && (!filepath.IsAbs(p.NetworkPairingFile) || strings.ContainsAny(p.NetworkPairingFile, "\x00\r\n")) { | |
| 46 | 新增: return errors.New("Windows 客机网络配对需要绝对本机路径") | |
| 47 | 新增: } | |
| 48 | 新增: return nil | |
| 49 | 新增:} | |
| 50 | 新增: | |
| 51 | 新增:func LoadWindowsProfile(root string) (*WindowsProfile, error) { | |
| 52 | 新增: path := WindowsProfilePath(root) | |
| 53 | 新增: info, err := os.Lstat(path) | |
| 54 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 55 | 新增: return nil, nil | |
| 56 | 新增: } | |
| 57 | 新增: if err != nil { | |
| 58 | 新增: return nil, err | |
| 59 | 新增: } | |
| 60 | 新增: if !info.Mode().IsRegular() || info.Size() == 0 || info.Size() > 16<<10 { | |
| 61 | 新增: return nil, errors.New("Windows 客机配置文件无效") | |
| 62 | 新增: } | |
| 63 | 新增: data, err := os.ReadFile(path) | |
| 64 | 新增: if err != nil { | |
| 65 | 新增: return nil, err | |
| 66 | 新增: } | |
| 67 | 新增: var binding WindowsProfile | |
| 68 | 新增: decoder := json.NewDecoder(bytes.NewReader(data)) | |
| 69 | 新增: decoder.DisallowUnknownFields() | |
| 70 | 新增: if decoder.Decode(&binding) != nil || decoder.Decode(new(any)) != io.EOF { | |
| 71 | 新增: return nil, errors.New("Windows 客机配置格式无效") | |
| 72 | 新增: } | |
| 73 | 新增: if err := binding.validate(); err != nil { | |
| 74 | 新增: return nil, err | |
| 75 | 新增: } | |
| 76 | 新增: return &binding, nil | |
| 77 | 新增:} | |
| 78 | 新增: | |
| 79 | 新增:// BindWindowsProfile publishes an independently verified VM/SID binding. | |
| 80 | 新增:// Windows provisioning owns verification and DPAPI pairing; this never discovers | |
| 81 | 新增:// a user or VM by scanning the machine and never replaces an existing binding. | |
| 82 | 新增:func BindWindowsProfile(root string, binding WindowsProfile) error { | |
| 83 | 新增: if err := binding.validate(); err != nil { | |
| 84 | 新增: return err | |
| 85 | 新增: } | |
| 86 | 新增: data, err := json.Marshal(binding) | |
| 87 | 新增: if err != nil { | |
| 88 | 新增: return err | |
| 89 | 新增: } | |
| 90 | 新增: if err := publishBinding(root, "windows-guest.json", append(data, '\n')); err != nil { | |
| 91 | 新增: return err | |
| 92 | 新增: } | |
| 93 | 新增: return protectWindowsProfile(WindowsProfilePath(root)) | |
| 94 | 新增:} | |
| 95 | 新增: | |
| 96 | 新增:// WindowsRelayCommand carries only the protected profile path and operation. | |
| 97 | 新增:// File bytes and UTF-8 path arrays travel in stdin, never a shell or command line. | |
| 98 | 新增:func WindowsRelayCommand(ctx context.Context, root, operation string, args ...string) (*exec.Cmd, error) { | |
| 99 | 新增: p, err := LoadWindowsProfile(root) | |
| 100 | 新增: if err != nil { | |
| 101 | 新增: return nil, err | |
| 102 | 新增: } | |
| 103 | 新增: if p == nil { | |
| 104 | 新增: return nil, errors.New("此配置尚未绑定 Windows 客机") | |
| 105 | 新增: } | |
| 106 | 新增: switch operation { | |
| 107 | 新增: case "versions": | |
| 108 | 新增: case "stream", "status", "import", "export", "terminal", "browser", "desktop", "attachments", "audio", "resources", "diagnostics", "safety", "project-mount", "network-stream", "network-settings", "cli": | |
| 109 | 新增: default: | |
| 110 | 新增: return nil, errors.New("Windows 客机剪贴板操作无效") | |
| 111 | 新增: } | |
| 112 | 新增: if len(args) != 0 && !(operation == "export" && len(args) == 1 && args[0] == "--paths-stdin") { | |
| 113 | 新增: return nil, errors.New("Windows 客机文件路径必须通过标准输入传递") | |
| 114 | 新增: } | |
| 115 | 新增: argv := append([]string{"--relay-profile", WindowsProfilePath(root), operation}, args...) | |
| 116 | 新增: return exec.CommandContext(ctx, p.RelayExecutable, argv...), nil | |
| 117 | 新增:} | |
| @@ -0,0 +1,6 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:// Non-Windows tests can validate the public binding without interpreting NTFS. | |
| 6 | 新增:func protectWindowsProfile(string) error { return nil } | |
| @@ -0,0 +1,91 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "testing" | |
| 9 | 新增: | |
| 10 | 新增: "github.com/google/uuid" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func windowsBindingFixture(root string) WindowsProfile { | |
| 14 | 新增: return WindowsProfile{Version: 1, VMID: uuid.MustParse("2a6f8208-3906-4e16-8233-2b9d28ecf7be"), GUIUserSID: "S-1-5-21-123-456-789-1001", GUIUser: "Guest", InstanceDirectory: filepath.Join(root, "vm"), RelayExecutable: filepath.Join(root, "agent.exe"), PairingFile: filepath.Join(root, "pairing.dpapi")} | |
| 15 | 新增:} | |
| 16 | 新增: | |
| 17 | 新增:func TestWindowsBindingPreservesIdentityAndHasNoSecretArgument(t *testing.T) { | |
| 18 | 新增: root := t.TempDir() | |
| 19 | 新增: binding := windowsBindingFixture(root) | |
| 20 | 新增: if err := BindWindowsProfile(root, binding); err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: loaded, err := LoadWindowsProfile(root) | |
| 24 | 新增: if err != nil || *loaded != binding { | |
| 25 | 新增: t.Fatalf("binding changed: %v", err) | |
| 26 | 新增: } | |
| 27 | 新增: cmd, err := WindowsRelayCommand(context.Background(), root, "export", "--paths-stdin") | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: if len(cmd.Args) != 5 || cmd.Args[1] != "--relay-profile" || cmd.Args[2] != WindowsProfilePath(root) || cmd.Args[3] != "export" || cmd.Args[4] != "--paths-stdin" { | |
| 32 | 新增: t.Fatal("relay command did not preserve the profile boundary") | |
| 33 | 新增: } | |
| 34 | 新增: different := binding | |
| 35 | 新增: different.GUIUserSID = "S-1-5-21-123-456-789-1002" | |
| 36 | 新增: if err := BindWindowsProfile(root, different); err == nil { | |
| 37 | 新增: t.Fatal("another GUI user replaced the binding") | |
| 38 | 新增: } | |
| 39 | 新增: if _, err := WindowsRelayCommand(context.Background(), root, "export", `["C:\\private"]`); err == nil { | |
| 40 | 新增: t.Fatal("paths accepted in argv") | |
| 41 | 新增: } | |
| 42 | 新增:} | |
| 43 | 新增: | |
| 44 | 新增:func TestWindowsBindingRejectsUnknownFieldsAndUnsafeIdentity(t *testing.T) { | |
| 45 | 新增: for _, kind := range []string{"system", "empty-vm", "relative", "relative-network", "unknown", "trailing"} { | |
| 46 | 新增: t.Run(kind, func(t *testing.T) { | |
| 47 | 新增: root := t.TempDir() | |
| 48 | 新增: binding := windowsBindingFixture(root) | |
| 49 | 新增: switch kind { | |
| 50 | 新增: case "system": | |
| 51 | 新增: binding.GUIUserSID = "S-1-5-18" | |
| 52 | 新增: case "empty-vm": | |
| 53 | 新增: binding.VMID = uuid.Nil | |
| 54 | 新增: case "relative": | |
| 55 | 新增: binding.PairingFile = "relative" | |
| 56 | 新增: case "relative-network": | |
| 57 | 新增: binding.NetworkPairingFile = "packet.dpapi" | |
| 58 | 新增: } | |
| 59 | 新增: data, _ := json.Marshal(binding) | |
| 60 | 新增: if kind == "unknown" { | |
| 61 | 新增: data = append(data[:len(data)-1], []byte(`,"secret":"must not be accepted"}`)...) | |
| 62 | 新增: } | |
| 63 | 新增: if kind == "trailing" { | |
| 64 | 新增: data = append(data, []byte(` {}`)...) | |
| 65 | 新增: } | |
| 66 | 新增: if err := os.WriteFile(WindowsProfilePath(root), data, 0600); err != nil { | |
| 67 | 新增: t.Fatal(err) | |
| 68 | 新增: } | |
| 69 | 新增: if _, err := LoadWindowsProfile(root); err == nil { | |
| 70 | 新增: t.Fatal("unsafe binding accepted") | |
| 71 | 新增: } | |
| 72 | 新增: }) | |
| 73 | 新增: } | |
| 74 | 新增:} | |
| 75 | 新增: | |
| 76 | 新增:func TestWindowsBindingKeepsPacketPairingOutOfArguments(t *testing.T) { | |
| 77 | 新增: root := t.TempDir() | |
| 78 | 新增: binding := windowsBindingFixture(root) | |
| 79 | 新增: binding.NetworkPairingFile = filepath.Join(root, "packet.dpapi") | |
| 80 | 新增: if err := BindWindowsProfile(root, binding); err != nil { | |
| 81 | 新增: t.Fatal(err) | |
| 82 | 新增: } | |
| 83 | 新增: loaded, err := LoadWindowsProfile(root) | |
| 84 | 新增: if err != nil || loaded.NetworkPairingFile != binding.NetworkPairingFile { | |
| 85 | 新增: t.Fatal("packet pairing binding lost") | |
| 86 | 新增: } | |
| 87 | 新增: cmd, err := WindowsRelayCommand(context.Background(), root, "network-stream") | |
| 88 | 新增: if err != nil || len(cmd.Args) != 4 || cmd.Args[3] != "network-stream" { | |
| 89 | 新增: t.Fatal("packet transport bypassed the protected profile") | |
| 90 | 新增: } | |
| 91 | 新增:} | |
| @@ -0,0 +1,23 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import "golang.org/x/sys/windows" | |
| 6 | 新增: | |
| 7 | 新增:// Go's 0600 mode does not establish an NTFS DACL. The relay accepts only a | |
| 8 | 新增:// protected binding owned by the current host user, SYSTEM and administrators. | |
| 9 | 新增:func protectWindowsProfile(path string) error { | |
| 10 | 新增: user, err := windows.GetCurrentProcessToken().GetTokenUser() | |
| 11 | 新增: if err != nil { | |
| 12 | 新增: return err | |
| 13 | 新增: } | |
| 14 | 新增: sd, err := windows.SecurityDescriptorFromString("D:P(A;;FA;;;" + user.User.Sid.String() + ")(A;;FA;;;SY)(A;;FA;;;BA)") | |
| 15 | 新增: if err != nil { | |
| 16 | 新增: return err | |
| 17 | 新增: } | |
| 18 | 新增: dacl, _, err := sd.DACL() | |
| 19 | 新增: if err != nil { | |
| 20 | 新增: return err | |
| 21 | 新增: } | |
| 22 | 新增: return windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil) | |
| 23 | 新增:} | |
| @@ -0,0 +1,34 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: _ "embed" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:// WindowsVMResourceCeiling is the limit enforced by the Hyper-V management service. | |
| 9 | 新增:func WindowsVMResourceCeiling(hostMemoryGiB, hostCPUs int) (memoryGiB, cpus int) { | |
| 10 | 新增: return min(256, hostMemoryGiB*3/4), min(64, hostCPUs) | |
| 11 | 新增:} | |
| 12 | 新增: | |
| 13 | 新增:type WindowsVMResourceState struct { | |
| 14 | 新增: State string `json:"state"` | |
| 15 | 新增: CPUs int `json:"cpus"` | |
| 16 | 新增: MemoryStartup uint64 `json:"memory_startup_bytes"` | |
| 17 | 新增: MemoryMinimum uint64 `json:"memory_minimum_bytes"` | |
| 18 | 新增: MemoryMaximum uint64 `json:"memory_maximum_bytes"` | |
| 19 | 新增: MemoryAssigned uint64 `json:"memory_assigned_bytes"` | |
| 20 | 新增: DynamicMemory bool `json:"dynamic_memory"` | |
| 21 | 新增:} | |
| 22 | 新增: | |
| 23 | 新增:// MatchesAllocation checks the Hyper-V configuration applied on a cold start. | |
| 24 | 新增:func (s WindowsVMResourceState) MatchesAllocation(memoryGiB, cpus int) bool { | |
| 25 | 新增: return s.DynamicMemory && s.MemoryMinimum == 4<<30 && s.MemoryStartup == 4<<30 && | |
| 26 | 新增: s.MemoryMaximum == uint64(memoryGiB)<<30 && s.CPUs == cpus | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增://go:embed windows_resources.ps1 | |
| 30 | 新增:var windowsVMResourcesScript string | |
| 31 | 新增: | |
| 32 | 新增:func WindowsVMResources(ctx context.Context, root string, memoryGiB, cpus int) (WindowsVMResourceState, error) { | |
| 33 | 新增: return windowsVMResources(ctx, root, memoryGiB, cpus) | |
| 34 | 新增:} | |
| @@ -0,0 +1,25 @@ | ||
| 1 | 新增:$ErrorActionPreference='Stop' | |
| 2 | 新增:$ProgressPreference='SilentlyContinue' | |
| 3 | 新增:[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) | |
| 4 | 新增:$vm=Hyper-V\Get-VM -Id $targetId | |
| 5 | 新增:if(!$vm -or $vm.Id -ne $targetId){throw 'Bound VM unavailable.'} | |
| 6 | 新增:$memory=Hyper-V\Get-VMMemory -VM $vm | |
| 7 | 新增:$processor=Hyper-V\Get-VMProcessor -VM $vm | |
| 8 | 新增:if($memoryGiB -ne 0 -or $cpus -ne 0){ | |
| 9 | 新增: if($memoryGiB -lt 4 -or $memoryGiB -gt 1024 -or $cpus -lt 1 -or $cpus -gt 1024 -or [string]$vm.State -ne 'Off'){throw 'Stop the guest before applying Windows 11 resources.'} | |
| 10 | 新增: $maximum=[int64]$memoryGiB*1GB | |
| 11 | 新增: try{ | |
| 12 | 新增: Hyper-V\Set-VMProcessor -VM $vm -Count $cpus | |
| 13 | 新增: Hyper-V\Set-VMMemory -VM $vm -DynamicMemoryEnabled $true -MinimumBytes 4GB -StartupBytes 4GB -MaximumBytes $maximum | |
| 14 | 新增: }catch{ | |
| 15 | 新增: # Restore only the same VM's prior resource settings; keep its disk untouched. | |
| 16 | 新增: try{Hyper-V\Set-VMProcessor -VM $vm -Count $processor.Count}catch{} | |
| 17 | 新增: try{Hyper-V\Set-VMMemory -VM $vm -DynamicMemoryEnabled $memory.DynamicMemoryEnabled -MinimumBytes $memory.Minimum -StartupBytes $memory.Startup -MaximumBytes $memory.Maximum}catch{} | |
| 18 | 新增: throw | |
| 19 | 新增: } | |
| 20 | 新增: $vm=Hyper-V\Get-VM -Id $targetId | |
| 21 | 新增: if(!$vm -or $vm.Id -ne $targetId){throw 'Bound VM changed.'} | |
| 22 | 新增: $memory=Hyper-V\Get-VMMemory -VM $vm | |
| 23 | 新增: $processor=Hyper-V\Get-VMProcessor -VM $vm | |
| 24 | 新增:} | |
| 25 | 新增:[ordered]@{state=[string]$vm.State;cpus=[int]$processor.Count;memory_startup_bytes=[uint64]$memory.Startup;memory_minimum_bytes=[uint64]$memory.Minimum;memory_maximum_bytes=[uint64]$memory.Maximum;memory_assigned_bytes=[uint64]$vm.MemoryAssigned;dynamic_memory=[bool]$memory.DynamicMemoryEnabled}|ConvertTo-Json -Compress | |
| @@ -0,0 +1,12 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func windowsVMResources(context.Context, string, int, int) (WindowsVMResourceState, error) { | |
| 11 | 新增: return WindowsVMResourceState{}, errors.New("Windows 客机资源管理需要Windows Hyper-V主机") | |
| 12 | 新增:} | |
| @@ -0,0 +1,22 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os/exec" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "testing" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestWindowsResourceExactVMAndRollback(t *testing.T) { | |
| 10 | 新增: shell, err := exec.LookPath("pwsh") | |
| 11 | 新增: if err != nil { | |
| 12 | 新增: t.Skip("PowerShell not installed") | |
| 13 | 新增: } | |
| 14 | 新增: query, err := filepath.Abs("windows_resources.ps1") | |
| 15 | 新增: if err != nil { | |
| 16 | 新增: t.Fatal(err) | |
| 17 | 新增: } | |
| 18 | 新增: cmd := exec.CommandContext(t.Context(), shell, "-NoLogo", "-NoProfile", "-NonInteractive", "-File", filepath.Join("testdata", "windows_resources.ps1"), "-Query", query) | |
| 19 | 新增: if data, err := cmd.CombinedOutput(); err != nil { | |
| 20 | 新增: t.Fatalf("Windows resource script failed: %v\n%s", err, data) | |
| 21 | 新增: } | |
| 22 | 新增:} | |
| @@ -0,0 +1,62 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "encoding/json" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "fmt" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/google/uuid" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func windowsVMResources(ctx context.Context, root string, memoryGiB, cpus int) (WindowsVMResourceState, error) { | |
| 15 | 新增: if (memoryGiB == 0) != (cpus == 0) || memoryGiB < 0 || memoryGiB > 1024 || cpus < 0 || cpus > 1024 { | |
| 16 | 新增: return WindowsVMResourceState{}, errors.New("Windows 客机资源参数无效") | |
| 17 | 新增: } | |
| 18 | 新增: binding, err := LoadWindowsProfile(root) | |
| 19 | 新增: if err != nil { | |
| 20 | 新增: return WindowsVMResourceState{}, err | |
| 21 | 新增: } | |
| 22 | 新增: if binding == nil { | |
| 23 | 新增: return WindowsVMResourceState{}, errors.New("此配置尚未绑定Windows客机") | |
| 24 | 新增: } | |
| 25 | 新增: var result WindowsVMResourceState | |
| 26 | 新增: if err := windowsHostManagerCall(ctx, binding.VMID, "resources", memoryGiB, cpus, &result); err != nil { | |
| 27 | 新增: return result, err | |
| 28 | 新增: } | |
| 29 | 新增: if result.CPUs < 1 || result.MemoryStartup < 2<<30 || result.State == "" { | |
| 30 | 新增: return result, errors.New("Windows 客机资源状态无效") | |
| 31 | 新增: } | |
| 32 | 新增: if memoryGiB != 0 && !result.MatchesAllocation(memoryGiB, cpus) { | |
| 33 | 新增: return result, errors.New("Windows 客机资源未达到请求值") | |
| 34 | 新增: } | |
| 35 | 新增: return result, nil | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func windowsVMResourcesNative(ctx context.Context, id uuid.UUID, memoryGiB, cpus int) (WindowsVMResourceState, error) { | |
| 39 | 新增: if id == uuid.Nil || (memoryGiB == 0) != (cpus == 0) || memoryGiB < 0 || memoryGiB > 1024 || cpus < 0 || cpus > 1024 { | |
| 40 | 新增: return WindowsVMResourceState{}, errors.New("Windows 客机资源参数无效") | |
| 41 | 新增: } | |
| 42 | 新增: script := fmt.Sprintf("$targetId=[guid]'%s'\n$memoryGiB=%d\n$cpus=%d\n", id.String(), memoryGiB, cpus) + windowsVMResourcesScript | |
| 43 | 新增: cmd, err := systemPowerShellQuery(ctx, script) | |
| 44 | 新增: if err != nil { | |
| 45 | 新增: return WindowsVMResourceState{}, err | |
| 46 | 新增: } | |
| 47 | 新增: data, err := cmd.Output() | |
| 48 | 新增: if ctx.Err() != nil { | |
| 49 | 新增: return WindowsVMResourceState{}, ctx.Err() | |
| 50 | 新增: } | |
| 51 | 新增: if err != nil { | |
| 52 | 新增: return WindowsVMResourceState{}, errors.New("Windows 客机资源操作未完成,请核对虚拟机状态与管理权限") | |
| 53 | 新增: } | |
| 54 | 新增: var result WindowsVMResourceState | |
| 55 | 新增: if json.Unmarshal(data, &result) != nil || result.CPUs < 1 || result.MemoryStartup < 2<<30 { | |
| 56 | 新增: return result, errors.New("Windows 客机资源状态无效") | |
| 57 | 新增: } | |
| 58 | 新增: if memoryGiB != 0 && !result.MatchesAllocation(memoryGiB, cpus) { | |
| 59 | 新增: return result, errors.New("Windows 客机资源未达到请求值") | |
| 60 | 新增: } | |
| 61 | 新增: return result, nil | |
| 62 | 新增:} | |
| @@ -0,0 +1,214 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "strings" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/google/uuid" | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:type windowsStorageSnapshot struct { | |
| 18 | 新增: Profile WindowsProfile `json:"profile"` | |
| 19 | 新增: Instance string `json:"instance"` | |
| 20 | 新增: Disk windowsStorageDisk `json:"disk"` | |
| 21 | 新增:} | |
| 22 | 新增: | |
| 23 | 新增:type windowsStorageRuntime struct { | |
| 24 | 新增: profile string | |
| 25 | 新增: call func(context.Context, uuid.UUID, windowsHostStorageRequest) (windowsHostStorageState, error) | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:func WindowsStorageRuntime(profile string) cage.StorageRuntime { | |
| 29 | 新增: return &windowsStorageRuntime{profile: profile, call: windowsHostStorage} | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 32 | 新增:// RecoverWindowsStorage is safe on ordinary startup. The helper is contacted | |
| 33 | 新增:// only when a durable Windows storage transaction still needs resolution. | |
| 34 | 新增:func RecoverWindowsStorage(ctx context.Context, profile string) error { | |
| 35 | 新增: return cage.RecoverStorage(ctx, profile, WindowsStorageRuntime(profile)) | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func (*windowsStorageRuntime) Name() string { return "windows-hyperv" } | |
| 39 | 新增: | |
| 40 | 新增:func (runtime *windowsStorageRuntime) Snapshot(ctx context.Context, source string) (cage.StorageRuntimeSnapshot, error) { | |
| 41 | 新增: var snapshot cage.StorageRuntimeSnapshot | |
| 42 | 新增: binding, err := LoadWindowsProfile(runtime.profile) | |
| 43 | 新增: if err != nil { | |
| 44 | 新增: return snapshot, err | |
| 45 | 新增: } | |
| 46 | 新增: if binding == nil { | |
| 47 | 新增: return snapshot, errors.New("Windows 客机尚未绑定") | |
| 48 | 新增: } | |
| 49 | 新增: state, err := runtime.call(ctx, binding.VMID, windowsHostStorageRequest{Action: "status"}) | |
| 50 | 新增: if err != nil { | |
| 51 | 新增: return snapshot, fmt.Errorf("请先更新或恢复 Windows 系统管理助手,再迁移环境存储:%w", err) | |
| 52 | 新增: } | |
| 53 | 新增: if state.Pending != "" { | |
| 54 | 新增: return snapshot, errors.New("这台 Windows 客机仍有待恢复的存储迁移,请打开发起迁移的原工作台") | |
| 55 | 新增: } | |
| 56 | 新增: instance, err := paths.Resolve(binding.InstanceDirectory) | |
| 57 | 新增: if err != nil { | |
| 58 | 新增: return snapshot, err | |
| 59 | 新增: } | |
| 60 | 新增: snapshot.State, err = json.Marshal(windowsStorageSnapshot{Profile: *binding, Instance: instance, Disk: state.Disk}) | |
| 61 | 新增: if !cage.StorageContains(source, instance) { | |
| 62 | 新增: snapshot.Backups = append(snapshot.Backups, instance) | |
| 63 | 新增: } | |
| 64 | 新增: if !cage.StorageContains(source, state.Disk.Path) && !cage.StorageContains(instance, state.Disk.Path) { | |
| 65 | 新增: snapshot.Backups = append(snapshot.Backups, state.Disk.Path) | |
| 66 | 新增: } | |
| 67 | 新增: if state.Layout != nil { | |
| 68 | 新增: // Hyper-V moves and backs up its own configuration and snapshot files. | |
| 69 | 新增: // Ordinary host-user copies must not inherit or replace their ACLs. | |
| 70 | 新增: for _, directory := range []string{filepath.Join(state.Layout.Configuration, "Virtual Machines"), filepath.Join(state.Layout.Snapshots, "Snapshots")} { | |
| 71 | 新增: physical, resolveErr := cage.StoragePhysicalPath(directory) | |
| 72 | 新增: if resolveErr != nil { | |
| 73 | 新增: return snapshot, resolveErr | |
| 74 | 新增: } | |
| 75 | 新增: if cage.StorageContains(source, physical) && !cage.StorageContains(physical, state.Disk.Path) { | |
| 76 | 新增: snapshot.Excluded = append(snapshot.Excluded, physical) | |
| 77 | 新增: } | |
| 78 | 新增: } | |
| 79 | 新增: } | |
| 80 | 新增: return snapshot, err | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:func windowsMoveSnapshot(move cage.StorageTransition) (windowsStorageSnapshot, error) { | |
| 84 | 新增: var snapshot windowsStorageSnapshot | |
| 85 | 新增: if json.Unmarshal(move.State, &snapshot) != nil || snapshot.Profile.validate() != nil || | |
| 86 | 新增: !filepath.IsAbs(snapshot.Instance) || !filepath.IsAbs(snapshot.Disk.Path) || snapshot.Disk.Volume == 0 || snapshot.Disk.FileID == 0 { | |
| 87 | 新增: return snapshot, errors.New("Windows 存储迁移的恢复信息无效") | |
| 88 | 新增: } | |
| 89 | 新增: return snapshot, nil | |
| 90 | 新增:} | |
| 91 | 新增: | |
| 92 | 新增:func (runtime *windowsStorageRuntime) action(ctx context.Context, move cage.StorageTransition, action, disk, directory string) error { | |
| 93 | 新增: snapshot, err := windowsMoveSnapshot(move) | |
| 94 | 新增: if err != nil { | |
| 95 | 新增: return err | |
| 96 | 新增: } | |
| 97 | 新增: state, err := runtime.call(ctx, snapshot.Profile.VMID, windowsHostStorageRequest{Action: action, ID: move.ID, | |
| 98 | 新增: SourceVolume: snapshot.Disk.Volume, SourceFileID: snapshot.Disk.FileID, Disk: disk, Directory: directory}) | |
| 99 | 新增: if err != nil { | |
| 100 | 新增: return err | |
| 101 | 新增: } | |
| 102 | 新增: if action == "begin" || action == "attach" { | |
| 103 | 新增: if state.Pending != move.ID { | |
| 104 | 新增: return errors.New("Windows 管理助手没有保留当前迁移事务") | |
| 105 | 新增: } | |
| 106 | 新增: } else if state.Pending != "" || state.Outcome != action { | |
| 107 | 新增: return errors.New("Windows 管理助手尚未完成迁移恢复") | |
| 108 | 新增: } | |
| 109 | 新增: return nil | |
| 110 | 新增:} | |
| 111 | 新增: | |
| 112 | 新增:func (runtime *windowsStorageRuntime) Begin(ctx context.Context, move cage.StorageTransition) error { | |
| 113 | 新增: return runtime.action(ctx, move, "begin", "", "") | |
| 114 | 新增:} | |
| 115 | 新增: | |
| 116 | 新增:func windowsMovedPath(value, source, target string) string { | |
| 117 | 新增: if !cage.StorageContains(source, value) { | |
| 118 | 新增: return value | |
| 119 | 新增: } | |
| 120 | 新增: rel, err := filepath.Rel(source, value) | |
| 121 | 新增: if err != nil { | |
| 122 | 新增: return value | |
| 123 | 新增: } | |
| 124 | 新增: return filepath.Join(target, rel) | |
| 125 | 新增:} | |
| 126 | 新增: | |
| 127 | 新增:func (runtime *windowsStorageRuntime) movedProfile(move cage.StorageTransition, snapshot windowsStorageSnapshot) (WindowsProfile, string) { | |
| 128 | 新增: logical := filepath.Join(runtime.profile, "state") | |
| 129 | 新增: instance := filepath.Join(logical, "windows-"+strings.ReplaceAll(snapshot.Profile.VMID.String(), "-", "")) | |
| 130 | 新增: if cage.StorageContains(move.Source, snapshot.Instance) { | |
| 131 | 新增: instance = windowsMovedPath(snapshot.Instance, move.Source, logical) | |
| 132 | 新增: } | |
| 133 | 新增: next := snapshot.Profile | |
| 134 | 新增: next.InstanceDirectory = instance | |
| 135 | 新增: remap := func(value string) string { | |
| 136 | 新增: value = windowsMovedPath(value, snapshot.Profile.InstanceDirectory, instance) | |
| 137 | 新增: value = windowsMovedPath(value, snapshot.Instance, instance) | |
| 138 | 新增: return windowsMovedPath(value, move.Source, logical) | |
| 139 | 新增: } | |
| 140 | 新增: next.RelayExecutable = remap(next.RelayExecutable) | |
| 141 | 新增: next.PairingFile = remap(next.PairingFile) | |
| 142 | 新增: next.NetworkPairingFile = remap(next.NetworkPairingFile) | |
| 143 | 新增: physicalInstance := windowsMovedPath(instance, logical, move.Destination) | |
| 144 | 新增: disk := windowsMovedPath(snapshot.Disk.Path, snapshot.Instance, physicalInstance) | |
| 145 | 新增: disk = windowsMovedPath(disk, move.Source, move.Destination) | |
| 146 | 新增: if disk == snapshot.Disk.Path { | |
| 147 | 新增: disk = filepath.Join(physicalInstance, filepath.Base(snapshot.Disk.Path)) | |
| 148 | 新增: } | |
| 149 | 新增: return next, disk | |
| 150 | 新增:} | |
| 151 | 新增: | |
| 152 | 新增:func (runtime *windowsStorageRuntime) Switch(ctx context.Context, move cage.StorageTransition) error { | |
| 153 | 新增: snapshot, err := windowsMoveSnapshot(move) | |
| 154 | 新增: if err != nil { | |
| 155 | 新增: return err | |
| 156 | 新增: } | |
| 157 | 新增: next, disk := runtime.movedProfile(move, snapshot) | |
| 158 | 新增: physicalInstance := windowsMovedPath(next.InstanceDirectory, filepath.Join(runtime.profile, "state"), move.Destination) | |
| 159 | 新增: if !cage.StorageContains(move.Source, snapshot.Instance) { | |
| 160 | 新增: if err = cage.CopyStorage(ctx, snapshot.Instance, physicalInstance, nil); err != nil { | |
| 161 | 新增: return err | |
| 162 | 新增: } | |
| 163 | 新增: } | |
| 164 | 新增: if !cage.StorageContains(move.Source, snapshot.Disk.Path) && !cage.StorageContains(snapshot.Instance, snapshot.Disk.Path) { | |
| 165 | 新增: if err = os.MkdirAll(physicalInstance, 0700); err != nil { | |
| 166 | 新增: return err | |
| 167 | 新增: } | |
| 168 | 新增: if err = cage.CopyStorageFile(ctx, snapshot.Disk.Path, disk); err != nil { | |
| 169 | 新增: return err | |
| 170 | 新增: } | |
| 171 | 新增: } | |
| 172 | 新增: directory := filepath.Join(move.Destination, "hyperv-"+snapshot.Profile.VMID.String()+"-"+move.ID) | |
| 173 | 新增: if err = os.Mkdir(directory, 0700); err != nil { | |
| 174 | 新增: return err | |
| 175 | 新增: } | |
| 176 | 新增: if err = runtime.action(ctx, move, "attach", disk, directory); err != nil { | |
| 177 | 新增: return err | |
| 178 | 新增: } | |
| 179 | 新增: return runtime.writeProfile(snapshot.Profile, next, next) | |
| 180 | 新增:} | |
| 181 | 新增: | |
| 182 | 新增:func (runtime *windowsStorageRuntime) Recover(ctx context.Context, move cage.StorageTransition, committed bool) error { | |
| 183 | 新增: snapshot, err := windowsMoveSnapshot(move) | |
| 184 | 新增: if err != nil { | |
| 185 | 新增: return err | |
| 186 | 新增: } | |
| 187 | 新增: next, _ := runtime.movedProfile(move, snapshot) | |
| 188 | 新增: chosen, action := snapshot.Profile, "rollback" | |
| 189 | 新增: if committed { | |
| 190 | 新增: chosen, action = next, "commit" | |
| 191 | 新增: } | |
| 192 | 新增: if err = runtime.action(ctx, move, action, "", ""); err != nil { | |
| 193 | 新增: return err | |
| 194 | 新增: } | |
| 195 | 新增: return runtime.writeProfile(snapshot.Profile, next, chosen) | |
| 196 | 新增:} | |
| 197 | 新增: | |
| 198 | 新增:func (runtime *windowsStorageRuntime) writeProfile(before, after, chosen WindowsProfile) error { | |
| 199 | 新增: current, err := LoadWindowsProfile(runtime.profile) | |
| 200 | 新增: if err != nil { | |
| 201 | 新增: return err | |
| 202 | 新增: } | |
| 203 | 新增: if current == nil || *current != before && *current != after { | |
| 204 | 新增: return errors.New("Windows 客机配对在迁移期间发生变化,请保留迁移记录并核对原配置") | |
| 205 | 新增: } | |
| 206 | 新增: if *current == chosen { | |
| 207 | 新增: return nil | |
| 208 | 新增: } | |
| 209 | 新增: data, err := json.Marshal(chosen) | |
| 210 | 新增: if err != nil { | |
| 211 | 新增: return err | |
| 212 | 新增: } | |
| 213 | 新增: return replaceWindowsStorageProfile(WindowsProfilePath(runtime.profile), append(data, '\n')) | |
| 214 | 新增:} | |
| @@ -0,0 +1,75 @@ | ||
| 1 | 新增:$ErrorActionPreference = 'Stop' | |
| 2 | 新增:$ProgressPreference = 'SilentlyContinue' | |
| 3 | 新增:$id = [guid]$inputData.vm_id | |
| 4 | 新增:$vm = Get-VM -Id $id | |
| 5 | 新增:if ($vm.State -ne 'Off' -or $vm.Generation -ne 2 -or | |
| 6 | 新增: @(Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or | |
| 7 | 新增: (Get-VMFirmware -VM $vm).SecureBoot -ne 'On' -or !(Get-VMSecurity -VM $vm).TpmEnabled) { | |
| 8 | 新增: throw 'vm_changed' | |
| 9 | 新增:} | |
| 10 | 新增:$disks = @(Get-VMHardDiskDrive -VM $vm) | |
| 11 | 新增:if ($disks.Count -ne 1) { throw 'vm_changed' } | |
| 12 | 新增:function Read-Storage { | |
| 13 | 新增: $current = Get-VM -Id $id | |
| 14 | 新增: [pscustomobject]@{ | |
| 15 | 新增: configuration = [string]$current.ConfigurationLocation | |
| 16 | 新增: snapshots = [string]$current.SnapshotFileLocation | |
| 17 | 新增: paging = [string]$current.SmartPagingFilePath | |
| 18 | 新增: } | |
| 19 | 新增:} | |
| 20 | 新增:if ($inputData.action -eq 'inspect') { | |
| 21 | 新增: Read-Storage | ConvertTo-Json -Compress | |
| 22 | 新增: exit 0 | |
| 23 | 新增:} | |
| 24 | 新增:if ($inputData.action -eq 'export') { | |
| 25 | 新增: $namespace = 'root\virtualization\v2' | |
| 26 | 新增: $system = Get-WmiObject -Namespace $namespace -Class Msvm_ComputerSystem -Filter ("Name='" + $id.ToString('D') + "'") | |
| 27 | 新增: $service = Get-WmiObject -Namespace $namespace -Class Msvm_VirtualSystemManagementService | |
| 28 | 新增: $settings = ([wmiclass]'\\.\root\virtualization\v2:Msvm_VirtualSystemExportSettingData').CreateInstance() | |
| 29 | 新增: $settings.CopySnapshotConfiguration = 0 | |
| 30 | 新增: $settings.CopyVmRuntimeInformation = $true | |
| 31 | 新增: $settings.CopyVmStorage = $false | |
| 32 | 新增: $settings.CreateVmExportSubdirectory = $false | |
| 33 | 新增: $result = $service.ExportSystemDefinition($system.__PATH, [string]$inputData.backup, $settings.GetText(1)) | |
| 34 | 新增: if ($result.ReturnValue -eq 4096) { | |
| 35 | 新增: $job = [wmi]$result.Job | |
| 36 | 新增: while ($job.JobState -in @(2, 3, 4, 6)) { Start-Sleep -Milliseconds 200; $job.Get() } | |
| 37 | 新增: if ($job.JobState -ne 7 -or $job.ErrorCode -ne 0) { throw 'storage_export_failed' } | |
| 38 | 新增: } elseif ($result.ReturnValue -ne 0) { | |
| 39 | 新增: throw 'storage_export_failed' | |
| 40 | 新增: } | |
| 41 | 新增: [pscustomobject]@{ exported = $true } | ConvertTo-Json -Compress | |
| 42 | 新增: exit 0 | |
| 43 | 新增:} | |
| 44 | 新增:if ($inputData.action -ne 'apply') { throw 'invalid_operation' } | |
| 45 | 新增:$old = $inputData.old | |
| 46 | 新增:$next = $inputData.next | |
| 47 | 新增:$current = Read-Storage | |
| 48 | 新增:foreach ($field in @('configuration', 'snapshots', 'paging')) { | |
| 49 | 新增: if ($current.$field -ine $old.$field -and $current.$field -ine $next.$field) { throw 'vm_changed' } | |
| 50 | 新增:} | |
| 51 | 新增:if ($disks[0].Path -ine $inputData.old_disk -and $disks[0].Path -ine $inputData.source_disk -and $disks[0].Path -ine $inputData.new_disk) { throw 'vm_changed' } | |
| 52 | 新增:$target = $inputData.target | |
| 53 | 新增:$move = @{} | |
| 54 | 新增:if ($current.configuration -ine $target.configuration) { $move.VirtualMachinePath = [string]$target.configuration } | |
| 55 | 新增:if ($current.snapshots -ine $target.snapshots) { $move.SnapshotFilePath = [string]$target.snapshots } | |
| 56 | 新增:if ($current.paging -ine $target.paging) { $move.SmartPagingFilePath = [string]$target.paging } | |
| 57 | 新增:if ($move.Count) { | |
| 58 | 新增: # Hyper-V owns configuration, vTPM state and snapshot metadata. Its native | |
| 59 | 新增: # storage operation preserves the registered VM identity and permissions. | |
| 60 | 新增: # The verified VHDX copy is attached separately so its original is retained. | |
| 61 | 新增: Move-VMStorage -VM $vm @move -Confirm:$false | |
| 62 | 新增:} | |
| 63 | 新增:$vm = Get-VM -Id $id | |
| 64 | 新增:$disks = @(Get-VMHardDiskDrive -VM $vm) | |
| 65 | 新增:if ($vm.State -ne 'Off' -or $disks.Count -ne 1) { throw 'vm_changed' } | |
| 66 | 新增:if ($disks[0].Path -ine $inputData.disk) { | |
| 67 | 新增: Set-VMHardDiskDrive -VMHardDiskDrive $disks[0] -Path ([string]$inputData.disk) | |
| 68 | 新增:} | |
| 69 | 新增:$readback = Read-Storage | |
| 70 | 新增:foreach ($field in @('configuration', 'snapshots', 'paging')) { | |
| 71 | 新增: if ($readback.$field -ine $target.$field) { throw 'storage_readback_failed' } | |
| 72 | 新增:} | |
| 73 | 新增:$disk = @(Get-VMHardDiskDrive -VM (Get-VM -Id $id)) | |
| 74 | 新增:if ($disk.Count -ne 1 -or $disk[0].Path -ine $inputData.disk) { throw 'storage_readback_failed' } | |
| 75 | 新增:[pscustomobject]@{ applied = $true } | ConvertTo-Json -Compress | |
| @@ -0,0 +1,32 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/google/uuid" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func windowsHostStorage(context.Context, uuid.UUID, windowsHostStorageRequest) (windowsHostStorageState, error) { | |
| 15 | 新增: return windowsHostStorageState{}, errors.New("Windows 客机存储迁移需要 Windows Hyper-V 主机") | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:func replaceWindowsStorageProfile(path string, data []byte) error { | |
| 19 | 新增: file, err := os.CreateTemp(filepath.Dir(path), ".windows-storage-*") | |
| 20 | 新增: if err != nil { | |
| 21 | 新增: return err | |
| 22 | 新增: } | |
| 23 | 新增: defer os.Remove(file.Name()) | |
| 24 | 新增: _, err = file.Write(data) | |
| 25 | 新增: if err == nil { | |
| 26 | 新增: err = file.Sync() | |
| 27 | 新增: } | |
| 28 | 新增: if err = errors.Join(err, file.Close()); err != nil { | |
| 29 | 新增: return err | |
| 30 | 新增: } | |
| 31 | 新增: return os.Rename(file.Name(), path) | |
| 32 | 新增:} | |
| @@ -0,0 +1,47 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/google/uuid" | |
| 12 | 新增: "golang.org/x/sys/windows" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:func windowsHostStorage(ctx context.Context, id uuid.UUID, input windowsHostStorageRequest) (windowsHostStorageState, error) { | |
| 16 | 新增: var state windowsHostStorageState | |
| 17 | 新增: err := windowsHostManagerRequestCall(ctx, windowsHostManagerRequest{Version: windowsHostManagerVersion, VMID: id, Operation: "storage", Storage: &input}, &state) | |
| 18 | 新增: return state, err | |
| 19 | 新增:} | |
| 20 | 新增: | |
| 21 | 新增:func replaceWindowsStorageProfile(path string, data []byte) error { | |
| 22 | 新增: file, err := os.CreateTemp(filepath.Dir(path), ".windows-storage-*") | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: return err | |
| 25 | 新增: } | |
| 26 | 新增: defer os.Remove(file.Name()) | |
| 27 | 新增: if err = protectWindowsProfile(file.Name()); err != nil { | |
| 28 | 新增: file.Close() | |
| 29 | 新增: return err | |
| 30 | 新增: } | |
| 31 | 新增: _, err = file.Write(data) | |
| 32 | 新增: if err == nil { | |
| 33 | 新增: err = file.Sync() | |
| 34 | 新增: } | |
| 35 | 新增: if err = errors.Join(err, file.Close()); err != nil { | |
| 36 | 新增: return err | |
| 37 | 新增: } | |
| 38 | 新增: from, err := windows.UTF16PtrFromString(file.Name()) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: return err | |
| 41 | 新增: } | |
| 42 | 新增: to, err := windows.UTF16PtrFromString(path) | |
| 43 | 新增: if err != nil { | |
| 44 | 新增: return err | |
| 45 | 新增: } | |
| 46 | 新增: return windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH) | |
| 47 | 新增:} | |
| @@ -0,0 +1,12 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package hostimage | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func expandWindowsCatalog(context.Context, []byte) ([]byte, error) { | |
| 11 | 新增: return nil, errors.New("Windows 安装目录需要 Windows 的系统解压组件") | |
| 12 | 新增:} | |
| @@ -0,0 +1,42 @@ | ||
| 1 | 新增:package hostimage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "os" | |
| 7 | 新增: "os/exec" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "syscall" | |
| 10 | 新增: | |
| 11 | 新增: "golang.org/x/sys/windows" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func expandWindowsCatalog(ctx context.Context, data []byte) ([]byte, error) { | |
| 15 | 新增: directory, err := os.MkdirTemp("", "cage-system-catalog-") | |
| 16 | 新增: if err != nil { | |
| 17 | 新增: return nil, err | |
| 18 | 新增: } | |
| 19 | 新增: defer os.RemoveAll(directory) | |
| 20 | 新增: archive := filepath.Join(directory, "products.cab") | |
| 21 | 新增: if err = os.WriteFile(archive, data, 0600); err != nil { | |
| 22 | 新增: return nil, err | |
| 23 | 新增: } | |
| 24 | 新增: system, err := windows.GetSystemDirectory() | |
| 25 | 新增: if err != nil { | |
| 26 | 新增: return nil, err | |
| 27 | 新增: } | |
| 28 | 新增: command := exec.CommandContext(ctx, filepath.Join(system, "expand.exe"), "-F:products.xml", archive, directory) | |
| 29 | 新增: command.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW} | |
| 30 | 新增: if err = command.Run(); err != nil { | |
| 31 | 新增: return nil, err | |
| 32 | 新增: } | |
| 33 | 新增: path := filepath.Join(directory, "products.xml") | |
| 34 | 新增: info, err := os.Lstat(path) | |
| 35 | 新增: if err != nil { | |
| 36 | 新增: return nil, err | |
| 37 | 新增: } | |
| 38 | 新增: if !info.Mode().IsRegular() || info.Size() > 8<<20 { | |
| 39 | 新增: return nil, errors.New("微软安装目录文件无效") | |
| 40 | 新增: } | |
| 41 | 新增: return os.ReadFile(path) | |
| 42 | 新增:} | |
| @@ -0,0 +1,275 @@ | ||
| 1 | 新增:package hostimage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "crypto/sha256" | |
| 6 | 新增: "crypto/sha512" | |
| 7 | 新增: "encoding/hex" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "fmt" | |
| 10 | 新增: "hash" | |
| 11 | 新增: "io" | |
| 12 | 新增: "net/http" | |
| 13 | 新增: "os" | |
| 14 | 新增: "path/filepath" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "time" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:func digestHash(digest string) (hash.Hash, error) { | |
| 20 | 新增: kind, value, ok := strings.Cut(digest, ":") | |
| 21 | 新增: decoded, err := hex.DecodeString(value) | |
| 22 | 新增: if !ok || err != nil { | |
| 23 | 新增: return nil, errors.New("系统镜像摘要无效") | |
| 24 | 新增: } | |
| 25 | 新增: switch { | |
| 26 | 新增: case kind == "sha256" && len(decoded) == sha256.Size: | |
| 27 | 新增: return sha256.New(), nil | |
| 28 | 新增: case kind == "sha512" && len(decoded) == sha512.Size: | |
| 29 | 新增: return sha512.New(), nil | |
| 30 | 新增: default: | |
| 31 | 新增: return nil, errors.New("系统镜像摘要算法无效") | |
| 32 | 新增: } | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:type progressReader struct { | |
| 36 | 新增: ctx context.Context | |
| 37 | 新增: reader io.Reader | |
| 38 | 新增: out io.Writer | |
| 39 | 新增: received int64 | |
| 40 | 新增: total int64 | |
| 41 | 新增: activity string | |
| 42 | 新增: system string | |
| 43 | 新增: last time.Time | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:func (r *progressReader) Read(p []byte) (int, error) { | |
| 47 | 新增: if err := r.ctx.Err(); err != nil { | |
| 48 | 新增: return 0, err | |
| 49 | 新增: } | |
| 50 | 新增: n, err := r.reader.Read(p) | |
| 51 | 新增: r.received += int64(n) | |
| 52 | 新增: if time.Since(r.last) > 3*time.Second || err == io.EOF || (r.total > 0 && r.received >= r.total) { | |
| 53 | 新增: operation := "download" | |
| 54 | 新增: if r.activity == "校验系统材料" { | |
| 55 | 新增: operation = "verify" | |
| 56 | 新增: } | |
| 57 | 新增: fmt.Fprintf(r.out, "CAGE_GUEST_BYTES %s %s %d %d\n", r.system, operation, r.received, r.total) | |
| 58 | 新增: if r.total > 0 { | |
| 59 | 新增: fmt.Fprintf(r.out, "%s %.1f / %.1f MiB(%.0f%%)\n", r.activity, float64(r.received)/(1<<20), float64(r.total)/(1<<20), 100*float64(r.received)/float64(r.total)) | |
| 60 | 新增: } else { | |
| 61 | 新增: fmt.Fprintf(r.out, "%s %.1f MiB\n", r.activity, float64(r.received)/(1<<20)) | |
| 62 | 新增: } | |
| 63 | 新增: r.last = time.Now() | |
| 64 | 新增: } | |
| 65 | 新增: return n, err | |
| 66 | 新增:} | |
| 67 | 新增: | |
| 68 | 新增:func verify(ctx context.Context, path string, plan Plan, output io.Writer) (string, error) { | |
| 69 | 新增: file, err := os.Open(path) | |
| 70 | 新增: if err != nil { | |
| 71 | 新增: return "", err | |
| 72 | 新增: } | |
| 73 | 新增: defer file.Close() | |
| 74 | 新增: before, err := file.Stat() | |
| 75 | 新增: if err != nil { | |
| 76 | 新增: return "", err | |
| 77 | 新增: } | |
| 78 | 新增: if !before.Mode().IsRegular() || (plan.Bytes > 0 && before.Size() != plan.Bytes) || | |
| 79 | 新增: (plan.Modified != 0 && before.ModTime().UnixNano() != plan.Modified) { | |
| 80 | 新增: return "", errors.New("本机镜像在选择后发生变化,请重新检查") | |
| 81 | 新增: } | |
| 82 | 新增: digest := plan.Digest | |
| 83 | 新增: if digest == "" { | |
| 84 | 新增: digest = "sha256:" + strings.Repeat("0", 64) | |
| 85 | 新增: } | |
| 86 | 新增: hasher, err := digestHash(digest) | |
| 87 | 新增: if err != nil { | |
| 88 | 新增: return "", err | |
| 89 | 新增: } | |
| 90 | 新增: if _, err = io.Copy(hasher, &progressReader{ctx: ctx, reader: file, out: output, total: before.Size(), activity: "校验系统材料", system: plan.Host.System}); err != nil { | |
| 91 | 新增: return "", err | |
| 92 | 新增: } | |
| 93 | 新增: after, err := file.Stat() | |
| 94 | 新增: current, pathErr := os.Stat(path) | |
| 95 | 新增: if err != nil || pathErr != nil || !os.SameFile(before, current) || after.Size() != before.Size() || after.ModTime() != before.ModTime() { | |
| 96 | 新增: return "", errors.New("校验期间系统镜像发生变化,请重新检查") | |
| 97 | 新增: } | |
| 98 | 新增: actual := strings.SplitN(digest, ":", 2)[0] + ":" + hex.EncodeToString(hasher.Sum(nil)) | |
| 99 | 新增: if plan.Digest != "" && actual != plan.Digest { | |
| 100 | 新增: return "", errors.New("系统镜像摘要不匹配,请重新选择或重新下载") | |
| 101 | 新增: } | |
| 102 | 新增: if plan.Format == "ipsw" { | |
| 103 | 新增: version, build, err := macImageIdentity(path) | |
| 104 | 新增: if err != nil || version != plan.Version || build != plan.Build { | |
| 105 | 新增: return "", errors.New("恢复镜像内容与已选择的 macOS 版本不一致") | |
| 106 | 新增: } | |
| 107 | 新增: } | |
| 108 | 新增: return actual, nil | |
| 109 | 新增:} | |
| 110 | 新增: | |
| 111 | 新增:// Prepare verifies existing media or resumes the exact pinned download. Only a | |
| 112 | 新增:// verified complete archive is published. Interruptions retain the partial file. | |
| 113 | 新增:func Prepare(ctx context.Context, cache string, plan Plan, output io.Writer, transport http.RoundTripper) (Plan, error) { | |
| 114 | 新增: if err := plan.Validate(); err != nil { | |
| 115 | 新增: return Plan{}, err | |
| 116 | 新增: } | |
| 117 | 新增: if output == nil { | |
| 118 | 新增: output = io.Discard | |
| 119 | 新增: } | |
| 120 | 新增: if plan.Path != "" { | |
| 121 | 新增: fmt.Fprintln(output, "正在校验系统镜像…") | |
| 122 | 新增: digest, err := verify(ctx, plan.Path, plan, output) | |
| 123 | 新增: if err != nil { | |
| 124 | 新增: return Plan{}, err | |
| 125 | 新增: } | |
| 126 | 新增: plan.Digest = digest | |
| 127 | 新增: info, err := os.Stat(plan.Path) | |
| 128 | 新增: if err != nil { | |
| 129 | 新增: return Plan{}, err | |
| 130 | 新增: } | |
| 131 | 新增: plan.Bytes, plan.Modified = info.Size(), info.ModTime().UnixNano() | |
| 132 | 新增: return plan, Save(cache, plan) | |
| 133 | 新增: } | |
| 134 | 新增: if err := os.MkdirAll(cache, 0700); err != nil { | |
| 135 | 新增: return Plan{}, err | |
| 136 | 新增: } | |
| 137 | 新增: root, err := os.OpenRoot(cache) | |
| 138 | 新增: if err != nil { | |
| 139 | 新增: return Plan{}, err | |
| 140 | 新增: } | |
| 141 | 新增: defer root.Close() | |
| 142 | 新增: final := filepath.Base(plan.CachedPath(cache)) | |
| 143 | 新增: if info, err := root.Lstat(final + ".lock"); err == nil && !info.Mode().IsRegular() { | |
| 144 | 新增: return Plan{}, errors.New("系统下载锁路径无效") | |
| 145 | 新增: } | |
| 146 | 新增: lock, err := root.OpenFile(final+".lock", os.O_CREATE|os.O_RDWR, 0600) | |
| 147 | 新增: if err != nil { | |
| 148 | 新增: return Plan{}, err | |
| 149 | 新增: } | |
| 150 | 新增: defer lock.Close() | |
| 151 | 新增: if err := lockDownload(lock); err != nil { | |
| 152 | 新增: return Plan{}, fmt.Errorf("另一项安装正在准备这份系统镜像,请等待它完成后继续:%w", err) | |
| 153 | 新增: } | |
| 154 | 新增: if info, err := root.Lstat(final); err == nil { | |
| 155 | 新增: if !info.Mode().IsRegular() { | |
| 156 | 新增: return Plan{}, errors.New("系统材料缓存路径无效") | |
| 157 | 新增: } | |
| 158 | 新增: plan.Path, plan.Modified = filepath.Join(cache, final), info.ModTime().UnixNano() | |
| 159 | 新增: return Prepare(ctx, cache, plan, output, transport) | |
| 160 | 新增: } else if !errors.Is(err, os.ErrNotExist) { | |
| 161 | 新增: return Plan{}, err | |
| 162 | 新增: } | |
| 163 | 新增: partial := final + ".partial" | |
| 164 | 新增: if info, err := root.Lstat(partial); err == nil && !info.Mode().IsRegular() { | |
| 165 | 新增: return Plan{}, errors.New("未完成的系统下载路径无效") | |
| 166 | 新增: } | |
| 167 | 新增: file, err := root.OpenFile(partial, os.O_CREATE|os.O_RDWR, 0600) | |
| 168 | 新增: if err != nil { | |
| 169 | 新增: return Plan{}, err | |
| 170 | 新增: } | |
| 171 | 新增: defer func() { _ = file.Close() }() | |
| 172 | 新增: info, err := file.Stat() | |
| 173 | 新增: if err != nil { | |
| 174 | 新增: return Plan{}, err | |
| 175 | 新增: } | |
| 176 | 新增: offset := info.Size() | |
| 177 | 新增: if plan.Bytes > 0 && offset > plan.Bytes { | |
| 178 | 新增: if err = file.Close(); err != nil { | |
| 179 | 新增: return Plan{}, err | |
| 180 | 新增: } | |
| 181 | 新增: if err = root.Rename(partial, partial+".invalid-"+time.Now().UTC().Format("20060102T150405.000000000")); err != nil { | |
| 182 | 新增: return Plan{}, err | |
| 183 | 新增: } | |
| 184 | 新增: file, err = root.OpenFile(partial, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) | |
| 185 | 新增: if err != nil { | |
| 186 | 新增: return Plan{}, err | |
| 187 | 新增: } | |
| 188 | 新增: offset = 0 | |
| 189 | 新增: fmt.Fprintln(output, "已保留大小异常的未完成文件,重新下载所选系统材料…") | |
| 190 | 新增: } | |
| 191 | 新增: if offset != plan.Bytes || plan.Bytes == 0 { | |
| 192 | 新增: fmt.Fprintf(output, "正在下载 %s %s 的系统材料,已保留 %.1f MiB…\n", plan.Host.System, plan.Version, float64(offset)/(1<<20)) | |
| 193 | 新增: err = download(ctx, plan, file, offset, output, transport) | |
| 194 | 新增: if err != nil { | |
| 195 | 新增: return Plan{}, fmt.Errorf("系统下载中断,已保留进度,可继续安装:%w", err) | |
| 196 | 新增: } | |
| 197 | 新增: } | |
| 198 | 新增: if err = file.Sync(); err != nil { | |
| 199 | 新增: return Plan{}, err | |
| 200 | 新增: } | |
| 201 | 新增: if err = file.Close(); err != nil { | |
| 202 | 新增: return Plan{}, err | |
| 203 | 新增: } | |
| 204 | 新增: if _, err = verify(ctx, filepath.Join(cache, partial), plan, output); err != nil { | |
| 205 | 新增: // Preserve the failed download for diagnosis. A new attempt can resume | |
| 206 | 新增: // into a new partial file, without reusing corrupt bytes. | |
| 207 | 新增: if ctx.Err() == nil { | |
| 208 | 新增: _ = root.Rename(partial, partial+".invalid-"+time.Now().UTC().Format("20060102T150405.000000000")) | |
| 209 | 新增: } | |
| 210 | 新增: return Plan{}, err | |
| 211 | 新增: } | |
| 212 | 新增: if err = root.Rename(partial, final); err != nil { | |
| 213 | 新增: return Plan{}, err | |
| 214 | 新增: } | |
| 215 | 新增: info, err = root.Stat(final) | |
| 216 | 新增: if err != nil { | |
| 217 | 新增: return Plan{}, err | |
| 218 | 新增: } | |
| 219 | 新增: plan.Path, plan.Modified, plan.Bytes = filepath.Join(cache, final), info.ModTime().UnixNano(), info.Size() | |
| 220 | 新增: return plan, Save(cache, plan) | |
| 221 | 新增:} | |
| 222 | 新增: | |
| 223 | 新增:func download(ctx context.Context, plan Plan, file *os.File, offset int64, output io.Writer, transport http.RoundTripper) error { | |
| 224 | 新增: client := &http.Client{Transport: transport, Timeout: 2 * time.Hour, CheckRedirect: func(request *http.Request, previous []*http.Request) error { | |
| 225 | 新增: if len(previous) >= 5 { | |
| 226 | 新增: return errors.New("系统下载重定向次数过多") | |
| 227 | 新增: } | |
| 228 | 新增: return trustedURL(request.URL.String(), plan.Host.System) | |
| 229 | 新增: }} | |
| 230 | 新增: defer client.CloseIdleConnections() | |
| 231 | 新增: request, err := http.NewRequestWithContext(ctx, http.MethodGet, plan.URL, nil) | |
| 232 | 新增: if err != nil { | |
| 233 | 新增: return err | |
| 234 | 新增: } | |
| 235 | 新增: request.Header.Set("Accept-Encoding", "identity") | |
| 236 | 新增: request.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Cage-SystemInstaller/1.0)") | |
| 237 | 新增: if offset > 0 { | |
| 238 | 新增: request.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) | |
| 239 | 新增: } | |
| 240 | 新增: response, err := client.Do(request) | |
| 241 | 新增: if err != nil { | |
| 242 | 新增: return err | |
| 243 | 新增: } | |
| 244 | 新增: defer response.Body.Close() | |
| 245 | 新增: switch response.StatusCode { | |
| 246 | 新增: case http.StatusOK: | |
| 247 | 新增: offset = 0 | |
| 248 | 新增: if err = file.Truncate(0); err != nil { | |
| 249 | 新增: return err | |
| 250 | 新增: } | |
| 251 | 新增: case http.StatusPartialContent: | |
| 252 | 新增: var start, end, total int64 | |
| 253 | 新增: if _, err = fmt.Sscanf(response.Header.Get("Content-Range"), "bytes %d-%d/%d", &start, &end, &total); err != nil || | |
| 254 | 新增: start != offset || end < start || (plan.Bytes > 0 && total != plan.Bytes) { | |
| 255 | 新增: return errors.New("服务器返回的续传范围与原镜像不一致") | |
| 256 | 新增: } | |
| 257 | 新增: default: | |
| 258 | 新增: return fmt.Errorf("系统下载返回 HTTP %d", response.StatusCode) | |
| 259 | 新增: } | |
| 260 | 新增: if _, err = file.Seek(offset, io.SeekStart); err != nil { | |
| 261 | 新增: return err | |
| 262 | 新增: } | |
| 263 | 新增: limit := int64(64 << 30) | |
| 264 | 新增: if plan.Bytes > 0 { | |
| 265 | 新增: limit = plan.Bytes | |
| 266 | 新增: } | |
| 267 | 新增: count, err := io.Copy(file, &progressReader{ctx: ctx, reader: io.LimitReader(response.Body, limit-offset+1), out: output, received: offset, total: plan.Bytes, activity: "下载系统材料", system: plan.Host.System}) | |
| 268 | 新增: if err != nil { | |
| 269 | 新增: return err | |
| 270 | 新增: } | |
| 271 | 新增: if offset+count > limit || (plan.Bytes > 0 && offset+count != plan.Bytes) { | |
| 272 | 新增: return errors.New("下载的系统材料大小不匹配") | |
| 273 | 新增: } | |
| 274 | 新增: return nil | |
| 275 | 新增:} | |
| @@ -0,0 +1,69 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package hostimage | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "os" | |
| 9 | 新增: "os/exec" | |
| 10 | 新增: "runtime" | |
| 11 | 新增: "strconv" | |
| 12 | 新增: "strings" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:func Host(ctx context.Context) (Identity, error) { | |
| 16 | 新增: if runtime.GOOS == "darwin" { | |
| 17 | 新增: output, err := exec.CommandContext(ctx, "/usr/bin/sw_vers").Output() | |
| 18 | 新增: if err != nil { | |
| 19 | 新增: return Identity{}, err | |
| 20 | 新增: } | |
| 21 | 新增: identity := Identity{System: "macos", Arch: runtime.GOARCH} | |
| 22 | 新增: for _, line := range strings.Split(string(output), "\n") { | |
| 23 | 新增: key, value, _ := strings.Cut(line, ":") | |
| 24 | 新增: switch key { | |
| 25 | 新增: case "ProductVersion": | |
| 26 | 新增: identity.Version = strings.TrimSpace(value) | |
| 27 | 新增: case "BuildVersion": | |
| 28 | 新增: identity.Build = strings.TrimSpace(value) | |
| 29 | 新增: } | |
| 30 | 新增: } | |
| 31 | 新增: return identity, nil | |
| 32 | 新增: } | |
| 33 | 新增: data, err := os.ReadFile("/etc/os-release") | |
| 34 | 新增: if err != nil { | |
| 35 | 新增: return Identity{}, err | |
| 36 | 新增: } | |
| 37 | 新增: return linuxIdentity(string(data)) | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:func linuxIdentity(data string) (Identity, error) { | |
| 41 | 新增: values := make(map[string]string) | |
| 42 | 新增: for _, line := range strings.Split(data, "\n") { | |
| 43 | 新增: key, value, ok := strings.Cut(line, "=") | |
| 44 | 新增: if !ok { | |
| 45 | 新增: continue | |
| 46 | 新增: } | |
| 47 | 新增: if strings.HasPrefix(value, `"`) { | |
| 48 | 新增: unquoted, err := strconv.Unquote(value) | |
| 49 | 新增: if err != nil { | |
| 50 | 新增: return Identity{}, err | |
| 51 | 新增: } | |
| 52 | 新增: value = unquoted | |
| 53 | 新增: } else { | |
| 54 | 新增: value = strings.Trim(value, "'") | |
| 55 | 新增: } | |
| 56 | 新增: values[key] = value | |
| 57 | 新增: } | |
| 58 | 新增: version := values["VERSION_ID"] | |
| 59 | 新增: if values["ID"] == "debian" { | |
| 60 | 新增: version = strings.SplitN(version, ".", 2)[0] | |
| 61 | 新增: } | |
| 62 | 新增: identity := Identity{System: values["ID"] + "-" + version, Version: version, Arch: runtime.GOARCH} | |
| 63 | 新增: switch identity.System { | |
| 64 | 新增: case "debian-12", "debian-13", "ubuntu-22.04", "ubuntu-24.04": | |
| 65 | 新增: return identity, nil | |
| 66 | 新增: default: | |
| 67 | 新增: return Identity{}, fmt.Errorf("当前尚未适配 %s 的本机系统创建,仍可选择 Debian 13", values["PRETTY_NAME"]) | |
| 68 | 新增: } | |
| 69 | 新增:} | |
| @@ -0,0 +1,12 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package hostimage | |
| 4 | 新增: | |
| 5 | 新增:import "testing" | |
| 6 | 新增: | |
| 7 | 新增:func TestUbuntu2204HostIdentity(t *testing.T) { | |
| 8 | 新增: identity, err := linuxIdentity("ID=ubuntu\nVERSION_ID=\"22.04\"\nPRETTY_NAME=\"Ubuntu 22.04.5 LTS\"\n") | |
| 9 | 新增: if err != nil || identity.System != "ubuntu-22.04" || identity.Version != "22.04" { | |
| 10 | 新增: t.Fatalf("identity: %+v %v", identity, err) | |
| 11 | 新增: } | |
| 12 | 新增:} | |
| @@ -0,0 +1,71 @@ | ||
| 1 | 新增:package hostimage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "fmt" | |
| 6 | 新增: "runtime" | |
| 7 | 新增: "strconv" | |
| 8 | 新增: "strings" | |
| 9 | 新增: | |
| 10 | 新增: "golang.org/x/sys/windows/registry" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func Host(ctx context.Context) (Identity, error) { | |
| 14 | 新增: if err := ctx.Err(); err != nil { | |
| 15 | 新增: return Identity{}, err | |
| 16 | 新增: } | |
| 17 | 新增: key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE) | |
| 18 | 新增: if err != nil { | |
| 19 | 新增: return Identity{}, err | |
| 20 | 新增: } | |
| 21 | 新增: defer key.Close() | |
| 22 | 新增: version, _, err := key.GetStringValue("DisplayVersion") | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: return Identity{}, err | |
| 25 | 新增: } | |
| 26 | 新增: build, _, err := key.GetStringValue("CurrentBuildNumber") | |
| 27 | 新增: if err != nil { | |
| 28 | 新增: return Identity{}, err | |
| 29 | 新增: } | |
| 30 | 新增: major, err := strconv.Atoi(build) | |
| 31 | 新增: if err != nil || major < 22000 { | |
| 32 | 新增: return Identity{}, fmt.Errorf("本机系统创建需要 Windows 11") | |
| 33 | 新增: } | |
| 34 | 新增: revision, _, err := key.GetIntegerValue("UBR") | |
| 35 | 新增: if err != nil { | |
| 36 | 新增: return Identity{}, err | |
| 37 | 新增: } | |
| 38 | 新增: edition, _, err := key.GetStringValue("EditionID") | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: return Identity{}, err | |
| 41 | 新增: } | |
| 42 | 新增: languageKey, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control\MUI\UILanguages`, registry.READ) | |
| 43 | 新增: if err != nil { | |
| 44 | 新增: return Identity{}, err | |
| 45 | 新增: } | |
| 46 | 新增: defer languageKey.Close() | |
| 47 | 新增: languages, err := languageKey.ReadSubKeyNames(-1) | |
| 48 | 新增: if err != nil || len(languages) == 0 { | |
| 49 | 新增: return Identity{}, fmt.Errorf("无法读取 Windows 安装语言") | |
| 50 | 新增: } | |
| 51 | 新增: // InstallLanguage is the base UI language. On multilingual installations, | |
| 52 | 新增: // prefer the installed-language key matching the system locale. | |
| 53 | 新增: locale, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control\Nls\Language`, registry.QUERY_VALUE) | |
| 54 | 新增: if err == nil { | |
| 55 | 新增: defer locale.Close() | |
| 56 | 新增: code, _, _ := locale.GetStringValue("InstallLanguage") | |
| 57 | 新增: for _, language := range languages { | |
| 58 | 新增: candidate, openErr := registry.OpenKey(languageKey, language, registry.QUERY_VALUE) | |
| 59 | 新增: if openErr != nil { | |
| 60 | 新增: continue | |
| 61 | 新增: } | |
| 62 | 新增: lcid, _, _ := candidate.GetIntegerValue("LCID") | |
| 63 | 新增: candidate.Close() | |
| 64 | 新增: if strings.EqualFold(fmt.Sprintf("%04x", lcid), code) { | |
| 65 | 新增: languages[0] = language | |
| 66 | 新增: break | |
| 67 | 新增: } | |
| 68 | 新增: } | |
| 69 | 新增: } | |
| 70 | 新增: return Identity{System: "windows-11", Version: version, Build: fmt.Sprintf("%s.%d", build, revision), Edition: edition, Language: languages[0], Arch: runtime.GOARCH}, nil | |
| 71 | 新增:} | |
| @@ -0,0 +1,122 @@ | ||
| 1 | 新增:package hostimage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func linuxTemplateData(plan Plan) ([]byte, error) { | |
| 11 | 新增: // These supported cloud images need no distribution-specific template | |
| 12 | 新增: // settings. Keep one pinned local image, with no network image fallback. | |
| 13 | 新增: value := map[string]any{ | |
| 14 | 新增: "minimumLimaVersion": "2.0.0", | |
| 15 | 新增: "images": []map[string]string{{"location": plan.Path, "arch": map[string]string{"amd64": "x86_64", "arm64": "aarch64"}[plan.Host.Arch], "digest": plan.Digest}}, | |
| 16 | 新增: } | |
| 17 | 新增: return json.Marshal(value) | |
| 18 | 新增:} | |
| 19 | 新增: | |
| 20 | 新增:func WriteLinuxTemplate(state string, plan Plan) error { | |
| 21 | 新增: if err := plan.Validate(); err != nil { | |
| 22 | 新增: return err | |
| 23 | 新增: } | |
| 24 | 新增: if !IsLinux(plan.Host.System) || plan.Path == "" || plan.Digest == "" { | |
| 25 | 新增: return errors.New("Linux 系统材料尚未准备好") | |
| 26 | 新增: } | |
| 27 | 新增: data, err := linuxTemplateData(plan) | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: return err | |
| 30 | 新增: } | |
| 31 | 新增: dir := filepath.Join(state, "guest-media") | |
| 32 | 新增: if err = os.MkdirAll(dir, 0700); err != nil { | |
| 33 | 新增: return err | |
| 34 | 新增: } | |
| 35 | 新增: path := filepath.Join(dir, "host-system.yaml") | |
| 36 | 新增: if current, err := os.ReadFile(path); err == nil { | |
| 37 | 新增: if string(current) != string(data) { | |
| 38 | 新增: return errors.New("Linux 安装已绑定另一份系统材料") | |
| 39 | 新增: } | |
| 40 | 新增: return Save(dir, plan) | |
| 41 | 新增: } else if !errors.Is(err, os.ErrNotExist) { | |
| 42 | 新增: return err | |
| 43 | 新增: } | |
| 44 | 新增: file, err := os.CreateTemp(dir, ".host-system-*.yaml") | |
| 45 | 新增: if err != nil { | |
| 46 | 新增: return err | |
| 47 | 新增: } | |
| 48 | 新增: defer os.Remove(file.Name()) | |
| 49 | 新增: _, err = file.Write(data) | |
| 50 | 新增: if err = errors.Join(err, file.Close()); err != nil { | |
| 51 | 新增: return err | |
| 52 | 新增: } | |
| 53 | 新增: if err = os.Rename(file.Name(), path); err != nil { | |
| 54 | 新增: return err | |
| 55 | 新增: } | |
| 56 | 新增: return Save(dir, plan) | |
| 57 | 新增:} | |
| 58 | 新增: | |
| 59 | 新增:// ClearLinuxTemplate releases an unstarted choice while retaining its media. | |
| 60 | 新增:func ClearLinuxTemplate(state string, plan Plan) error { | |
| 61 | 新增: dir := filepath.Join(state, "guest-media") | |
| 62 | 新增: path := filepath.Join(dir, "host-system.yaml") | |
| 63 | 新增: data, err := os.ReadFile(path) | |
| 64 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 65 | 新增: return nil | |
| 66 | 新增: } | |
| 67 | 新增: if err != nil { | |
| 68 | 新增: return err | |
| 69 | 新增: } | |
| 70 | 新增: expected, err := linuxTemplateData(plan) | |
| 71 | 新增: if err != nil || string(expected) != string(data) { | |
| 72 | 新增: return errors.New("本机系统模板归属已变化") | |
| 73 | 新增: } | |
| 74 | 新增: if err := os.Remove(path); err != nil { | |
| 75 | 新增: return err | |
| 76 | 新增: } | |
| 77 | 新增: if err := os.Remove(filepath.Join(dir, sourceRecord)); !errors.Is(err, os.ErrNotExist) { | |
| 78 | 新增: return err | |
| 79 | 新增: } | |
| 80 | 新增: return nil | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:func LinuxTemplate(state string) (string, error) { | |
| 84 | 新增: path := filepath.Join(state, "guest-media", "host-system.yaml") | |
| 85 | 新增: info, err := os.Lstat(path) | |
| 86 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 87 | 新增: if _, recordErr := os.Lstat(filepath.Join(state, "guest-media", sourceRecord)); !errors.Is(recordErr, os.ErrNotExist) { | |
| 88 | 新增: return "", errors.New("所选 Linux 系统的安装模板缺失,请恢复原环境资料;不会改用其他系统") | |
| 89 | 新增: } | |
| 90 | 新增: return "template:debian-13", nil | |
| 91 | 新增: } | |
| 92 | 新增: if err != nil { | |
| 93 | 新增: return "", err | |
| 94 | 新增: } | |
| 95 | 新增: if !info.Mode().IsRegular() || info.Size() > 32<<10 { | |
| 96 | 新增: return "", errors.New("本机系统安装模板无效") | |
| 97 | 新增: } | |
| 98 | 新增: plan, err := Load(filepath.Join(state, "guest-media")) | |
| 99 | 新增: if err != nil || !IsLinux(plan.Host.System) { | |
| 100 | 新增: return "", errors.New("所选 Linux 系统来源记录无效,请恢复原环境资料") | |
| 101 | 新增: } | |
| 102 | 新增: expected, err := linuxTemplateData(plan) | |
| 103 | 新增: data, readErr := os.ReadFile(path) | |
| 104 | 新增: if err != nil || readErr != nil || string(data) != string(expected) { | |
| 105 | 新增: return "", errors.New("所选 Linux 系统的模板与来源不一致,请核对原环境资料") | |
| 106 | 新增: } | |
| 107 | 新增: return path, nil | |
| 108 | 新增:} | |
| 109 | 新增: | |
| 110 | 新增:// LinuxSystem reads the durable image choice, including after installation | |
| 111 | 新增:// has finished and its temporary installation record has been removed. | |
| 112 | 新增:func LinuxSystem(state string) (string, error) { | |
| 113 | 新增: path, err := LinuxTemplate(state) | |
| 114 | 新增: if err != nil { | |
| 115 | 新增: return "", err | |
| 116 | 新增: } | |
| 117 | 新增: if path == "template:debian-13" { | |
| 118 | 新增: return "debian-13", nil | |
| 119 | 新增: } | |
| 120 | 新增: plan, err := Load(filepath.Join(state, "guest-media")) | |
| 121 | 新增: return plan.Host.System, err | |
| 122 | 新增:} | |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package hostimage | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "os" | |
| 7 | 新增: | |
| 8 | 新增: "golang.org/x/sys/unix" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func lockDownload(file *os.File) error { | |
| 12 | 新增: return unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB) | |
| 13 | 新增:} | |
| @@ -0,0 +1,11 @@ | ||
| 1 | 新增:package hostimage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: | |
| 6 | 新增: "golang.org/x/sys/windows" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func lockDownload(file *os.File) error { | |
| 10 | 新增: return windows.LockFileEx(windows.Handle(file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, new(windows.Overlapped)) | |
| 11 | 新增:} | |
| @@ -0,0 +1,86 @@ | ||
| 1 | 新增:package hostimage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "archive/zip" | |
| 5 | 新增: "encoding/xml" | |
| 6 | 新增: "io" | |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "strings" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func localMacImage(host Identity, directories ...string) (Plan, bool) { | |
| 13 | 新增: for _, directory := range directories { | |
| 14 | 新增: entries, err := os.ReadDir(directory) | |
| 15 | 新增: if err != nil { | |
| 16 | 新增: continue | |
| 17 | 新增: } | |
| 18 | 新增: for _, entry := range entries { | |
| 19 | 新增: if !strings.EqualFold(filepath.Ext(entry.Name()), ".ipsw") || entry.Type()&os.ModeSymlink != 0 { | |
| 20 | 新增: continue | |
| 21 | 新增: } | |
| 22 | 新增: path := filepath.Join(directory, entry.Name()) | |
| 23 | 新增: info, err := entry.Info() | |
| 24 | 新增: if err != nil || !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > 64<<30 { | |
| 25 | 新增: continue | |
| 26 | 新增: } | |
| 27 | 新增: version, build, err := macImageIdentity(path) | |
| 28 | 新增: if err != nil || version != host.Version || build != host.Build { | |
| 29 | 新增: continue | |
| 30 | 新增: } | |
| 31 | 新增: return Plan{Host: host, Version: version, Build: build, Format: "ipsw", Bytes: info.Size(), Path: path, Modified: info.ModTime().UnixNano()}, true | |
| 32 | 新增: } | |
| 33 | 新增: } | |
| 34 | 新增: return Plan{}, false | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:func macImageIdentity(path string) (string, string, error) { | |
| 38 | 新增: archive, err := zip.OpenReader(path) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: return "", "", err | |
| 41 | 新增: } | |
| 42 | 新增: defer archive.Close() | |
| 43 | 新增: manifest, err := archive.Open("BuildManifest.plist") | |
| 44 | 新增: if err != nil { | |
| 45 | 新增: return "", "", err | |
| 46 | 新增: } | |
| 47 | 新增: defer manifest.Close() | |
| 48 | 新增: // Apple's universal archives list many hardware variants before the root | |
| 49 | 新增: // version fields. The macOS 26.5 manifest alone is over 25 MiB. | |
| 50 | 新增: decoder := xml.NewDecoder(io.LimitReader(manifest, 128<<20)) | |
| 51 | 新增: depth := 0 | |
| 52 | 新增: var key, version, build string | |
| 53 | 新增: for { | |
| 54 | 新增: token, err := decoder.Token() | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: return version, build, err | |
| 57 | 新增: } | |
| 58 | 新增: switch element := token.(type) { | |
| 59 | 新增: case xml.StartElement: | |
| 60 | 新增: depth++ | |
| 61 | 新增: if depth == 3 && element.Name.Local == "key" { | |
| 62 | 新增: if err = decoder.DecodeElement(&key, &element); err != nil { | |
| 63 | 新增: return "", "", err | |
| 64 | 新增: } | |
| 65 | 新增: depth-- | |
| 66 | 新增: } else if depth == 3 && element.Name.Local == "string" { | |
| 67 | 新增: var value string | |
| 68 | 新增: if err = decoder.DecodeElement(&value, &element); err != nil { | |
| 69 | 新增: return "", "", err | |
| 70 | 新增: } | |
| 71 | 新增: depth-- | |
| 72 | 新增: switch key { | |
| 73 | 新增: case "ProductVersion": | |
| 74 | 新增: version = value | |
| 75 | 新增: case "ProductBuildVersion": | |
| 76 | 新增: build = value | |
| 77 | 新增: } | |
| 78 | 新增: if version != "" && build != "" { | |
| 79 | 新增: return version, build, nil | |
| 80 | 新增: } | |
| 81 | 新增: } | |
| 82 | 新增: case xml.EndElement: | |
| 83 | 新增: depth-- | |
| 84 | 新增: } | |
| 85 | 新增: } | |
| 86 | 新增:} | |
| @@ -0,0 +1,361 @@ | ||
| 1 | 新增:// Package hostimage prepares clean installation media matching the host OS. | |
| 2 | 新增:// It reads OS identity and installation media without copying personal data. | |
| 3 | 新增:package hostimage | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "crypto/sha256" | |
| 8 | 新增: "encoding/hex" | |
| 9 | 新增: "encoding/json" | |
| 10 | 新增: "encoding/xml" | |
| 11 | 新增: "errors" | |
| 12 | 新增: "fmt" | |
| 13 | 新增: "io" | |
| 14 | 新增: "net/http" | |
| 15 | 新增: "net/url" | |
| 16 | 新增: "os" | |
| 17 | 新增: "path/filepath" | |
| 18 | 新增: "regexp" | |
| 19 | 新增: "strings" | |
| 20 | 新增: "time" | |
| 21 | 新增: | |
| 22 | 新增: "go.yaml.in/yaml/v3" | |
| 23 | 新增: "golang.org/x/mod/semver" | |
| 24 | 新增:) | |
| 25 | 新增: | |
| 26 | 新增:type Identity struct { | |
| 27 | 新增: System string `json:"system"` | |
| 28 | 新增: Version string `json:"version"` | |
| 29 | 新增: Build string `json:"build,omitempty"` | |
| 30 | 新增: Edition string `json:"edition,omitempty"` | |
| 31 | 新增: Language string `json:"language,omitempty"` | |
| 32 | 新增: Arch string `json:"arch"` | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:func IsLinux(system string) bool { | |
| 36 | 新增: return system == "debian-12" || system == "debian-13" || system == "ubuntu-22.04" || system == "ubuntu-24.04" | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:// Plan is immutable after the user chooses it. Path refers only to source | |
| 40 | 新增:// media. Download destinations are derived independently from its digest. | |
| 41 | 新增:type Plan struct { | |
| 42 | 新增: Host Identity `json:"host"` | |
| 43 | 新增: Version string `json:"version"` | |
| 44 | 新增: Build string `json:"build,omitempty"` | |
| 45 | 新增: Format string `json:"format"` | |
| 46 | 新增: URL string `json:"url,omitempty"` | |
| 47 | 新增: Digest string `json:"digest,omitempty"` | |
| 48 | 新增: Bytes int64 `json:"bytes"` | |
| 49 | 新增: Path string `json:"path,omitempty"` | |
| 50 | 新增: Modified int64 `json:"modified,omitempty"` | |
| 51 | 新增:} | |
| 52 | 新增: | |
| 53 | 新增:func (p Plan) Key() string { | |
| 54 | 新增: if p.URL != "" && p.Digest != "" { | |
| 55 | 新增: p.Path, p.Modified = "", 0 | |
| 56 | 新增: } | |
| 57 | 新增: data, _ := json.Marshal(p) | |
| 58 | 新增: digest := sha256.Sum256(data) | |
| 59 | 新增: return hex.EncodeToString(digest[:]) | |
| 60 | 新增:} | |
| 61 | 新增: | |
| 62 | 新增:func (p Plan) Validate() error { | |
| 63 | 新增: if p.Host.Arch != "arm64" && p.Host.Arch != "amd64" { | |
| 64 | 新增: return errors.New("本机系统架构暂不支持创建客机") | |
| 65 | 新增: } | |
| 66 | 新增: if p.Version == "" || p.Version != p.Host.Version || p.Bytes < 0 || p.Bytes > 64<<30 { | |
| 67 | 新增: return errors.New("系统镜像与本机版本不匹配") | |
| 68 | 新增: } | |
| 69 | 新增: switch p.Host.System { | |
| 70 | 新增: case "macos": | |
| 71 | 新增: if p.Format != "ipsw" || p.Build != p.Host.Build || p.Host.Arch != "arm64" { | |
| 72 | 新增: return errors.New("macOS 恢复镜像与本机版本不匹配") | |
| 73 | 新增: } | |
| 74 | 新增: if !semver.IsValid("v"+p.Version) || semver.Compare("v"+p.Version, "v26.4") < 0 { | |
| 75 | 新增: return errors.New("自动匹配 macOS 镜像需要本机运行 macOS 26.4 或更新版本,以支持当前工作台使用的 FSKit 只读挂载") | |
| 76 | 新增: } | |
| 77 | 新增: case "windows-11": | |
| 78 | 新增: if p.Format != "esd" || p.Host.Arch != "amd64" || p.Host.Edition == "" || p.Host.Language == "" || p.Build == "" { | |
| 79 | 新增: return errors.New("Windows 安装镜像信息不完整") | |
| 80 | 新增: } | |
| 81 | 新增: case "debian-12", "debian-13", "ubuntu-22.04", "ubuntu-24.04": | |
| 82 | 新增: if p.Format != "qcow2" { | |
| 83 | 新增: return errors.New("Linux 安装镜像与本机不匹配") | |
| 84 | 新增: } | |
| 85 | 新增: default: | |
| 86 | 新增: return errors.New("当前支持的本机系统为 macOS、Windows 11、Debian 12/13 和 Ubuntu 22.04/24.04") | |
| 87 | 新增: } | |
| 88 | 新增: if p.Path != "" && (!filepath.IsAbs(p.Path) || filepath.Clean(p.Path) != p.Path || strings.ContainsAny(p.Path, "\r\n\x00")) { | |
| 89 | 新增: return errors.New("本机系统镜像路径无效") | |
| 90 | 新增: } | |
| 91 | 新增: if p.URL != "" { | |
| 92 | 新增: if err := trustedURL(p.URL, p.Host.System); err != nil { | |
| 93 | 新增: return err | |
| 94 | 新增: } | |
| 95 | 新增: if _, err := digestHash(p.Digest); err != nil { | |
| 96 | 新增: return err | |
| 97 | 新增: } | |
| 98 | 新增: } | |
| 99 | 新增: if p.Path == "" && p.URL == "" { | |
| 100 | 新增: return errors.New("缺少系统安装材料") | |
| 101 | 新增: } | |
| 102 | 新增: return nil | |
| 103 | 新增:} | |
| 104 | 新增: | |
| 105 | 新增:func trustedURL(raw, system string) error { | |
| 106 | 新增: u, err := url.Parse(raw) | |
| 107 | 新增: if err != nil || u.User != nil || u.Port() != "" || u.Fragment != "" { | |
| 108 | 新增: return errors.New("系统材料下载地址无效") | |
| 109 | 新增: } | |
| 110 | 新增: // Microsoft's HTTPS catalog publishes ESDs on this HTTP-only CDN route. | |
| 111 | 新增: // Its pinned SHA-256 is mandatory and verified before any image is applied. | |
| 112 | 新增: microsoftESD := system == "windows-11" && u.Scheme == "http" && u.Hostname() == "dl.delivery.mp.microsoft.com" | |
| 113 | 新增: if u.Scheme != "https" && !microsoftESD { | |
| 114 | 新增: return errors.New("系统材料下载协议无效") | |
| 115 | 新增: } | |
| 116 | 新增: allowed := map[string][]string{ | |
| 117 | 新增: "macos": {"updates.cdn-apple.com", "appldnld.apple.com"}, | |
| 118 | 新增: "windows-11": {"dl.delivery.mp.microsoft.com", "download.microsoft.com", "software.download.prss.microsoft.com"}, | |
| 119 | 新增: "debian-12": {"cloud.debian.org"}, "debian-13": {"cloud.debian.org"}, | |
| 120 | 新增: "ubuntu-22.04": {"cloud-images.ubuntu.com"}, | |
| 121 | 新增: "ubuntu-24.04": {"cloud-images.ubuntu.com"}, | |
| 122 | 新增: } | |
| 123 | 新增: for _, domain := range allowed[system] { | |
| 124 | 新增: if u.Hostname() == domain { | |
| 125 | 新增: return nil | |
| 126 | 新增: } | |
| 127 | 新增: } | |
| 128 | 新增: return errors.New("系统材料下载地址不属于受支持的系统厂商") | |
| 129 | 新增:} | |
| 130 | 新增: | |
| 131 | 新增:func metadata(ctx context.Context, client *http.Client, address string, out any) error { | |
| 132 | 新增: req, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil) | |
| 133 | 新增: if err != nil { | |
| 134 | 新增: return err | |
| 135 | 新增: } | |
| 136 | 新增: req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Cage-SystemInstaller/1.0)") | |
| 137 | 新增: response, err := client.Do(req) | |
| 138 | 新增: if err != nil { | |
| 139 | 新增: return err | |
| 140 | 新增: } | |
| 141 | 新增: defer response.Body.Close() | |
| 142 | 新增: if response.StatusCode != http.StatusOK { | |
| 143 | 新增: return fmt.Errorf("系统目录返回 HTTP %d", response.StatusCode) | |
| 144 | 新增: } | |
| 145 | 新增: data, err := io.ReadAll(io.LimitReader(response.Body, (8<<20)+1)) | |
| 146 | 新增: if err != nil { | |
| 147 | 新增: return err | |
| 148 | 新增: } | |
| 149 | 新增: if len(data) > 8<<20 { | |
| 150 | 新增: return errors.New("系统目录超过大小限制") | |
| 151 | 新增: } | |
| 152 | 新增: if strings.HasSuffix(address, ".xml") { | |
| 153 | 新增: return xml.Unmarshal(data, out) | |
| 154 | 新增: } | |
| 155 | 新增: return json.Unmarshal(data, out) | |
| 156 | 新增:} | |
| 157 | 新增: | |
| 158 | 新增:// Resolve first reuses previously verified media metadata. Template is the | |
| 159 | 新增:// application's bundled, pinned Linux image list, supplied by its owner. | |
| 160 | 新增:func Resolve(ctx context.Context, identity Identity, cache, downloads string, template []byte, transport http.RoundTripper) (Plan, error) { | |
| 161 | 新增: client := &http.Client{Transport: transport, Timeout: 30 * time.Second} | |
| 162 | 新增: if plan, err := Load(cache); err == nil && plan.Host == identity { | |
| 163 | 新增: if plan.Path != "" && usableFile(plan.Path, plan.Bytes) { | |
| 164 | 新增: info, _ := os.Stat(plan.Path) | |
| 165 | 新增: if info.ModTime().UnixNano() == plan.Modified { | |
| 166 | 新增: return plan, nil | |
| 167 | 新增: } | |
| 168 | 新增: } | |
| 169 | 新增: if path := plan.CachedPath(cache); usableFile(path, plan.Bytes) { | |
| 170 | 新增: plan.Path = path | |
| 171 | 新增: info, _ := os.Stat(path) | |
| 172 | 新增: plan.Modified = info.ModTime().UnixNano() | |
| 173 | 新增: return plan, plan.Validate() | |
| 174 | 新增: } | |
| 175 | 新增: } | |
| 176 | 新增: var plan Plan | |
| 177 | 新增: var err error | |
| 178 | 新增: switch identity.System { | |
| 179 | 新增: case "macos": | |
| 180 | 新增: if plan, ok := localMacImage(identity, cache, downloads); ok { | |
| 181 | 新增: return plan, plan.Validate() | |
| 182 | 新增: } | |
| 183 | 新增: plan, err = macCatalog(ctx, client, identity) | |
| 184 | 新增: case "windows-11": | |
| 185 | 新增: plan, err = windowsCatalog(ctx, client, identity) | |
| 186 | 新增: default: | |
| 187 | 新增: plan, err = linuxCatalog(identity, template) | |
| 188 | 新增: } | |
| 189 | 新增: if err != nil { | |
| 190 | 新增: return Plan{}, err | |
| 191 | 新增: } | |
| 192 | 新增: for _, candidate := range []string{plan.CachedPath(cache), filepath.Join(downloads, filepath.Base(plan.URL))} { | |
| 193 | 新增: if usableFile(candidate, plan.Bytes) { | |
| 194 | 新增: info, _ := os.Stat(candidate) | |
| 195 | 新增: plan.Path, plan.Modified = candidate, info.ModTime().UnixNano() | |
| 196 | 新增: if plan.Bytes == 0 { | |
| 197 | 新增: plan.Bytes = info.Size() | |
| 198 | 新增: } | |
| 199 | 新增: break | |
| 200 | 新增: } | |
| 201 | 新增: } | |
| 202 | 新增: return plan, plan.Validate() | |
| 203 | 新增:} | |
| 204 | 新增: | |
| 205 | 新增:func usableFile(path string, size int64) bool { | |
| 206 | 新增: info, err := os.Lstat(path) | |
| 207 | 新增: return err == nil && info.Mode().IsRegular() && info.Size() > 0 && (size == 0 || info.Size() == size) | |
| 208 | 新增:} | |
| 209 | 新增: | |
| 210 | 新增:func macCatalog(ctx context.Context, client *http.Client, host Identity) (Plan, error) { | |
| 211 | 新增: // IPSW.me indexes historical Apple URLs. The archive is fetched only from | |
| 212 | 新增: // Apple and independently verified by Apple's installer before restoration. | |
| 213 | 新增: var catalog struct { | |
| 214 | 新增: Firmware []struct { | |
| 215 | 新增: Version string `json:"version"` | |
| 216 | 新增: Build string `json:"buildid"` | |
| 217 | 新增: URL string `json:"url"` | |
| 218 | 新增: Bytes int64 `json:"filesize"` | |
| 219 | 新增: SHA256 string `json:"sha256sum"` | |
| 220 | 新增: } `json:"firmwares"` | |
| 221 | 新增: } | |
| 222 | 新增: if err := metadata(ctx, client, "https://api.ipsw.me/v4/device/VirtualMac2,1?type=ipsw", &catalog); err != nil { | |
| 223 | 新增: return Plan{}, fmt.Errorf("查找与本机一致的 Apple 恢复镜像失败,可选择已有 IPSW:%w", err) | |
| 224 | 新增: } | |
| 225 | 新增: for _, media := range catalog.Firmware { | |
| 226 | 新增: if media.Version == host.Version && media.Build == host.Build { | |
| 227 | 新增: return Plan{Host: host, Version: media.Version, Build: media.Build, Format: "ipsw", URL: media.URL, Digest: "sha256:" + media.SHA256, Bytes: media.Bytes}, nil | |
| 228 | 新增: } | |
| 229 | 新增: } | |
| 230 | 新增: return Plan{}, fmt.Errorf("未找到 macOS %s(%s)的恢复镜像,请选择已有的对应 IPSW", host.Version, host.Build) | |
| 231 | 新增:} | |
| 232 | 新增: | |
| 233 | 新增:const windowsCatalogURL = "https://download.microsoft.com/download/eb1cc454-1c9a-4c94-adf8-b30c7f3d03d1/products.xml" | |
| 234 | 新增: | |
| 235 | 新增:type windowsMediaCatalog struct { | |
| 236 | 新增: Files []struct { | |
| 237 | 新增: Name string `xml:"FileName"` | |
| 238 | 新增: Language string `xml:"LanguageCode"` | |
| 239 | 新增: Edition string `xml:"Edition"` | |
| 240 | 新增: Arch string `xml:"Architecture"` | |
| 241 | 新增: Bytes int64 `xml:"Size"` | |
| 242 | 新增: SHA256 string `xml:"Sha256"` | |
| 243 | 新增: URL string `xml:"FilePath"` | |
| 244 | 新增: } `xml:"Files>File"` | |
| 245 | 新增:} | |
| 246 | 新增: | |
| 247 | 新增:func windowsCatalog(ctx context.Context, client *http.Client, host Identity) (Plan, error) { | |
| 248 | 新增: current, currentErr := currentWindowsCatalog(ctx, client, host) | |
| 249 | 新增: if currentErr == nil { | |
| 250 | 新增: if plan, ok := selectWindowsMedia(current, host); ok { | |
| 251 | 新增: return plan, nil | |
| 252 | 新增: } | |
| 253 | 新增: } | |
| 254 | 新增: // Microsoft's current catalog can omit an older feature release. Keep the | |
| 255 | 新增: // published 25H2 catalog as a fallback, without changing the selected release. | |
| 256 | 新增: var catalog windowsMediaCatalog | |
| 257 | 新增: if err := metadata(ctx, client, windowsCatalogURL, &catalog); err != nil { | |
| 258 | 新增: return Plan{}, fmt.Errorf("读取微软安装目录失败,可选择已有 ISO:%w", err) | |
| 259 | 新增: } | |
| 260 | 新增: if plan, ok := selectWindowsMedia(catalog, host); ok { | |
| 261 | 新增: return plan, nil | |
| 262 | 新增: } | |
| 263 | 新增: if currentErr != nil { | |
| 264 | 新增: return Plan{}, fmt.Errorf("无法读取匹配本机版本的微软目录,请检查所选代理后重试:%w", currentErr) | |
| 265 | 新增: } | |
| 266 | 新增: return Plan{}, fmt.Errorf("微软当前目录没有 Windows 11 %s %s %s 的对应介质,请选择已有 ISO", host.Version, host.Edition, host.Language) | |
| 267 | 新增:} | |
| 268 | 新增: | |
| 269 | 新增:func selectWindowsMedia(catalog windowsMediaCatalog, host Identity) (Plan, bool) { | |
| 270 | 新增: major := strings.SplitN(host.Build, ".", 2)[0] | |
| 271 | 新增: for _, file := range catalog.Files { | |
| 272 | 新增: if file.Arch != "x64" || file.Edition != host.Edition || !strings.EqualFold(file.Language, host.Language) || | |
| 273 | 新增: major == "" || !strings.HasPrefix(file.Name, major+".") { | |
| 274 | 新增: continue | |
| 275 | 新增: } | |
| 276 | 新增: build := regexp.MustCompile(`^\d+\.\d+`).FindString(file.Name) | |
| 277 | 新增: return Plan{Host: host, Version: host.Version, Build: build, Format: "esd", Bytes: file.Bytes, | |
| 278 | 新增: Digest: "sha256:" + strings.ToLower(file.SHA256), URL: file.URL}, true | |
| 279 | 新增: } | |
| 280 | 新增: return Plan{}, false | |
| 281 | 新增:} | |
| 282 | 新增: | |
| 283 | 新增:func linuxCatalog(host Identity, template []byte) (Plan, error) { | |
| 284 | 新增: var config struct { | |
| 285 | 新增: Images []struct { | |
| 286 | 新增: Location string `yaml:"location"` | |
| 287 | 新增: Arch string `yaml:"arch"` | |
| 288 | 新增: Digest string `yaml:"digest"` | |
| 289 | 新增: Bytes int64 `yaml:"bytes"` | |
| 290 | 新增: } `yaml:"images"` | |
| 291 | 新增: } | |
| 292 | 新增: if err := yaml.Unmarshal(template, &config); err != nil { | |
| 293 | 新增: return Plan{}, err | |
| 294 | 新增: } | |
| 295 | 新增: arch := map[string]string{"amd64": "x86_64", "arm64": "aarch64"}[host.Arch] | |
| 296 | 新增: for _, image := range config.Images { | |
| 297 | 新增: if arch != "" && image.Arch == arch && image.Digest != "" { | |
| 298 | 新增: return Plan{Host: host, Version: host.Version, Format: "qcow2", URL: image.Location, Digest: image.Digest, Bytes: image.Bytes}, nil | |
| 299 | 新增: } | |
| 300 | 新增: } | |
| 301 | 新增: return Plan{}, errors.New("此安装包缺少与本机发行版一致的已校验 Linux 镜像") | |
| 302 | 新增:} | |
| 303 | 新增: | |
| 304 | 新增:func (p Plan) CachedPath(cache string) string { | |
| 305 | 新增: key := strings.ReplaceAll(p.Digest, ":", "-") | |
| 306 | 新增: if key == "" { | |
| 307 | 新增: key = p.Key() | |
| 308 | 新增: } | |
| 309 | 新增: return filepath.Join(cache, key+"."+p.Format) | |
| 310 | 新增:} | |
| 311 | 新增: | |
| 312 | 新增:func (p Plan) RemainingBytes(cache string) int64 { | |
| 313 | 新增: if p.Path != "" { | |
| 314 | 新增: return 0 | |
| 315 | 新增: } | |
| 316 | 新增: if usableFile(p.CachedPath(cache), p.Bytes) { | |
| 317 | 新增: return 0 | |
| 318 | 新增: } | |
| 319 | 新增: info, err := os.Lstat(p.CachedPath(cache) + ".partial") | |
| 320 | 新增: if err == nil && info.Mode().IsRegular() && info.Size() <= p.Bytes { | |
| 321 | 新增: return p.Bytes - info.Size() | |
| 322 | 新增: } | |
| 323 | 新增: return p.Bytes | |
| 324 | 新增:} | |
| 325 | 新增: | |
| 326 | 新增:const sourceRecord = "host-system-source.json" | |
| 327 | 新增: | |
| 328 | 新增:func Save(cache string, plan Plan) error { | |
| 329 | 新增: if err := plan.Validate(); err != nil { | |
| 330 | 新增: return err | |
| 331 | 新增: } | |
| 332 | 新增: if err := os.MkdirAll(cache, 0700); err != nil { | |
| 333 | 新增: return err | |
| 334 | 新增: } | |
| 335 | 新增: file, err := os.CreateTemp(cache, ".host-system-source-*") | |
| 336 | 新增: if err != nil { | |
| 337 | 新增: return err | |
| 338 | 新增: } | |
| 339 | 新增: defer os.Remove(file.Name()) | |
| 340 | 新增: err = json.NewEncoder(file).Encode(plan) | |
| 341 | 新增: closeErr := file.Close() | |
| 342 | 新增: if err = errors.Join(err, closeErr); err != nil { | |
| 343 | 新增: return err | |
| 344 | 新增: } | |
| 345 | 新增: return os.Rename(file.Name(), filepath.Join(cache, sourceRecord)) | |
| 346 | 新增:} | |
| 347 | 新增: | |
| 348 | 新增:func Load(cache string) (Plan, error) { | |
| 349 | 新增: var plan Plan | |
| 350 | 新增: file, err := os.Open(filepath.Join(cache, sourceRecord)) | |
| 351 | 新增: if err != nil { | |
| 352 | 新增: return plan, err | |
| 353 | 新增: } | |
| 354 | 新增: defer file.Close() | |
| 355 | 新增: decoder := json.NewDecoder(io.LimitReader(file, 32<<10)) | |
| 356 | 新增: decoder.DisallowUnknownFields() | |
| 357 | 新增: if err = decoder.Decode(&plan); err != nil { | |
| 358 | 新增: return plan, err | |
| 359 | 新增: } | |
| 360 | 新增: return plan, plan.Validate() | |
| 361 | 新增:} | |
| @@ -0,0 +1,298 @@ | ||
| 1 | 新增:package hostimage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "archive/zip" | |
| 5 | 新增: "bytes" | |
| 6 | 新增: "context" | |
| 7 | 新增: "crypto/sha256" | |
| 8 | 新增: "encoding/hex" | |
| 9 | 新增: "encoding/json" | |
| 10 | 新增: "encoding/xml" | |
| 11 | 新增: "fmt" | |
| 12 | 新增: "io" | |
| 13 | 新增: "net" | |
| 14 | 新增: "net/http" | |
| 15 | 新增: "net/http/httptest" | |
| 16 | 新增: "os" | |
| 17 | 新增: "path/filepath" | |
| 18 | 新增: "runtime" | |
| 19 | 新增: "strings" | |
| 20 | 新增: "testing" | |
| 21 | 新增: | |
| 22 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 23 | 新增:) | |
| 24 | 新增: | |
| 25 | 新增:func TestMacSourceReadsIdentityWithoutUserFiles(t *testing.T) { | |
| 26 | 新增: dir := t.TempDir() | |
| 27 | 新增: path := filepath.Join(dir, "system.ipsw") | |
| 28 | 新增: file, err := os.Create(path) | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: t.Fatal(err) | |
| 31 | 新增: } | |
| 32 | 新增: archive := zip.NewWriter(file) | |
| 33 | 新增: manifest, _ := archive.Create("BuildManifest.plist") | |
| 34 | 新增: fmt.Fprint(manifest, `<plist><dict><key>BuildIdentities</key><array><dict><key>ProductVersion</key><string>wrong</string></dict>`) | |
| 35 | 新增: // Universal IPSWs place their root identity after a large hardware list. | |
| 36 | 新增: fmt.Fprint(manifest, strings.Repeat(" ", 17<<20)) | |
| 37 | 新增: fmt.Fprint(manifest, `</array><key>ProductVersion</key><string>26.5</string><key>ProductBuildVersion</key><string>25F71</string></dict></plist>`) | |
| 38 | 新增: if err = archive.Close(); err != nil { | |
| 39 | 新增: t.Fatal(err) | |
| 40 | 新增: } | |
| 41 | 新增: file.Close() | |
| 42 | 新增: host := Identity{System: "macos", Version: "26.5", Build: "25F71", Arch: "arm64"} | |
| 43 | 新增: plan, ok := localMacImage(host, dir) | |
| 44 | 新增: if !ok || plan.Path != path { | |
| 45 | 新增: t.Fatalf("source not found: %+v", plan) | |
| 46 | 新增: } | |
| 47 | 新增: prepared, err := Prepare(t.Context(), filepath.Join(dir, "cache"), plan, io.Discard, nil) | |
| 48 | 新增: if err != nil || !strings.HasPrefix(prepared.Digest, "sha256:") { | |
| 49 | 新增: t.Fatalf("prepare: %+v %v", prepared, err) | |
| 50 | 新增: } | |
| 51 | 新增: host.Build = "25F84" | |
| 52 | 新增: if _, ok := localMacImage(host, dir); ok { | |
| 53 | 新增: t.Fatal("accepted different macOS build") | |
| 54 | 新增: } | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:func TestSourceRejectsUntrustedURLsAndUnsupportedSystems(t *testing.T) { | |
| 58 | 新增: base := Plan{Host: Identity{System: "macos", Version: "26.5", Build: "25F71", Arch: "arm64"}, Version: "26.5", Build: "25F71", Format: "ipsw", Digest: "sha256:" + strings.Repeat("a", 64), URL: "https://updates.cdn-apple.com/system.ipsw"} | |
| 59 | 新增: if err := base.Validate(); err != nil { | |
| 60 | 新增: t.Fatal(err) | |
| 61 | 新增: } | |
| 62 | 新增: for _, url := range []string{"http://updates.cdn-apple.com/a", "https://updates.cdn-apple.com.evil.test/a", "https://[email protected]/a", "https://updates.cdn-apple.com:443/a"} { | |
| 63 | 新增: plan := base | |
| 64 | 新增: plan.URL = url | |
| 65 | 新增: if err := plan.Validate(); err == nil { | |
| 66 | 新增: t.Errorf("accepted %q", url) | |
| 67 | 新增: } | |
| 68 | 新增: } | |
| 69 | 新增: base.Host.System = "arch-linux" | |
| 70 | 新增: if err := base.Validate(); err == nil { | |
| 71 | 新增: t.Fatal("accepted unsupported source") | |
| 72 | 新增: } | |
| 73 | 新增:} | |
| 74 | 新增: | |
| 75 | 新增:func TestMacCloneRequiresGuestFileSystemSupport(t *testing.T) { | |
| 76 | 新增: for _, version := range []string{"14.7.6", "15.4", "26.3", "26.4", "26.5"} { | |
| 77 | 新增: plan := Plan{Host: Identity{System: "macos", Version: version, Build: "fixture", Arch: "arm64"}, Version: version, | |
| 78 | 新增: Build: "fixture", Format: "ipsw", Path: filepath.Join(t.TempDir(), "system.ipsw")} | |
| 79 | 新增: err := plan.Validate() | |
| 80 | 新增: allowed := version == "26.4" || version == "26.5" | |
| 81 | 新增: if (err == nil) != allowed { | |
| 82 | 新增: t.Fatalf("version %s: %v", version, err) | |
| 83 | 新增: } | |
| 84 | 新增: } | |
| 85 | 新增:} | |
| 86 | 新增: | |
| 87 | 新增:func TestSourceKeyAndSpaceAllowCompletedConcurrentDownload(t *testing.T) { | |
| 88 | 新增: cache := t.TempDir() | |
| 89 | 新增: plan := Plan{Host: Identity{System: "windows-11", Version: "25H2", Arch: "amd64", Edition: "Professional", Language: "en-US"}, Version: "25H2", Build: "26200.1", Format: "esd", URL: "http://dl.delivery.mp.microsoft.com/example.esd", Digest: "sha256:" + strings.Repeat("a", 64), Bytes: 10} | |
| 90 | 新增: if err := plan.Validate(); err != nil { | |
| 91 | 新增: t.Fatal(err) | |
| 92 | 新增: } | |
| 93 | 新增: if err := os.WriteFile(plan.CachedPath(cache)+".partial", []byte("123456"), 0600); err != nil { | |
| 94 | 新增: t.Fatal(err) | |
| 95 | 新增: } | |
| 96 | 新增: if remaining := plan.RemainingBytes(cache); remaining != 4 { | |
| 97 | 新增: t.Fatalf("remaining=%d", remaining) | |
| 98 | 新增: } | |
| 99 | 新增: ready := plan | |
| 100 | 新增: ready.Path = plan.CachedPath(cache) | |
| 101 | 新增: ready.Modified = 123 | |
| 102 | 新增: if ready.Key() != plan.Key() { | |
| 103 | 新增: t.Fatal("a completed cache invalidated the selected image") | |
| 104 | 新增: } | |
| 105 | 新增: if remaining := ready.RemainingBytes(cache); remaining != 0 { | |
| 106 | 新增: t.Fatalf("ready remaining=%d", remaining) | |
| 107 | 新增: } | |
| 108 | 新增: plan.Digest = "" | |
| 109 | 新增: if err := plan.Validate(); err == nil { | |
| 110 | 新增: t.Fatal("accepted HTTP media without the HTTPS catalog digest") | |
| 111 | 新增: } | |
| 112 | 新增:} | |
| 113 | 新增: | |
| 114 | 新增:func TestWindowsCatalogKeepsFeatureReleaseAndEdition(t *testing.T) { | |
| 115 | 新增: var catalog windowsMediaCatalog | |
| 116 | 新增: data := `<PublishedMedia><Files><File><FileName>26300.9457.26h2_release.esd</FileName><LanguageCode>zh-cn</LanguageCode><Edition>Professional</Edition><Architecture>x64</Architecture><Size>100</Size><Sha256>` + strings.Repeat("a", 64) + `</Sha256><FilePath>http://dl.delivery.mp.microsoft.com/windows.esd</FilePath></File></Files></PublishedMedia>` | |
| 117 | 新增: if err := xml.Unmarshal([]byte(data), &catalog); err != nil { | |
| 118 | 新增: t.Fatal(err) | |
| 119 | 新增: } | |
| 120 | 新增: host := Identity{System: "windows-11", Version: "26H2", Build: "26300.9711", Edition: "Professional", Language: "zh-CN", Arch: "amd64"} | |
| 121 | 新增: plan, ok := selectWindowsMedia(catalog, host) | |
| 122 | 新增: if !ok || plan.Build != "26300.9457" || plan.Version != "26H2" { | |
| 123 | 新增: t.Fatalf("catalog match: %+v %v", plan, ok) | |
| 124 | 新增: } | |
| 125 | 新增: if err := plan.Validate(); err != nil { | |
| 126 | 新增: t.Fatal(err) | |
| 127 | 新增: } | |
| 128 | 新增: host.Build = "26200.9711" | |
| 129 | 新增: host.Version = "25H2" | |
| 130 | 新增: if _, ok := selectWindowsMedia(catalog, host); ok { | |
| 131 | 新增: t.Fatal("silently changed the Windows feature release") | |
| 132 | 新增: } | |
| 133 | 新增: host.Build = "26300.9711" | |
| 134 | 新增: host.Edition = "Enterprise" | |
| 135 | 新增: if _, ok := selectWindowsMedia(catalog, host); ok { | |
| 136 | 新增: t.Fatal("silently changed the Windows edition") | |
| 137 | 新增: } | |
| 138 | 新增:} | |
| 139 | 新增: | |
| 140 | 新增:func TestDownloadResumesAndRejectsWrongRange(t *testing.T) { | |
| 141 | 新增: for _, wrong := range []bool{false, true} { | |
| 142 | 新增: t.Run(fmt.Sprint(wrong), func(t *testing.T) { | |
| 143 | 新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 144 | 新增: if r.Header.Get("Range") != "bytes=3-" { | |
| 145 | 新增: t.Error("did not request resume") | |
| 146 | 新增: } | |
| 147 | 新增: start := 3 | |
| 148 | 新增: if wrong { | |
| 149 | 新增: start = 2 | |
| 150 | 新增: } | |
| 151 | 新增: w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-5/6", start)) | |
| 152 | 新增: w.WriteHeader(http.StatusPartialContent) | |
| 153 | 新增: fmt.Fprint(w, "def") | |
| 154 | 新增: })) | |
| 155 | 新增: defer server.Close() | |
| 156 | 新增: file, err := os.CreateTemp(t.TempDir(), "partial") | |
| 157 | 新增: if err != nil { | |
| 158 | 新增: t.Fatal(err) | |
| 159 | 新增: } | |
| 160 | 新增: defer file.Close() | |
| 161 | 新增: file.WriteString("abc") | |
| 162 | 新增: var progress bytes.Buffer | |
| 163 | 新增: err = download(t.Context(), Plan{Host: Identity{System: "windows-11"}, URL: server.URL, Bytes: 6}, file, 3, &progress, nil) | |
| 164 | 新增: if wrong { | |
| 165 | 新增: if err == nil { | |
| 166 | 新增: t.Fatal("accepted wrong range") | |
| 167 | 新增: } | |
| 168 | 新增: return | |
| 169 | 新增: } | |
| 170 | 新增: if err != nil { | |
| 171 | 新增: t.Fatal(err) | |
| 172 | 新增: } | |
| 173 | 新增: data, _ := os.ReadFile(file.Name()) | |
| 174 | 新增: if string(data) != "abcdef" { | |
| 175 | 新增: t.Fatalf("got %q", data) | |
| 176 | 新增: } | |
| 177 | 新增: if !strings.Contains(progress.String(), "CAGE_GUEST_BYTES windows-11 download 6 6") { | |
| 178 | 新增: t.Fatalf("missing actual resumed byte progress: %s", progress.String()) | |
| 179 | 新增: } | |
| 180 | 新增: }) | |
| 181 | 新增: } | |
| 182 | 新增:} | |
| 183 | 新增: | |
| 184 | 新增:func TestPrepareRejectsModifiedSourceAndPreservesIt(t *testing.T) { | |
| 185 | 新增: dir := t.TempDir() | |
| 186 | 新增: path := filepath.Join(dir, "system.esd") | |
| 187 | 新增: os.WriteFile(path, []byte("original"), 0600) | |
| 188 | 新增: info, _ := os.Stat(path) | |
| 189 | 新增: digest := sha256.Sum256([]byte("original")) | |
| 190 | 新增: plan := Plan{Host: Identity{System: "windows-11", Version: "25H2", Build: "26200.9", Edition: "Professional", Language: "en-US", Arch: "amd64"}, Version: "25H2", Build: "26200.8", Format: "esd", Path: path, Bytes: 8, Modified: info.ModTime().UnixNano(), Digest: "sha256:" + hex.EncodeToString(digest[:])} | |
| 191 | 新增: os.WriteFile(path, []byte("tampered"), 0600) | |
| 192 | 新增: if _, err := Prepare(t.Context(), filepath.Join(dir, "cache"), plan, io.Discard, nil); err == nil { | |
| 193 | 新增: t.Fatal("accepted changed source") | |
| 194 | 新增: } | |
| 195 | 新增: data, _ := os.ReadFile(path) | |
| 196 | 新增: if string(data) != "tampered" { | |
| 197 | 新增: t.Fatal("changed user's source") | |
| 198 | 新增: } | |
| 199 | 新增:} | |
| 200 | 新增: | |
| 201 | 新增:func TestPrepareRecoversOversizedPartialWithoutDiscardingIt(t *testing.T) { | |
| 202 | 新增: cache := t.TempDir() | |
| 203 | 新增: content := []byte("valid image") | |
| 204 | 新增: digest := sha256.Sum256(content) | |
| 205 | 新增: plan := Plan{ | |
| 206 | 新增: Host: Identity{System: "windows-11", Version: "25H2", Build: "26200.9", Edition: "Professional", Language: "en-US", Arch: "amd64"}, | |
| 207 | 新增: Version: "25H2", Build: "26200.8", Format: "esd", Bytes: int64(len(content)), | |
| 208 | 新增: URL: "http://dl.delivery.mp.microsoft.com/fixture.esd", Digest: "sha256:" + hex.EncodeToString(digest[:]), | |
| 209 | 新增: } | |
| 210 | 新增: partial := plan.CachedPath(cache) + ".partial" | |
| 211 | 新增: bad := []byte("oversized incomplete response") | |
| 212 | 新增: if err := os.WriteFile(partial, bad, 0600); err != nil { | |
| 213 | 新增: t.Fatal(err) | |
| 214 | 新增: } | |
| 215 | 新增: requests := 0 | |
| 216 | 新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 217 | 新增: requests++ | |
| 218 | 新增: if r.Header.Get("Range") != "" { | |
| 219 | 新增: t.Error("retried using the oversized prefix") | |
| 220 | 新增: } | |
| 221 | 新增: _, _ = w.Write(content) | |
| 222 | 新增: })) | |
| 223 | 新增: defer server.Close() | |
| 224 | 新增: transport := &http.Transport{DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { | |
| 225 | 新增: return new(net.Dialer).DialContext(ctx, network, server.Listener.Addr().String()) | |
| 226 | 新增: }} | |
| 227 | 新增: defer transport.CloseIdleConnections() | |
| 228 | 新增: for attempt := 0; attempt < 2; attempt++ { | |
| 229 | 新增: ready, err := Prepare(t.Context(), cache, plan, io.Discard, transport) | |
| 230 | 新增: if err != nil || ready.Digest != plan.Digest || ready.Path != plan.CachedPath(cache) { | |
| 231 | 新增: t.Fatalf("retry did not prepare the original image: %+v %v", ready, err) | |
| 232 | 新增: } | |
| 233 | 新增: } | |
| 234 | 新增: retained, err := filepath.Glob(partial + ".invalid-*") | |
| 235 | 新增: if err != nil || len(retained) != 1 || requests != 1 { | |
| 236 | 新增: t.Fatalf("retained=%v requests=%d error=%v", retained, requests, err) | |
| 237 | 新增: } | |
| 238 | 新增: data, err := os.ReadFile(retained[0]) | |
| 239 | 新增: if err != nil || !bytes.Equal(data, bad) { | |
| 240 | 新增: t.Fatal("discarded the failed response", err) | |
| 241 | 新增: } | |
| 242 | 新增:} | |
| 243 | 新增: | |
| 244 | 新增:// Opt-in integration uses a caller-created private directory. It never boots | |
| 245 | 新增:// a VM or reads a user's personal data. Media downloads require a second opt-in. | |
| 246 | 新增:func TestLiveHostSource(t *testing.T) { | |
| 247 | 新增: dir := os.Getenv("CAGE_TEST_HOST_SOURCE") | |
| 248 | 新增: if dir == "" { | |
| 249 | 新增: t.Skip("set CAGE_TEST_HOST_SOURCE to a private test directory") | |
| 250 | 新增: } | |
| 251 | 新增: if !filepath.IsAbs(dir) { | |
| 252 | 新增: t.Fatal("absolute test directory required") | |
| 253 | 新增: } | |
| 254 | 新增: host, err := Host(context.Background()) | |
| 255 | 新增: if err != nil { | |
| 256 | 新增: t.Fatal(err) | |
| 257 | 新增: } | |
| 258 | 新增: if IsLinux(host.System) { | |
| 259 | 新增: t.Skip("Linux live source uses bundled template through the workbench") | |
| 260 | 新增: } | |
| 261 | 新增: var transport *http.Transport | |
| 262 | 新增: if config := os.Getenv("CAGE_TEST_HOST_CONFIG"); config != "" { | |
| 263 | 新增: cfg, err := cage.Load(config) | |
| 264 | 新增: if err != nil { | |
| 265 | 新增: t.Fatal(err) | |
| 266 | 新增: } | |
| 267 | 新增: egress, err := cage.NewEgress(cfg) | |
| 268 | 新增: if err != nil { | |
| 269 | 新增: t.Fatal(err) | |
| 270 | 新增: } | |
| 271 | 新增: transport = &http.Transport{Proxy: nil, DialContext: egress.DialContext} | |
| 272 | 新增: defer transport.CloseIdleConnections() | |
| 273 | 新增: } | |
| 274 | 新增: var roundTripper http.RoundTripper | |
| 275 | 新增: if transport != nil { | |
| 276 | 新增: roundTripper = transport | |
| 277 | 新增: } | |
| 278 | 新增: plan, err := Resolve(t.Context(), host, dir, dir, nil, roundTripper) | |
| 279 | 新增: if err != nil { | |
| 280 | 新增: t.Fatal(err) | |
| 281 | 新增: } | |
| 282 | 新增: data, _ := json.MarshalIndent(plan, "", " ") | |
| 283 | 新增: t.Log(runtime.GOOS, string(data)) | |
| 284 | 新增: if err = os.WriteFile(filepath.Join(dir, "plan.json"), data, 0600); err != nil { | |
| 285 | 新增: t.Fatal(err) | |
| 286 | 新增: } | |
| 287 | 新增: if os.Getenv("CAGE_TEST_HOST_SOURCE_DOWNLOAD") != "1" { | |
| 288 | 新增: return | |
| 289 | 新增: } | |
| 290 | 新增: plan, err = Prepare(t.Context(), dir, plan, os.Stdout, roundTripper) | |
| 291 | 新增: if err != nil { | |
| 292 | 新增: t.Fatal(err) | |
| 293 | 新增: } | |
| 294 | 新增: data, _ = json.MarshalIndent(plan, "", " ") | |
| 295 | 新增: if err = os.WriteFile(filepath.Join(dir, "plan.json"), data, 0600); err != nil { | |
| 296 | 新增: t.Fatal(err) | |
| 297 | 新增: } | |
| 298 | 新增:} | |
| @@ -0,0 +1,71 @@ | ||
| 1 | 新增:package hostimage_test | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "strings" | |
| 9 | 新增: "testing" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/sylvinus/agent-vm/internal/hostimage" | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/limaembed" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:func TestUbuntu2204PinnedImageAndPersistentTemplate(t *testing.T) { | |
| 16 | 新增: template, err := limaembed.ReadImageTemplate("ubuntu-22.04") | |
| 17 | 新增: if err != nil { | |
| 18 | 新增: t.Fatal(err) | |
| 19 | 新增: } | |
| 20 | 新增: identity := hostimage.Identity{System: "ubuntu-22.04", Version: "22.04", Arch: "amd64"} | |
| 21 | 新增: state := t.TempDir() | |
| 22 | 新增: plan, err := hostimage.Resolve(context.Background(), identity, state, t.TempDir(), template, nil) | |
| 23 | 新增: if err != nil || !strings.Contains(plan.URL, "/jammy/release-20261106/") || len(plan.Digest) != 71 { | |
| 24 | 新增: t.Fatalf("source: %+v %v", plan, err) | |
| 25 | 新增: } | |
| 26 | 新增: plan.Path = filepath.Join(state, "ubuntu.img") | |
| 27 | 新增: if err := hostimage.WriteLinuxTemplate(state, plan); err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: saved, err := hostimage.Load(filepath.Join(state, "guest-media")) | |
| 31 | 新增: if err != nil || saved != plan { | |
| 32 | 新增: t.Fatalf("persistent media: %+v %v", saved, err) | |
| 33 | 新增: } | |
| 34 | 新增: path, err := hostimage.LinuxTemplate(state) | |
| 35 | 新增: if err != nil { | |
| 36 | 新增: t.Fatal(err) | |
| 37 | 新增: } | |
| 38 | 新增: data, err := os.ReadFile(path) | |
| 39 | 新增: var config struct{ Images []map[string]string } | |
| 40 | 新增: if err != nil || json.Unmarshal(data, &config) != nil || len(config.Images) != 1 || config.Images[0]["location"] != plan.Path { | |
| 41 | 新增: t.Fatalf("template changed source or added fallbacks: %s %v", data, err) | |
| 42 | 新增: } | |
| 43 | 新增: plan.URL = "https://cloud-images.ubuntu.com.evil.test/ubuntu.img" | |
| 44 | 新增: if err := plan.Validate(); err == nil { | |
| 45 | 新增: t.Fatal("accepted an untrusted Ubuntu image source") | |
| 46 | 新增: } | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:func TestUbuntuChoiceNeverFallsBackAfterMetadataLoss(t *testing.T) { | |
| 50 | 新增: for _, removed := range []string{"host-system.yaml", "host-system-source.json"} { | |
| 51 | 新增: state := t.TempDir() | |
| 52 | 新增: template, _ := limaembed.ReadImageTemplate("ubuntu-22.04") | |
| 53 | 新增: plan, err := hostimage.Resolve(t.Context(), hostimage.Identity{System: "ubuntu-22.04", Version: "22.04", Arch: "arm64"}, state, state, template, nil) | |
| 54 | 新增: if err != nil { | |
| 55 | 新增: t.Fatal(err) | |
| 56 | 新增: } | |
| 57 | 新增: plan.Path = filepath.Join(state, "ubuntu.img") | |
| 58 | 新增: if err := hostimage.WriteLinuxTemplate(state, plan); err != nil { | |
| 59 | 新增: t.Fatal(err) | |
| 60 | 新增: } | |
| 61 | 新增: if system, err := hostimage.LinuxSystem(state); err != nil || system != "ubuntu-22.04" { | |
| 62 | 新增: t.Fatalf("identity: %q %v", system, err) | |
| 63 | 新增: } | |
| 64 | 新增: if err := os.Remove(filepath.Join(state, "guest-media", removed)); err != nil { | |
| 65 | 新增: t.Fatal(err) | |
| 66 | 新增: } | |
| 67 | 新增: if _, err := hostimage.LinuxTemplate(state); err == nil { | |
| 68 | 新增: t.Fatalf("silently fell back after losing %s", removed) | |
| 69 | 新增: } | |
| 70 | 新增: } | |
| 71 | 新增:} | |
| @@ -0,0 +1,118 @@ | ||
| 1 | 新增:package hostimage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/sha256" | |
| 7 | 新增: "encoding/base64" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "encoding/xml" | |
| 10 | 新增: "errors" | |
| 11 | 新增: "fmt" | |
| 12 | 新增: "io" | |
| 13 | 新增: "net/http" | |
| 14 | 新增: "net/url" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "time" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:// The Microsoft service publishes a SHA-256-authenticated CAB containing the | |
| 20 | 新增:// current MCT catalog. Discovery sends only the OS build and architecture. | |
| 21 | 新增:func currentWindowsCatalog(ctx context.Context, client *http.Client, host Identity) (windowsMediaCatalog, error) { | |
| 22 | 新增: ctx, cancel := context.WithTimeout(ctx, 12*time.Second) | |
| 23 | 新增: defer cancel() | |
| 24 | 新增: var catalog windowsMediaCatalog | |
| 25 | 新增: body, _ := json.Marshal(map[string]string{ | |
| 26 | 新增: "Products": "PN=Windows.Products.Cab.amd64&V=0.0.0.0", | |
| 27 | 新增: "DeviceAttributes": "DUScan=1;OSVersion=10.0." + host.Build, | |
| 28 | 新增: }) | |
| 29 | 新增: request, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://fe3.delivery.mp.microsoft.com/UpdateMetadataService/updates/search/v1/bydeviceinfo", bytes.NewReader(body)) | |
| 30 | 新增: if err != nil { | |
| 31 | 新增: return catalog, err | |
| 32 | 新增: } | |
| 33 | 新增: request.Header.Set("Content-Type", "application/json") | |
| 34 | 新增: request.Header.Set("Accept", "*/*") | |
| 35 | 新增: request.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Cage-SystemInstaller/1.0)") | |
| 36 | 新增: data, err := catalogResponse(client, request) | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: return catalog, err | |
| 39 | 新增: } | |
| 40 | 新增: var records []json.RawMessage | |
| 41 | 新增: trimmed := bytes.TrimSpace(data) | |
| 42 | 新增: if len(trimmed) > 0 && trimmed[0] == '[' { | |
| 43 | 新增: if err = json.Unmarshal(trimmed, &records); err != nil { | |
| 44 | 新增: return catalog, err | |
| 45 | 新增: } | |
| 46 | 新增: } else { | |
| 47 | 新增: records = []json.RawMessage{trimmed} | |
| 48 | 新增: } | |
| 49 | 新增: if len(records) != 1 { | |
| 50 | 新增: return catalog, errors.New("微软目录更新返回多个结果") | |
| 51 | 新增: } | |
| 52 | 新增: var update struct { | |
| 53 | 新增: Files []struct { | |
| 54 | 新增: Name string `json:"FileName"` | |
| 55 | 新增: URL string `json:"Url"` | |
| 56 | 新增: Digest string `json:"Digest"` | |
| 57 | 新增: Size json.Number `json:"Size"` | |
| 58 | 新增: } `json:"FileLocations"` | |
| 59 | 新增: } | |
| 60 | 新增: if err = json.Unmarshal(records[0], &update); err != nil { | |
| 61 | 新增: return catalog, err | |
| 62 | 新增: } | |
| 63 | 新增: for _, file := range update.Files { | |
| 64 | 新增: if file.Name != "products.cab" { | |
| 65 | 新增: continue | |
| 66 | 新增: } | |
| 67 | 新增: address, err := url.Parse(file.URL) | |
| 68 | 新增: if err != nil || address.User != nil || address.Port() != "" || address.Fragment != "" || | |
| 69 | 新增: (address.Scheme != "https" && address.Scheme != "http") || | |
| 70 | 新增: !(strings.HasSuffix(address.Hostname(), ".delivery.mp.microsoft.com") || address.Hostname() == "download.microsoft.com" || address.Hostname() == "download.windowsupdate.com") { | |
| 71 | 新增: return catalog, errors.New("微软目录更新地址无法核验") | |
| 72 | 新增: } | |
| 73 | 新增: digest, err := base64.StdEncoding.DecodeString(file.Digest) | |
| 74 | 新增: size, sizeErr := file.Size.Int64() | |
| 75 | 新增: if err != nil || sizeErr != nil || len(digest) != sha256.Size || size <= 0 || size > 8<<20 { | |
| 76 | 新增: return catalog, errors.New("微软目录更新摘要或大小无效") | |
| 77 | 新增: } | |
| 78 | 新增: request, err := http.NewRequestWithContext(ctx, http.MethodGet, file.URL, nil) | |
| 79 | 新增: if err != nil { | |
| 80 | 新增: return catalog, err | |
| 81 | 新增: } | |
| 82 | 新增: request.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Cage-SystemInstaller/1.0)") | |
| 83 | 新增: compressed, err := catalogResponse(client, request) | |
| 84 | 新增: if err != nil { | |
| 85 | 新增: return catalog, err | |
| 86 | 新增: } | |
| 87 | 新增: actual := sha256.Sum256(compressed) | |
| 88 | 新增: if int64(len(compressed)) != size || !bytes.Equal(actual[:], digest) { | |
| 89 | 新增: return catalog, errors.New("微软目录更新校验失败") | |
| 90 | 新增: } | |
| 91 | 新增: data, err := expandWindowsCatalog(ctx, compressed) | |
| 92 | 新增: if err != nil { | |
| 93 | 新增: return catalog, err | |
| 94 | 新增: } | |
| 95 | 新增: err = xml.Unmarshal(data, &catalog) | |
| 96 | 新增: return catalog, err | |
| 97 | 新增: } | |
| 98 | 新增: return catalog, errors.New("微软尚未提供当前系统的安装目录") | |
| 99 | 新增:} | |
| 100 | 新增: | |
| 101 | 新增:func catalogResponse(client *http.Client, request *http.Request) ([]byte, error) { | |
| 102 | 新增: response, err := client.Do(request) | |
| 103 | 新增: if err != nil { | |
| 104 | 新增: return nil, err | |
| 105 | 新增: } | |
| 106 | 新增: defer response.Body.Close() | |
| 107 | 新增: if response.StatusCode != http.StatusOK { | |
| 108 | 新增: return nil, fmt.Errorf("微软目录返回 HTTP %d", response.StatusCode) | |
| 109 | 新增: } | |
| 110 | 新增: data, err := io.ReadAll(io.LimitReader(response.Body, (8<<20)+1)) | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: return nil, err | |
| 113 | 新增: } | |
| 114 | 新增: if len(data) > 8<<20 { | |
| 115 | 新增: return nil, errors.New("微软目录超过大小限制") | |
| 116 | 新增: } | |
| 117 | 新增: return data, nil | |
| 118 | 新增:} | |
| @@ -0,0 +1,50 @@ | ||
| 1 | 新增:// Package keepawake holds a host power request without keeping its display on. | |
| 2 | 新增:package keepawake | |
| 3 | 新增: | |
| 4 | 新增:import ( | |
| 5 | 新增: "context" | |
| 6 | 新增: "time" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:type State struct { | |
| 10 | 新增: Active bool `json:"active"` | |
| 11 | 新增: Error string `json:"error,omitempty"` | |
| 12 | 新增:} | |
| 13 | 新增: | |
| 14 | 新增:// Run owns the request until ctx ends, including time between phone connections. | |
| 15 | 新增:// A failed or unexpectedly exited helper is reported and retried. The caller | |
| 16 | 新增:// must wait for Run to return when shutting down its hosting service. | |
| 17 | 新增:func Run(ctx context.Context, report func(State)) { | |
| 18 | 新增: run(ctx, report, hold) | |
| 19 | 新增:} | |
| 20 | 新增: | |
| 21 | 新增:func run(ctx context.Context, report func(State), acquire func(context.Context, func()) error) { | |
| 22 | 新增: var previous State | |
| 23 | 新增: emit := func(state State) { | |
| 24 | 新增: if state != previous { | |
| 25 | 新增: previous = state | |
| 26 | 新增: report(state) | |
| 27 | 新增: } | |
| 28 | 新增: } | |
| 29 | 新增: delay := time.Second | |
| 30 | 新增: defer emit(State{}) | |
| 31 | 新增: for ctx.Err() == nil { | |
| 32 | 新增: err := acquire(ctx, func() { emit(State{Active: true}); delay = time.Second }) | |
| 33 | 新增: if ctx.Err() != nil { | |
| 34 | 新增: return | |
| 35 | 新增: } | |
| 36 | 新增: message := "主机防休眠请求已结束" | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: message = err.Error() | |
| 39 | 新增: } | |
| 40 | 新增: emit(State{Error: message}) | |
| 41 | 新增: timer := time.NewTimer(delay) | |
| 42 | 新增: select { | |
| 43 | 新增: case <-ctx.Done(): | |
| 44 | 新增: timer.Stop() | |
| 45 | 新增: return | |
| 46 | 新增: case <-timer.C: | |
| 47 | 新增: } | |
| 48 | 新增: delay = min(30*time.Second, delay*2) | |
| 49 | 新增: } | |
| 50 | 新增:} | |
| @@ -0,0 +1,7 @@ | ||
| 1 | 新增:package keepawake | |
| 2 | 新增: | |
| 3 | 新增:import "context" | |
| 4 | 新增: | |
| 5 | 新增:func hold(ctx context.Context, ready func()) error { | |
| 6 | 新增: return holdProcess(ctx, ready, "/usr/bin/caffeinate", "-i", "/bin/sh", "-c", waitForHost) | |
| 7 | 新增:} | |
| @@ -0,0 +1,74 @@ | ||
| 1 | 新增:package keepawake | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "os" | |
| 6 | 新增: "os/exec" | |
| 7 | 新增: "regexp" | |
| 8 | 新增: "strconv" | |
| 9 | 新增: "strings" | |
| 10 | 新增: "testing" | |
| 11 | 新增: "time" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func TestMacNativePowerRequest(t *testing.T) { | |
| 15 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 16 | 新增: defer cancel() | |
| 17 | 新增: ready := make(chan struct{}) | |
| 18 | 新增: done := make(chan error, 1) | |
| 19 | 新增: go func() { done <- hold(ctx, func() { close(ready) }) }() | |
| 20 | 新增: select { | |
| 21 | 新增: case <-ready: | |
| 22 | 新增: case err := <-done: | |
| 23 | 新增: t.Fatal("power request failed", err) | |
| 24 | 新增: case <-time.After(6 * time.Second): | |
| 25 | 新增: t.Fatal("power request did not start") | |
| 26 | 新增: } | |
| 27 | 新增: owned := func(pid int) bool { | |
| 28 | 新增: for i := 0; i < 8 && pid > 1; i++ { | |
| 29 | 新增: if pid == os.Getpid() { | |
| 30 | 新增: return true | |
| 31 | 新增: } | |
| 32 | 新增: value, err := exec.Command("/bin/ps", "-o", "ppid=", "-p", strconv.Itoa(pid)).Output() | |
| 33 | 新增: if err != nil { | |
| 34 | 新增: return false | |
| 35 | 新增: } | |
| 36 | 新增: pid, _ = strconv.Atoi(strings.TrimSpace(string(value))) | |
| 37 | 新增: } | |
| 38 | 新增: return false | |
| 39 | 新增: } | |
| 40 | 新增: pattern := regexp.MustCompile(`pid ([0-9]+)\(caffeinate\):[^\n]+`) | |
| 41 | 新增: var assertionPID string | |
| 42 | 新增: deadline := time.Now().Add(3 * time.Second) | |
| 43 | 新增: for time.Now().Before(deadline) && assertionPID == "" { | |
| 44 | 新增: data, err := exec.Command("/usr/bin/pmset", "-g", "assertions").Output() | |
| 45 | 新增: if err != nil { | |
| 46 | 新增: t.Fatal(err) | |
| 47 | 新增: } | |
| 48 | 新增: for _, match := range pattern.FindAllStringSubmatch(string(data), -1) { | |
| 49 | 新增: pid, _ := strconv.Atoi(match[1]) | |
| 50 | 新增: if owned(pid) { | |
| 51 | 新增: if !strings.Contains(match[0], "PreventUserIdleSystemSleep") || strings.Contains(match[0], "PreventUserIdleDisplaySleep") { | |
| 52 | 新增: t.Fatal("wrong assertion", match[0]) | |
| 53 | 新增: } | |
| 54 | 新增: assertionPID = match[1] | |
| 55 | 新增: } | |
| 56 | 新增: } | |
| 57 | 新增: if assertionPID == "" { | |
| 58 | 新增: time.Sleep(50 * time.Millisecond) | |
| 59 | 新增: } | |
| 60 | 新增: } | |
| 61 | 新增: if assertionPID == "" { | |
| 62 | 新增: t.Fatal("no owned idle-system-sleep assertion found") | |
| 63 | 新增: } | |
| 64 | 新增: cancel() | |
| 65 | 新增: select { | |
| 66 | 新增: case <-done: | |
| 67 | 新增: case <-time.After(3 * time.Second): | |
| 68 | 新增: t.Fatal("power helper did not exit") | |
| 69 | 新增: } | |
| 70 | 新增: data, err := exec.Command("/usr/bin/pmset", "-g", "assertions").Output() | |
| 71 | 新增: if err != nil || strings.Contains(string(data), "pid "+assertionPID+"(caffeinate):") { | |
| 72 | 新增: t.Fatal("power assertion survived cancellation", err) | |
| 73 | 新增: } | |
| 74 | 新增:} | |
| @@ -0,0 +1,7 @@ | ||
| 1 | 新增:package keepawake | |
| 2 | 新增: | |
| 3 | 新增:import "context" | |
| 4 | 新增: | |
| 5 | 新增:func hold(ctx context.Context, ready func()) error { | |
| 6 | 新增: return holdProcess(ctx, ready, "/usr/bin/systemd-inhibit", "--what=sleep", "--mode=block", "--who=Cage", "--why=Cage remote access", "--no-ask-password", "/bin/sh", "-c", waitForHost) | |
| 7 | 新增:} | |
| @@ -0,0 +1,60 @@ | ||
| 1 | 新增:package keepawake | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "testing" | |
| 7 | 新增: "time" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func TestRetryAndRelease(t *testing.T) { | |
| 11 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 12 | 新增: defer cancel() | |
| 13 | 新增: states := make(chan State, 8) | |
| 14 | 新增: done := make(chan struct{}) | |
| 15 | 新增: released := make(chan struct{}) | |
| 16 | 新增: attempts := 0 | |
| 17 | 新增: go func() { | |
| 18 | 新增: defer close(done) | |
| 19 | 新增: run(ctx, func(state State) { states <- state }, func(ctx context.Context, ready func()) error { | |
| 20 | 新增: attempts++ | |
| 21 | 新增: if attempts == 1 { | |
| 22 | 新增: return errors.New("inhibitor unavailable") | |
| 23 | 新增: } | |
| 24 | 新增: ready() | |
| 25 | 新增: <-ctx.Done() | |
| 26 | 新增: close(released) | |
| 27 | 新增: return ctx.Err() | |
| 28 | 新增: }) | |
| 29 | 新增: }() | |
| 30 | 新增: read := func() State { | |
| 31 | 新增: t.Helper() | |
| 32 | 新增: select { | |
| 33 | 新增: case state := <-states: | |
| 34 | 新增: return state | |
| 35 | 新增: case <-time.After(3 * time.Second): | |
| 36 | 新增: t.Fatal("missing power request state") | |
| 37 | 新增: return State{} | |
| 38 | 新增: } | |
| 39 | 新增: } | |
| 40 | 新增: if state := read(); state.Active || state.Error == "" { | |
| 41 | 新增: t.Fatal("failed request was hidden", state) | |
| 42 | 新增: } | |
| 43 | 新增: if state := read(); !state.Active || state.Error != "" { | |
| 44 | 新增: t.Fatal("request did not recover", state) | |
| 45 | 新增: } | |
| 46 | 新增: cancel() | |
| 47 | 新增: select { | |
| 48 | 新增: case <-done: | |
| 49 | 新增: case <-time.After(time.Second): | |
| 50 | 新增: t.Fatal("request leaked after cancellation") | |
| 51 | 新增: } | |
| 52 | 新增: select { | |
| 53 | 新增: case <-released: | |
| 54 | 新增: default: | |
| 55 | 新增: t.Fatal("native request was not released") | |
| 56 | 新增: } | |
| 57 | 新增: if state := read(); state != (State{}) { | |
| 58 | 新增: t.Fatal("stopped request remained active", state) | |
| 59 | 新增: } | |
| 60 | 新增:} | |
| @@ -0,0 +1,49 @@ | ||
| 1 | 新增:package keepawake | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "fmt" | |
| 6 | 新增: "runtime" | |
| 7 | 新增: "unsafe" | |
| 8 | 新增: | |
| 9 | 新增: "golang.org/x/sys/windows" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:var powerLibrary = windows.NewLazySystemDLL("kernel32.dll") | |
| 13 | 新增:var powerCreate = powerLibrary.NewProc("PowerCreateRequest") | |
| 14 | 新增:var powerSet = powerLibrary.NewProc("PowerSetRequest") | |
| 15 | 新增:var powerClear = powerLibrary.NewProc("PowerClearRequest") | |
| 16 | 新增: | |
| 17 | 新增:// Match REASON_CONTEXT's full union layout, including its detailed variant. | |
| 18 | 新增:type reasonContext struct { | |
| 19 | 新增: Version, Flags uint32 | |
| 20 | 新增: SimpleReason uintptr | |
| 21 | 新增: ResourceID, StringCount uint32 | |
| 22 | 新增: Strings uintptr | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:func hold(ctx context.Context, ready func()) error { | |
| 26 | 新增: reason, err := windows.UTF16PtrFromString("Cage 远程连接待机") | |
| 27 | 新增: if err != nil { | |
| 28 | 新增: return err | |
| 29 | 新增: } | |
| 30 | 新增: value := reasonContext{Flags: 1, SimpleReason: uintptr(unsafe.Pointer(reason))} | |
| 31 | 新增: handle, _, callErr := powerCreate.Call(uintptr(unsafe.Pointer(&value))) | |
| 32 | 新增: runtime.KeepAlive(reason) | |
| 33 | 新增: if handle == ^uintptr(0) || handle == 0 { | |
| 34 | 新增: return fmt.Errorf("无法创建主机防休眠请求:%w", callErr) | |
| 35 | 新增: } | |
| 36 | 新增: defer windows.CloseHandle(windows.Handle(handle)) | |
| 37 | 新增: // POWER_REQUEST_TYPE: SystemRequired=1, ExecutionRequired=3. No display or | |
| 38 | 新增: // away-mode request: monitors can sleep and explicit user sleep is respected. | |
| 39 | 新增: for _, kind := range []uintptr{1, 3} { | |
| 40 | 新增: ok, _, err := powerSet.Call(handle, kind) | |
| 41 | 新增: if ok == 0 { | |
| 42 | 新增: return fmt.Errorf("无法启用主机防休眠请求:%w", err) | |
| 43 | 新增: } | |
| 44 | 新增: defer powerClear.Call(handle, kind) | |
| 45 | 新增: } | |
| 46 | 新增: ready() | |
| 47 | 新增: <-ctx.Done() | |
| 48 | 新增: return ctx.Err() | |
| 49 | 新增:} | |
| @@ -0,0 +1,76 @@ | ||
| 1 | 新增://go:build darwin || linux | |
| 2 | 新增: | |
| 3 | 新增:package keepawake | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bufio" | |
| 7 | 新增: "bytes" | |
| 8 | 新增: "context" | |
| 9 | 新增: "errors" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "time" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:// The child acknowledges startup only after the inhibitor utility launches it. | |
| 16 | 新增:// Closing stdin ends the shell's builtin read, so no orphaned sleep process or | |
| 17 | 新增:// permanent system setting remains after the hosting service exits. | |
| 18 | 新增:const waitForHost = `printf 'ready\n'; read -r cage_remote_wait` | |
| 19 | 新增: | |
| 20 | 新增:func holdProcess(ctx context.Context, ready func(), command string, args ...string) error { | |
| 21 | 新增: cmd := exec.Command(command, args...) | |
| 22 | 新增: cmd.WaitDelay = 2 * time.Second | |
| 23 | 新增: stdin, err := cmd.StdinPipe() | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: return err | |
| 26 | 新增: } | |
| 27 | 新增: defer stdin.Close() | |
| 28 | 新增: stdout, err := cmd.StdoutPipe() | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: return err | |
| 31 | 新增: } | |
| 32 | 新增: var stderr bytes.Buffer | |
| 33 | 新增: cmd.Stderr = &stderr | |
| 34 | 新增: if err := cmd.Start(); err != nil { | |
| 35 | 新增: return err | |
| 36 | 新增: } | |
| 37 | 新增: done := make(chan struct{}) | |
| 38 | 新增: var waitErr error | |
| 39 | 新增: go func() { waitErr = cmd.Wait(); close(done) }() | |
| 40 | 新增: finish := func() { | |
| 41 | 新增: _ = stdin.Close() | |
| 42 | 新增: select { | |
| 43 | 新增: case <-done: | |
| 44 | 新增: case <-time.After(2 * time.Second): | |
| 45 | 新增: _ = cmd.Process.Kill() | |
| 46 | 新增: <-done | |
| 47 | 新增: } | |
| 48 | 新增: } | |
| 49 | 新增: defer finish() | |
| 50 | 新增: ack := make(chan bool, 1) | |
| 51 | 新增: go func() { line, err := bufio.NewReader(stdout).ReadString('\n'); ack <- err == nil && line == "ready\n" }() | |
| 52 | 新增: timer := time.NewTimer(5 * time.Second) | |
| 53 | 新增: defer timer.Stop() | |
| 54 | 新增: select { | |
| 55 | 新增: case <-ctx.Done(): | |
| 56 | 新增: return ctx.Err() | |
| 57 | 新增: case <-timer.C: | |
| 58 | 新增: return errors.New("主机防休眠请求超时") | |
| 59 | 新增: case ok := <-ack: | |
| 60 | 新增: if !ok { | |
| 61 | 新增: finish() | |
| 62 | 新增: message := strings.TrimSpace(stderr.String()) | |
| 63 | 新增: if len(message) > 512 { | |
| 64 | 新增: message = message[:512] | |
| 65 | 新增: } | |
| 66 | 新增: return errors.New("无法启用主机防休眠:" + message) | |
| 67 | 新增: } | |
| 68 | 新增: } | |
| 69 | 新增: ready() | |
| 70 | 新增: select { | |
| 71 | 新增: case <-ctx.Done(): | |
| 72 | 新增: return ctx.Err() | |
| 73 | 新增: case <-done: | |
| 74 | 新增: return waitErr | |
| 75 | 新增: } | |
| 76 | 新增:} | |
| @@ -1,3 +1,3 @@ | ||
| 1 | 删除:Filled by `make`: Lima's guest agent for this architecture (gzipped) and | |
| 2 | 删除:Lima's templates, embedded in agent-vm (see ../share.go). Without them, | |
| 3 | 删除:agent-vm builds but cannot create or start a VM. | |
| 1 | 新增:The Makefile places Lima's templates and the gzipped Linux guest agent here. | |
| 2 | 新增:Apple Silicon builds also place the macOS guest agent in Darwin/. Other builds | |
| 3 | 新增:exclude that directory. See ../share.go for extraction and guest selection. | |
| @@ -0,0 +1,6 @@ | ||
| 1 | 新增:package limaembed | |
| 2 | 新增: | |
| 3 | 新增:import "embed" | |
| 4 | 新增: | |
| 5 | 新增://go:embed all:assets | |
| 6 | 新增:var assets embed.FS | |
| @@ -0,0 +1,10 @@ | ||
| 1 | 新增://go:build !darwin || !arm64 | |
| 2 | 新增: | |
| 3 | 新增:package limaembed | |
| 4 | 新增: | |
| 5 | 新增:import "embed" | |
| 6 | 新增: | |
| 7 | 新增:// Exclude the Darwin directory even when cross-compiling in a Mac checkout. | |
| 8 | 新增:// | |
| 9 | 新增://go:embed all:assets/[^D]* | |
| 10 | 新增:var assets embed.FS | |
| @@ -0,0 +1,11 @@ | ||
| 1 | 新增:# Canonical Jammy release-20261106, verified against its published SHA256SUMS. | |
| 2 | 新增:# Keep this outside generated Lima assets so `make assets` preserves the pin. | |
| 3 | 新增:images: | |
| 4 | 新增:- location: "https://cloud-images.ubuntu.com/releases/jammy/release-20261106/ubuntu-22.04-server-cloudimg-amd64.img" | |
| 5 | 新增: arch: "x86_64" | |
| 6 | 新增: digest: "sha256:f77bc6d59cb8deaa9657095736b5f5003f7705b47055f01823459715c967de6a" | |
| 7 | 新增: bytes: 730617344 | |
| 8 | 新增:- location: "https://cloud-images.ubuntu.com/releases/jammy/release-20261106/ubuntu-22.04-server-cloudimg-arm64.img" | |
| 9 | 新增: arch: "aarch64" | |
| 10 | 新增: digest: "sha256:7fc0212296c65f8e20f8e9af89aaab9500ea4ec73cfb245afa0f2b509bb90785" | |
| 11 | 新增: bytes: 701041664 | |
| @@ -28,6 +28,7 @@ import ( | ||
| 28 | 28 | "github.com/sylvinus/agent-vm/internal/cage" |
| 29 | 29 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 30 | 30 | "github.com/sylvinus/agent-vm/internal/guard" |
| 31 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 31 | 32 | "github.com/sylvinus/agent-vm/internal/netguard" |
| 32 | 33 | "github.com/sylvinus/agent-vm/internal/state" |
| 33 | 34 | "github.com/sylvinus/agent-vm/internal/vmname" |
| @@ -116,6 +117,15 @@ func Run(args []string) bool { | ||
| 116 | 117 | if stopGateControl, err = cage.StartGateControl(path, filepath.Join(string(st), "lima", name), gate); err != nil { |
| 117 | 118 | logrus.Fatal(err) |
| 118 | 119 | } |
| 120 | 新增: if name == "mac" { | |
| 121 | 新增: // The installed Mac profile binds this exact VZ instance. Other | |
| 122 | 新增: // workloads retain their existing switch behavior. | |
| 123 | 新增: if binding, err := guestos.LoadMacOSProfile(filepath.Dir(path)); err != nil { | |
| 124 | 新增: logrus.Fatal(err) | |
| 125 | 新增: } else if binding != nil && binding.Instance == name { | |
| 126 | 新增: usernet.DroppedIPv6 = gate.ObserveDroppedIPv6 | |
| 127 | 新增: } | |
| 128 | 新增: } | |
| 119 | 129 | usernet.Outbound, usernet.GuestDial = gate.Allows, gate.DialContext |
| 120 | 130 | usernet.DNSExchange, dns.Exchange = gate.ExchangeDNS, gate.ExchangeDNS |
| 121 | 131 | } |
| @@ -2,7 +2,7 @@ package limaembed | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "crypto/sha256" |
| 5 | 删除: "embed" | |
| 5 | 新增: _ "embed" | |
| 6 | 6 | "errors" |
| 7 | 7 | "fmt" |
| 8 | 8 | "io/fs" |
| @@ -12,19 +12,28 @@ import ( | ||
| 12 | 12 | "strings" |
| 13 | 13 | ) |
| 14 | 14 | |
| 15 | 删除:// What Lima finds in <prefix>/share/lima next to limactl: the guest agent and | |
| 16 | 删除:// the templates. Put in by the Makefile; see assets/README. | |
| 17 | 删除:// | |
| 18 | 删除://go:embed all:assets | |
| 19 | 删除:var assets embed.FS | |
| 20 | 删除: | |
| 21 | 15 | // Share is Lima's share/lima, written out of the binary. |
| 22 | 16 | type Share struct { |
| 23 | 删除: // Dir holds templates/ and the guest agent. | |
| 24 | 删除: Dir string | |
| 25 | 删除: // GuestAgent is the guest agent for Linux guests of this host's | |
| 26 | 删除: // architecture, gzipped: Lima decompresses it. | |
| 27 | 删除: GuestAgent string | |
| 17 | 新增: // Dir holds templates/ and the bundled guest agents. | |
| 18 | 新增: Dir string | |
| 19 | 新增: guestAgents map[string]string | |
| 20 | 新增:} | |
| 21 | 新增: | |
| 22 | 新增:// Cage owns this pin independently of Lima's periodically regenerated templates. | |
| 23 | 新增:// | |
| 24 | 新增://go:embed host-images/ubuntu-22.04.yaml | |
| 25 | 新增:var ubuntu2204Image []byte | |
| 26 | 新增: | |
| 27 | 新增:// ReadImageTemplate returns the pinned images bundled with this application. | |
| 28 | 新增:func ReadImageTemplate(system string) ([]byte, error) { | |
| 29 | 新增: switch system { | |
| 30 | 新增: case "ubuntu-22.04": | |
| 31 | 新增: return ubuntu2204Image, nil | |
| 32 | 新增: case "debian-12", "debian-13", "ubuntu-24.04": | |
| 33 | 新增: return fs.ReadFile(assets, "assets/templates/_images/"+system+".yaml") | |
| 34 | 新增: default: | |
| 35 | 新增: return nil, fmt.Errorf("unsupported host image template %q", system) | |
| 36 | 新增: } | |
| 28 | 37 | } |
| 29 | 38 | |
| 30 | 39 | // Templates is where Lima reads templates from (LIMA_TEMPLATES_PATH). |
| @@ -32,6 +41,16 @@ func (s *Share) Templates() string { | ||
| 32 | 41 | return filepath.Join(s.Dir, "templates") |
| 33 | 42 | } |
| 34 | 43 | |
| 44 | 新增:// GuestAgent returns only helpers that were extracted from this executable. | |
| 45 | 新增:// An older installation may have left other binaries in the same directory. | |
| 46 | 新增:func (s *Share) GuestAgent(guestOS, arch string) (string, error) { | |
| 47 | 新增: name := "lima-guestagent." + guestOS + "-" + arch + ".gz" | |
| 48 | 新增: if agent, ok := s.guestAgents[name]; ok { | |
| 49 | 新增: return agent, nil | |
| 50 | 新增: } | |
| 51 | 新增: return "", fmt.Errorf("this build does not include the Lima guest agent for %s/%s", guestOS, arch) | |
| 52 | 新增:} | |
| 53 | 新增: | |
| 35 | 54 | // ErrNoAssets is returned by WriteShare when agent-vm was built without |
| 36 | 55 | // the guest agent (`go build` instead of `make`). |
| 37 | 56 | var ErrNoAssets = errors.New("this agent-vm was built without Lima's guest agent: build it with make") |
| @@ -40,12 +59,15 @@ var ErrNoAssets = errors.New("this agent-vm was built without Lima's guest agent | ||
| 40 | 59 | // missing or differs from the embedded copy, and returns where they are. The |
| 41 | 60 | // files are checked on every call: a damaged guest agent never reaches a VM. |
| 42 | 61 | func WriteShare(dir string) (*Share, error) { |
| 43 | 删除: agent := "lima-guestagent.Linux-" + guestArch() + ".gz" | |
| 44 | 删除: if _, err := fs.Stat(assets, "assets/"+agent); err != nil { | |
| 62 | 新增: return writeShare(dir, assets) | |
| 63 | 新增:} | |
| 64 | 新增: | |
| 65 | 新增:func writeShare(dir string, files fs.FS) (*Share, error) { | |
| 66 | 新增: if _, err := fs.Stat(files, "assets/lima-guestagent.Linux-"+guestArch()+".gz"); err != nil { | |
| 45 | 67 | return nil, ErrNoAssets |
| 46 | 68 | } |
| 47 | 删除: share := filepath.Join(dir, "share", "lima") | |
| 48 | 删除: err := fs.WalkDir(assets, "assets", func(p string, d fs.DirEntry, err error) error { | |
| 69 | 新增: share := &Share{Dir: filepath.Join(dir, "share", "lima"), guestAgents: make(map[string]string)} | |
| 70 | 新增: err := fs.WalkDir(files, "assets", func(p string, d fs.DirEntry, err error) error { | |
| 49 | 71 | if err != nil { |
| 50 | 72 | return err |
| 51 | 73 | } |
| @@ -53,20 +75,26 @@ func WriteShare(dir string) (*Share, error) { | ||
| 53 | 75 | if rel == "README" { |
| 54 | 76 | return nil |
| 55 | 77 | } |
| 56 | 删除: dst := filepath.Join(share, filepath.FromSlash(rel)) | |
| 78 | 新增: dst := filepath.Join(share.Dir, filepath.FromSlash(rel)) | |
| 57 | 79 | if d.IsDir() { |
| 58 | 80 | return os.MkdirAll(dst, 0o700) |
| 59 | 81 | } |
| 60 | 删除: want, err := assets.ReadFile(p) | |
| 82 | 新增: want, err := fs.ReadFile(files, p) | |
| 61 | 83 | if err != nil { |
| 62 | 84 | return err |
| 63 | 85 | } |
| 64 | 删除: return writeIfChanged(dst, want) | |
| 86 | 新增: if err := writeIfChanged(dst, want); err != nil { | |
| 87 | 新增: return err | |
| 88 | 新增: } | |
| 89 | 新增: if strings.HasPrefix(d.Name(), "lima-guestagent.") && strings.HasSuffix(d.Name(), ".gz") { | |
| 90 | 新增: share.guestAgents[d.Name()] = dst | |
| 91 | 新增: } | |
| 92 | 新增: return nil | |
| 65 | 93 | }) |
| 66 | 94 | if err != nil { |
| 67 | 删除: return nil, fmt.Errorf("writing Lima's files to %s: %w", share, err) | |
| 95 | 新增: return nil, fmt.Errorf("writing Lima's files to %s: %w", share.Dir, err) | |
| 68 | 96 | } |
| 69 | 删除: return &Share{Dir: share, GuestAgent: filepath.Join(share, agent)}, nil | |
| 97 | 新增: return share, nil | |
| 70 | 98 | } |
| 71 | 99 | |
| 72 | 100 | func writeIfChanged(dst string, want []byte) error { |
| @@ -0,0 +1,47 @@ | ||
| 1 | 新增:package limaembed | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "testing" | |
| 6 | 新增: "testing/fstest" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestGuestAgentMatchesGuestAndCurrentBuild(t *testing.T) { | |
| 10 | 新增: linuxArch := guestArch() | |
| 11 | 新增: const darwinFile = "assets/Darwin/lima-guestagent.Darwin-aarch64.gz" | |
| 12 | 新增: files := fstest.MapFS{ | |
| 13 | 新增: "assets/lima-guestagent.Linux-" + linuxArch + ".gz": {Data: []byte("linux")}, | |
| 14 | 新增: darwinFile: {Data: []byte("darwin")}, | |
| 15 | 新增: } | |
| 16 | 新增: dir := t.TempDir() | |
| 17 | 新增: share, err := writeShare(dir, files) | |
| 18 | 新增: if err != nil { | |
| 19 | 新增: t.Fatal(err) | |
| 20 | 新增: } | |
| 21 | 新增: for _, guest := range []struct{ os, arch, data string }{ | |
| 22 | 新增: {"Linux", linuxArch, "linux"}, | |
| 23 | 新增: {"Darwin", "aarch64", "darwin"}, | |
| 24 | 新增: } { | |
| 25 | 新增: path, err := share.GuestAgent(guest.os, guest.arch) | |
| 26 | 新增: if err != nil { | |
| 27 | 新增: t.Fatal(err) | |
| 28 | 新增: } | |
| 29 | 新增: data, err := os.ReadFile(path) | |
| 30 | 新增: if err != nil || string(data) != guest.data { | |
| 31 | 新增: t.Fatalf("%s/%s: read %q, %v", guest.os, guest.arch, data, err) | |
| 32 | 新增: } | |
| 33 | 新增: } | |
| 34 | 新增: if path, err := share.GuestAgent("Darwin", "x86_64"); err == nil { | |
| 35 | 新增: t.Fatalf("used %s for an unbundled architecture", path) | |
| 36 | 新增: } | |
| 37 | 新增: | |
| 38 | 新增: // A different build can reuse the same profile with the old file on disk. | |
| 39 | 新增: delete(files, darwinFile) | |
| 40 | 新增: share, err = writeShare(dir, files) | |
| 41 | 新增: if err != nil { | |
| 42 | 新增: t.Fatal(err) | |
| 43 | 新增: } | |
| 44 | 新增: if path, err := share.GuestAgent("Darwin", "aarch64"); err == nil { | |
| 45 | 新增: t.Fatalf("used %s after the build stopped bundling it", path) | |
| 46 | 新增: } | |
| 47 | 新增:} | |
| @@ -0,0 +1,9 @@ | ||
| 1 | 新增:#include <stdbool.h> | |
| 2 | 新增:#include <stdlib.h> | |
| 3 | 新增:void cageLoginLoop(void *machine); | |
| 4 | 新增:void cageLoginStop(void); | |
| 5 | 新增:void cageLoginEnable(bool enabled); | |
| 6 | 新增:void *cageLoginImage(int *size); | |
| 7 | 新增:bool cageLoginClick(int x, int y); | |
| 8 | 新增:bool cageLoginScroll(int x, int y, int deltaX, int deltaY); | |
| 9 | 新增:bool cageLoginKey(int code, bool shift); | |
| @@ -0,0 +1,84 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && !no_vz | |
| 2 | 新增:#import <Cocoa/Cocoa.h> | |
| 3 | 新增:#import <IOKit/hidsystem/IOLLEvent.h> | |
| 4 | 新增:#import "bridge.h" | |
| 5 | 新增:#import "../../scripts/guest-os/macos-setup-view.m" | |
| 6 | 新增: | |
| 7 | 新增:static VZVirtualMachine *machine; | |
| 8 | 新增:static CageGuestSetupView *loginView; | |
| 9 | 新增:// Match the virtual Mac's scanout. The input protocol retains its original | |
| 10 | 新增:// 16:10 coordinate system, regardless of host window size or display scaling. | |
| 11 | 新增:static const CGFloat scanWidth = 1920, scanHeight = 1200; | |
| 12 | 新增: | |
| 13 | 新增:void cageLoginLoop(void *ref) { | |
| 14 | 新增: @autoreleasepool { | |
| 15 | 新增: machine = (__bridge VZVirtualMachine *)ref; | |
| 16 | 新增: NSApplication *app = [NSApplication sharedApplication]; | |
| 17 | 新增: [app setActivationPolicy:NSApplicationActivationPolicyProhibited]; | |
| 18 | 新增: [app run]; | |
| 19 | 新增: [loginView close]; loginView = nil; machine = nil; | |
| 20 | 新增: } | |
| 21 | 新增:} | |
| 22 | 新增:void cageLoginStop(void) { | |
| 23 | 新增: dispatch_async(dispatch_get_main_queue(), ^{ | |
| 24 | 新增: [NSApp stop:nil]; | |
| 25 | 新增: [NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint | |
| 26 | 新增: modifierFlags:0 timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0] atStart:YES]; | |
| 27 | 新增: }); | |
| 28 | 新增:} | |
| 29 | 新增:void cageLoginEnable(bool enabled) { | |
| 30 | 新增: dispatch_sync(dispatch_get_main_queue(), ^{ | |
| 31 | 新增: [loginView close]; loginView = nil; | |
| 32 | 新增: if (enabled && machine) loginView = [[CageGuestSetupView alloc] initWithMachine:machine size:NSMakeSize(scanWidth,scanHeight) | |
| 33 | 新增: setupAuthorized:^BOOL { return machine != nil; }]; | |
| 34 | 新增: }); | |
| 35 | 新增:} | |
| 36 | 新增:void *cageLoginImage(int *size) { | |
| 37 | 新增: __block void *copy = NULL; | |
| 38 | 新增: dispatch_sync(dispatch_get_main_queue(), ^{ | |
| 39 | 新增: @autoreleasepool { | |
| 40 | 新增: NSData *image = [loginView snapshotJPEG]; | |
| 41 | 新增: if (image.length && image.length <= (4<<20)) { | |
| 42 | 新增: copy = malloc(image.length); | |
| 43 | 新增: if (copy) { memcpy(copy, image.bytes, image.length); *size = (int)image.length; } | |
| 44 | 新增: } | |
| 45 | 新增: } | |
| 46 | 新增: }); | |
| 47 | 新增: return copy; | |
| 48 | 新增:} | |
| 49 | 新增:bool cageLoginClick(int x, int y) { | |
| 50 | 新增: __block BOOL ok = NO; | |
| 51 | 新增: dispatch_sync(dispatch_get_main_queue(), ^{ ok = [loginView clickAtX:x * scanWidth / 1024.0 y:y * scanHeight / 640.0]; }); | |
| 52 | 新增: return ok; | |
| 53 | 新增:} | |
| 54 | 新增:bool cageLoginKey(int code, bool shift) { | |
| 55 | 新增: __block BOOL ok = NO; | |
| 56 | 新增: dispatch_sync(dispatch_get_main_queue(), ^{ | |
| 57 | 新增: if (!loginView) return; | |
| 58 | 新增: // A hardware modifier carries both the aggregate flag and the left/right | |
| 59 | 新增: // device bit. The offscreen view has no host keyboard state to inherit. | |
| 60 | 新增: NSEventModifierFlags flags = shift ? NSEventModifierFlagShift | NX_DEVICELSHIFTKEYMASK : 0; | |
| 61 | 新增: NSEvent *(^event)(NSEventType, int, NSEventModifierFlags) = ^NSEvent *(NSEventType kind, int key, NSEventModifierFlags mods) { | |
| 62 | 新增: return [NSEvent keyEventWithType:kind location:NSZeroPoint modifierFlags:mods timestamp:NSProcessInfo.processInfo.systemUptime | |
| 63 | 新增: windowNumber:0 context:nil characters:@"" charactersIgnoringModifiers:@"" isARepeat:NO keyCode:(unsigned short)key]; | |
| 64 | 新增: }; | |
| 65 | 新增: if (shift) { | |
| 66 | 新增: [loginView sendKey:event(NSEventTypeFlagsChanged,56,flags)]; | |
| 67 | 新增: [loginView sendKey:event(NSEventTypeKeyDown,56,flags)]; | |
| 68 | 新增: } | |
| 69 | 新增: ok = [loginView sendKey:event(NSEventTypeKeyDown,code,flags)] && [loginView sendKey:event(NSEventTypeKeyUp,code,flags)]; | |
| 70 | 新增: if (shift) { | |
| 71 | 新增: [loginView sendKey:event(NSEventTypeKeyUp,56,0)]; | |
| 72 | 新增: [loginView sendKey:event(NSEventTypeFlagsChanged,56,0)]; | |
| 73 | 新增: } | |
| 74 | 新增: }); | |
| 75 | 新增: return ok; | |
| 76 | 新增:} | |
| 77 | 新增:bool cageLoginScroll(int x, int y, int deltaX, int deltaY) { | |
| 78 | 新增: __block BOOL ok = NO; | |
| 79 | 新增: dispatch_sync(dispatch_get_main_queue(), ^{ | |
| 80 | 新增: ok = [loginView scrollAtX:x * scanWidth / 1024.0 y:y * scanHeight / 640.0 | |
| 81 | 新增: deltaX:deltaX * scanWidth / 1024.0 deltaY:deltaY * scanHeight / 640.0]; | |
| 82 | 新增: }); | |
| 83 | 新增: return ok; | |
| 84 | 新增:} | |
| @@ -0,0 +1,300 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:// Package maclogin presents only the Apple login screen of the bound trial VM. | |
| 4 | 新增:// The owner of the VZ instance creates its view on the AppKit main thread. | |
| 5 | 新增:package maclogin | |
| 6 | 新增: | |
| 7 | 新增:/* | |
| 8 | 新增:#cgo CFLAGS: -x objective-c -fobjc-arc | |
| 9 | 新增:#cgo LDFLAGS: -framework AppKit -framework Virtualization | |
| 10 | 新增:#include "bridge.h" | |
| 11 | 新增:*/ | |
| 12 | 新增:import "C" | |
| 13 | 新增: | |
| 14 | 新增:import ( | |
| 15 | 新增: "bytes" | |
| 16 | 新增: "context" | |
| 17 | 新增: "crypto/rand" | |
| 18 | 新增: "crypto/subtle" | |
| 19 | 新增: "encoding/json" | |
| 20 | 新增: "errors" | |
| 21 | 新增: "io" | |
| 22 | 新增: "net" | |
| 23 | 新增: "os" | |
| 24 | 新增: "os/exec" | |
| 25 | 新增: "path/filepath" | |
| 26 | 新增: "runtime" | |
| 27 | 新增: | |
| 28 | 新增: "al.essio.dev/pkg/shellescape" | |
| 29 | 新增: "time" | |
| 30 | 新增: "unsafe" | |
| 31 | 新增: | |
| 32 | 新增: apple "github.com/Code-Hex/vz/v3" | |
| 33 | 新增: driver "github.com/lima-vm/lima/v2/pkg/driver/vz" | |
| 34 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 35 | 新增:) | |
| 36 | 新增: | |
| 37 | 新增:type objectReference interface{ CageViewObject() unsafe.Pointer } | |
| 38 | 新增: | |
| 39 | 新增:func init() { | |
| 40 | 新增: if _, built := any((*apple.VirtualMachine)(nil)).(objectReference); !built { | |
| 41 | 新增: return | |
| 42 | 新增: } | |
| 43 | 新增: if len(os.Args) > 1 && (os.Args[1] == "hostagent" || os.Args[1] == "--debug") { | |
| 44 | 新增: runtime.LockOSThread() | |
| 45 | 新增: } | |
| 46 | 新增: driver.OwnsOffscreenView = func(dir string) bool { | |
| 47 | 新增: config := os.Getenv("CLAUDE_CAGE_CONFIG") | |
| 48 | 新增: if !filepath.IsAbs(config) || !sameGuestDirectory(dir, filepath.Join(filepath.Dir(config), "state", "lima", "mac")) { | |
| 49 | 新增: return false | |
| 50 | 新增: } | |
| 51 | 新增: profile, err := guestos.LoadMacOSProfile(filepath.Dir(config)) | |
| 52 | 新增: return err == nil && profile != nil | |
| 53 | 新增: } | |
| 54 | 新增: driver.OffscreenView = run | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:type request = guestos.MacLoginRequest | |
| 58 | 新增:type reply = guestos.MacLoginReply | |
| 59 | 新增: | |
| 60 | 新增:type loginSession struct { | |
| 61 | 新增: profile string | |
| 62 | 新增: token string | |
| 63 | 新增: expires time.Time | |
| 64 | 新增: screenID string | |
| 65 | 新增: setup bool | |
| 66 | 新增:} | |
| 67 | 新增: | |
| 68 | 新增:func (s *loginSession) currentScreen() string { | |
| 69 | 新增: // Check via the separate provisioning account. Guest development files | |
| 70 | 新增: // and the standard user's shell initialization cannot grant this view. | |
| 71 | 新增: bound, err := guestos.LoadMacOSProfile(s.profile) | |
| 72 | 新增: if err != nil || bound == nil { | |
| 73 | 新增: return "" | |
| 74 | 新增: } | |
| 75 | 新增: if s.setup { | |
| 76 | 新增: if bound.SetupID == "" { | |
| 77 | 新增: return "" | |
| 78 | 新增: } | |
| 79 | 新增: return "setup-" + bound.SetupID | |
| 80 | 新增: } | |
| 81 | 新增: args, err := guestos.MacOSSSHArgs(s.profile, "cage") | |
| 82 | 新增: if err != nil { | |
| 83 | 新增: return "" | |
| 84 | 新增: } | |
| 85 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond) | |
| 86 | 新增: defer cancel() | |
| 87 | 新增: script := `set -eu | |
| 88 | 新增:/usr/bin/pgrep -x loginwindow >/dev/null | |
| 89 | 新增:owner=$(/usr/bin/stat -f '%u %Su' /dev/console) | |
| 90 | 新增:if [ "$owner" = "0 root" ]; then /usr/bin/printf 'system-login'; exit 0; fi | |
| 91 | 新增:uid=$(/usr/bin/id -u ` + shellescape.Quote(bound.User) + `) | |
| 92 | 新增:/usr/bin/printf '%s %s\n' "$owner" "$uid" | |
| 93 | 新增:/usr/sbin/ioreg -a -d1 -c IORegistryEntry -k IOConsoleUsers -l | /usr/bin/plutil -extract IOConsoleUsers xml1 -o - -` | |
| 94 | 新增: cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", "exec /bin/sh -c "+shellescape.Quote(script))...) | |
| 95 | 新增: cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"} | |
| 96 | 新增: reader, err := cmd.StdoutPipe() | |
| 97 | 新增: if err != nil || cmd.Start() != nil { | |
| 98 | 新增: return "" | |
| 99 | 新增: } | |
| 100 | 新增: b, readErr := io.ReadAll(io.LimitReader(reader, (32<<10)+1)) | |
| 101 | 新增: if readErr != nil || len(b) > 32<<10 { | |
| 102 | 新增: cancel() | |
| 103 | 新增: } | |
| 104 | 新增: if err = cmd.Wait(); err != nil || readErr != nil || len(b) > 32<<10 { | |
| 105 | 新增: return "" | |
| 106 | 新增: } | |
| 107 | 新增: return permittedLoginScreen(bytes.TrimSpace(b), bound.User) | |
| 108 | 新增:} | |
| 109 | 新增: | |
| 110 | 新增:func (s *loginSession) close() { | |
| 111 | 新增: if s.token != "" { | |
| 112 | 新增: C.cageLoginEnable(false) | |
| 113 | 新增: } | |
| 114 | 新增: s.token = "" | |
| 115 | 新增: s.screenID = "" | |
| 116 | 新增: s.setup = false | |
| 117 | 新增:} | |
| 118 | 新增: | |
| 119 | 新增:func (s *loginSession) handle(in request) reply { | |
| 120 | 新增: if in.Action == "finish" && in.Setup { | |
| 121 | 新增: bound, err := guestos.LoadMacOSProfile(s.profile) | |
| 122 | 新增: if err != nil || bound == nil || bound.SetupID == "" { | |
| 123 | 新增: return reply{Closed: true} | |
| 124 | 新增: } | |
| 125 | 新增: s.close() | |
| 126 | 新增: if err = guestos.FinishMacOSSetup(s.profile, bound.SetupID); err != nil { | |
| 127 | 新增: return reply{Error: "未能保存首次设置,请重试"} | |
| 128 | 新增: } | |
| 129 | 新增: return reply{Closed: true} | |
| 130 | 新增: } | |
| 131 | 新增: if in.Action == "open" { | |
| 132 | 新增: s.close() | |
| 133 | 新增: s.setup = in.Setup | |
| 134 | 新增: s.screenID = s.currentScreen() | |
| 135 | 新增: if s.screenID == "" { | |
| 136 | 新增: return reply{Error: "客机已解锁,或尚未进入系统登录画面。"} | |
| 137 | 新增: } | |
| 138 | 新增: s.token = rand.Text() | |
| 139 | 新增: s.expires = time.Now().Add(2 * time.Minute) | |
| 140 | 新增: if s.setup { | |
| 141 | 新增: s.expires = time.Now().Add(15 * time.Minute) | |
| 142 | 新增: } | |
| 143 | 新增: C.cageLoginEnable(true) | |
| 144 | 新增: return reply{Session: s.token} | |
| 145 | 新增: } | |
| 146 | 新增: if s.token == "" || s.setup != in.Setup || subtle.ConstantTimeCompare([]byte(in.Session), []byte(s.token)) != 1 { | |
| 147 | 新增: return reply{Closed: true} | |
| 148 | 新增: } | |
| 149 | 新增: if time.Now().After(s.expires) || in.Action == "close" || s.currentScreen() != s.screenID { | |
| 150 | 新增: s.close() | |
| 151 | 新增: return reply{Closed: true} | |
| 152 | 新增: } | |
| 153 | 新增: switch in.Action { | |
| 154 | 新增: case "fill-password": | |
| 155 | 新增: sequence, valid := passwordKeys(in.Password) | |
| 156 | 新增: if !s.setup || !valid || !s.authorizationDialog() { | |
| 157 | 新增: return reply{Error: "请先打开系统授权对话框,并选中密码输入框"} | |
| 158 | 新增: } | |
| 159 | 新增: for _, key := range sequence { | |
| 160 | 新增: if !bool(C.cageLoginKey(C.int(key.code), C.bool(key.shift))) { | |
| 161 | 新增: return reply{Error: "授权密码未能填写,请重试"} | |
| 162 | 新增: } | |
| 163 | 新增: } | |
| 164 | 新增: case "frame": | |
| 165 | 新增: var n C.int | |
| 166 | 新增: p := C.cageLoginImage(&n) | |
| 167 | 新增: if p == nil { | |
| 168 | 新增: return reply{Error: "尚未收到 Apple 登录画面"} | |
| 169 | 新增: } | |
| 170 | 新增: defer C.free(p) | |
| 171 | 新增: if s.currentScreen() != s.screenID { | |
| 172 | 新增: s.close() | |
| 173 | 新增: return reply{Closed: true} | |
| 174 | 新增: } | |
| 175 | 新增: return reply{Image: C.GoBytes(p, n), MIME: "image/jpeg"} | |
| 176 | 新增: case "click": | |
| 177 | 新增: if in.X < 0 || in.Y < 0 || in.X >= 1024 || in.Y >= 640 || !bool(C.cageLoginClick(C.int(in.X), C.int(in.Y))) { | |
| 178 | 新增: return reply{Error: "无效的登录位置"} | |
| 179 | 新增: } | |
| 180 | 新增: case "key": | |
| 181 | 新增: // ANSI printable keys, Return, Tab, Escape and Backspace. No global shortcuts. | |
| 182 | 新增: setupNavigation := s.setup && (in.Code >= 123 && in.Code <= 126 || in.Code == 116 || in.Code == 121) | |
| 183 | 新增: if in.Code < 0 || (in.Code > 53 && !setupNavigation) || !bool(C.cageLoginKey(C.int(in.Code), C.bool(in.Shift))) { | |
| 184 | 新增: return reply{Error: "不支持此登录按键"} | |
| 185 | 新增: } | |
| 186 | 新增: if in.Code == 36 && !s.setup { | |
| 187 | 新增: s.close() | |
| 188 | 新增: return reply{Closed: true} | |
| 189 | 新增: } | |
| 190 | 新增: case "scroll": | |
| 191 | 新增: if !s.setup || in.X < 0 || in.Y < 0 || in.X >= 1024 || in.Y >= 640 || | |
| 192 | 新增: in.DeltaX < -512 || in.DeltaX > 512 || in.DeltaY < -512 || in.DeltaY > 512 || | |
| 193 | 新增: !bool(C.cageLoginScroll(C.int(in.X), C.int(in.Y), C.int(in.DeltaX), C.int(in.DeltaY))) { | |
| 194 | 新增: return reply{Error: "无效的首次设置滚动操作"} | |
| 195 | 新增: } | |
| 196 | 新增: default: | |
| 197 | 新增: return reply{Error: "未知的登录操作"} | |
| 198 | 新增: } | |
| 199 | 新增: return reply{} | |
| 200 | 新增:} | |
| 201 | 新增: | |
| 202 | 新增:func (s *loginSession) authorizationDialog() bool { | |
| 203 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) | |
| 204 | 新增: defer cancel() | |
| 205 | 新增: bound, err := guestos.LoadMacOSProfile(s.profile) | |
| 206 | 新增: if err != nil || bound == nil { | |
| 207 | 新增: return false | |
| 208 | 新增: } | |
| 209 | 新增: args, err := guestos.MacOSSSHArgs(s.profile, bound.User) | |
| 210 | 新增: if err != nil { | |
| 211 | 新增: return false | |
| 212 | 新增: } | |
| 213 | 新增: cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", `printf '%s\n' '{"action":"setup-password-focus"}' | /usr/bin/nc -U "$HOME/Library/Caches/dev.cage.GuestClaudeWindow/window.sock"`)...) | |
| 214 | 新增: cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"} | |
| 215 | 新增: data, err := cmd.Output() | |
| 216 | 新增: var result struct { | |
| 217 | 新增: Focused bool `json:"focused"` | |
| 218 | 新增: } | |
| 219 | 新增: return err == nil && json.Unmarshal(data, &result) == nil && result.Focused | |
| 220 | 新增:} | |
| 221 | 新增: | |
| 222 | 新增:func run(ctx context.Context, machine *apple.VirtualMachine, dir string) error { | |
| 223 | 新增: if !driver.OwnsOffscreenView(dir) { | |
| 224 | 新增: return errors.New("invalid local macOS login view") | |
| 225 | 新增: } | |
| 226 | 新增: socket := filepath.Join(dir, "cage-login.sock") | |
| 227 | 新增: if fi, err := os.Lstat(socket); err == nil { | |
| 228 | 新增: if fi.Mode()&os.ModeSocket == 0 { | |
| 229 | 新增: return errors.New("unexpected login socket path") | |
| 230 | 新增: } | |
| 231 | 新增: existing, err := net.DialTimeout("unix", socket, 300*time.Millisecond) | |
| 232 | 新增: if err == nil { | |
| 233 | 新增: existing.Close() | |
| 234 | 新增: return errors.New("this instance already has a login view") | |
| 235 | 新增: } | |
| 236 | 新增: if err = os.Remove(socket); err != nil { | |
| 237 | 新增: return err | |
| 238 | 新增: } | |
| 239 | 新增: } | |
| 240 | 新增: ln, err := net.ListenUnix("unix", &net.UnixAddr{Name: socket, Net: "unix"}) | |
| 241 | 新增: if err != nil { | |
| 242 | 新增: return err | |
| 243 | 新增: } | |
| 244 | 新增: defer ln.Close() | |
| 245 | 新增: if err = os.Chmod(socket, 0600); err != nil { | |
| 246 | 新增: return err | |
| 247 | 新增: } | |
| 248 | 新增: runCtx, cancel := context.WithCancel(ctx) | |
| 249 | 新增: defer cancel() | |
| 250 | 新增: s := loginSession{profile: filepath.Dir(os.Getenv("CLAUDE_CAGE_CONFIG"))} | |
| 251 | 新增: go func() { | |
| 252 | 新增: for { | |
| 253 | 新增: _ = ln.SetDeadline(time.Now().Add(time.Second)) | |
| 254 | 新增: conn, err := ln.Accept() | |
| 255 | 新增: if err != nil { | |
| 256 | 新增: if n, ok := err.(net.Error); ok && n.Timeout() && runCtx.Err() == nil { | |
| 257 | 新增: if s.token != "" && (time.Now().After(s.expires) || s.currentScreen() != s.screenID) { | |
| 258 | 新增: s.close() | |
| 259 | 新增: } | |
| 260 | 新增: continue | |
| 261 | 新增: } | |
| 262 | 新增: return | |
| 263 | 新增: } | |
| 264 | 新增: _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) | |
| 265 | 新增: var input request | |
| 266 | 新增: if json.NewDecoder(io.LimitReader(conn, 4096)).Decode(&input) == nil { | |
| 267 | 新增: _ = json.NewEncoder(conn).Encode(s.handle(input)) | |
| 268 | 新增: } | |
| 269 | 新增: _ = conn.Close() | |
| 270 | 新增: } | |
| 271 | 新增: }() | |
| 272 | 新增: go func() { | |
| 273 | 新增: ticker := time.NewTicker(250 * time.Millisecond) | |
| 274 | 新增: defer ticker.Stop() | |
| 275 | 新增: running := false | |
| 276 | 新增: for { | |
| 277 | 新增: select { | |
| 278 | 新增: case <-runCtx.Done(): | |
| 279 | 新增: C.cageLoginStop() | |
| 280 | 新增: return | |
| 281 | 新增: case <-ticker.C: | |
| 282 | 新增: state := machine.State() | |
| 283 | 新增: if state == apple.VirtualMachineStateRunning { | |
| 284 | 新增: running = true | |
| 285 | 新增: } | |
| 286 | 新增: if running && (state == apple.VirtualMachineStateStopped || state == apple.VirtualMachineStateError) { | |
| 287 | 新增: C.cageLoginStop() | |
| 288 | 新增: return | |
| 289 | 新增: } | |
| 290 | 新增: } | |
| 291 | 新增: } | |
| 292 | 新增: }() | |
| 293 | 新增: ref, ok := any(machine).(objectReference) | |
| 294 | 新增: if !ok { | |
| 295 | 新增: return errors.New("this build has no macOS login view") | |
| 296 | 新增: } | |
| 297 | 新增: C.cageLoginLoop(ref.CageViewObject()) | |
| 298 | 新增: runtime.KeepAlive(machine) | |
| 299 | 新增: return nil | |
| 300 | 新增:} | |
| @@ -0,0 +1,91 @@ | ||
| 1 | 新增:package maclogin | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "encoding/xml" | |
| 6 | 新增: "io" | |
| 7 | 新增: "os" | |
| 8 | 新增: "strconv" | |
| 9 | 新增: "strings" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/google/uuid" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:// The trusted guest probe supplies the console owner and bound account UID | |
| 15 | 新增:// before Apple's unmodified IOConsoleUsers array. Accept exactly one active, | |
| 16 | 新增:// completed, explicitly locked session for that same user. | |
| 17 | 新增:func permittedLoginScreen(data []byte, user string) string { | |
| 18 | 新增: if bytes.Equal(data, []byte("system-login")) { | |
| 19 | 新增: return "system-login" | |
| 20 | 新增: } | |
| 21 | 新增: header, payload, ok := bytes.Cut(data, []byte("\n")) | |
| 22 | 新增: fields := strings.Fields(string(header)) | |
| 23 | 新增: if !ok || len(fields) != 3 || fields[1] != user || fields[0] != fields[2] { | |
| 24 | 新增: return "" | |
| 25 | 新增: } | |
| 26 | 新增: uid, err := strconv.ParseUint(fields[0], 10, 32) | |
| 27 | 新增: if err != nil || uid < 500 || len(payload) > 32<<10 { | |
| 28 | 新增: return "" | |
| 29 | 新增: } | |
| 30 | 新增: type item struct { | |
| 31 | 新增: XMLName xml.Name | |
| 32 | 新增: Value string `xml:",chardata"` | |
| 33 | 新增: } | |
| 34 | 新增: var doc struct { | |
| 35 | 新增: XMLName xml.Name `xml:"plist"` | |
| 36 | 新增: Values []struct { | |
| 37 | 新增: XMLName xml.Name | |
| 38 | 新增: Records []struct { | |
| 39 | 新增: XMLName xml.Name | |
| 40 | 新增: Items []item `xml:",any"` | |
| 41 | 新增: } `xml:",any"` | |
| 42 | 新增: } `xml:",any"` | |
| 43 | 新增: } | |
| 44 | 新增: decoder := xml.NewDecoder(bytes.NewReader(bytes.TrimSpace(payload))) | |
| 45 | 新增: if decoder.Decode(&doc) != nil || len(doc.Values) != 1 || doc.Values[0].XMLName.Local != "array" { | |
| 46 | 新增: return "" | |
| 47 | 新增: } | |
| 48 | 新增: if _, err := decoder.Token(); err != io.EOF { | |
| 49 | 新增: return "" | |
| 50 | 新增: } | |
| 51 | 新增: key := "" | |
| 52 | 新增: for _, record := range doc.Values[0].Records { | |
| 53 | 新增: if record.XMLName.Local != "dict" || len(record.Items)%2 != 0 { | |
| 54 | 新增: return "" | |
| 55 | 新增: } | |
| 56 | 新增: values := map[string]item{} | |
| 57 | 新增: for i := 0; i < len(record.Items); i += 2 { | |
| 58 | 新增: k, v := record.Items[i], record.Items[i+1] | |
| 59 | 新增: if k.XMLName.Local != "key" || k.Value == "" || values[k.Value].XMLName.Local != "" { | |
| 60 | 新增: return "" | |
| 61 | 新增: } | |
| 62 | 新增: values[k.Value] = v | |
| 63 | 新增: } | |
| 64 | 新增: on := values["kCGSSessionOnConsoleKey"] | |
| 65 | 新增: if on.XMLName.Local == "false" && on.Value == "" { | |
| 66 | 新增: continue | |
| 67 | 新增: } | |
| 68 | 新增: boolTrue := func(k string) bool { v := values[k]; return v.XMLName.Local == "true" && v.Value == "" } | |
| 69 | 新增: id, name := values["kCGSSessionUserIDKey"], values["kCGSSessionUserNameKey"] | |
| 70 | 新增: session := values["CGSSessionUniqueSessionUUID"] | |
| 71 | 新增: sessionID, err := uuid.Parse(session.Value) | |
| 72 | 新增: if key != "" || !boolTrue("kCGSSessionOnConsoleKey") || !boolTrue("kCGSessionLoginDoneKey") || | |
| 73 | 新增: !boolTrue("CGSSessionScreenIsLocked") || id.XMLName.Local != "integer" || id.Value != fields[0] || | |
| 74 | 新增: name.XMLName.Local != "string" || name.Value != user || session.XMLName.Local != "string" || err != nil || sessionID == uuid.Nil { | |
| 75 | 新增: return "" | |
| 76 | 新增: } | |
| 77 | 新增: key = "locked-" + sessionID.String() | |
| 78 | 新增: } | |
| 79 | 新增: return key | |
| 80 | 新增:} | |
| 81 | 新增: | |
| 82 | 新增:// Lima can shorten a Unix socket path with a symlink on macOS. Bind the view | |
| 83 | 新增:// to the same existing instance directory, including /tmp and /private/tmp. | |
| 84 | 新增:func sameGuestDirectory(actual, expected string) bool { | |
| 85 | 新增: a, err := os.Stat(actual) | |
| 86 | 新增: if err != nil || !a.IsDir() { | |
| 87 | 新增: return false | |
| 88 | 新增: } | |
| 89 | 新增: b, err := os.Stat(expected) | |
| 90 | 新增: return err == nil && b.IsDir() && os.SameFile(a, b) | |
| 91 | 新增:} | |
| @@ -0,0 +1,51 @@ | ||
| 1 | 新增:package maclogin | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "strings" | |
| 7 | 新增: "testing" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func TestLockedConsoleBoundToOneUserAndSession(t *testing.T) { | |
| 11 | 新增: const session = "607bceb6-c53f-4253-bad4-9c22b4ae7325" | |
| 12 | 新增: const row = "<dict><key>kCGSSessionOnConsoleKey</key><true/><key>kCGSessionLoginDoneKey</key><true/><key>CGSSessionScreenIsLocked</key><true/><key>kCGSSessionUserIDKey</key><integer>502</integer><key>kCGSSessionUserNameKey</key><string>trial</string><key>CGSSessionUniqueSessionUUID</key><string>" + session + "</string></dict>" | |
| 13 | 新增: const other = "<dict><key>kCGSSessionOnConsoleKey</key><false/></dict>" | |
| 14 | 新增: makeProbe := func(header, rows string) string { return header + "\n<plist><array>" + rows + "</array></plist>" } | |
| 15 | 新增: valid := makeProbe("502 trial 502", row) | |
| 16 | 新增: for _, tc := range []struct{ label, input, want string }{ | |
| 17 | 新增: {"system login", "system-login", "system-login"}, | |
| 18 | 新增: {"locked", valid, "locked-" + session}, | |
| 19 | 新增: {"logged-out second user", makeProbe("502 trial 502", other+row), "locked-" + session}, | |
| 20 | 新增: {"unlocked", strings.Replace(valid, "ScreenIsLocked</key><true/>", "ScreenIsLocked</key><false/>", 1), ""}, | |
| 21 | 新增: {"missing lock value", strings.Replace(valid, "<key>CGSSessionScreenIsLocked</key><true/>", "", 1), ""}, | |
| 22 | 新增: {"wrong lock type", strings.Replace(valid, "ScreenIsLocked</key><true/>", "ScreenIsLocked</key><string>true</string>", 1), ""}, | |
| 23 | 新增: {"different console", makeProbe("503 other 502", row), ""}, | |
| 24 | 新增: {"different profile UID", makeProbe("503 trial 502", row), ""}, | |
| 25 | 新增: {"different registry UID", strings.Replace(valid, "<integer>502", "<integer>503", 1), ""}, | |
| 26 | 新增: {"different registry user", strings.Replace(valid, "<string>trial", "<string>other", 1), ""}, | |
| 27 | 新增: {"not logged in", strings.Replace(valid, "LoginDoneKey</key><true/>", "LoginDoneKey</key><false/>", 1), ""}, | |
| 28 | 新增: {"ambiguous", makeProbe("502 trial 502", row+row), ""}, | |
| 29 | 新增: {"missing session identity", strings.Replace(valid, session, "", 1), ""}, | |
| 30 | 新增: {"missing active flag", strings.Replace(valid, "<key>kCGSSessionOnConsoleKey</key><true/>", "", 1), ""}, | |
| 31 | 新增: {"bad plist", valid + "<", ""}, | |
| 32 | 新增: {"no session", makeProbe("502 trial 502", other), ""}, | |
| 33 | 新增: } { | |
| 34 | 新增: t.Run(tc.label, func(t *testing.T) { | |
| 35 | 新增: if got := permittedLoginScreen([]byte(tc.input), "trial"); got != tc.want { | |
| 36 | 新增: t.Fatalf("allowed screen %q; want %q", got, tc.want) | |
| 37 | 新增: } | |
| 38 | 新增: }) | |
| 39 | 新增: } | |
| 40 | 新增:} | |
| 41 | 新增: | |
| 42 | 新增:func TestOffscreenViewMatchesDirectoryAliases(t *testing.T) { | |
| 43 | 新增: instance := t.TempDir() | |
| 44 | 新增: alias := filepath.Join(t.TempDir(), "lima-mac") | |
| 45 | 新增: if err := os.Symlink(instance, alias); err != nil { | |
| 46 | 新增: t.Skipf("symlink unavailable: %v", err) | |
| 47 | 新增: } | |
| 48 | 新增: if !sameGuestDirectory(alias, instance) || sameGuestDirectory(t.TempDir(), instance) || sameGuestDirectory(filepath.Join(alias, "absent"), filepath.Join(instance, "absent")) { | |
| 49 | 新增: t.Fatal("offscreen view must be bound to an existing instance, including its socket path alias") | |
| 50 | 新增: } | |
| 51 | 新增:} | |
| @@ -0,0 +1,42 @@ | ||
| 1 | 新增:package maclogin | |
| 2 | 新增: | |
| 3 | 新增:type loginKey struct { | |
| 4 | 新增: code int | |
| 5 | 新增: shift bool | |
| 6 | 新增:} | |
| 7 | 新增: | |
| 8 | 新增:// These are the physical ANSI keys used by the installer's US login layout. | |
| 9 | 新增:func passwordKeys(password string) ([]loginKey, bool) { | |
| 10 | 新增: rows := []struct { | |
| 11 | 新增: characters string | |
| 12 | 新增: code int | |
| 13 | 新增: }{ | |
| 14 | 新增: {"aA", 0}, {"sS", 1}, {"dD", 2}, {"fF", 3}, {"hH", 4}, {"gG", 5}, {"zZ", 6}, {"xX", 7}, {"cC", 8}, {"vV", 9}, | |
| 15 | 新增: {"bB", 11}, {"qQ", 12}, {"wW", 13}, {"eE", 14}, {"rR", 15}, {"yY", 16}, {"tT", 17}, | |
| 16 | 新增: {"1!", 18}, {"2@", 19}, {"3#", 20}, {"4$", 21}, {"6^", 22}, {"5%", 23}, {"=+", 24}, {"9(", 25}, {"7&", 26}, {"-_", 27}, {"8*", 28}, {"0)", 29}, | |
| 17 | 新增: {"]}", 30}, {"oO", 31}, {"uU", 32}, {"[{", 33}, {"iI", 34}, {"pP", 35}, {"lL", 37}, {"jJ", 38}, {"'\"", 39}, {"kK", 40}, {";:", 41}, {"\\|", 42}, {",<", 43}, {"/?", 44}, {"nN", 45}, {"mM", 46}, {".>", 47}, {"`~", 50}, {" ", 49}, | |
| 18 | 新增: } | |
| 19 | 新增: if len(password) < 8 || len(password) > 256 { | |
| 20 | 新增: return nil, false | |
| 21 | 新增: } | |
| 22 | 新增: result := make([]loginKey, 0, len(password)) | |
| 23 | 新增: for _, ch := range password { | |
| 24 | 新增: found := false | |
| 25 | 新增: for _, row := range rows { | |
| 26 | 新增: for index, candidate := range row.characters { | |
| 27 | 新增: if ch == candidate { | |
| 28 | 新增: result = append(result, loginKey{row.code, index == 1}) | |
| 29 | 新增: found = true | |
| 30 | 新增: break | |
| 31 | 新增: } | |
| 32 | 新增: } | |
| 33 | 新增: if found { | |
| 34 | 新增: break | |
| 35 | 新增: } | |
| 36 | 新增: } | |
| 37 | 新增: if !found { | |
| 38 | 新增: return nil, false | |
| 39 | 新增: } | |
| 40 | 新增: } | |
| 41 | 新增: return result, true | |
| 42 | 新增:} | |
| @@ -0,0 +1,26 @@ | ||
| 1 | 新增:package maclogin | |
| 2 | 新增: | |
| 3 | 新增:import "testing" | |
| 4 | 新增: | |
| 5 | 新增:func TestPasswordKeysKeepPrintableKeysSeparateFromSubmit(t *testing.T) { | |
| 6 | 新增: keys, ok := passwordKeys("Aa7! _-\\\"[]{}") | |
| 7 | 新增: if !ok || len(keys) != 13 { | |
| 8 | 新增: t.Fatalf("password encoding failed: %v %d", ok, len(keys)) | |
| 9 | 新增: } | |
| 10 | 新增: if keys[0] != (loginKey{0, true}) || keys[1] != (loginKey{0, false}) || keys[3] != (loginKey{18, true}) { | |
| 11 | 新增: t.Fatal("shifted keys lost their physical code") | |
| 12 | 新增: } | |
| 13 | 新增: for _, key := range keys { | |
| 14 | 新增: if key.code == 36 || key.code == 48 || key.code == 53 { | |
| 15 | 新增: t.Fatal("password emitted a submit or navigation key") | |
| 16 | 新增: } | |
| 17 | 新增: } | |
| 18 | 新增: for _, value := range []string{"password\nreturn", "password\x00", "密码password"} { | |
| 19 | 新增: if _, ok := passwordKeys(value); ok { | |
| 20 | 新增: t.Fatal("accepted control or unsupported character") | |
| 21 | 新增: } | |
| 22 | 新增: } | |
| 23 | 新增: if _, ok := passwordKeys("short"); ok { | |
| 24 | 新增: t.Fatal("accepted invalid length") | |
| 25 | 新增: } | |
| 26 | 新增:} | |
| @@ -0,0 +1,52 @@ | ||
| 1 | 新增:package vm | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "io" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "strings" | |
| 9 | 新增: "testing" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/hostimage" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:func TestHostLinuxImageHasNoFallbackOrHostMounts(t *testing.T) { | |
| 16 | 新增: l := newTestLima(t) | |
| 17 | 新增: directory := t.TempDir() | |
| 18 | 新增: config := filepath.Join(directory, "config.json") | |
| 19 | 新增: data, _ := json.Marshal(cage.DefaultConfig()) | |
| 20 | 新增: if err := os.WriteFile(config, data, 0600); err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: t.Setenv(cage.ConfigEnv, config) | |
| 24 | 新增: plan := hostimage.Plan{Host: hostimage.Identity{System: "ubuntu-22.04", Version: "22.04", Arch: "amd64"}, Version: "22.04", Format: "qcow2", Path: filepath.Join(directory, "ubuntu.img"), Digest: "sha256:" + strings.Repeat("a", 64)} | |
| 25 | 新增: if err := hostimage.WriteLinuxTemplate(directory, plan); err != nil { | |
| 26 | 新增: t.Fatal(err) | |
| 27 | 新增: } | |
| 28 | 新增: template, err := hostimage.LinuxTemplate(directory) | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: t.Fatal(err) | |
| 31 | 新增: } | |
| 32 | 新增: none := []Mount{} | |
| 33 | 新增: if err := l.Create(t.Context(), "x", template, Settings{Mounts: &none, NoContainerd: true}, io.Discard); err != nil { | |
| 34 | 新增: t.Fatal(err) | |
| 35 | 新增: } | |
| 36 | 新增: instance, err := l.inspect(t.Context(), "x") | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: t.Fatal(err) | |
| 39 | 新增: } | |
| 40 | 新增: if len(instance.Config.Images) != 1 || instance.Config.Images[0].Location != plan.Path || string(instance.Config.Images[0].Digest) != plan.Digest { | |
| 41 | 新增: t.Fatalf("unexpected image fallback: %+v", instance.Config.Images) | |
| 42 | 新增: } | |
| 43 | 新增: if len(instance.Config.Mounts) != 0 { | |
| 44 | 新增: t.Fatal("host directories were mounted") | |
| 45 | 新增: } | |
| 46 | 新增: if err := hostimage.ClearLinuxTemplate(directory, plan); err != nil { | |
| 47 | 新增: t.Fatal(err) | |
| 48 | 新增: } | |
| 49 | 新增: if path, err := hostimage.LinuxTemplate(directory); err != nil || path != "template:debian-13" { | |
| 50 | 新增: t.Fatalf("selection was retained: %q %v", path, err) | |
| 51 | 新增: } | |
| 52 | 新增:} | |
| @@ -16,6 +16,7 @@ import ( | ||
| 16 | 16 | "strconv" |
| 17 | 17 | "strings" |
| 18 | 18 | "sync" |
| 19 | 新增: "time" | |
| 19 | 20 | |
| 20 | 21 | "al.essio.dev/pkg/shellescape" |
| 21 | 22 | "github.com/coreos/go-semver/semver" |
| @@ -326,10 +327,15 @@ func (l *Lima) Create(ctx context.Context, name, template string, s Settings, lo | ||
| 326 | 327 | e = append(e, ".images = "+string(images)) |
| 327 | 328 | // cloud-init rewrites Debian's mirror list after bootcmd. |
| 328 | 329 | // Configure it immediately before Lima installs dependencies. |
| 329 | 删除: e = append(e, `.provision += [{"mode": "dependency", "script": `+strconv.Quote(cage.DebianMirrorsScript)+`}]`) | |
| 330 | 新增: e = append(e, `.provision += [{"mode": "dependency", "script": `+strconv.Quote(cage.DebianPrepareScript)+`}]`) | |
| 330 | 331 | } |
| 331 | 332 | tz, _ := json.Marshal(cfg.Timezone) |
| 332 | 删除: e = append(e, ".propagateProxyEnv = false", `.env = {"http_proxy":"","https_proxy":"","ftp_proxy":"","no_proxy":"","HTTP_PROXY":"","HTTPS_PROXY":"","FTP_PROXY":"","NO_PROXY":"","ALL_PROXY":"","all_proxy":""}`, ".timezone = "+string(tz), ".user.name = \"cage\"", ".user.home = \"/home/cage\"", ".user.uid = 1000") | |
| 333 | 新增: e = append(e, ".propagateProxyEnv = false", `.env = {"http_proxy":"","https_proxy":"","ftp_proxy":"","no_proxy":"","HTTP_PROXY":"","HTTPS_PROXY":"","FTP_PROXY":"","NO_PROXY":"","ALL_PROXY":"","all_proxy":""}`, ".timezone = "+string(tz)) | |
| 334 | 新增: if tmpl.Config.OS != nil && *tmpl.Config.OS == limatype.DARWIN { | |
| 335 | 新增: e = append(e, `.user.name = "cageprovision"`, `.user.home = "/Users/cageprovision"`, `.user.comment = "Cage Provisioning"`, ".user.uid = 501", `.video.display = "offscreen"`) | |
| 336 | 新增: } else { | |
| 337 | 新增: e = append(e, `.user.name = "cage"`, `.user.home = "/home/cage"`, ".user.uid = 1000") | |
| 338 | 新增: } | |
| 333 | 339 | } |
| 334 | 340 | if len(e) > 0 { |
| 335 | 341 | if tmpl.Bytes, err = yqutil.EvaluateExpression(ctx, yqutil.Join(e), tmpl.Bytes); err != nil { |
| @@ -515,8 +521,25 @@ func (l *Lima) Start(ctx context.Context, name string, log io.Writer) error { | ||
| 515 | 521 | // Here, so that VMs made before it get it too; nothing is written when |
| 516 | 522 | // it is there already. |
| 517 | 523 | settings := Settings{noEphemeralPorts: true} |
| 518 | 删除: if os.Getenv(cage.ConfigEnv) != "" { | |
| 519 | 删除: settings.MemoryGiB, settings.CPUs = cage.ResourceLimits() | |
| 524 | 新增: if configPath := os.Getenv(cage.ConfigEnv); configPath != "" { | |
| 525 | 新增: allocation, loadErr := cage.LoadResourceAllocation(configPath) | |
| 526 | 新增: if loadErr != nil { | |
| 527 | 新增: return loadErr | |
| 528 | 新增: } | |
| 529 | 新增: settings.MemoryGiB, settings.CPUs, err = allocation.Limits() | |
| 530 | 新增: if *inst.Config.OS == limatype.DARWIN && err == nil { | |
| 531 | 新增: requirements, requirementErr := ReadMacOSResourceRequirements(inst.Dir) | |
| 532 | 新增: if requirementErr != nil { | |
| 533 | 新增: return requirementErr | |
| 534 | 新增: } | |
| 535 | 新增: settings.MemoryGiB, settings.CPUs, err = requirements.Limits(allocation) | |
| 536 | 新增: if err == nil { | |
| 537 | 新增: err = saveMacOSResourceRequirements(inst.Dir, requirements) | |
| 538 | 新增: } | |
| 539 | 新增: } | |
| 540 | 新增: if err != nil { | |
| 541 | 新增: return err | |
| 542 | 新增: } | |
| 520 | 543 | } |
| 521 | 544 | if err := l.Edit(ctx, name, settings); err != nil { |
| 522 | 545 | return err |
| @@ -530,11 +553,21 @@ func (l *Lima) Start(ctx context.Context, name string, log io.Writer) error { | ||
| 530 | 553 | if err := NetworkConfined(inst.Config); err != nil { |
| 531 | 554 | return err |
| 532 | 555 | } |
| 556 | 新增: var guestAgent string | |
| 557 | 新增: // Lima always needs the Darwin helper for first boot. Windows and FreeBSD | |
| 558 | 新增: // have no guest agent, and Linux plain mode works without one. | |
| 559 | 新增: if *inst.Config.OS == limatype.DARWIN || (*inst.Config.OS == limatype.LINUX && !*inst.Config.Plain) { | |
| 560 | 新增: guestAgent, err = share.GuestAgent(*inst.Config.OS, *inst.Config.Arch) | |
| 561 | 新增: if err != nil { | |
| 562 | 新增: return err | |
| 563 | 新增: } | |
| 564 | 新增: } | |
| 533 | 565 | return withLog(log, func() error { |
| 534 | 566 | if err := reconcile.Reconcile(ctx, name); err != nil { |
| 535 | 567 | return err |
| 536 | 568 | } |
| 537 | 删除: return instance.StartWithPaths(ctx, inst, false, false, "", share.GuestAgent) | |
| 569 | 新增: started := time.Now() | |
| 570 | 新增: return vmStartError(instance.StartWithPaths(ctx, inst, false, false, "", guestAgent), inst.Dir, started) | |
| 538 | 571 | }) |
| 539 | 572 | } |
| 540 | 573 | |
| @@ -16,12 +16,14 @@ import ( | ||
| 16 | 16 | "testing" |
| 17 | 17 | "time" |
| 18 | 18 | |
| 19 | 新增: "github.com/lima-vm/lima/v2/pkg/driverutil" | |
| 19 | 20 | "github.com/lima-vm/lima/v2/pkg/guestagent/api" |
| 20 | 21 | "github.com/lima-vm/lima/v2/pkg/hostagent/events" |
| 21 | 22 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 22 | 23 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 23 | 24 | "github.com/lima-vm/lima/v2/pkg/limayaml" |
| 24 | 25 | "github.com/lima-vm/lima/v2/pkg/portfwd" |
| 26 | 新增: "github.com/lima-vm/lima/v2/pkg/registry" | |
| 25 | 27 | |
| 26 | 28 | "github.com/sylvinus/agent-vm/internal/cage" |
| 27 | 29 | "github.com/sylvinus/agent-vm/internal/limaembed" |
| @@ -67,7 +69,7 @@ func TestCageDebianMirrors(t *testing.T) { | ||
| 67 | 69 | } |
| 68 | 70 | earlyAPT := false |
| 69 | 71 | for _, step := range instance.Config.Provision { |
| 70 | 删除: if step.Mode == limatype.ProvisionModeDependency && step.Script != nil && *step.Script == cage.DebianMirrorsScript { | |
| 72 | 新增: if step.Mode == limatype.ProvisionModeDependency && step.Script != nil && *step.Script == cage.DebianPrepareScript { | |
| 71 | 73 | earlyAPT = true |
| 72 | 74 | } |
| 73 | 75 | } |
| @@ -489,6 +491,48 @@ func TestUserLimaHome(t *testing.T) { | ||
| 489 | 491 | } |
| 490 | 492 | } |
| 491 | 493 | |
| 494 | 新增:func TestLimaDrivers(t *testing.T) { | |
| 495 | 新增: l := newTestLima(t) | |
| 496 | 新增: ctx := t.Context() | |
| 497 | 新增: none := []Mount{} | |
| 498 | 新增: if err := l.Create(ctx, "base", "template:debian-13", Settings{Mounts: &none}, io.Discard); err != nil { | |
| 499 | 新增: t.Fatal(err) | |
| 500 | 新增: } | |
| 501 | 新增: for _, kind := range []string{limatype.QEMU, limatype.VZ} { | |
| 502 | 新增: if registry.CheckInternalOrExternal(kind) != registry.Internal { | |
| 503 | 新增: continue | |
| 504 | 新增: } | |
| 505 | 新增: t.Run(kind, func(t *testing.T) { | |
| 506 | 新增: first, err := l.inspect(ctx, "base") | |
| 507 | 新增: if err != nil { | |
| 508 | 新增: t.Fatal(err) | |
| 509 | 新增: } | |
| 510 | 新增: second, err := l.inspect(ctx, "base") | |
| 511 | 新增: if err != nil { | |
| 512 | 新增: t.Fatal(err) | |
| 513 | 新增: } | |
| 514 | 新增: first.Dir = filepath.Join(first.Dir, "first") | |
| 515 | 新增: second.Dir = filepath.Join(second.Dir, "second") | |
| 516 | 新增: first.Config.VMType = &kind | |
| 517 | 新增: second.Config.VMType = &kind | |
| 518 | 新增: firstDriver, err := driverutil.CreateConfiguredDriver(ctx, first, 0) | |
| 519 | 新增: if err != nil { | |
| 520 | 新增: t.Fatal(err) | |
| 521 | 新增: } | |
| 522 | 新增: secondDriver, err := driverutil.CreateConfiguredDriver(ctx, second, 0) | |
| 523 | 新增: if err != nil { | |
| 524 | 新增: t.Fatal(err) | |
| 525 | 新增: } | |
| 526 | 新增: if firstDriver.Driver == secondDriver.Driver || firstDriver.Info(ctx).InstanceDir != first.Dir { | |
| 527 | 新增: t.Fatal("configuring another VM changed the first VM's driver") | |
| 528 | 新增: } | |
| 529 | 新增: if secondDriver.Info(ctx).InstanceDir != second.Dir { | |
| 530 | 新增: t.Fatal("the second driver lost its instance") | |
| 531 | 新增: } | |
| 532 | 新增: }) | |
| 533 | 新增: } | |
| 534 | 新增:} | |
| 535 | 新增: | |
| 492 | 536 | // Edits at once each write a whole lima.yaml, and leave nothing behind. |
| 493 | 537 | func TestLimaEditConcurrent(t *testing.T) { |
| 494 | 538 | ctx := context.Background() |
| @@ -0,0 +1,340 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && e2e && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:package vm | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bytes" | |
| 7 | 新增: "context" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "github.com/google/uuid" | |
| 10 | 新增: "image/png" | |
| 11 | 新增: "io" | |
| 12 | 新增: "os" | |
| 13 | 新增: "os/exec" | |
| 14 | 新增: "path/filepath" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "testing" | |
| 17 | 新增: "time" | |
| 18 | 新增: | |
| 19 | 新增: "al.essio.dev/pkg/shellescape" | |
| 20 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 21 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 22 | 新增: "github.com/sylvinus/agent-vm/internal/managedproxy" | |
| 23 | 新增:) | |
| 24 | 新增: | |
| 25 | 新增:// Run the signed test binary with CAGE_TEST_MACOS_IPSW pointing to an Apple | |
| 26 | 新增:// restore image. CAGE_TEST_CLAUDE_DMG optionally exercises the official app. | |
| 27 | 新增:func TestMacOSGuest(t *testing.T) { | |
| 28 | 新增: image := os.Getenv("CAGE_TEST_MACOS_IPSW") | |
| 29 | 新增: if image == "" { | |
| 30 | 新增: t.Skip("set CAGE_TEST_MACOS_IPSW to a local Apple restore image") | |
| 31 | 新增: } | |
| 32 | 新增: if !filepath.IsAbs(image) { | |
| 33 | 新增: t.Fatal("CAGE_TEST_MACOS_IPSW must be absolute") | |
| 34 | 新增: } | |
| 35 | 新增: if info, err := os.Stat(image); err != nil || !info.Mode().IsRegular() { | |
| 36 | 新增: t.Fatalf("invalid restore image %q: %v", image, err) | |
| 37 | 新增: } | |
| 38 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 45*time.Minute) | |
| 39 | 新增: defer cancel() | |
| 40 | 新增: profile, err := os.MkdirTemp("/tmp", "cgmac-") | |
| 41 | 新增: if err != nil { | |
| 42 | 新增: t.Fatal(err) | |
| 43 | 新增: } | |
| 44 | 新增: t.Cleanup(func() { | |
| 45 | 新增: if t.Failed() && os.Getenv("CAGE_TEST_KEEP_FAILED_VM") == "1" { | |
| 46 | 新增: t.Log("Retained this test's private VM for diagnosis:", profile) | |
| 47 | 新增: return | |
| 48 | 新增: } | |
| 49 | 新增: if err := os.RemoveAll(profile); err != nil { | |
| 50 | 新增: t.Error(err) | |
| 51 | 新增: } | |
| 52 | 新增: }) | |
| 53 | 新增: configPath := filepath.Join(profile, "config.json") | |
| 54 | 新增: state := filepath.Join(profile, "state") | |
| 55 | 新增: t.Setenv(cage.ConfigEnv, configPath) | |
| 56 | 新增: t.Setenv("AGENT_VM_STATE_DIR", state) | |
| 57 | 新增: t.Setenv("LIMA_HOME", filepath.Join(state, "lima")) | |
| 58 | 新增: t.Setenv("LIMA_CACHE_HOME", filepath.Join(profile, "cache")) | |
| 59 | 新增: t.Setenv("AGENT_VM_UNSAFE_OPEN_NETWORK", "") | |
| 60 | 新增: t.Setenv("AGENT_VM_UNSAFE_WRITABLE_GIT", "") | |
| 61 | 新增: t.Setenv("AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS", "") | |
| 62 | 新增: // Use a private, unstarted proxy configuration. Installation uses local | |
| 63 | 新增: // media and SSH. No part of this test requires external guest traffic. | |
| 64 | 新增: proxy, err := managedproxy.Load(profile) | |
| 65 | 新增: if err != nil { | |
| 66 | 新增: t.Fatal(err) | |
| 67 | 新增: } | |
| 68 | 新增: if err := proxy.Import("offline", "", []byte("proxies: [{name: offline, type: socks5, server: 127.0.0.1, port: 9}]"), "offline", 0, ""); err != nil { | |
| 69 | 新增: t.Fatal(err) | |
| 70 | 新增: } | |
| 71 | 新增: proxy.Selected = proxy.Sources[0].Nodes[0].ID | |
| 72 | 新增: proxy.Revision = "offline" | |
| 73 | 新增: if err := proxy.Save(profile); err != nil { | |
| 74 | 新增: t.Fatal(err) | |
| 75 | 新增: } | |
| 76 | 新增: cfg := cage.DefaultConfig() | |
| 77 | 新增: cfg.ProxyURL, cfg.ProxyRevision = proxy.Endpoint(), proxy.Revision | |
| 78 | 新增: writeJSON := func(path string, value any) { | |
| 79 | 新增: t.Helper() | |
| 80 | 新增: data, err := json.Marshal(value) | |
| 81 | 新增: if err != nil { | |
| 82 | 新增: t.Fatal(err) | |
| 83 | 新增: } | |
| 84 | 新增: if err := os.WriteFile(path, data, 0600); err != nil { | |
| 85 | 新增: t.Fatal(err) | |
| 86 | 新增: } | |
| 87 | 新增: } | |
| 88 | 新增: writeJSON(configPath, cfg) | |
| 89 | 新增: writeJSON(cage.ResourceAllocationPath(configPath), cage.ResourceAllocation{MemoryGiB: 4, CPUs: 2}) | |
| 90 | 新增: l, err := NewLima(filepath.Join(state, "lima"), state) | |
| 91 | 新增: if err != nil { | |
| 92 | 新增: t.Fatal(err) | |
| 93 | 新增: } | |
| 94 | 新增: const name = "mac" | |
| 95 | 新增: if err := l.CreateMacOSFromIPSW(ctx, name, image, Settings{CPUs: 2, MemoryGiB: 4, DiskGiB: 64}, os.Stderr); err != nil { | |
| 96 | 新增: t.Fatal(err) | |
| 97 | 新增: } | |
| 98 | 新增: t.Cleanup(func() { | |
| 99 | 新增: cleanup, cancel := context.WithTimeout(context.Background(), time.Minute) | |
| 100 | 新增: defer cancel() | |
| 101 | 新增: if err := l.Stop(cleanup, name); err != nil { | |
| 102 | 新增: t.Error(err) | |
| 103 | 新增: } | |
| 104 | 新增: }) | |
| 105 | 新增: t.Log("Restoring a new macOS test VM from local media") | |
| 106 | 新增: if err := l.Start(ctx, name, os.Stderr); err != nil { | |
| 107 | 新增: t.Fatal(err) | |
| 108 | 新增: } | |
| 109 | 新增: run := func(script string, input io.Reader) string { | |
| 110 | 新增: t.Helper() | |
| 111 | 新增: var out bytes.Buffer | |
| 112 | 新增: code, err := l.Shell(ctx, name, ShellOpts{Args: []string{"/bin/sh", "-ec", script}, Stdin: input, Stdout: &out, Stderr: &out}) | |
| 113 | 新增: if err != nil || code != 0 { | |
| 114 | 新增: t.Fatalf("guest command failed (%d): %v\n%s", code, err, out.String()) | |
| 115 | 新增: } | |
| 116 | 新增: return strings.TrimSpace(out.String()) | |
| 117 | 新增: } | |
| 118 | 新增: t.Log(run("test \"$(uname -s)\" = Darwin && /usr/bin/sw_vers && test \"$HOME\" = /Users/cageprovision", nil)) | |
| 119 | 新增: run("cd \"$HOME\" && /usr/bin/osacompile -l JavaScript -o cage-qa.scpt -e '6*7' && test \"$(/usr/bin/osascript cage-qa.scpt)\" = 42", nil) | |
| 120 | 新增: serialKey, err := guestos.MacOSInstallHostKey(profile) | |
| 121 | 新增: if err != nil { | |
| 122 | 新增: t.Fatal(err) | |
| 123 | 新增: } | |
| 124 | 新增: guestKey := run("cat /etc/ssh/ssh_host_ed25519_key.pub", nil) | |
| 125 | 新增: if !strings.HasPrefix(guestKey+" ", strings.TrimSpace(string(serialKey))+" ") { | |
| 126 | 新增: t.Fatal("VZ serial key differs from the restored guest identity") | |
| 127 | 新增: } | |
| 128 | 新增: if kit := os.Getenv("CAGE_TEST_MACOS_AUTOMATION_KIT"); kit != "" { | |
| 129 | 新增: // Minimal first-run experiment: the production account receipt and session | |
| 130 | 新增: // configuration run in a newly restored VM, with no daily guest data. | |
| 131 | 新增: tar := exec.CommandContext(ctx, "/usr/bin/tar", "--no-mac-metadata", "-cf", "-", "-C", kit, ".") | |
| 132 | 新增: pipe, err := tar.StdoutPipe() | |
| 133 | 新增: if err != nil { | |
| 134 | 新增: t.Fatal(err) | |
| 135 | 新增: } | |
| 136 | 新增: if err := tar.Start(); err != nil { | |
| 137 | 新增: t.Fatal(err) | |
| 138 | 新增: } | |
| 139 | 新增: run(`mkdir "$HOME/automation-kit"; cd "$HOME/automation-kit"; tar -xf -`, pipe) | |
| 140 | 新增: if err := tar.Wait(); err != nil { | |
| 141 | 新增: t.Fatal(err) | |
| 142 | 新增: } | |
| 143 | 新增: password := "Aa7!" + uuid.NewString() | |
| 144 | 新增: run(`umask 077; cat > "$HOME/automation-input"`, strings.NewReader(password+"\n")) | |
| 145 | 新增: admin := func(script string) string { | |
| 146 | 新增: return run("sudo -S -p '' /bin/bash -ec "+shellescape.Quote(script)+` < "$HOME/password"`, nil) | |
| 147 | 新增: } | |
| 148 | 新增: installation := uuid.NewString() | |
| 149 | 新增: admin(`echo macos > /var/db/cage-guest-os; chmod 600 /var/db/cage-guest-os; chown -R root:wheel /Users/cageprovision/automation-kit; | |
| 150 | 新增:printf '%s\n' "$(cat /Users/cageprovision/automation-input)" | sysadminctl -addUser cage -fullName cage -password - -home /Users/cage; | |
| 151 | 新增:createhomedir -c -u cage >/dev/null; | |
| 152 | 新增:/Users/cageprovision/automation-kit/cage-finish-initial-setup prepare ` + installation + ` < /Users/cageprovision/automation-input; | |
| 153 | 新增:/bin/bash /Users/cageprovision/automation-kit/configure-macos-session.sh cage ` + installation + ` < /Users/cageprovision/automation-input`) | |
| 154 | 新增: run(`test "$(sudo -S -p '' defaults read /Library/Preferences/com.apple.loginwindow autoLoginUser < "$HOME/password")" = cage`, nil) | |
| 155 | 新增: if err := l.Stop(ctx, name); err != nil { | |
| 156 | 新增: t.Fatal(err) | |
| 157 | 新增: } | |
| 158 | 新增: if err := l.Start(ctx, name, os.Stderr); err != nil { | |
| 159 | 新增: t.Fatal(err) | |
| 160 | 新增: } | |
| 161 | 新增: loggedIn := false | |
| 162 | 新增: for i := 0; i < 60; i++ { | |
| 163 | 新增: if run(`stat -f '%Su' /dev/console`, nil) == "cage" { | |
| 164 | 新增: loggedIn = true | |
| 165 | 新增: break | |
| 166 | 新增: } | |
| 167 | 新增: time.Sleep(time.Second) | |
| 168 | 新增: } | |
| 169 | 新增: if !loggedIn { | |
| 170 | 新增: t.Fatal("guest did not automatically log in") | |
| 171 | 新增: } | |
| 172 | 新增: admin(`! pgrep -x 'Setup Assistant' >/dev/null; uid=$(id -u cage); launchctl print gui/$uid >/dev/null; | |
| 173 | 新增:/Users/cageprovision/automation-kit/cage-finish-initial-setup; | |
| 174 | 新增:! id -Gn cage | grep -qw admin; ! id -Gn cagesetup | grep -qw admin; | |
| 175 | 新增:test "$(stat -f %OLp /etc/kcpassword)" = 600`) | |
| 176 | 新增: t.Log("Fresh guest: automatic graphical login, skipped optional Setup Assistant, standard account and retired temporary administrator verified") | |
| 177 | 新增: return | |
| 178 | 新增: } | |
| 179 | 新增: if kit, media := os.Getenv("CAGE_TEST_MACOS_WORKBENCH_KIT"), os.Getenv("CAGE_TEST_MACOS_WORKBENCH_MEDIA"); kit != "" && media != "" { | |
| 180 | 新增: // Exercise the shipped provisioning script in this disposable fresh VM. | |
| 181 | 新增: tar := exec.CommandContext(ctx, "/usr/bin/tar", "--no-mac-metadata", "-cf", "-", "-C", kit, ".", "-C", media, "node.tgz", "editor.tgz", "playwright.tgz", "chrome.dmg", "claude.dmg", "cli", "macfuse.pkg") | |
| 182 | 新增: pipe, err := tar.StdoutPipe() | |
| 183 | 新增: if err != nil { | |
| 184 | 新增: t.Fatal(err) | |
| 185 | 新增: } | |
| 186 | 新增: tar.Stderr = os.Stderr | |
| 187 | 新增: if err := tar.Start(); err != nil { | |
| 188 | 新增: t.Fatal(err) | |
| 189 | 新增: } | |
| 190 | 新增: run(`mkdir "$HOME/kit"; cd "$HOME/kit"; tar -xf -; mv macfuse.pkg project/macfuse.pkg`, pipe) | |
| 191 | 新增: if err := tar.Wait(); err != nil { | |
| 192 | 新增: t.Fatal(err) | |
| 193 | 新增: } | |
| 194 | 新增: password := "Aa7!" + uuid.NewString() | |
| 195 | 新增: run(`umask 077; cat > "$HOME/login-input"`, strings.NewReader(password+"\n")) | |
| 196 | 新增: admin := func(script string) string { | |
| 197 | 新增: return run("sudo -S -p '' /bin/bash -ec "+shellescape.Quote(script)+` < "$HOME/password"`, nil) | |
| 198 | 新增: } | |
| 199 | 新增: stage := admin(`mktemp -d /private/var/tmp/cage-install.XXXXXXXX`) | |
| 200 | 新增: admin(`mv /Users/cageprovision/kit ` + stage + `/kit; chown -R root:wheel ` + stage + `; cd /; /bin/bash ` + stage + `/kit/provision-macos-workbench.sh ` + stage + `/kit ` + uuid.NewString() + ` cageprovision < /Users/cageprovision/login-input`) | |
| 201 | 新增: run(`/usr/bin/dscl /Local/Default -authonly cage >/dev/null`, strings.NewReader(password+"\n")) | |
| 202 | 新增: admin(`test "$(dscl . -read /Users/cage NFSHomeDirectory)" = 'NFSHomeDirectory: /Users/cage'; if id -Gn cage | grep -qw admin; then exit 1; fi; dscl . -read /Users/cageprovision IsHidden | grep -q ": 1$"; /usr/local/libexec/cage-finish-initial-setup`) | |
| 203 | 新增: admin(`if id -Gn cagesetup | grep -qw admin; then exit 1; fi; dscl . -read /Users/cagesetup UserShell | grep -q /usr/bin/false`) | |
| 204 | 新增: t.Log("Fresh cage account, user-selected password, ordinary privileges and temporary administrator retirement verified") | |
| 205 | 新增: } | |
| 206 | 新增: verifyMacOSGuestNetwork(t, ctx, filepath.Join(state, "lima", name), run) | |
| 207 | 新增: verifyMacOSProjectTransfer(t, ctx, l, name) | |
| 208 | 新增: if err := l.Stop(ctx, name); err != nil { | |
| 209 | 新增: t.Fatal(err) | |
| 210 | 新增: } | |
| 211 | 新增: if err := l.Start(ctx, name, os.Stderr); err != nil { | |
| 212 | 新增: t.Fatal(err) | |
| 213 | 新增: } | |
| 214 | 新增: run("test \"$(/usr/bin/osascript \"$HOME/cage-qa.scpt\")\" = 42", nil) | |
| 215 | 新增: t.Log("Native compilation, closed external connection and persistent disk verified") | |
| 216 | 新增: if dmg := os.Getenv("CAGE_TEST_CLAUDE_DMG"); dmg != "" { | |
| 217 | 新增: h, err := os.ReadFile("../../scripts/guest-os/claude-desktop-macos.sh") | |
| 218 | 新增: if err != nil { | |
| 219 | 新增: t.Fatal(err) | |
| 220 | 新增: } | |
| 221 | 新增: run("umask 077; cat > \"$HOME/claude-desktop-qa.sh\"", bytes.NewReader(h)) | |
| 222 | 新增: f, err := os.Open(dmg) | |
| 223 | 新增: if err != nil { | |
| 224 | 新增: t.Fatal(err) | |
| 225 | 新增: } | |
| 226 | 新增: defer f.Close() | |
| 227 | 新增: run("umask 077; cat > \"$HOME/Claude.dmg\"", f) | |
| 228 | 新增: // Lima generates a random password inside this new VM. Use it only | |
| 229 | 新增: // for this guest's privileged setup, without transferring it to the host. | |
| 230 | 新增: admin := func(script string) string { | |
| 231 | 新增: t.Helper() | |
| 232 | 新增: return run("sudo -S -p '' -- /bin/sh -ec "+shellescape.Quote(script)+` < "$HOME/password"`, nil) | |
| 233 | 新增: } | |
| 234 | 新增: admin("umask 022; echo macos > /var/db/cage-guest-os") | |
| 235 | 新增: t.Log(admin("/bin/bash /Users/cageprovision/claude-desktop-qa.sh install /Users/cageprovision/Claude.dmg")) | |
| 236 | 新增: t.Log(run("/bin/bash \"$HOME/claude-desktop-qa.sh\" inspect", nil)) | |
| 237 | 新增: if helper := os.Getenv("CAGE_TEST_CLAUDE_WINDOW"); helper != "" { | |
| 238 | 新增: t.Log(run("/bin/bash \"$HOME/claude-desktop-qa.sh\" launch", nil)) | |
| 239 | 新增: f, err := os.Open(helper) | |
| 240 | 新增: if err != nil { | |
| 241 | 新增: t.Fatal(err) | |
| 242 | 新增: } | |
| 243 | 新增: defer f.Close() | |
| 244 | 新增: run(`umask 077; cat > "$HOME/window-helper"`, f) | |
| 245 | 新增: admin("mkdir -p /usr/local/libexec && install -o root -g wheel -m 755 /Users/cageprovision/window-helper /usr/local/libexec/cage-claude-window") | |
| 246 | 新增: var frame, stderr bytes.Buffer | |
| 247 | 新增: code, err := l.Shell(ctx, name, ShellOpts{ | |
| 248 | 新增: Args: []string{"/bin/sh", "-ec", `sudo -S -p '' /bin/launchctl asuser "$(id -u)" sudo -nu "$(id -un)" -- /usr/local/libexec/cage-claude-window < "$HOME/password"`}, | |
| 249 | 新增: Stdout: &frame, Stderr: &stderr, | |
| 250 | 新增: }) | |
| 251 | 新增: if err != nil || code != 0 { | |
| 252 | 新增: t.Fatalf("single-window capture (%d): %v %s", code, err, stderr.String()) | |
| 253 | 新增: } | |
| 254 | 新增: img, err := png.DecodeConfig(&frame) | |
| 255 | 新增: if err != nil || img.Width <= 0 || img.Height <= 0 { | |
| 256 | 新增: t.Fatalf("invalid window PNG: %v", err) | |
| 257 | 新增: } | |
| 258 | 新增: t.Logf("Verified Claude window PNG, %d × %d", img.Width, img.Height) | |
| 259 | 新增: } | |
| 260 | 新增: } | |
| 261 | 新增:} | |
| 262 | 新增: | |
| 263 | 新增:// A failed request alone could mean that the guest network is misconfigured. | |
| 264 | 新增:// Check that each guest probe reached the closed gate for this instance. | |
| 265 | 新增:func verifyMacOSGuestNetwork(t *testing.T, ctx context.Context, instance string, run func(string, io.Reader) string) { | |
| 266 | 新增: t.Helper() | |
| 267 | 新增: client, err := cage.OpenGateClient(instance) | |
| 268 | 新增: if err != nil { | |
| 269 | 新增: t.Fatal(err) | |
| 270 | 新增: } | |
| 271 | 新增: status := func() cage.GateStatus { | |
| 272 | 新增: t.Helper() | |
| 273 | 新增: s, err := client.Status(ctx) | |
| 274 | 新增: if err != nil { | |
| 275 | 新增: t.Fatal(err) | |
| 276 | 新增: } | |
| 277 | 新增: if s.Mode != cage.GateClosed { | |
| 278 | 新增: t.Fatalf("expected a closed network gate, got %q", s.Mode) | |
| 279 | 新增: } | |
| 280 | 新增: return s | |
| 281 | 新增: } | |
| 282 | 新增: check := func(label, script string, denied func(cage.GateCounters) uint64) { | |
| 283 | 新增: t.Helper() | |
| 284 | 新增: before := status() | |
| 285 | 新增: run(script, nil) | |
| 286 | 新增: deadline := time.Now().Add(3 * time.Second) | |
| 287 | 新增: for { | |
| 288 | 新增: after := status() | |
| 289 | 新增: if after.RunID != before.RunID || after.Epoch != before.Epoch { | |
| 290 | 新增: t.Fatalf("network gate changed during %s probe", label) | |
| 291 | 新增: } | |
| 292 | 新增: if n := denied(after.Counters); n > denied(before.Counters) { | |
| 293 | 新增: t.Logf("Closed gate denied guest %s (%d → %d)", label, denied(before.Counters), n) | |
| 294 | 新增: return | |
| 295 | 新增: } | |
| 296 | 新增: if time.Now().After(deadline) { | |
| 297 | 新增: t.Fatalf("host gate did not record the guest %s probe", label) | |
| 298 | 新增: } | |
| 299 | 新增: time.Sleep(100 * time.Millisecond) | |
| 300 | 新增: } | |
| 301 | 新增: } | |
| 302 | 新增: check("TCP", "if /usr/bin/nc -G 2 -z 1.1.1.1 443; then exit 1; fi", func(c cage.GateCounters) uint64 { return c.TCPDenied }) | |
| 303 | 新增: // Sending a UDP datagram can succeed locally even when the host drops it. | |
| 304 | 新增: check("UDP", "printf cage | /usr/bin/nc -u -w 1 1.1.1.1 3478", func(c cage.GateCounters) uint64 { return c.UDPDenied }) | |
| 305 | 新增: check("DNS", `resolver=$(awk '/^nameserver[[:space:]]/{print $2; exit}' /etc/resolv.conf) | |
| 306 | 新增:test -n "$resolver" | |
| 307 | 新增:response=$(/usr/bin/dig @"$resolver" +time=2 +tries=1 +noall +comments +answer "cage-check-$(uuidgen).example.com." A) || : | |
| 308 | 新增:if printf '%s\n' "$response" | grep -Eq 'status: NOERROR|[[:space:]]IN[[:space:]]+A[[:space:]]'; then exit 1; fi`, func(c cage.GateCounters) uint64 { return c.DNSDenied }) | |
| 309 | 新增: | |
| 310 | 新增: if _, err := client.BeginCheck(ctx); err != nil { | |
| 311 | 新增: t.Fatal(err) | |
| 312 | 新增: } | |
| 313 | 新增: defer func() { | |
| 314 | 新增: if _, err := client.Close(ctx, "guest network test finished"); err != nil { | |
| 315 | 新增: t.Error(err) | |
| 316 | 新增: } | |
| 317 | 新增: }() | |
| 318 | 新增: probe := func(path, want string) { | |
| 319 | 新增: t.Helper() | |
| 320 | 新增: response := run("curl --noproxy '*' -sS --max-time 15 -o /dev/null -w '%{http_code}' http://"+cage.DiagnosticHost+path, nil) | |
| 321 | 新增: if response != want { | |
| 322 | 新增: t.Fatalf("guest diagnostic %s: got %q, want %q", path, response, want) | |
| 323 | 新增: } | |
| 324 | 新增: } | |
| 325 | 新增: probe("/", "200") | |
| 326 | 新增: before, err := client.SetFault(ctx, true) | |
| 327 | 新增: if err != nil { | |
| 328 | 新增: t.Fatal(err) | |
| 329 | 新增: } | |
| 330 | 新增: probe("/egress", "503") | |
| 331 | 新增: probe("/dns", "503") | |
| 332 | 新增: after, err := client.Status(ctx) | |
| 333 | 新增: if err != nil { | |
| 334 | 新增: t.Fatal(err) | |
| 335 | 新增: } | |
| 336 | 新增: if after.Counters.FaultTCP <= before.Counters.FaultTCP || after.Counters.FaultDNS <= before.Counters.FaultDNS { | |
| 337 | 新增: t.Fatal("missing proxy fault observations for guest TCP or DNS") | |
| 338 | 新增: } | |
| 339 | 新增: t.Log("Guest diagnostic service reachable; both fixed probes reported injected proxy failure") | |
| 340 | 新增:} | |
| @@ -0,0 +1,222 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:package vm | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "encoding/json" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "fmt" | |
| 10 | 新增: "io" | |
| 11 | 新增: "os" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "strings" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/Code-Hex/vz/v3" | |
| 16 | 新增: "github.com/lima-vm/lima/v2/pkg/fileutils" | |
| 17 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 18 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype/dirnames" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:// CheckMacOSGuest verifies a prepared instance before binding or starting a | |
| 22 | 新增:// native workbench. Project access goes through a separate confined service. | |
| 23 | 新增:func (l *Lima) CheckMacOSGuest(ctx context.Context, name string) error { | |
| 24 | 新增: inst, err := l.inspect(ctx, name) | |
| 25 | 新增: if err != nil { | |
| 26 | 新增: return err | |
| 27 | 新增: } | |
| 28 | 新增: c := inst.Config | |
| 29 | 新增: if c == nil || c.OS == nil || *c.OS != limatype.DARWIN || c.VMType == nil || *c.VMType != limatype.VZ || | |
| 30 | 新增: len(c.Mounts) != 0 || len(c.AdditionalDisks) != 0 || c.Video.Display == nil || *c.Video.Display != "offscreen" { | |
| 31 | 新增: return errors.New("expected a headless macOS VZ guest with its own system disk and no host shares") | |
| 32 | 新增: } | |
| 33 | 新增: for _, p := range c.PortForwards { | |
| 34 | 新增: if !p.Ignore { | |
| 35 | 新增: return errors.New("macOS guest has an unmanaged forwarded port") | |
| 36 | 新增: } | |
| 37 | 新增: } | |
| 38 | 新增: return NetworkConfined(c) | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:// MatchMacOSInstallSource permits retrying an interrupted restore only with | |
| 42 | 新增:// the same pinned IPSW. An existing disk is left to Lima's restore transaction. | |
| 43 | 新增:func (l *Lima) MatchMacOSInstallSource(ctx context.Context, name, image string) error { | |
| 44 | 新增: if err := l.CheckMacOSGuest(ctx, name); err != nil { | |
| 45 | 新增: return err | |
| 46 | 新增: } | |
| 47 | 新增: inst, err := l.inspect(ctx, name) | |
| 48 | 新增: if err != nil { | |
| 49 | 新增: return err | |
| 50 | 新增: } | |
| 51 | 新增: if !filepath.IsAbs(image) || len(inst.Config.Images) != 1 { | |
| 52 | 新增: return errors.New("an interrupted installation requires its original local IPSW") | |
| 53 | 新增: } | |
| 54 | 新增: image, err = filepath.EvalSymlinks(image) | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: return err | |
| 57 | 新增: } | |
| 58 | 新增: original := inst.Config.Images[0] | |
| 59 | 新增: if original.Location != image || original.Digest == "" { | |
| 60 | 新增: return errors.New("the existing macOS installation uses different restore media") | |
| 61 | 新增: } | |
| 62 | 新增: info, err := os.Stat(image) | |
| 63 | 新增: if err != nil { | |
| 64 | 新增: return err | |
| 65 | 新增: } | |
| 66 | 新增: if !info.Mode().IsRegular() { | |
| 67 | 新增: return errors.New("the restore image must be a regular file") | |
| 68 | 新增: } | |
| 69 | 新增: digest, err := fileutils.RestoreImageDigest(ctx, image, info) | |
| 70 | 新增: if err != nil { | |
| 71 | 新增: return err | |
| 72 | 新增: } | |
| 73 | 新增: if string(original.Digest) != string(digest) { | |
| 74 | 新增: return errors.New("the existing macOS installation is pinned to a different IPSW digest") | |
| 75 | 新增: } | |
| 76 | 新增: return nil | |
| 77 | 新增:} | |
| 78 | 新增: | |
| 79 | 新增:// CreateMacOSFromIPSW creates the stopped VM. Lima restores the local image | |
| 80 | 新增:// into its private disk at first start, so the source must remain available. | |
| 81 | 新增:func (l *Lima) CreateMacOSFromIPSW(ctx context.Context, name, imagePath string, settings Settings, log io.Writer) error { | |
| 82 | 新增: if err := ctx.Err(); err != nil { | |
| 83 | 新增: return err | |
| 84 | 新增: } | |
| 85 | 新增: if settings.Mounts != nil && len(*settings.Mounts) != 0 { | |
| 86 | 新增: return errors.New("macOS installation does not accept shared host directories") | |
| 87 | 新增: } | |
| 88 | 新增: if err := dirnames.ValidateInstName(name); err != nil { | |
| 89 | 新增: return err | |
| 90 | 新增: } | |
| 91 | 新增: if !filepath.IsAbs(imagePath) || !strings.EqualFold(filepath.Ext(imagePath), ".ipsw") { | |
| 92 | 新增: return errors.New("select a local .ipsw file using its absolute path") | |
| 93 | 新增: } | |
| 94 | 新增: image, err := filepath.EvalSymlinks(imagePath) | |
| 95 | 新增: if err != nil { | |
| 96 | 新增: return err | |
| 97 | 新增: } | |
| 98 | 新增: info, err := os.Stat(image) | |
| 99 | 新增: if err != nil { | |
| 100 | 新增: return err | |
| 101 | 新增: } | |
| 102 | 新增: if !info.Mode().IsRegular() { | |
| 103 | 新增: return errors.New("the selected IPSW must be a regular file") | |
| 104 | 新增: } | |
| 105 | 新增: home, err := dirnames.LimaDir() | |
| 106 | 新增: if err != nil { | |
| 107 | 新增: return err | |
| 108 | 新增: } | |
| 109 | 新增: // Compare actual directories, including on case-insensitive volumes and a | |
| 110 | 新增: // profile whose Lima home is a symlink to another volume. | |
| 111 | 新增: store, err := os.Stat(home) | |
| 112 | 新增: if err != nil && !errors.Is(err, os.ErrNotExist) { | |
| 113 | 新增: return err | |
| 114 | 新增: } | |
| 115 | 新增: if store != nil { | |
| 116 | 新增: for dir := filepath.Dir(image); ; dir = filepath.Dir(dir) { | |
| 117 | 新增: ancestor, err := os.Stat(dir) | |
| 118 | 新增: if err != nil { | |
| 119 | 新增: return err | |
| 120 | 新增: } | |
| 121 | 新增: if os.SameFile(ancestor, store) { | |
| 122 | 新增: return errors.New("keep the source IPSW outside the Lima instance storage directory") | |
| 123 | 新增: } | |
| 124 | 新增: if filepath.Dir(dir) == dir { | |
| 125 | 新增: break | |
| 126 | 新增: } | |
| 127 | 新增: } | |
| 128 | 新增: } | |
| 129 | 新增: restore, err := vz.LoadMacOSRestoreImageFromPath(image) | |
| 130 | 新增: if err != nil { | |
| 131 | 新增: return fmt.Errorf("Apple Virtualization could not read the selected restore image: %w", err) | |
| 132 | 新增: } | |
| 133 | 新增: if err := applyMacOSRequirements(restore, &settings); err != nil { | |
| 134 | 新增: return err | |
| 135 | 新增: } | |
| 136 | 新增: selectedDigest, err := fileutils.RestoreImageDigest(ctx, image, info) | |
| 137 | 新增: if err != nil { | |
| 138 | 新增: return fmt.Errorf("pinning the selected macOS restore image: %w", err) | |
| 139 | 新增: } | |
| 140 | 新增: template, err := os.CreateTemp("", "cage-macos-*.yaml") | |
| 141 | 新增: if err != nil { | |
| 142 | 新增: return err | |
| 143 | 新增: } | |
| 144 | 新增: defer os.Remove(template.Name()) | |
| 145 | 新增: location, err := json.Marshal(image) | |
| 146 | 新增: if err == nil { | |
| 147 | 新增: _, err = fmt.Fprintf(template, macOSInstallTemplate, location, selectedDigest) | |
| 148 | 新增: } | |
| 149 | 新增: closeErr := template.Close() | |
| 150 | 新增: if err := errors.Join(err, closeErr); err != nil { | |
| 151 | 新增: return err | |
| 152 | 新增: } | |
| 153 | 新增: settings.NoContainerd = true | |
| 154 | 新增: if err := l.Create(ctx, name, template.Name(), settings, log); err != nil { | |
| 155 | 新增: return err | |
| 156 | 新增: } | |
| 157 | 新增: requirements, err := macOSImageResourceRequirements(restore) | |
| 158 | 新增: if err != nil { | |
| 159 | 新增: return err | |
| 160 | 新增: } | |
| 161 | 新增: return saveMacOSResourceRequirements(filepath.Join(home, name), requirements) | |
| 162 | 新增:} | |
| 163 | 新增: | |
| 164 | 新增:func applyMacOSRequirements(restore *vz.MacOSRestoreImage, settings *Settings) error { | |
| 165 | 新增: requirements, err := macOSImageResourceRequirements(restore) | |
| 166 | 新增: if err != nil { | |
| 167 | 新增: return err | |
| 168 | 新增: } | |
| 169 | 新增: minCPU, minGiB := requirements.CPUs, requirements.MemoryGiB | |
| 170 | 新增: if settings.CPUs == 0 { | |
| 171 | 新增: settings.CPUs = minCPU | |
| 172 | 新增: } | |
| 173 | 新增: if settings.MemoryGiB == 0 { | |
| 174 | 新增: settings.MemoryGiB = minGiB | |
| 175 | 新增: } | |
| 176 | 新增: if settings.CPUs < minCPU || settings.MemoryGiB < minGiB { | |
| 177 | 新增: return fmt.Errorf("this macOS restore image requires at least %d CPUs and %d GiB RAM", minCPU, minGiB) | |
| 178 | 新增: } | |
| 179 | 新增: return nil | |
| 180 | 新增:} | |
| 181 | 新增: | |
| 182 | 新增:const macOSInstallTemplate = `os: Darwin | |
| 183 | 新增:arch: aarch64 | |
| 184 | 新增:vmType: vz | |
| 185 | 新增:images: | |
| 186 | 新增: - location: %s | |
| 187 | 新增: arch: aarch64 | |
| 188 | 新增: digest: %s | |
| 189 | 新增:user: | |
| 190 | 新增: name: cageprovision | |
| 191 | 新增: comment: Cage Provisioning | |
| 192 | 新增: home: /Users/cageprovision | |
| 193 | 新增: uid: 501 | |
| 194 | 新增:osOpts: | |
| 195 | 新增: Darwin: | |
| 196 | 新增: suppressFirstLoginSetup: true | |
| 197 | 新增:provision: | |
| 198 | 新增: - mode: system | |
| 199 | 新增: script: | | |
| 200 | 新增: #!/bin/sh | |
| 201 | 新增: set -eu | |
| 202 | 新增: [ "$(/usr/bin/uname -sm)" = "Darwin arm64" ] | |
| 203 | 新增: case "$(/usr/sbin/sysctl -n hw.model)" in VirtualMac*,*) ;; *) exit 1 ;; esac | |
| 204 | 新增: /usr/bin/ssh-keygen -A >/dev/null | |
| 205 | 新增: # This serial port is attached by VZ to this specific private instance. | |
| 206 | 新增: # Publish only the public key. SSH is pinned before provisioning begins. | |
| 207 | 新增: /bin/echo "CAGE-GUEST-HOST-KEY $(/bin/cat /etc/ssh/ssh_host_ed25519_key.pub)" >/dev/tty.virtio | |
| 208 | 新增:video: | |
| 209 | 新增: display: offscreen | |
| 210 | 新增:mounts: [] | |
| 211 | 新增:networks: [] | |
| 212 | 新增:ssh: | |
| 213 | 新增: loadDotSSHPubKeys: false | |
| 214 | 新增: forwardAgent: false | |
| 215 | 新增: forwardX11: false | |
| 216 | 新增:portForwards: | |
| 217 | 新增: - guestIP: 0.0.0.0 | |
| 218 | 新增: guestIPMustBeZero: false | |
| 219 | 新增: guestPortRange: [1, 65535] | |
| 220 | 新增: proto: any | |
| 221 | 新增: ignore: true | |
| 222 | 新增:` | |
| @@ -0,0 +1,130 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:package vm | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "testing" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/Code-Hex/vz/v3" | |
| 15 | 新增: "github.com/lima-vm/lima/v2/pkg/fileutils" | |
| 16 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 17 | 新增: "github.com/lima-vm/lima/v2/pkg/limayaml" | |
| 18 | 新增: "github.com/opencontainers/go-digest" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:func TestMacOSInstallSourceAndMounts(t *testing.T) { | |
| 22 | 新增: l := &Lima{} | |
| 23 | 新增: dir := t.TempDir() | |
| 24 | 新增: t.Setenv("LIMA_HOME", filepath.Join(dir, "instances")) | |
| 25 | 新增: ipsw := filepath.Join(dir, "bad.ipsw") | |
| 26 | 新增: if err := os.WriteFile(ipsw, []byte("not a restore image"), 0o600); err != nil { | |
| 27 | 新增: t.Fatal(err) | |
| 28 | 新增: } | |
| 29 | 新增: shares := []Mount{{Location: dir}} | |
| 30 | 新增: for _, tc := range []struct { | |
| 31 | 新增: file string | |
| 32 | 新增: s Settings | |
| 33 | 新增: want string | |
| 34 | 新增: }{ | |
| 35 | 新增: {ipsw, Settings{Mounts: &shares}, "shared host directories"}, | |
| 36 | 新增: {"https://localhost/mac.ipsw", Settings{}, "absolute path"}, | |
| 37 | 新增: {ipsw, Settings{}, "Apple Virtualization"}, | |
| 38 | 新增: } { | |
| 39 | 新增: if err := l.CreateMacOSFromIPSW(t.Context(), "mac", tc.file, tc.s, io.Discard); err == nil || !strings.Contains(err.Error(), tc.want) { | |
| 40 | 新增: t.Fatalf("%q: expected %q, got %v", tc.file, tc.want, err) | |
| 41 | 新增: } | |
| 42 | 新增: } | |
| 43 | 新增: t.Setenv("LIMA_HOME", dir) | |
| 44 | 新增: if err := l.CreateMacOSFromIPSW(t.Context(), "mac", ipsw, Settings{}, io.Discard); err == nil || !strings.Contains(err.Error(), "outside") { | |
| 45 | 新增: t.Fatalf("selected image in instance storage: %v", err) | |
| 46 | 新增: } | |
| 47 | 新增: if _, err := os.Stat(filepath.Join(dir, "mac")); !errors.Is(err, os.ErrNotExist) { | |
| 48 | 新增: t.Fatalf("unexpected instance after preflight: %v", err) | |
| 49 | 新增: } | |
| 50 | 新增: if err := applyMacOSRequirements(&vz.MacOSRestoreImage{}, &Settings{}); err == nil { | |
| 51 | 新增: t.Fatal("accepted an unsupported native restore image") | |
| 52 | 新增: } | |
| 53 | 新增:} | |
| 54 | 新增: | |
| 55 | 新增:func TestMacOSHostSourceCompatibility(t *testing.T) { | |
| 56 | 新增: path := os.Getenv("CAGE_TEST_MACOS_SOURCE") | |
| 57 | 新增: if path == "" { | |
| 58 | 新增: t.Skip("set CAGE_TEST_MACOS_SOURCE to verified local restore media") | |
| 59 | 新增: } | |
| 60 | 新增: image, err := vz.LoadMacOSRestoreImageFromPath(path) | |
| 61 | 新增: if err != nil { | |
| 62 | 新增: t.Fatal(err) | |
| 63 | 新增: } | |
| 64 | 新增: settings := Settings{DiskGiB: 64} | |
| 65 | 新增: if err := applyMacOSRequirements(image, &settings); err != nil { | |
| 66 | 新增: t.Fatal(err) | |
| 67 | 新增: } | |
| 68 | 新增: t.Logf("Apple accepted the restore image, minimum CPUs=%d memoryGiB=%d", settings.CPUs, settings.MemoryGiB) | |
| 69 | 新增:} | |
| 70 | 新增: | |
| 71 | 新增:func TestMacOSInstallTemplateIsolation(t *testing.T) { | |
| 72 | 新增: expectedDigest := "sha256:" + strings.Repeat("a", 64) | |
| 73 | 新增: body := fmt.Sprintf(macOSInstallTemplate, `"/example.ipsw"`, expectedDigest) | |
| 74 | 新增: cfg, err := limayaml.Load(t.Context(), []byte(body), "macos.yaml") | |
| 75 | 新增: if err != nil { | |
| 76 | 新增: t.Fatal(err) | |
| 77 | 新增: } | |
| 78 | 新增: if err := limayaml.Validate(cfg, false); err != nil { | |
| 79 | 新增: t.Fatal(err) | |
| 80 | 新增: } | |
| 81 | 新增: if len(cfg.Images) != 1 || cfg.Images[0].Digest.String() != expectedDigest { | |
| 82 | 新增: t.Fatal("selected restore image digest was lost") | |
| 83 | 新增: } | |
| 84 | 新增: if cfg.User.Comment == nil || *cfg.User.Comment != "Cage Provisioning" || *cfg.User.Name != "cageprovision" || *cfg.User.Home != "/Users/cageprovision" { | |
| 85 | 新增: t.Fatal("macOS template must not inherit the host account's full name") | |
| 86 | 新增: } | |
| 87 | 新增: var options limatype.DarwinOpts | |
| 88 | 新增: if err := limayaml.Convert(cfg.OsOpts[limatype.DARWIN], &options, "osOpts.Darwin"); err != nil || options.SuppressFirstLoginSetup == nil || !*options.SuppressFirstLoginSetup { | |
| 89 | 新增: t.Fatal("new guest did not prepare first-login settings", err) | |
| 90 | 新增: } | |
| 91 | 新增: if len(cfg.Mounts) != 0 || len(cfg.Networks) != 0 || *cfg.SSH.LoadDotSSHPubKeys || *cfg.SSH.ForwardAgent || *cfg.SSH.ForwardX11 { | |
| 92 | 新增: t.Fatal("unexpected host sharing in macOS template") | |
| 93 | 新增: } | |
| 94 | 新增: if len(cfg.PortForwards) != 1 || !cfg.PortForwards[0].Ignore || cfg.PortForwards[0].GuestPortRange != [2]int{1, 65535} || cfg.PortForwards[0].Proto != "any" || *cfg.PortForwards[0].GuestIPMustBeZero { | |
| 95 | 新增: t.Fatal("default guest port forwarding is not disabled") | |
| 96 | 新增: } | |
| 97 | 新增:} | |
| 98 | 新增: | |
| 99 | 新增:func TestSelectedIPSWRejectsReplacementAtSamePath(t *testing.T) { | |
| 100 | 新增: dir := t.TempDir() | |
| 101 | 新增: path := filepath.Join(dir, "selected.ipsw") | |
| 102 | 新增: if err := os.WriteFile(path, []byte("original"), 0o600); err != nil { | |
| 103 | 新增: t.Fatal(err) | |
| 104 | 新增: } | |
| 105 | 新增: selected, err := os.Stat(path) | |
| 106 | 新增: if err != nil { | |
| 107 | 新增: t.Fatal(err) | |
| 108 | 新增: } | |
| 109 | 新增: pin, err := fileutils.RestoreImageDigest(t.Context(), path, selected) | |
| 110 | 新增: if err != nil || pin != digest.FromString("original") { | |
| 111 | 新增: t.Fatalf("unexpected media pin: %s, %v", pin, err) | |
| 112 | 新增: } | |
| 113 | 新增: replacement := filepath.Join(dir, "renamed") | |
| 114 | 新增: if err := os.WriteFile(replacement, []byte("replaced"), 0o600); err != nil { | |
| 115 | 新增: t.Fatal(err) | |
| 116 | 新增: } | |
| 117 | 新增: if err := os.Chtimes(replacement, selected.ModTime(), selected.ModTime()); err != nil { | |
| 118 | 新增: t.Fatal(err) | |
| 119 | 新增: } | |
| 120 | 新增: if err := os.Rename(replacement, path); err != nil { | |
| 121 | 新增: t.Fatal(err) | |
| 122 | 新增: } | |
| 123 | 新增: if _, err := fileutils.RestoreImageDigest(t.Context(), path, selected); err == nil || !strings.Contains(err.Error(), "changed") { | |
| 124 | 新增: t.Fatalf("accepted another inode with the original size and mtime: %v", err) | |
| 125 | 新增: } | |
| 126 | 新增: file := limatype.File{Location: path, Arch: limatype.AARCH64, Digest: pin} | |
| 127 | 新增: if _, err := fileutils.DownloadFile(t.Context(), filepath.Join(dir, "image"), file, true, "restore image", limatype.AARCH64, nil); err == nil || !strings.Contains(err.Error(), "expected digest") { | |
| 128 | 新增: t.Fatalf("Lima accepted replaced installation media: %v", err) | |
| 129 | 新增: } | |
| 130 | 新增:} | |
| @@ -0,0 +1,96 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && e2e && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:package vm | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bytes" | |
| 7 | 新增: "context" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "io" | |
| 10 | 新增: "os" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "testing" | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/lima-vm/sshocker/pkg/reversesshfs" | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/mounts" | |
| 17 | 新增: "golang.org/x/sys/unix" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:// Verify the workbench's restricted project service with the OpenSSH client | |
| 21 | 新增:// shipped by Apple. The guest accesses the service only through its existing | |
| 22 | 新增:// management SSH connection. This does not mount the project in the guest. | |
| 23 | 新增:func verifyMacOSProjectTransfer(t *testing.T, ctx context.Context, l *Lima, name string) { | |
| 24 | 新增: t.Helper() | |
| 25 | 新增: project := t.TempDir() | |
| 26 | 新增: if err := os.Mkdir(filepath.Join(project, ".git"), 0700); err != nil { | |
| 27 | 新增: t.Fatal(err) | |
| 28 | 新增: } | |
| 29 | 新增: write := func(path, contents string, mode os.FileMode) { | |
| 30 | 新增: t.Helper() | |
| 31 | 新增: if err := os.WriteFile(filepath.Join(project, path), []byte(contents), mode); err != nil { | |
| 32 | 新增: t.Fatal(err) | |
| 33 | 新增: } | |
| 34 | 新增: } | |
| 35 | 新增: write(".git/HEAD", "ref: refs/heads/test\n", 0600) | |
| 36 | 新增: write("build script", "#!/bin/sh\nprintf 'ran in guest'\n", 0755) | |
| 37 | 新增: if err := os.Symlink("build script", filepath.Join(project, "build-link")); err != nil { | |
| 38 | 新增: t.Fatal(err) | |
| 39 | 新增: } | |
| 40 | 新增: | |
| 41 | 新增: fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_STREAM, 0) | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: t.Fatal(err) | |
| 44 | 新增: } | |
| 45 | 新增: for _, fd := range fds { | |
| 46 | 新增: unix.CloseOnExec(fd) | |
| 47 | 新增: } | |
| 48 | 新增: server := os.NewFile(uintptr(fds[0]), "project-server") | |
| 49 | 新增: guest := os.NewFile(uintptr(fds[1]), "guest-ssh") | |
| 50 | 新增: done := make(chan error, 1) | |
| 51 | 新增: go func() { | |
| 52 | 新增: defer server.Close() | |
| 53 | 新增: done <- reversesshfs.ServeConfined(server, project, false, mounts.BaseNames) | |
| 54 | 新增: }() | |
| 55 | 新增: // nc relays only the SFTP protocol on SSH stdin/stdout. The client | |
| 56 | 新增: // connects in a private guest directory. All diagnostics use stderr. | |
| 57 | 新增: const script = `set -eu | |
| 58 | 新增:umask 077 | |
| 59 | 新增:work=$(mktemp -d /tmp/cage-project.XXXXXXXX) | |
| 60 | 新增:cd "$work" | |
| 61 | 新增:exec 3<&0 | |
| 62 | 新增:/usr/bin/nc -lU wire <&3 3<&- & | |
| 63 | 新增:relay=$! | |
| 64 | 新增:exec 3<&- </dev/null >&2 | |
| 65 | 新增:trap 'kill "$relay" 2>/dev/null || :; wait "$relay" 2>/dev/null || :; rm -rf "$work"' EXIT | |
| 66 | 新增:for ((i=0; i<100; i++)); do [[ -S wire ]] && break; sleep 0.05; done | |
| 67 | 新增:test -S wire | |
| 68 | 新增:printf 'guest save' > edit | |
| 69 | 新增:cat > batch <<'EOF' | |
| 70 | 新增:get -p build-link build | |
| 71 | 新增:get .git/HEAD head-copy | |
| 72 | 新增:put edit .saving | |
| 73 | 新增:rename .saving "source file" | |
| 74 | 新增:put edit .git/denied | |
| 75 | 新增:EOF | |
| 76 | 新增:if /usr/bin/sftp -q -b batch -D '/usr/bin/nc -U wire' unused; then exit 1; fi | |
| 77 | 新增:test "$(cat head-copy)" = 'ref: refs/heads/test' | |
| 78 | 新增:test "$(./build)" = 'ran in guest'` | |
| 79 | 新增: ctx, cancel := context.WithTimeout(ctx, 30*time.Second) | |
| 80 | 新增: defer cancel() | |
| 81 | 新增: var output bytes.Buffer | |
| 82 | 新增: code, shellErr := l.Shell(ctx, name, ShellOpts{Args: []string{"/bin/bash", "-c", script}, Stdin: guest, Stdout: guest, Stderr: &output}) | |
| 83 | 新增: guest.Close() | |
| 84 | 新增: serverErr := <-done | |
| 85 | 新增: if code != 0 || shellErr != nil || (serverErr != nil && !errors.Is(serverErr, io.EOF)) { | |
| 86 | 新增: t.Fatalf("guest transfer (%d): SSH %v, SFTP %v\n%s", code, shellErr, serverErr, output.String()) | |
| 87 | 新增: } | |
| 88 | 新增: data, err := os.ReadFile(filepath.Join(project, "source file")) | |
| 89 | 新增: if err != nil || string(data) != "guest save" { | |
| 90 | 新增: t.Fatalf("guest atomic save did not reach the host: %v", err) | |
| 91 | 新增: } | |
| 92 | 新增: if _, err := os.Lstat(filepath.Join(project, ".git", "denied")); !errors.Is(err, os.ErrNotExist) { | |
| 93 | 新增: t.Fatalf("guest protected write: %v", err) | |
| 94 | 新增: } | |
| 95 | 新增: t.Log("Guest SFTP executed a transferred script, saved to the host, and was denied a Git metadata write") | |
| 96 | 新增:} | |
| @@ -0,0 +1,107 @@ | ||
| 1 | 新增:package vm | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/docker/go-units" | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 13 | 新增: "go.yaml.in/yaml/v3" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:// MacOSResourceRequirements belong to the installed guest, independent of the | |
| 17 | 新增:// user's current allocation. Older guests retain their known bootable floor. | |
| 18 | 新增:type MacOSResourceRequirements struct { | |
| 19 | 新增: Version int `json:"version"` | |
| 20 | 新增: MemoryGiB int `json:"minimum_memory_gib"` | |
| 21 | 新增: CPUs int `json:"minimum_cpus"` | |
| 22 | 新增: Source string `json:"source"` | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:const macOSRequirementsFile = "cage-macos-resource-requirements.json" | |
| 26 | 新增: | |
| 27 | 新增:func (requirements MacOSResourceRequirements) Limits(allocation cage.ResourceAllocation) (int, int, error) { | |
| 28 | 新增: memory, cpus, err := allocation.Limits() | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: return 0, 0, err | |
| 31 | 新增: } | |
| 32 | 新增: if memory < requirements.MemoryGiB || cpus < requirements.CPUs { | |
| 33 | 新增: return 0, 0, fmt.Errorf("这台 macOS 客机至少需要 %d GiB 内存与 %d 个 CPU 逻辑核心,请调整资源配置", requirements.MemoryGiB, requirements.CPUs) | |
| 34 | 新增: } | |
| 35 | 新增: return memory, cpus, nil | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func ReadMacOSResourceRequirements(instanceDir string) (MacOSResourceRequirements, error) { | |
| 39 | 新增: var requirements MacOSResourceRequirements | |
| 40 | 新增: data, err := os.ReadFile(filepath.Join(instanceDir, macOSRequirementsFile)) | |
| 41 | 新增: if err == nil { | |
| 42 | 新增: if json.Unmarshal(data, &requirements) != nil || requirements.Version != 1 || requirements.MemoryGiB < 1 || requirements.CPUs < 1 || | |
| 43 | 新增: (requirements.Source != "restore-image" && requirements.Source != "existing-configuration") { | |
| 44 | 新增: return requirements, errors.New("macOS 最低资源要求记录无效,请检查原环境配置") | |
| 45 | 新增: } | |
| 46 | 新增: if requirements.Source == "restore-image" { | |
| 47 | 新增: return requirements, nil | |
| 48 | 新增: } | |
| 49 | 新增: } | |
| 50 | 新增: if err != nil && !errors.Is(err, os.ErrNotExist) { | |
| 51 | 新增: return requirements, errors.New("无法读取 macOS 最低资源要求记录") | |
| 52 | 新增: } | |
| 53 | 新增: data, err = os.ReadFile(filepath.Join(instanceDir, "lima.yaml")) | |
| 54 | 新增: if err != nil { | |
| 55 | 新增: return requirements, errors.New("无法读取这台 macOS 客机的启动配置") | |
| 56 | 新增: } | |
| 57 | 新增: var config struct { | |
| 58 | 新增: OS string `yaml:"os"` | |
| 59 | 新增: Memory string `yaml:"memory"` | |
| 60 | 新增: CPUs int `yaml:"cpus"` | |
| 61 | 新增: Images []struct { | |
| 62 | 新增: Location string `yaml:"location"` | |
| 63 | 新增: } `yaml:"images"` | |
| 64 | 新增: } | |
| 65 | 新增: if yaml.Unmarshal(data, &config) != nil || config.OS != "Darwin" { | |
| 66 | 新增: return requirements, errors.New("macOS 客机启动配置无效") | |
| 67 | 新增: } | |
| 68 | 新增: candidates := []string{filepath.Join(instanceDir, "image.ipsw")} | |
| 69 | 新增: if len(config.Images) == 1 && filepath.IsAbs(config.Images[0].Location) { | |
| 70 | 新增: candidates = append(candidates, config.Images[0].Location) | |
| 71 | 新增: } | |
| 72 | 新增: for _, image := range candidates { | |
| 73 | 新增: if info, err := os.Stat(image); err == nil && info.Mode().IsRegular() { | |
| 74 | 新增: if requirements, err := macOSRestoreResourceRequirements(image); err == nil { | |
| 75 | 新增: return requirements, nil | |
| 76 | 新增: } | |
| 77 | 新增: } | |
| 78 | 新增: } | |
| 79 | 新增: if requirements.Version == 1 { | |
| 80 | 新增: return requirements, nil | |
| 81 | 新增: } | |
| 82 | 新增: memory, err := units.RAMInBytes(config.Memory) | |
| 83 | 新增: if err != nil || memory < 1<<30 || config.CPUs < 1 { | |
| 84 | 新增: return requirements, errors.New("无法确定已有 macOS 客机的可启动资源配置") | |
| 85 | 新增: } | |
| 86 | 新增: return MacOSResourceRequirements{Version: 1, MemoryGiB: int((memory-1)/(1<<30) + 1), CPUs: config.CPUs, Source: "existing-configuration"}, nil | |
| 87 | 新增:} | |
| 88 | 新增: | |
| 89 | 新增:func saveMacOSResourceRequirements(instanceDir string, requirements MacOSResourceRequirements) error { | |
| 90 | 新增: data, err := json.Marshal(requirements) | |
| 91 | 新增: if err != nil { | |
| 92 | 新增: return err | |
| 93 | 新增: } | |
| 94 | 新增: if current, err := os.ReadFile(filepath.Join(instanceDir, macOSRequirementsFile)); err == nil && bytes.Equal(current, data) { | |
| 95 | 新增: return nil | |
| 96 | 新增: } | |
| 97 | 新增: file, err := os.CreateTemp(instanceDir, ".macos-resources-*") | |
| 98 | 新增: if err != nil { | |
| 99 | 新增: return err | |
| 100 | 新增: } | |
| 101 | 新增: defer os.Remove(file.Name()) | |
| 102 | 新增: _, err = file.Write(data) | |
| 103 | 新增: if err = errors.Join(err, file.Close()); err != nil { | |
| 104 | 新增: return err | |
| 105 | 新增: } | |
| 106 | 新增: return os.Rename(file.Name(), filepath.Join(instanceDir, macOSRequirementsFile)) | |
| 107 | 新增:} | |
| @@ -0,0 +1,32 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:package vm | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "errors" | |
| 7 | 新增: | |
| 8 | 新增: "github.com/Code-Hex/vz/v3" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func macOSRestoreResourceRequirements(image string) (MacOSResourceRequirements, error) { | |
| 12 | 新增: restore, err := vz.LoadMacOSRestoreImageFromPath(image) | |
| 13 | 新增: if err != nil { | |
| 14 | 新增: return MacOSResourceRequirements{}, err | |
| 15 | 新增: } | |
| 16 | 新增: return macOSImageResourceRequirements(restore) | |
| 17 | 新增:} | |
| 18 | 新增: | |
| 19 | 新增:func macOSImageResourceRequirements(restore *vz.MacOSRestoreImage) (MacOSResourceRequirements, error) { | |
| 20 | 新增: if restore == nil { | |
| 21 | 新增: return MacOSResourceRequirements{}, errors.New("missing macOS restore image") | |
| 22 | 新增: } | |
| 23 | 新增: requirements := restore.MostFeaturefulSupportedConfiguration() | |
| 24 | 新增: if requirements == nil || requirements.MinimumSupportedCPUCount() == 0 || requirements.MinimumSupportedMemorySize() == 0 { | |
| 25 | 新增: return MacOSResourceRequirements{}, errors.New("this macOS restore image has no supported configuration for this Mac") | |
| 26 | 新增: } | |
| 27 | 新增: model := requirements.HardwareModel() | |
| 28 | 新增: if model == nil || !model.Supported() || len(model.DataRepresentation()) == 0 { | |
| 29 | 新增: return MacOSResourceRequirements{}, errors.New("this Mac does not support the restore image's hardware model") | |
| 30 | 新增: } | |
| 31 | 新增: return MacOSResourceRequirements{Version: 1, CPUs: int(requirements.MinimumSupportedCPUCount()), MemoryGiB: int((requirements.MinimumSupportedMemorySize()-1)/(1<<30) + 1), Source: "restore-image"}, nil | |
| 32 | 新增:} | |
| @@ -0,0 +1,9 @@ | ||
| 1 | 新增://go:build !darwin || !arm64 || !cgo || no_vz | |
| 2 | 新增: | |
| 3 | 新增:package vm | |
| 4 | 新增: | |
| 5 | 新增:import "errors" | |
| 6 | 新增: | |
| 7 | 新增:func macOSRestoreResourceRequirements(string) (MacOSResourceRequirements, error) { | |
| 8 | 新增: return MacOSResourceRequirements{}, errors.New("Apple 恢复镜像要求只能在 Apple Silicon Mac 上读取") | |
| 9 | 新增:} | |
| @@ -0,0 +1,58 @@ | ||
| 1 | 新增:package vm | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "testing" | |
| 7 | 新增: | |
| 8 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func TestMacOSResourceRequirementsPreserveExistingFloor(t *testing.T) { | |
| 13 | 新增: directory := t.TempDir() | |
| 14 | 新增: config := filepath.Join(directory, "lima.yaml") | |
| 15 | 新增: if err := os.WriteFile(config, []byte("os: Darwin\nmemory: 8GiB\ncpus: 4\n"), 0600); err != nil { | |
| 16 | 新增: t.Fatal(err) | |
| 17 | 新增: } | |
| 18 | 新增: requirements, err := ReadMacOSResourceRequirements(directory) | |
| 19 | 新增: if err != nil || requirements.MemoryGiB != 8 || requirements.CPUs != 4 || requirements.Source != "existing-configuration" { | |
| 20 | 新增: t.Fatalf("existing guest floor lost: %+v %v", requirements, err) | |
| 21 | 新增: } | |
| 22 | 新增: if err = saveMacOSResourceRequirements(directory, requirements); err != nil { | |
| 23 | 新增: t.Fatal(err) | |
| 24 | 新增: } | |
| 25 | 新增: if err = os.WriteFile(config, []byte("os: Darwin\nmemory: 12GiB\ncpus: 6\n"), 0600); err != nil { | |
| 26 | 新增: t.Fatal(err) | |
| 27 | 新增: } | |
| 28 | 新增: after, err := ReadMacOSResourceRequirements(directory) | |
| 29 | 新增: if err != nil || after != requirements { | |
| 30 | 新增: t.Fatalf("minimum drifted with allocation: %+v %v", after, err) | |
| 31 | 新增: } | |
| 32 | 新增: if err = os.WriteFile(filepath.Join(directory, macOSRequirementsFile), []byte(`{"version":1,"minimum_memory_gib":0}`), 0600); err != nil { | |
| 33 | 新增: t.Fatal(err) | |
| 34 | 新增: } | |
| 35 | 新增: if _, err = ReadMacOSResourceRequirements(directory); err == nil { | |
| 36 | 新增: t.Fatal("corrupt minimum silently accepted") | |
| 37 | 新增: } | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:func TestMacOSResourceRequirementsUseRestoreMinimumAndHostShare(t *testing.T) { | |
| 41 | 新增: oldMemory, oldCPUs := host.MemGiB, host.CPUs | |
| 42 | 新增: t.Cleanup(func() { host.MemGiB, host.CPUs = oldMemory, oldCPUs }) | |
| 43 | 新增: host.MemGiB = func() int { return 24 } | |
| 44 | 新增: host.CPUs = func() int { return 10 } | |
| 45 | 新增: t.Setenv("AGENT_VM_HOST_SHARE", "2") | |
| 46 | 新增: requirements := MacOSResourceRequirements{Version: 1, MemoryGiB: 4, CPUs: 2, Source: "restore-image"} | |
| 47 | 新增: for _, allocation := range []cage.ResourceAllocation{{MemoryGiB: 2, CPUs: 2}, {MemoryGiB: 4, CPUs: 1}, {MemoryGiB: 13, CPUs: 2}, {MemoryGiB: 4, CPUs: 6}} { | |
| 48 | 新增: if _, _, err := requirements.Limits(allocation); err == nil { | |
| 49 | 新增: t.Fatalf("accepted incompatible allocation %+v", allocation) | |
| 50 | 新增: } | |
| 51 | 新增: } | |
| 52 | 新增: if memory, cpus, err := requirements.Limits(cage.ResourceAllocation{Automatic: true}); err != nil || memory != 12 || cpus != 5 { | |
| 53 | 新增: t.Fatalf("automatic=%d/%d %v", memory, cpus, err) | |
| 54 | 新增: } | |
| 55 | 新增: if memory, cpus, err := requirements.Limits(cage.ResourceAllocation{MemoryGiB: 4, CPUs: 2}); err != nil || memory != 4 || cpus != 2 { | |
| 56 | 新增: t.Fatalf("manual=%d/%d %v", memory, cpus, err) | |
| 57 | 新增: } | |
| 58 | 新增:} | |
| @@ -0,0 +1,81 @@ | ||
| 1 | 新增:package vm | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "time" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:// Keep the first QEMU stderr messages from this failed start visible through | |
| 18 | 新增:// the CLI and desktop job, rather than only the later hostagent exit error. | |
| 19 | 新增:func vmStartError(cause error, instanceDir string, since time.Time) error { | |
| 20 | 新增: if cause == nil || errors.Is(cause, context.Canceled) { | |
| 21 | 新增: return cause | |
| 22 | 新增: } | |
| 23 | 新增: f, err := os.Open(filepath.Join(instanceDir, "ha.stderr.log")) | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: return cause | |
| 26 | 新增: } | |
| 27 | 新增: defer f.Close() | |
| 28 | 新增: info, err := f.Stat() | |
| 29 | 新增: if err != nil || info.ModTime().Before(since) { | |
| 30 | 新增: return cause | |
| 31 | 新增: } | |
| 32 | 新增: if info.Size() > 64<<10 { | |
| 33 | 新增: _, _ = f.Seek(info.Size()-(64<<10), io.SeekStart) | |
| 34 | 新增: } | |
| 35 | 新增: b, err := io.ReadAll(io.LimitReader(f, 64<<10)) | |
| 36 | 新增: if err != nil { | |
| 37 | 新增: return cause | |
| 38 | 新增: } | |
| 39 | 新增: if info.Size() > 64<<10 { | |
| 40 | 新增: // Never export a partial record cut through a credential or private key. | |
| 41 | 新增: if next := strings.IndexByte(string(b), '\n'); next >= 0 { | |
| 42 | 新增: b = b[next+1:] | |
| 43 | 新增: } else { | |
| 44 | 新增: b = nil | |
| 45 | 新增: } | |
| 46 | 新增: } | |
| 47 | 新增: // Keep the bounded hostagent log available in the existing diagnostic | |
| 48 | 新增: // export, including failures which happened before the guest could boot. | |
| 49 | 新增: stream := diagnostics.NewStream(diagnostics.Default(), "vm/start", "error", nil) | |
| 50 | 新增: _, _ = stream.Write(b) | |
| 51 | 新增: _ = stream.Close() | |
| 52 | 新增: var messages []string | |
| 53 | 新增: for _, line := range strings.Split(string(b), "\n") { | |
| 54 | 新增: var record struct { | |
| 55 | 新增: Message string `json:"msg"` | |
| 56 | 新增: } | |
| 57 | 新增: if json.Unmarshal([]byte(line), &record) == nil && record.Message != "" { | |
| 58 | 新增: line = record.Message | |
| 59 | 新增: } | |
| 60 | 新增: _, message, ok := strings.Cut(line, "qemu[stderr]") | |
| 61 | 新增: if !ok { | |
| 62 | 新增: continue | |
| 63 | 新增: } | |
| 64 | 新增: message = strings.TrimSpace(strings.TrimLeft(message, "]: \"")) | |
| 65 | 新增: if message == "" || strings.Contains(strings.ToLower(message), "warning:") { | |
| 66 | 新增: continue | |
| 67 | 新增: } | |
| 68 | 新增: messages = append(messages, diagnostics.Redact(message)) | |
| 69 | 新增: if len(messages) == 6 { | |
| 70 | 新增: break | |
| 71 | 新增: } | |
| 72 | 新增: } | |
| 73 | 新增: if len(messages) == 0 { | |
| 74 | 新增: return cause | |
| 75 | 新增: } | |
| 76 | 新增: summary := strings.Join(messages, ";") | |
| 77 | 新增: if len(summary) > 2048 { | |
| 78 | 新增: summary = strings.ToValidUTF8(summary[:2048], "") | |
| 79 | 新增: } | |
| 80 | 新增: return fmt.Errorf("QEMU 启动失败:%s;%w", summary, cause) | |
| 81 | 新增:} | |
| @@ -0,0 +1,69 @@ | ||
| 1 | 新增:package vm | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "archive/zip" | |
| 5 | 新增: "bytes" | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "testing" | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:func TestVMStartErrorPreservesQEMUFailureAndRedactsSecrets(t *testing.T) { | |
| 19 | 新增: previous := diagnostics.Default() | |
| 20 | 新增: store := diagnostics.New(t.TempDir()) | |
| 21 | 新增: diagnostics.SetDefault(store) | |
| 22 | 新增: t.Cleanup(func() { diagnostics.SetDefault(previous) }) | |
| 23 | 新增: dir := t.TempDir() | |
| 24 | 新增: log := strings.Repeat("{\"msg\":\"[qemu[stderr]] warning: host doesn't support requested feature\"}\n", 12) + `{"msg":"[qemu[stderr]] WHPX: Failed to enable nested virtualization, hr=80370302"} | |
| 25 | 新增:{"msg":"[qemu[stderr]] failed to initialize whpx: Invalid argument token=private-test-value"} | |
| 26 | 新增:panic: send on closed channel | |
| 27 | 新增:` | |
| 28 | 新增: if err := os.WriteFile(filepath.Join(dir, "ha.stderr.log"), []byte(log), 0600); err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: cause := errors.New("host agent process has exited") | |
| 32 | 新增: err := vmStartError(cause, dir, time.Time{}) | |
| 33 | 新增: if !errors.Is(err, cause) || !strings.Contains(err.Error(), "80370302") || strings.Contains(err.Error(), "private-test-value") || strings.Contains(err.Error(), "panic:") { | |
| 34 | 新增: t.Fatalf("bad startup error: %v", err) | |
| 35 | 新增: } | |
| 36 | 新增: var bundle bytes.Buffer | |
| 37 | 新增: if err := store.Export(&bundle, "test", nil, "guest never booted"); err != nil { | |
| 38 | 新增: t.Fatal(err) | |
| 39 | 新增: } | |
| 40 | 新增: archive, err := zip.NewReader(bytes.NewReader(bundle.Bytes()), int64(bundle.Len())) | |
| 41 | 新增: if err != nil { | |
| 42 | 新增: t.Fatal(err) | |
| 43 | 新增: } | |
| 44 | 新增: var exported strings.Builder | |
| 45 | 新增: for _, file := range archive.File { | |
| 46 | 新增: if !strings.HasPrefix(file.Name, "logs/") { | |
| 47 | 新增: continue | |
| 48 | 新增: } | |
| 49 | 新增: r, err := file.Open() | |
| 50 | 新增: if err != nil { | |
| 51 | 新增: t.Fatal(err) | |
| 52 | 新增: } | |
| 53 | 新增: data, err := io.ReadAll(r) | |
| 54 | 新增: r.Close() | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: exported.Write(data) | |
| 59 | 新增: } | |
| 60 | 新增: if text := exported.String(); !strings.Contains(text, "80370302") || !strings.Contains(text, "panic:") || strings.Contains(text, "private-test-value") { | |
| 61 | 新增: t.Fatalf("diagnostic export lost details or exposed credentials: %s", text) | |
| 62 | 新增: } | |
| 63 | 新增: if vmStartError(context.Canceled, dir, time.Time{}) != context.Canceled { | |
| 64 | 新增: t.Fatal("cancellation replaced by an old QEMU error") | |
| 65 | 新增: } | |
| 66 | 新增: if vmStartError(cause, dir, time.Now().Add(time.Second)) != cause { | |
| 67 | 新增: t.Fatal("an earlier attempt's log replaced this failure") | |
| 68 | 新增: } | |
| 69 | 新增:} | |

