File: conn_linux.go

package info (click to toggle)
golang-github-mdlayher-vsock 0.0~git20210303.10d5918-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 204 kB
  • sloc: makefile: 3
file content (72 lines) | stat: -rw-r--r-- 1,440 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
67
68
69
70
71
72
//+build linux

package vsock

import (
	"golang.org/x/sys/unix"
)

// newConn creates a Conn using a connFD, immediately setting the connFD to
// non-blocking mode for use with the runtime network poller.
func newConn(cfd connFD, local, remote *Addr) (*Conn, error) {
	// Note: if any calls fail after this point, cfd.Close should be invoked
	// for cleanup because the socket is now non-blocking.
	if err := cfd.SetNonblocking(local.fileName()); err != nil {
		return nil, err
	}

	return &Conn{
		fd:     cfd,
		local:  local,
		remote: remote,
	}, nil
}

// dial is the entry point for Dial on Linux.
func dial(cid, port uint32) (*Conn, error) {
	cfd, err := newConnFD()
	if err != nil {
		return nil, err
	}

	return dialLinux(cfd, cid, port)
}

// dialLinux is the entry point for tests on Linux.
func dialLinux(cfd connFD, cid, port uint32) (c *Conn, err error) {
	defer func() {
		if err != nil {
			// If any system calls fail during setup, the socket must be closed
			// to avoid file descriptor leaks.
			_ = cfd.EarlyClose()
		}
	}()

	rsa := &unix.SockaddrVM{
		CID:  cid,
		Port: port,
	}

	if err := cfd.Connect(rsa); err != nil {
		return nil, err
	}

	lsa, err := cfd.Getsockname()
	if err != nil {
		return nil, err
	}

	lsavm := lsa.(*unix.SockaddrVM)

	local := &Addr{
		ContextID: lsavm.CID,
		Port:      lsavm.Port,
	}

	remote := &Addr{
		ContextID: cid,
		Port:      port,
	}

	return newConn(cfd, local, remote)
}