| 1 | package host |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os" |
| 6 | "os/exec" |
| 7 | "path/filepath" |
| 8 | "runtime" |
| 9 | "strings" |
| 10 | "syscall" |
| 11 | "unsafe" |
| 12 | |
| 13 | "golang.org/x/sys/windows" |
| 14 | ) |
| 15 | |
| 16 | |
| 17 | func HideCommandWindow(cmd *exec.Cmd) { |
| 18 | if cmd.SysProcAttr == nil { |
| 19 | cmd.SysProcAttr = &syscall.SysProcAttr{} |
| 20 | } |
| 21 | cmd.SysProcAttr.HideWindow = true |
| 22 | cmd.SysProcAttr.CreationFlags |= windows.CREATE_NO_WINDOW |
| 23 | } |
| 24 | |
| 25 | |
| 26 | |
| 27 | func ConfigureWindowsRuntime() error { |
| 28 | |
| 29 | |
| 30 | for _, name := range []string{"OPENSSH_STDIO_MODE", "c28fc6f98a2c44abbbd89d6a3037d0d9_POSIX_FD_STATE"} { |
| 31 | os.Unsetenv(name) |
| 32 | } |
| 33 | version := windows.RtlGetVersion() |
| 34 | if runtime.GOARCH != "amd64" || version.MajorVersion < 10 || version.BuildNumber < 19045 { |
| 35 | return fmt.Errorf("Cage 需要 64 位 Windows 10 22H2(19045)或 Windows 11") |
| 36 | } |
| 37 | var processMachine, nativeMachine uint16 |
| 38 | if err := windows.IsWow64Process2(windows.CurrentProcess(), &processMachine, &nativeMachine); err != nil || nativeMachine != 0x8664 { |
| 39 | return fmt.Errorf("Cage Windows 版本需要 Intel 或 AMD 的 x64 处理器,暂不支持 Windows on ARM") |
| 40 | } |
| 41 | exe, err := os.Executable() |
| 42 | if err != nil { |
| 43 | return err |
| 44 | } |
| 45 | base := filepath.Join(filepath.Dir(exe), "runtime") |
| 46 | paths := []string{} |
| 47 | for _, item := range []struct{ dir, exe string }{{"qemu", "qemu-system-x86_64.exe"}, {"openssh", "ssh.exe"}} { |
| 48 | dir := filepath.Join(base, item.dir) |
| 49 | if st, err := os.Stat(filepath.Join(dir, item.exe)); err == nil && st.Mode().IsRegular() { |
| 50 | paths = append(paths, dir) |
| 51 | if item.dir == "qemu" { |
| 52 | os.Setenv("AGENT_VM_QEMU_DIR", dir) |
| 53 | } else { |
| 54 | |
| 55 | |
| 56 | os.Setenv("SSH", "'"+strings.ReplaceAll(filepath.ToSlash(filepath.Join(dir, "ssh.exe")), "'", "'\\''")+"'") |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | if len(paths) > 0 { |
| 61 | paths = append(paths, os.Getenv("PATH")) |
| 62 | return os.Setenv("PATH", strings.Join(paths, string(os.PathListSeparator))) |
| 63 | } |
| 64 | return nil |
| 65 | } |
| 66 | |
| 67 | |
| 68 | |
| 69 | func windowsHypervisorReady() error { |
| 70 | proc := windows.NewLazySystemDLL("WinHvPlatform.dll").NewProc("WHvGetCapability") |
| 71 | if err := proc.Find(); err != nil { |
| 72 | return fmt.Errorf("请启用 Windows Hypervisor Platform(Windows 虚拟机监控程序平台)并重启后再启动环境") |
| 73 | } |
| 74 | var present, written uint32 |
| 75 | result, _, _ := proc.Call(0, uintptr(unsafe.Pointer(&present)), unsafe.Sizeof(present), uintptr(unsafe.Pointer(&written))) |
| 76 | if result != 0 || written != 4 || present == 0 { |
| 77 | return fmt.Errorf("Windows 虚拟化尚未就绪:请在固件中启用 CPU 虚拟化,启用 Windows Hypervisor Platform 并重启") |
| 78 | } |
| 79 | return nil |
| 80 | } |