File: hyperkit_darwin.go

package info (click to toggle)
golang-github-linuxkit-virtsock 0.0~git20220523.1a23e78%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 464 kB
  • sloc: ansic: 1,481; makefile: 81; sh: 7
file content (66 lines) | stat: -rw-r--r-- 2,020 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Package vsock provides bindings to the hyperkit based
// implementation on macOS hosts.  virtio Sockets are exposed as named
// pipes on macOS. Two modes are supported (to be set with
// SockerMode()):
// - Hyperkit mode: The package needs to be initialised with the path
//   to where the named pipe was created.
// - Docker for Mac mode: This is a shortcut which hard codes the
//   location of the named pipe.
package vsock

import (
	"fmt"
	"log"
	"net"
	"os"
	"path/filepath"
	"strings"

	"github.com/pkg/errors"
)

var (
	socketPath  string
	connectPath string
	socketFmt   string
)

// SocketMode initialises the bindings to either raw hyperkit mode
// ("hyperkit:/path") or Docker for Mac mode ("docker"). This function
// must be called before using the vsock bindings.
func SocketMode(socketMode string) {
	socketFmt = "%08x.%08x"

	if strings.HasPrefix(socketMode, "hyperkit:") {
		socketPath = socketMode[len("hyperkit:"):]
	} else if socketMode == "docker" {
		socketPath = filepath.Join(os.Getenv("HOME"), "/Library/Containers/com.docker.docker/Data/vms/0")
	} else {
		log.Fatalln("Unknown socket mode: ", socketMode)
	}

	connectPath = filepath.Join(socketPath, "connect")
}

// Dial creates a connection to the VM with the given client ID and port
func Dial(cid, port uint32) (Conn, error) {
	c, err := net.DialUnix("unix", nil, &net.UnixAddr{connectPath, "unix"})
	if err != nil {
		return c, errors.Wrapf(err, "failed to dial on %s", connectPath)
	}
	if _, err := fmt.Fprintf(c, "%08x.%08x\n", cid, port); err != nil {
		return c, errors.Wrapf(err, "Failed to write dest (%08x.%08x) to %s", cid, port, connectPath)
	}
	return c, nil
}

// Listen creates a listener for a specifc vsock.
func Listen(cid, port uint32) (net.Listener, error) {
	sock := filepath.Join(socketPath, fmt.Sprintf(socketFmt, cid, port))
	if err := os.Remove(sock); err != nil && !os.IsNotExist(err) {
		log.Fatalln("Listen(): Remove:", err)
		return nil, err
	}

	return net.ListenUnix("unix", &net.UnixAddr{sock, "unix"})
}