Debian Codegraph @

tpm2/transport/linuxudstpm/linuxudstpm.go

raw
1 //go:build !windows
2
3 // Package linuxudstpm provides access to a TPM device via a Unix domain socket.
4 package linuxudstpm
5
6 import (
7 "errors"
8 "fmt"
9 "net"
10 "os"
11
12 "github.com/google/go-tpm/tpm2/transport"
13 )
14
15 var (
16 // ErrFileIsNotSocket indicates that the TPM file is not a socket.
17 ErrFileIsNotSocket = errors.New("TPM file is not a socket")
18 // ErrMustCallWriteThenRead indicates that the file was not written-then-read in the expected pattern.
19 ErrMustCallWriteThenRead = errors.New("must call Write then Read in an alternating sequence")
20 // ErrNotOpen indicates that the TPM file is not currently open.
21 ErrNotOpen = errors.New("no connection is open")
22 )
23
24 // Open opens the TPM socket at the given path.
25 func Open(path string) (transport.TPMCloser, error) {
26 fi, err := os.Stat(path)
27 if err != nil {
28 return nil, err
29 }
30
31 if fi.Mode()&os.ModeSocket == 0 {
32 return nil, fmt.Errorf("%w: %s (%s)", ErrFileIsNotSocket, fi.Mode().String(), path)
33 }
34 return transport.FromReadWriteCloser(newEmulatorReadWriteCloser(path)), nil
35 }
36
37 // dialer abstracts the net.Dial call so test code can provide its own net.Conn
38 // implementation.
39 type dialer func(network, path string) (net.Conn, error)
40
41 // emulatorReadWriteCloser manages connections with a TPM emulator over a Unix
42 // domain socket. These emulators often operate in a write/read/disconnect
43 // sequence, so the Write method always connects, and the Read method always
44 // closes. emulatorReadWriteCloser is not thread safe.
45 type emulatorReadWriteCloser struct {
46 path string
47 conn net.Conn
48 dialer dialer
49 }
50
51 // newEmulatorReadWriteCloser stores information about a Unix domain socket to
52 // write to and read from.
53 func newEmulatorReadWriteCloser(path string) *emulatorReadWriteCloser {
54 return &emulatorReadWriteCloser{
55 path: path,
56 dialer: net.Dial,
57 }
58 }
59
60 // Read implements the io.Reader interface.
61 func (erw *emulatorReadWriteCloser) Read(p []byte) (int, error) {
62 // Read is always the second operation in a Write/Read sequence.
63 if erw.conn == nil {
64 return 0, ErrMustCallWriteThenRead
65 }
66 n, err := erw.conn.Read(p)
67 erw.conn.Close()
68 erw.conn = nil
69 return n, err
70 }
71
72 // Write implements the io.Writer interface.
73 func (erw *emulatorReadWriteCloser) Write(p []byte) (int, error) {
74 if erw.conn != nil {
75 return 0, ErrMustCallWriteThenRead
76 }
77 var err error
78 erw.conn, err = erw.dialer("unix", erw.path)
79 if err != nil {
80 return 0, err
81 }
82 return erw.conn.Write(p)
83 }
84
85 // Close implements the io.Closer interface.
86 func (erw *emulatorReadWriteCloser) Close() error {
87 if erw.conn == nil {
88 // This is an expected possible state, e.g., if someone sent the TPM a command and didn't read the response.
89 return nil
90 }
91 err := erw.conn.Close()
92 erw.conn = nil
93 return err
94 }