244 lines
6.2 KiB
Go
244 lines
6.2 KiB
Go
package qmp
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const rebootSocketName = "reims-go-reboot.sock"
|
|
|
|
type qmpEvent struct {
|
|
Event string `json:"event"`
|
|
Data struct {
|
|
Guest bool `json:"guest"`
|
|
Reason string `json:"reason"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
// RebootSocketPath picks an AF_UNIX socket path for the Win10 cold-reboot QMP
|
|
// channel. Using AF_UNIX instead of tcp:127.0.0.1 prevents guest code from
|
|
// reaching unauthenticated QMP through SLIRP's 10.0.2.2 host-loopback forward.
|
|
// Falls back to tmpDir when vmDir would exceed Windows' 108-byte sun_path limit.
|
|
func RebootSocketPath(vmDir, tmpDir, vmName string) string {
|
|
if vmDir != "" {
|
|
cand := filepath.Join(vmDir, rebootSocketName)
|
|
if len(cand) <= 100 {
|
|
return cand
|
|
}
|
|
}
|
|
sum := sha256.Sum256([]byte(vmName))
|
|
short := hex.EncodeToString(sum[:6])
|
|
if tmpDir != "" {
|
|
return filepath.Join(tmpDir, "qmp-"+short+".sock")
|
|
}
|
|
return filepath.Join(vmDir, "q-"+short+".sock")
|
|
}
|
|
|
|
// StripLegacyWin10RebootArgs removes reims-go managed Win10 cold-reboot args
|
|
// (`-no-reboot` + `-qmp <managed>`) ONLY when a managed QMP target is present,
|
|
// preserving any user hand-written `-no-reboot` on hosts without managed QMP.
|
|
func StripLegacyWin10RebootArgs(existing string) string {
|
|
tokens := splitShellTokens(existing)
|
|
hasManagedQMP := false
|
|
for i := 0; i < len(tokens); i++ {
|
|
if tokens[i] == "-qmp" && i+1 < len(tokens) && isManagedQMPTarget(tokens[i+1]) {
|
|
hasManagedQMP = true
|
|
break
|
|
}
|
|
}
|
|
if !hasManagedQMP {
|
|
return strings.TrimSpace(existing)
|
|
}
|
|
cleaned := make([]string, 0, len(tokens))
|
|
for i := 0; i < len(tokens); i++ {
|
|
tok := tokens[i]
|
|
if tok == "-no-reboot" {
|
|
continue
|
|
}
|
|
if tok == "-qmp" && i+1 < len(tokens) && isManagedQMPTarget(tokens[i+1]) {
|
|
i++
|
|
continue
|
|
}
|
|
cleaned = append(cleaned, tok)
|
|
}
|
|
return strings.Join(cleaned, " ")
|
|
}
|
|
|
|
// MergeWin10RebootUnixArgs idempotently merges `-no-reboot` and a local AF_UNIX
|
|
// `-qmp unix:<path>,server=on,wait=off` into existing extra_args while stripping
|
|
// any legacy managed TCP or Unix QMP arguments.
|
|
func MergeWin10RebootUnixArgs(existing, sockPath string) string {
|
|
tokens := splitShellTokens(existing)
|
|
cleaned := make([]string, 0, len(tokens)+3)
|
|
for i := 0; i < len(tokens); i++ {
|
|
tok := tokens[i]
|
|
if tok == "-no-reboot" {
|
|
continue
|
|
}
|
|
if tok == "-qmp" && i+1 < len(tokens) && isManagedQMPTarget(tokens[i+1]) {
|
|
i++
|
|
continue
|
|
}
|
|
cleaned = append(cleaned, tok)
|
|
}
|
|
escaped := strings.ReplaceAll(sockPath, ",", ",,")
|
|
escaped = strings.ReplaceAll(escaped, `\`, `/`)
|
|
qmpVal := fmt.Sprintf("unix:%s,server=on,wait=off", escaped)
|
|
if strings.ContainsAny(qmpVal, " \t") {
|
|
qmpVal = `"` + strings.ReplaceAll(qmpVal, `"`, `\"`) + `"`
|
|
}
|
|
cleaned = append(cleaned, "-no-reboot", "-qmp", qmpVal)
|
|
return strings.Join(cleaned, " ")
|
|
}
|
|
|
|
func isManagedQMPTarget(arg string) bool {
|
|
arg = strings.Trim(arg, "'\"")
|
|
if !strings.HasSuffix(arg, ",server=on,wait=off") {
|
|
return false
|
|
}
|
|
if strings.HasPrefix(arg, "tcp:127.0.0.1:") {
|
|
return true
|
|
}
|
|
if strings.HasPrefix(arg, "unix:") {
|
|
return strings.Contains(arg, rebootSocketName) || strings.Contains(arg, "/qmp-") || strings.Contains(arg, `\qmp-`)
|
|
}
|
|
return false
|
|
}
|
|
|
|
func splitShellTokens(s string) []string {
|
|
var out []string
|
|
var cur strings.Builder
|
|
var quote byte
|
|
for i := 0; i < len(s); i++ {
|
|
c := s[i]
|
|
if quote != 0 {
|
|
cur.WriteByte(c)
|
|
if c == quote {
|
|
quote = 0
|
|
}
|
|
continue
|
|
}
|
|
if c == '\'' || c == '"' {
|
|
quote = c
|
|
cur.WriteByte(c)
|
|
continue
|
|
}
|
|
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
|
|
if cur.Len() > 0 {
|
|
out = append(out, cur.String())
|
|
cur.Reset()
|
|
}
|
|
continue
|
|
}
|
|
cur.WriteByte(c)
|
|
}
|
|
if cur.Len() > 0 {
|
|
out = append(out, cur.String())
|
|
}
|
|
return out
|
|
}
|
|
|
|
// WatchForGuestReset connects to QEMU's secondary QMP endpoint (AF_UNIX path or
|
|
// "unix:<path>"), negotiates capabilities, and waits for a SHUTDOWN event. It
|
|
// returns true iff the VM exited because the guest requested a reset
|
|
// (`reason == "guest-reset"` under `-no-reboot`).
|
|
func WatchForGuestReset(ctx context.Context, addr string) (bool, error) {
|
|
reason, err := WatchShutdownReason(ctx, addr)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return reason == "guest-reset", nil
|
|
}
|
|
|
|
// WatchShutdownReason waits for QEMU's SHUTDOWN event over QMP and returns its
|
|
// reason (e.g. "guest-reset", "guest-shutdown", "host-qmp-quit"), or "" on EOF.
|
|
func WatchShutdownReason(ctx context.Context, addr string) (string, error) {
|
|
conn, err := dialWithRetry(ctx, addr, 20*time.Second)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer conn.Close()
|
|
|
|
go func() {
|
|
<-ctx.Done()
|
|
_ = conn.Close()
|
|
}()
|
|
|
|
reader := bufio.NewScanner(conn)
|
|
// Increase buffer in case a QMP greeting or event is large.
|
|
reader.Buffer(make([]byte, 0, 64*1024), 512*1024)
|
|
|
|
// Read QMP greeting.
|
|
if !reader.Scan() {
|
|
if ctx.Err() != nil {
|
|
return "", ctx.Err()
|
|
}
|
|
return "", reader.Err()
|
|
}
|
|
|
|
if _, err := conn.Write([]byte("{\"execute\":\"qmp_capabilities\"}\n")); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
for reader.Scan() {
|
|
line := strings.TrimSpace(reader.Text())
|
|
if line == "" {
|
|
continue
|
|
}
|
|
var ev qmpEvent
|
|
if err := json.Unmarshal([]byte(line), &ev); err != nil {
|
|
continue
|
|
}
|
|
if ev.Event == "SHUTDOWN" {
|
|
return ev.Data.Reason, nil
|
|
}
|
|
}
|
|
if ctx.Err() != nil {
|
|
return "", ctx.Err()
|
|
}
|
|
return "", reader.Err()
|
|
}
|
|
|
|
func resolveQMPEndpoint(addr string) (network, target string) {
|
|
if strings.HasPrefix(addr, "unix:") {
|
|
return "unix", strings.TrimPrefix(addr, "unix:")
|
|
}
|
|
if strings.HasSuffix(strings.ToLower(addr), ".sock") || filepath.IsAbs(addr) {
|
|
return "unix", addr
|
|
}
|
|
return "tcp", addr
|
|
}
|
|
|
|
func dialWithRetry(ctx context.Context, addr string, timeout time.Duration) (net.Conn, error) {
|
|
network, target := resolveQMPEndpoint(addr)
|
|
deadline := time.Now().Add(timeout)
|
|
var lastErr error
|
|
for {
|
|
if ctx.Err() != nil {
|
|
return nil, ctx.Err()
|
|
}
|
|
d := net.Dialer{Timeout: 500 * time.Millisecond}
|
|
conn, err := d.DialContext(ctx, network, target)
|
|
if err == nil {
|
|
return conn, nil
|
|
}
|
|
lastErr = err
|
|
if time.Now().After(deadline) {
|
|
return nil, fmt.Errorf("connect QMP %s (%s): %w", target, network, lastErr)
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil, ctx.Err()
|
|
case <-time.After(250 * time.Millisecond):
|
|
}
|
|
}
|
|
}
|