Debian Codegraph @

vsock.go

raw
1 package vsock
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "net"
9 "os"
10 "runtime"
11 "strings"
12 "syscall"
13 "time"
14 )
15
16 const (
17 // Hypervisor specifies that a socket should communicate with the hypervisor
18 // process. Note that this is _not_ the same as a socket owned by a process
19 // running on the hypervisor. Most users should probably use Host instead.
20 Hypervisor = 0x0
21
22 // Local specifies that a socket should communicate with a matching socket
23 // on the same machine. This provides an alternative to UNIX sockets or
24 // similar and may be useful in testing VM sockets applications.
25 Local = 0x1
26
27 // Host specifies that a socket should communicate with processes other than
28 // the hypervisor on the host machine. This is the correct choice to
29 // communicate with a process running on a hypervisor using a socket dialed
30 // from a guest.
31 Host = 0x2
32
33 // Error numbers we recognize, copied here to avoid importing x/sys/unix in
34 // cross-platform code.
35 ebadf = 9
36 enotconn = 107
37
38 // devVsock is the location of /dev/vsock. It is exposed on both the
39 // hypervisor and on virtual machines.
40 devVsock = "/dev/vsock"
41
42 // network is the vsock network reported in net.OpError.
43 network = "vsock"
44
45 // Operation names which may be returned in net.OpError.
46 opAccept = "accept"
47 opClose = "close"
48 opDial = "dial"
49 opListen = "listen"
50 opRawControl = "raw-control"
51 opRawRead = "raw-read"
52 opRawWrite = "raw-write"
53 opRead = "read"
54 opSet = "set"
55 opSyscallConn = "syscall-conn"
56 opWrite = "write"
57 )
58
59 // errUnimplemented is returned by all functions on platforms that
60 // cannot make use of VM sockets.
61 var errUnimplemented = fmt.Errorf("vsock: not implemented on %s", runtime.GOOS)
62
63 // TODO(mdlayher): plumb through socket.Config.NetNS if it makes sense.
64
65 // Config contains options for a Conn or Listener.
66 type Config struct{}
67
68 // Listen opens a connection-oriented net.Listener for incoming VM sockets
69 // connections. The port parameter specifies the port for the Listener. Config
70 // specifies optional configuration for the Listener. If config is nil, a
71 // default configuration will be used.
72 //
73 // To allow the server to assign a port automatically, specify 0 for port. The
74 // address of the server can be retrieved using the Addr method.
75 //
76 // Listen automatically infers the appropriate context ID for this machine by
77 // calling ContextID and passing that value to ListenContextID. Callers with
78 // advanced use cases (such as using the Local context ID) may wish to use
79 // ListenContextID directly.
80 //
81 // When the Listener is no longer needed, Close must be called to free
82 // resources.
83 func Listen(port uint32, cfg *Config) (*Listener, error) {
84 cid, err := ContextID()
85 if err != nil {
86 // No addresses available.
87 return nil, opError(opListen, err, nil, nil)
88 }
89
90 return ListenContextID(cid, port, cfg)
91 }
92
93 // ListenContextID is the same as Listen, but also accepts an explicit context
94 // ID parameter. This function is intended for advanced use cases and most
95 // callers should use Listen instead.
96 //
97 // See the documentation of Listen for more details.
98 func ListenContextID(contextID, port uint32, cfg *Config) (*Listener, error) {
99 l, err := listen(contextID, port, cfg)
100 if err != nil {
101 // No remote address available.
102 return nil, opError(opListen, err, &Addr{
103 ContextID: contextID,
104 Port: port,
105 }, nil)
106 }
107
108 return l, nil
109 }
110
111 // FileListener returns a copy of the network listener corresponding to an open
112 // os.File. It is the caller's responsibility to close the Listener when
113 // finished. Closing the Listener does not affect the os.File, and closing the
114 // os.File does not affect the Listener.
115 //
116 // This function is intended for advanced use cases and most callers should use
117 // Listen instead.
118 func FileListener(f *os.File) (*Listener, error) {
119 l, err := fileListener(f)
120 if err != nil {
121 // No addresses available.
122 return nil, opError(opListen, err, nil, nil)
123 }
124
125 return l, nil
126 }
127
128 var _ net.Listener = &Listener{}
129
130 // A Listener is a VM sockets implementation of a net.Listener.
131 type Listener struct {
132 l *listener
133 }
134
135 // Accept implements the Accept method in the net.Listener interface; it waits
136 // for the next call and returns a generic net.Conn. The returned net.Conn will
137 // always be of type *Conn.
138 func (l *Listener) Accept() (net.Conn, error) {
139 c, err := l.l.Accept()
140 if err != nil {
141 return nil, l.opError(opAccept, err)
142 }
143
144 return c, nil
145 }
146
147 // Addr returns the listener's network address, a *Addr. The Addr returned is
148 // shared by all invocations of Addr, so do not modify it.
149 func (l *Listener) Addr() net.Addr { return l.l.Addr() }
150
151 // Close stops listening on the VM sockets address. Already Accepted connections
152 // are not closed.
153 func (l *Listener) Close() error {
154 return l.opError(opClose, l.l.Close())
155 }
156
157 // SetDeadline sets the deadline associated with the listener. A zero time value
158 // disables the deadline.
159 func (l *Listener) SetDeadline(t time.Time) error {
160 return l.opError(opSet, l.l.SetDeadline(t))
161 }
162
163 // opError is a convenience for the function opError that also passes the local
164 // address of the Listener.
165 func (l *Listener) opError(op string, err error) error {
166 // No remote address for a Listener.
167 return opError(op, err, l.Addr(), nil)
168 }
169
170 // Dial dials a connection-oriented net.Conn to a VM sockets listener. The
171 // context ID and port parameters specify the address of the listener. Config
172 // specifies optional configuration for the Conn. If config is nil, a default
173 // configuration will be used.
174 //
175 // If dialing a connection from the hypervisor to a virtual machine, the VM's
176 // context ID should be specified.
177 //
178 // If dialing from a VM to the hypervisor, Hypervisor should be used to
179 // communicate with the hypervisor process, or Host should be used to
180 // communicate with other processes on the host machine.
181 //
182 // When the connection is no longer needed, Close must be called to free
183 // resources.
184 func Dial(contextID, port uint32, cfg *Config) (*Conn, error) {
185 return DialContext(context.Background(), contextID, port, cfg)
186 }
187
188 func DialContext(ctx context.Context, contextID, port uint32, cfg *Config) (*Conn, error) {
189 c, err := dial(ctx, contextID, port, cfg)
190 if err != nil {
191 // No local address, but we have a remote address we can return.
192 return nil, opError(opDial, err, nil, &Addr{
193 ContextID: contextID,
194 Port: port,
195 })
196 }
197
198 return c, nil
199 }
200
201 var (
202 _ net.Conn = &Conn{}
203 _ syscall.Conn = &Conn{}
204 )
205
206 // A Conn is a VM sockets implementation of a net.Conn.
207 type Conn struct {
208 c *conn
209 local *Addr
210 remote *Addr
211 }
212
213 // Close closes the connection.
214 func (c *Conn) Close() error {
215 return c.opError(opClose, c.c.Close())
216 }
217
218 // CloseRead shuts down the reading side of the VM sockets connection. Most
219 // callers should just use Close.
220 func (c *Conn) CloseRead() error {
221 return c.opError(opClose, c.c.CloseRead())
222 }
223
224 // CloseWrite shuts down the writing side of the VM sockets connection. Most
225 // callers should just use Close.
226 func (c *Conn) CloseWrite() error {
227 return c.opError(opClose, c.c.CloseWrite())
228 }
229
230 // LocalAddr returns the local network address. The Addr returned is shared by
231 // all invocations of LocalAddr, so do not modify it.
232 func (c *Conn) LocalAddr() net.Addr { return c.local }
233
234 // RemoteAddr returns the remote network address. The Addr returned is shared by
235 // all invocations of RemoteAddr, so do not modify it.
236 func (c *Conn) RemoteAddr() net.Addr { return c.remote }
237
238 // Read implements the net.Conn Read method.
239 func (c *Conn) Read(b []byte) (int, error) {
240 n, err := c.c.Read(b)
241 if err != nil {
242 return n, c.opError(opRead, err)
243 }
244
245 return n, nil
246 }
247
248 // Write implements the net.Conn Write method.
249 func (c *Conn) Write(b []byte) (int, error) {
250 n, err := c.c.Write(b)
251 if err != nil {
252 return n, c.opError(opWrite, err)
253 }
254
255 return n, nil
256 }
257
258 // SetDeadline implements the net.Conn SetDeadline method.
259 func (c *Conn) SetDeadline(t time.Time) error {
260 return c.opError(opSet, c.c.SetDeadline(t))
261 }
262
263 // SetReadDeadline implements the net.Conn SetReadDeadline method.
264 func (c *Conn) SetReadDeadline(t time.Time) error {
265 return c.opError(opSet, c.c.SetReadDeadline(t))
266 }
267
268 // SetWriteDeadline implements the net.Conn SetWriteDeadline method.
269 func (c *Conn) SetWriteDeadline(t time.Time) error {
270 return c.opError(opSet, c.c.SetWriteDeadline(t))
271 }
272
273 // SyscallConn returns a raw network connection. This implements the
274 // syscall.Conn interface.
275 func (c *Conn) SyscallConn() (syscall.RawConn, error) {
276 rc, err := c.c.SyscallConn()
277 if err != nil {
278 return nil, c.opError(opSyscallConn, err)
279 }
280
281 return &rawConn{
282 rc: rc,
283 local: c.local,
284 remote: c.remote,
285 }, nil
286 }
287
288 // opError is a convenience for the function opError that also passes the local
289 // and remote addresses of the Conn.
290 func (c *Conn) opError(op string, err error) error {
291 return opError(op, err, c.local, c.remote)
292 }
293
294 // TODO(mdlayher): see if we can port smarter net.OpError with local/remote
295 // address error logic into socket.Conn's SyscallConn type to avoid the need for
296 // this wrapper.
297
298 var _ syscall.RawConn = &rawConn{}
299
300 // A rawConn is a syscall.RawConn that wraps an internal syscall.RawConn in order
301 // to produce net.OpError error values.
302 type rawConn struct {
303 rc syscall.RawConn
304 local, remote *Addr
305 }
306
307 // Control implements the syscall.RawConn Control method.
308 func (rc *rawConn) Control(fn func(fd uintptr)) error {
309 return rc.opError(opRawControl, rc.rc.Control(fn))
310 }
311
312 // Control implements the syscall.RawConn Read method.
313 func (rc *rawConn) Read(fn func(fd uintptr) (done bool)) error {
314 return rc.opError(opRawRead, rc.rc.Read(fn))
315 }
316
317 // Control implements the syscall.RawConn Write method.
318 func (rc *rawConn) Write(fn func(fd uintptr) (done bool)) error {
319 return rc.opError(opRawWrite, rc.rc.Write(fn))
320 }
321
322 // opError is a convenience for the function opError that also passes the local
323 // and remote addresses of the rawConn.
324 func (rc *rawConn) opError(op string, err error) error {
325 return opError(op, err, rc.local, rc.remote)
326 }
327
328 var _ net.Addr = &Addr{}
329
330 // An Addr is the address of a VM sockets endpoint.
331 type Addr struct {
332 ContextID, Port uint32
333 }
334
335 // Network returns the address's network name, "vsock".
336 func (a *Addr) Network() string { return network }
337
338 // String returns a human-readable representation of Addr, and indicates if
339 // ContextID is meant to be used for a hypervisor, host, VM, etc.
340 func (a *Addr) String() string {
341 var host string
342
343 switch a.ContextID {
344 case Hypervisor:
345 host = fmt.Sprintf("hypervisor(%d)", a.ContextID)
346 case Local:
347 host = fmt.Sprintf("local(%d)", a.ContextID)
348 case Host:
349 host = fmt.Sprintf("host(%d)", a.ContextID)
350 default:
351 host = fmt.Sprintf("vm(%d)", a.ContextID)
352 }
353
354 return fmt.Sprintf("%s:%d", host, a.Port)
355 }
356
357 // fileName returns a file name for use with os.NewFile for Addr.
358 func (a *Addr) fileName() string {
359 return fmt.Sprintf("%s:%s", a.Network(), a.String())
360 }
361
362 // ContextID retrieves the local VM sockets context ID for this system.
363 // ContextID can be used to directly determine if a system is capable of using
364 // VM sockets.
365 //
366 // If the kernel module is unavailable, access to the kernel module is denied,
367 // or VM sockets are unsupported on this system, it returns an error.
368 func ContextID() (uint32, error) {
369 return contextID()
370 }
371
372 // opError unpacks err if possible, producing a net.OpError with the input
373 // parameters in order to implement net.Conn. As a convenience, opError returns
374 // nil if the input error is nil.
375 func opError(op string, err error, local, remote net.Addr) error {
376 if err == nil {
377 return nil
378 }
379
380 // TODO(mdlayher): this entire function is suspect and should probably be
381 // looked at carefully, especially with Go 1.13+ error wrapping.
382 //
383 // Eventually this *net.OpError logic should probably be ported into
384 // mdlayher/socket because similar checks are necessary to comply with
385 // nettest.TestConn.
386
387 // Unwrap inner errors from error types.
388 //
389 // TODO(mdlayher): errors.Cause or similar in Go 1.13.
390 switch xerr := err.(type) {
391 // os.PathError produced by os.File method calls.
392 case *os.PathError:
393 // Although we could make use of xerr.Op here, we're passing it manually
394 // for consistency, since some of the Conn calls we are making don't
395 // wrap an os.File, which would return an Op for us.
396 //
397 // As a special case, if the error is related to access to the /dev/vsock
398 // device, we don't unwrap it, so the caller has more context as to why
399 // their operation actually failed than "permission denied" or similar.
400 if xerr.Path != devVsock {
401 err = xerr.Err
402 }
403 }
404
405 switch {
406 case err == io.EOF, isErrno(err, enotconn):
407 // We may see a literal io.EOF as happens with x/net/nettest, but
408 // "transport not connected" also means io.EOF in Go.
409 return io.EOF
410 case err == os.ErrClosed, isErrno(err, ebadf), strings.Contains(err.Error(), "use of closed"):
411 // Different operations may return different errors that all effectively
412 // indicate a closed file.
413 //
414 // To rectify the differences, net.TCPConn uses an error with this text
415 // from internal/poll for the backing file already being closed.
416 err = errors.New("use of closed network connection")
417 default:
418 // Nothing to do, return this directly.
419 }
420
421 // Determine source and addr using the rules defined by net.OpError's
422 // documentation: https://golang.org/pkg/net/#OpError.
423 var source, addr net.Addr
424 switch op {
425 case opClose, opDial, opRawRead, opRawWrite, opRead, opWrite:
426 if local != nil {
427 source = local
428 }
429 if remote != nil {
430 addr = remote
431 }
432 case opAccept, opListen, opRawControl, opSet, opSyscallConn:
433 if local != nil {
434 addr = local
435 }
436 }
437
438 return &net.OpError{
439 Op: op,
440 Net: network,
441 Source: source,
442 Addr: addr,
443 Err: err,
444 }
445 }