* fix(app,ui,overlay,ocr,cli): harden autoinstall auth, upgrade defaults, and lifecycle after #134 * fix(app,cli,ui): address PR #210 review findings and keep default auto-install enabled
385 lines
14 KiB
Go
385 lines
14 KiB
Go
package cli
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/config"
|
|
"github.com/Nwflower/reims-go/internal/console"
|
|
"github.com/Nwflower/reims-go/internal/driver"
|
|
"github.com/Nwflower/reims-go/internal/guesttools"
|
|
"github.com/Nwflower/reims-go/internal/host"
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
"github.com/Nwflower/reims-go/internal/lifecycle"
|
|
"github.com/Nwflower/reims-go/internal/macos/guest"
|
|
"github.com/Nwflower/reims-go/internal/macos/installer"
|
|
"github.com/Nwflower/reims-go/internal/macos/opencore"
|
|
"github.com/Nwflower/reims-go/internal/macos/reims"
|
|
"github.com/Nwflower/reims-go/internal/macos/startprep"
|
|
"github.com/Nwflower/reims-go/internal/networkmsg"
|
|
"github.com/Nwflower/reims-go/internal/plugin"
|
|
)
|
|
|
|
func defaultMacOSGuestLang(loc i18n.Locale) string { return opencore.DefaultGuestLang(loc) }
|
|
|
|
func defaultCreateDriver() string {
|
|
if guest.UsesAppleVirtualization() {
|
|
return guest.AppleDriverID()
|
|
}
|
|
return driver.BuiltinReimsMacOSDriverID
|
|
}
|
|
|
|
func isAppleCreateDriver(id string) bool { return id == guest.AppleDriverID() }
|
|
|
|
func nativeVirtualizationStatus(ctx context.Context) (bool, error) {
|
|
if !guest.UsesAppleVirtualization() {
|
|
return false, nil
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
return true, guest.ProbeAppleVirtualization(ctx)
|
|
}
|
|
|
|
func printAppleUsage(loc i18n.Locale) {
|
|
fmt.Println(i18n.T(loc, "cli.usage.apple.header"))
|
|
fmt.Println(i18n.T(loc, "cli.usage.line_cmd"))
|
|
fmt.Println()
|
|
for _, k := range []string{
|
|
"cli.usage.apple.doctor", "cli.usage.apple.create", "cli.usage.cmd_vm_list",
|
|
"cli.usage.apple.start", "cli.usage.apple.stop", "cli.usage.apple.delete",
|
|
"cli.usage.cmd_vm_set", "cli.usage.cmd_plugin", "cli.usage.cmd_version",
|
|
} {
|
|
fmt.Println(i18n.T(loc, k))
|
|
}
|
|
}
|
|
|
|
func printAppleVirtualizationStatus(loc i18n.Locale, status *host.AppleVirtualizationStatus) {
|
|
key := "doctor.apple_virtualization.ready"
|
|
if !status.Ready {
|
|
key = "doctor.apple_virtualization.unavailable"
|
|
}
|
|
fmt.Printf("%-36s: %s\n", "Apple Virtualization", i18n.T(loc, key))
|
|
if status.Detail != "" {
|
|
fmt.Fprintln(os.Stderr, status.Detail)
|
|
}
|
|
}
|
|
|
|
func requireDirectNetwork(vm driver.VMInfo) error {
|
|
if vm.Ref().DriverID != driver.BuiltinReimsMacOSDriverID {
|
|
return nil
|
|
}
|
|
mode, _ := vm.DriverData["network_mode"].(string)
|
|
extra, _ := vm.DriverData["extra_args"].(string)
|
|
if mode == "bridge" || reims.PacketBridgeSocket(extra) != "" || reims.PacketBridgePort(extra) > 0 {
|
|
return networkmsg.Error("cli_managed_required", nil)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkDirectMacOSNetwork 由驱动在持有操作锁时再次检查,避免配置在解析后被切换。
|
|
func checkDirectMacOSNetwork(ctx context.Context, cfg *config.Config, name string) error {
|
|
prep, err := startprep.New(*cfg, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
d, err := prep.Client.Show(ctx, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if d.NetworkMode == "bridge" || reims.PacketBridgeSocket(d.ExtraArgs) != "" || reims.PacketBridgePort(d.ExtraArgs) > 0 {
|
|
return networkmsg.Error("cli_managed_required", nil)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func requireCLIMacOSEnabled(cfg *config.Config, loc i18n.Locale) error {
|
|
st, err := plugin.NewStateStore(plugin.NewPluginsLayout(cfg.DataRoot).Root).Load()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if entry := st.Plugins[guest.ID]; entry != nil && !entry.Enabled {
|
|
return errors.New(i18n.T(loc, "err.macos.disabled"))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func createAppleVM(ctx context.Context, cfg *config.Config, id, name, dir, ipsw string, cpus int, mem, disk string, start bool, flags *flag.FlagSet) error {
|
|
options := map[string]any{"restore_path": ipsw}
|
|
var unsupported error
|
|
flags.Visit(func(f *flag.Flag) {
|
|
switch f.Name {
|
|
case "driver", "ipsw", "start":
|
|
case "cpus":
|
|
options["cpus"] = cpus
|
|
case "memory":
|
|
options["memory"] = mem
|
|
case "disk-size":
|
|
options["disk_size"] = disk
|
|
default:
|
|
unsupported = fmt.Errorf("--%s is not supported by the Apple Virtualization driver", f.Name)
|
|
}
|
|
})
|
|
if unsupported != nil {
|
|
return unsupported
|
|
}
|
|
if dir != "" {
|
|
return errors.New("the Apple Virtualization driver manages its VM directories under the data folder")
|
|
}
|
|
mgr, router, err := openCLIPluginManager(cfg, false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer mgr.Close()
|
|
drv, err := router.DriverByID(id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
|
|
defer cancel()
|
|
req := driver.CreateRequest{DriverID: drv.ID(), Name: name, Options: options}
|
|
if err := drv.Create(ctx, req, os.Stdout, os.Stderr); err != nil || !start {
|
|
return err
|
|
}
|
|
_, err = lifecycle.New(mgr.Registry(), router, nil).Start(ctx, driver.NewVMRef(drv.ID(), name), os.Stdout, os.Stderr)
|
|
return err
|
|
}
|
|
|
|
// macOSCreateOptions is the CLI-neutral input to the native macOS create flow.
|
|
type macOSCreateOptions struct {
|
|
Name, Dir, MacOS, Memory, DiskSize, Disk, DiskMode, DiskCache, GPU, GuestLang string
|
|
CPUs int
|
|
Capture, Logs bool
|
|
}
|
|
|
|
func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in macOSCreateOptions, startAfterCreate, viaWindow bool) error {
|
|
if err := requireCLIMacOSEnabled(cfg, loc); err != nil {
|
|
return err
|
|
}
|
|
prep, err := startprep.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !prep.Runtime.Manifest.HasCapability("win32-native-aio") {
|
|
if dcache := strings.TrimSpace(in.DiskCache); dcache != "" && !strings.EqualFold(dcache, "default") {
|
|
return errors.New(i18n.T(loc, "validate.disk_cache_requires_runtime"))
|
|
}
|
|
if reims.IsWindowsRawDevicePath(in.Disk) {
|
|
return errors.New(i18n.T(loc, "validate.raw_disk_requires_runtime"))
|
|
}
|
|
}
|
|
client := prep.Client
|
|
opts := reims.CreateOpts{Name: in.Name, Dir: in.Dir, MacOS: in.MacOS, CPUs: in.CPUs, Memory: in.Memory, DiskSize: in.DiskSize, Disk: in.Disk, DiskMode: in.DiskMode, DiskCache: in.DiskCache, GPU: in.GPU, Capture: &in.Capture, Logs: &in.Logs, GuestLang: strings.TrimSpace(in.GuestLang), Start: false}
|
|
existingVMs, err := client.List(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("check existing VMs before create: %w", err)
|
|
}
|
|
if issue := reims.ValidateCreateTargetDir(cfg.XDGDataDir(), opts, existingVMs, loc); issue != nil {
|
|
return errors.New(issue.Message)
|
|
}
|
|
if removed, rerr := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), opts, existingVMs); rerr != nil {
|
|
return fmt.Errorf("clean unfinished VM directory: %w", rerr)
|
|
} else if removed != "" {
|
|
fmt.Fprintf(os.Stderr, "Removed unfinished directory from earlier interrupted create: %s\n", removed)
|
|
}
|
|
if installer.ShouldPrefetchOcBinaryData(prep.Runtime.Manifest.UtilCommit, prep.Runtime.Manifest.UtilVersion) {
|
|
if err := installer.EnsureCachedAsset(ctx, cfg.XDGCacheDir(), installer.OcBinaryDataAsset, nil, nil); err != nil {
|
|
fmt.Fprintf(os.Stderr, "OpenCore resource pre-fetch skipped (reims-ctl will retry): %v\n", err)
|
|
}
|
|
}
|
|
if err := client.Create(ctx, opts, os.Stdout, os.Stderr); err != nil {
|
|
return err
|
|
}
|
|
createdDir := strings.TrimSpace(opts.Dir)
|
|
if det, err := client.Show(ctx, opts.Name); err == nil && det.Directory != "" {
|
|
createdDir = det.Directory
|
|
}
|
|
if createdDir == "" {
|
|
createdDir = filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", opts.Name)
|
|
}
|
|
if err := driver.WriteOwnerDriver(createdDir, driver.BuiltinReimsMacOSDriverID); err != nil {
|
|
return err
|
|
}
|
|
if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, client.AllowsSetCapture()); ok {
|
|
if err := client.Set(ctx, postSet, os.Stdout, os.Stderr); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: could not apply post-create defaults: %v\n", err)
|
|
}
|
|
}
|
|
if opts.GuestLang != "" {
|
|
vmDir := opts.Dir
|
|
if det, err := client.Show(ctx, in.Name); err == nil && det.Directory != "" {
|
|
vmDir = det.Directory
|
|
} else if vmDir == "" {
|
|
vmDir = filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", in.Name)
|
|
}
|
|
if err := prep.ApplyGuestLang(ctx, vmDir, opts.GuestLang, false); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: could not apply macOS language (%s): %v\n", opts.GuestLang, err)
|
|
}
|
|
}
|
|
if startAfterCreate {
|
|
if err := startVM(ctx, cfg, driver.BuiltinReimsMacOSDriverID, in.Name, viaWindow); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
fmt.Println("\n" + i18n.T(loc, "vm.install_guide.title"))
|
|
fmt.Println(i18n.T(loc, "vm.install_guide.step1"))
|
|
fmt.Println(i18n.T(loc, "vm.install_guide.step2"))
|
|
fmt.Println(i18n.T(loc, "vm.install_guide.step3", in.Name))
|
|
return nil
|
|
}
|
|
|
|
func typeMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error {
|
|
if len(args) < 2 {
|
|
return fmt.Errorf("usage: reims-go vm type <name> [text] (no text: read stdin)")
|
|
}
|
|
if err := requireCLIMacOSEnabled(cfg, loc); err != nil {
|
|
return err
|
|
}
|
|
prep, err := startprep.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
|
|
if err != nil {
|
|
return err
|
|
}
|
|
text := strings.Join(args[2:], " ")
|
|
if len(args) < 3 {
|
|
raw, err := io.ReadAll(os.Stdin)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
text = strings.TrimRight(string(raw), "\r\n")
|
|
}
|
|
detail, err := prep.Client.Show(ctx, args[1])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
n, err := console.NewManager().TypeText(ctx, detail.Directory, text, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fmt.Println(i18n.T(loc, "vm.typed", n))
|
|
return nil
|
|
}
|
|
|
|
func cmdVMMacOSProvision(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error {
|
|
if err := requireCLIMacOSEnabled(cfg, loc); err != nil {
|
|
return err
|
|
}
|
|
fs := flag.NewFlagSet("vm provision", flag.ContinueOnError)
|
|
fullName := fs.String("full-name", "", "macOS account display name (printable ASCII)")
|
|
accountName := fs.String("account", "", "macOS short account name (^[a-z][a-z0-9_-]{0,31}$)")
|
|
password := fs.String("password", "", "macOS account password (4+ printable ASCII; hashed via PBKDF2, never stored in plaintext)")
|
|
passwordStdin := fs.Bool("password-stdin", false, "Read account password from stdin")
|
|
appearance := fs.String("appearance", "auto", "macOS appearance (auto|light|dark)")
|
|
agreeSLA := fs.Bool("agree-sla", false, "Confirm Apple macOS software license agreement")
|
|
noGuestTools := fs.Bool("no-guest-tools", false, "Skip pre-staging Reims Guest Tools")
|
|
clearImg := fs.Bool("clear", false, "Securely wipe and remove the VM's REIMSPROV image")
|
|
statusOnly := fs.Bool("status", false, "Print whether the VM currently has a staged REIMSPROV image")
|
|
|
|
vmName := ""
|
|
parseArgs := args
|
|
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
|
|
vmName = strings.TrimSpace(args[0])
|
|
parseArgs = args[1:]
|
|
}
|
|
if err := fs.Parse(parseArgs); err != nil {
|
|
return err
|
|
}
|
|
if vmName == "" && fs.NArg() > 0 {
|
|
vmName = strings.TrimSpace(fs.Arg(0))
|
|
}
|
|
if vmName == "" {
|
|
return errors.New("usage: reims-go vm provision <vm> --full-name <ascii> --account <ascii> (--password <ascii> | --password-stdin) --agree-sla [--appearance auto|light|dark] [--no-guest-tools] | --clear | --status")
|
|
}
|
|
|
|
prep, err := startprep.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
|
|
if err != nil {
|
|
return err
|
|
}
|
|
det, err := prep.Client.Show(ctx, vmName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if strings.TrimSpace(det.Directory) == "" {
|
|
return fmt.Errorf("VM %q directory is unavailable", vmName)
|
|
}
|
|
|
|
if *statusOnly {
|
|
if installer.HasProvisionImage(det.Directory) {
|
|
fmt.Printf("REIMSPROV staged: %s\n", installer.ProvisionImagePath(det.Directory))
|
|
} else {
|
|
fmt.Printf("REIMSPROV not staged for %s\n", det.Name)
|
|
}
|
|
return nil
|
|
}
|
|
if *clearImg {
|
|
if det.State == "running" || det.State == "paused" {
|
|
return fmt.Errorf("cannot clear REIMSPROV while VM %q is %s; stop the VM first", det.Name, det.State)
|
|
}
|
|
if err := installer.SecureRemoveProvisionImage(det.Directory); err != nil {
|
|
return err
|
|
}
|
|
if stripped := reims.StripProvisionArgs(det.ExtraArgs); stripped != det.ExtraArgs {
|
|
_ = prep.Client.Set(ctx, reims.SetOpts{Name: det.Name, ExtraArgs: &stripped}, io.Discard, io.Discard)
|
|
}
|
|
fmt.Printf("Securely wiped REIMSPROV for %s.\n", det.Name)
|
|
return nil
|
|
}
|
|
if (det.State == "running" || det.State == "paused") && installer.HasProvisionImage(det.Directory) {
|
|
return fmt.Errorf("cannot overwrite existing REIMSPROV while VM %q is %s; stop the VM first", det.Name, det.State)
|
|
}
|
|
|
|
pw := *password
|
|
if *passwordStdin {
|
|
raw, rerr := io.ReadAll(os.Stdin)
|
|
if rerr != nil {
|
|
return rerr
|
|
}
|
|
pw = strings.TrimRight(string(raw), "\r\n")
|
|
}
|
|
defer func() { pw = "" }()
|
|
|
|
pCfg := installer.ProvisionConfig{
|
|
FullName: *fullName,
|
|
AccountName: *accountName,
|
|
Password: pw,
|
|
Appearance: *appearance,
|
|
SLAAccepted: *agreeSLA,
|
|
}
|
|
if err := installer.ValidateProvisionConfig(&pCfg); err != nil {
|
|
return err
|
|
}
|
|
if !*noGuestTools {
|
|
gtCfg, gerr := guesttools.LoadOrCreateVMConfig(det.Directory, det.Name, filepath.Join(cfg.SharedDir(), det.Name), 0)
|
|
if gerr != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: could not stage Guest Tools in REIMSPROV: %v\n", gerr)
|
|
} else {
|
|
for _, pf := range guesttools.ToolsProvisionFiles(gtCfg) {
|
|
pCfg.GuestTools = append(pCfg.GuestTools, installer.ProvisionGuestToolFile{
|
|
Name: pf.Name,
|
|
Mode: pf.Mode,
|
|
Data: pf.Data,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
imgPath, err := installer.BuildProvisionDiskImage(det.Directory, pCfg)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fmt.Printf("REIMSPROV image ready: %s\n", imgPath)
|
|
fmt.Printf("Account: %s (%s), appearance=%s, guest_tools=%v\n", pCfg.AccountName, pCfg.FullName, pCfg.Appearance, len(pCfg.GuestTools) > 0)
|
|
if det.State == "running" {
|
|
fmt.Println("Note: VM is currently running; stop and start it so QEMU attaches /Volumes/REIMSPROV.")
|
|
} else {
|
|
fmt.Printf("Next: start %s into Recovery and run `sh /Volumes/REIMSHELP/install.sh` (auto-detects /Volumes/REIMSPROV/provision.pkg).\n", det.Name)
|
|
}
|
|
return nil
|
|
}
|