| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "net" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "os/signal" |
| 13 | "path/filepath" |
| 14 | "runtime" |
| 15 | "sync" |
| 16 | "syscall" |
| 17 | "time" |
| 18 | |
| 19 | "github.com/containers/gvisor-tap-vsock/pkg/types" |
| 20 | "github.com/containers/gvisor-tap-vsock/pkg/virtualnetwork" |
| 21 | "github.com/sylvinus/agent-vm/internal/cage" |
| 22 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 23 | "github.com/sylvinus/agent-vm/internal/host" |
| 24 | ) |
| 25 | |
| 26 | type windowsHostNetwork struct { |
| 27 | cancel context.CancelFunc |
| 28 | done chan struct{} |
| 29 | } |
| 30 | |
| 31 | const windowsPacketDisconnectedReason = "Windows 客机网络通道已断开,等待重新检查" |
| 32 | |
| 33 | func (s *Server) startWindowsNetwork() error { |
| 34 | s.mu.Lock() |
| 35 | if current := s.windowsNetwork; current != nil { |
| 36 | select { |
| 37 | case <-current.done: |
| 38 | s.windowsNetwork = nil |
| 39 | default: |
| 40 | s.mu.Unlock() |
| 41 | return nil |
| 42 | } |
| 43 | } |
| 44 | if s.closing || s.exe == "" { |
| 45 | s.mu.Unlock() |
| 46 | return errors.New("Windows 客机网络服务尚未准备好") |
| 47 | } |
| 48 | ctx, cancel := context.WithCancel(s.lifetimeContextLocked()) |
| 49 | process := &windowsHostNetwork{cancel: cancel, done: make(chan struct{})} |
| 50 | s.windowsNetwork = process |
| 51 | s.mu.Unlock() |
| 52 | cmd := exec.CommandContext(ctx, s.exe, "windows-network-host") |
| 53 | cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+s.configPath) |
| 54 | cmd.Stdout = io.Discard |
| 55 | cmd.Stderr = io.Discard |
| 56 | host.HideCommandWindow(cmd) |
| 57 | if err := cmd.Start(); err != nil { |
| 58 | cancel() |
| 59 | close(process.done) |
| 60 | return err |
| 61 | } |
| 62 | go func() { defer close(process.done); _ = cmd.Wait() }() |
| 63 | |
| 64 | wait, cancelWait := context.WithTimeout(s.operationContext(), 30*time.Second) |
| 65 | defer cancelWait() |
| 66 | for { |
| 67 | if gate, err := s.gateClient(); err == nil { |
| 68 | if state, e := gate.Status(wait); e == nil { |
| 69 | s.publishGate(state) |
| 70 | return nil |
| 71 | } |
| 72 | } |
| 73 | select { |
| 74 | case <-process.done: |
| 75 | return errors.New("Windows 客机网络服务未能启动") |
| 76 | case <-wait.Done(): |
| 77 | cancel() |
| 78 | <-process.done |
| 79 | return errors.New("Windows 客机网络服务启动超时") |
| 80 | case <-time.After(100 * time.Millisecond): |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | func (s *Server) closeWindowsNetwork() { |
| 86 | s.mu.Lock() |
| 87 | network := s.windowsNetwork |
| 88 | s.windowsNetwork = nil |
| 89 | s.mu.Unlock() |
| 90 | if network != nil { |
| 91 | network.cancel() |
| 92 | <-network.done |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | |
| 97 | |
| 98 | func ServeWindowsPacketNetwork(configPath string) error { |
| 99 | if runtime.GOOS != "windows" { |
| 100 | return errors.New("Windows 客机网络需要 Windows Hyper-V 主机") |
| 101 | } |
| 102 | if err := containWindowsNetworkProcess(); err != nil { |
| 103 | return err |
| 104 | } |
| 105 | profile := filepath.Dir(configPath) |
| 106 | binding, err := guestos.LoadWindowsProfile(profile) |
| 107 | if err != nil || binding == nil { |
| 108 | return errors.New("Windows 客机尚未绑定") |
| 109 | } |
| 110 | cfg, err := loadConfig(configPath) |
| 111 | if err != nil { |
| 112 | return err |
| 113 | } |
| 114 | gate, err := cage.NewEgressGate(cfg) |
| 115 | if err != nil { |
| 116 | return err |
| 117 | } |
| 118 | ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 119 | defer cancel() |
| 120 | defer gate.Close("Windows 客机网络已停止") |
| 121 | var stop func() |
| 122 | defer func() { |
| 123 | if stop != nil { |
| 124 | stop() |
| 125 | } |
| 126 | }() |
| 127 | network, err := virtualnetwork.New(&types.Configuration{ |
| 128 | Subnet: "192.168.127.0/24", GatewayIP: "192.168.127.1", GatewayMacAddress: "5a:94:ef:e4:0c:dd", MTU: 1500, |
| 129 | DHCPStaticLeases: map[string]string{"192.168.127.2": "5a:94:ef:e4:0c:ee"}, |
| 130 | NAT: map[string]string{}, Forwards: map[string]string{}, Outbound: gate.Allows, DialContext: gate.DialContext, DNSExchange: gate.ExchangeDNS, |
| 131 | }) |
| 132 | if err != nil { |
| 133 | return err |
| 134 | } |
| 135 | for ctx.Err() == nil { |
| 136 | command, err := guestos.WindowsRelayCommand(ctx, profile, "network-stream") |
| 137 | if err != nil { |
| 138 | return err |
| 139 | } |
| 140 | conn, err := openWindowsPacketRelay(ctx, command, binding) |
| 141 | if err == nil { |
| 142 | if stop == nil { |
| 143 | stop, err = cage.StartGateControl(configPath, binding.InstanceDirectory, gate) |
| 144 | if err != nil { |
| 145 | _ = conn.Close() |
| 146 | return err |
| 147 | } |
| 148 | } |
| 149 | _ = network.AcceptQemu(ctx, conn) |
| 150 | _ = conn.Close() |
| 151 | } |
| 152 | gate.Close(windowsPacketDisconnectedReason) |
| 153 | select { |
| 154 | case <-ctx.Done(): |
| 155 | return nil |
| 156 | case <-time.After(time.Second): |
| 157 | } |
| 158 | } |
| 159 | return nil |
| 160 | } |
| 161 | |
| 162 | type windowsPacketRelay struct { |
| 163 | net.Conn |
| 164 | closeOnce sync.Once |
| 165 | finish func() |
| 166 | } |
| 167 | |
| 168 | func (c *windowsPacketRelay) Close() error { |
| 169 | c.closeOnce.Do(func() { _ = c.Conn.Close(); c.finish() }) |
| 170 | return nil |
| 171 | } |
| 172 | |
| 173 | func openWindowsPacketRelay(parent context.Context, cmd *exec.Cmd, binding *guestos.WindowsProfile) (net.Conn, error) { |
| 174 | input, err := cmd.StdinPipe() |
| 175 | if err != nil { |
| 176 | return nil, err |
| 177 | } |
| 178 | output, err := cmd.StdoutPipe() |
| 179 | if err != nil { |
| 180 | input.Close() |
| 181 | return nil, err |
| 182 | } |
| 183 | diagnostic, err := cmd.StderrPipe() |
| 184 | if err != nil { |
| 185 | input.Close() |
| 186 | output.Close() |
| 187 | return nil, err |
| 188 | } |
| 189 | if err = cmd.Start(); err != nil { |
| 190 | input.Close() |
| 191 | output.Close() |
| 192 | diagnostic.Close() |
| 193 | return nil, err |
| 194 | } |
| 195 | deadlineDone := make(chan struct{}) |
| 196 | deadline := time.AfterFunc(25*time.Second, func() { defer close(deadlineDone); _ = cmd.Process.Kill(); diagnostic.Close() }) |
| 197 | reader := bufio.NewReaderSize(diagnostic, 4096) |
| 198 | err = readWindowsPacketReady(reader, binding) |
| 199 | stopped := cancelWindowsAdmissionDeadline(deadline, deadlineDone) |
| 200 | if err != nil || !stopped || parent.Err() != nil { |
| 201 | input.Close() |
| 202 | output.Close() |
| 203 | diagnostic.Close() |
| 204 | _ = cmd.Process.Kill() |
| 205 | _ = cmd.Wait() |
| 206 | return nil, errors.New("Windows 专用网络尚未建立,外网保持关闭") |
| 207 | } |
| 208 | diagnosticDone := make(chan struct{}) |
| 209 | go func() { defer close(diagnosticDone); _, _ = io.Copy(io.Discard, reader) }() |
| 210 | local, remote := net.Pipe() |
| 211 | done := make(chan struct{}) |
| 212 | writeDone := make(chan struct{}) |
| 213 | go func() { defer close(writeDone); _, _ = io.Copy(input, remote); _ = input.Close() }() |
| 214 | go func() { |
| 215 | defer close(done) |
| 216 | _, _ = io.Copy(remote, output) |
| 217 | _ = remote.Close() |
| 218 | _ = input.Close() |
| 219 | _ = output.Close() |
| 220 | if cmd.Process != nil { |
| 221 | _ = cmd.Process.Kill() |
| 222 | } |
| 223 | <-writeDone |
| 224 | _ = cmd.Wait() |
| 225 | _ = diagnostic.Close() |
| 226 | <-diagnosticDone |
| 227 | }() |
| 228 | connection := &windowsPacketRelay{Conn: local, finish: func() { |
| 229 | _ = remote.Close() |
| 230 | _ = input.Close() |
| 231 | _ = output.Close() |
| 232 | if cmd.Process != nil { |
| 233 | _ = cmd.Process.Kill() |
| 234 | } |
| 235 | <-done |
| 236 | }} |
| 237 | return connection, nil |
| 238 | } |
| 239 | |
| 240 | func readWindowsPacketReady(reader *bufio.Reader, binding *guestos.WindowsProfile) error { |
| 241 | line, err := reader.ReadSlice('\n') |
| 242 | if err != nil { |
| 243 | return err |
| 244 | } |
| 245 | var ready struct { |
| 246 | Ready bool `json:"network_ready"` |
| 247 | Version int `json:"version"` |
| 248 | VMID string `json:"vm_id"` |
| 249 | SID string `json:"gui_user_sid"` |
| 250 | Session string `json:"session"` |
| 251 | Network string `json:"network"` |
| 252 | Available bool `json:"available"` |
| 253 | } |
| 254 | if json.Unmarshal(line, &ready) != nil || binding == nil || !ready.Ready || ready.Version != 1 || ready.VMID != binding.VMID.String() || ready.SID != binding.GUIUserSID || ready.Network != "packet" || !ready.Available || len(ready.Session) == 0 || len(ready.Session) > 128 { |
| 255 | return errors.New("Windows 专用网络身份或就绪回执无效") |
| 256 | } |
| 257 | return nil |
| 258 | } |