Debian Codegraph @

conn_linux.go

raw
1 //go:build linux
2 // +build linux
3
4 package vsock
5
6 import (
7 "context"
8
9 "github.com/mdlayher/socket"
10 "golang.org/x/sys/unix"
11 )
12
13 // A conn is the net.Conn implementation for connection-oriented VM sockets.
14 // We can use socket.Conn directly on Linux to implement all of the necessary
15 // methods.
16 type conn = socket.Conn
17
18 // dial is the entry point for Dial on Linux.
19 func dial(ctx context.Context, cid, port uint32, _ *Config) (*Conn, error) {
20 // TODO(mdlayher): Config default nil check and initialize. Pass options to
21 // socket.Config where necessary.
22
23 c, err := socket.Socket(unix.AF_VSOCK, unix.SOCK_STREAM, 0, "vsock", nil)
24 if err != nil {
25 return nil, err
26 }
27
28 sa := &unix.SockaddrVM{CID: cid, Port: port}
29 rsa, err := c.Connect(ctx, sa)
30 if err != nil {
31 _ = c.Close()
32 return nil, err
33 }
34
35 // TODO(mdlayher): getpeername(2) appears to return nil in the GitHub CI
36 // environment, so in the event of a nil sockaddr, fall back to the previous
37 // method of synthesizing the remote address.
38 if rsa == nil {
39 rsa = sa
40 }
41
42 lsa, err := c.Getsockname()
43 if err != nil {
44 _ = c.Close()
45 return nil, err
46 }
47
48 lsavm := lsa.(*unix.SockaddrVM)
49 rsavm := rsa.(*unix.SockaddrVM)
50
51 return &Conn{
52 c: c,
53 local: &Addr{
54 ContextID: lsavm.CID,
55 Port: lsavm.Port,
56 },
57 remote: &Addr{
58 ContextID: rsavm.CID,
59 Port: rsavm.Port,
60 },
61 }, nil
62 }