Debian Codegraph @

tpm2/transport/tpm.go

raw
1 // Package transport implements types for physically talking to TPMs.
2 package transport
3
4 import (
5 "io"
6
7 "github.com/google/go-tpm/tpmutil"
8 )
9
10 // TPM represents a logical connection to a TPM.
11 type TPM interface {
12 Send(input []byte) ([]byte, error)
13 }
14
15 // TPMCloser represents a logical connection to a TPM and you can close it.
16 type TPMCloser interface {
17 TPM
18 io.Closer
19 }
20
21 // wrappedRW represents a struct that wraps an io.ReadWriter
22 // to a transport.TPM to be compatible with tpmdirect.
23 type wrappedRW struct {
24 transport io.ReadWriter
25 }
26
27 // wrappedRWC represents a struct that wraps an io.ReadWriteCloser
28 // to a transport.TPM to be compatible with tpmdirect.
29 type wrappedRWC struct {
30 transport io.ReadWriteCloser
31 }
32
33 // wrappedTPM represents a struct that wraps a transport.TPM's underlying
34 // transport to use with legacy code that expects an io.ReadWriter.
35 type wrappedTPM struct {
36 response []byte
37 tpm TPM
38 }
39
40 // FromReadWriter takes in a io.ReadWriter and returns a
41 // transport.TPM wrapping the io.ReadWriter.
42 func FromReadWriter(rw io.ReadWriter) TPM {
43 return &wrappedRW{transport: rw}
44 }
45
46 // FromReadWriteCloser takes in a io.ReadWriteCloser and returns a
47 // transport.TPMCloser wrapping the io.ReadWriteCloser.
48 func FromReadWriteCloser(rwc io.ReadWriteCloser) TPMCloser {
49 return &wrappedRWC{transport: rwc}
50 }
51
52 // ToReadWriter takes in a transport TPM and returns an
53 // io.ReadWriter wrapping the transport TPM.
54 func ToReadWriter(tpm TPM) io.ReadWriter {
55 return &wrappedTPM{tpm: tpm}
56 }
57
58 // Read copies t.response into the p buffer and return the appropriate length.
59 func (t *wrappedTPM) Read(p []byte) (int, error) {
60 n := copy(p, t.response)
61 t.response = t.response[n:]
62 if len(t.response) == 0 {
63 return n, io.EOF
64 }
65 return n, nil
66 }
67
68 // Write implements the io.ReadWriter interface.
69 func (t *wrappedTPM) Write(p []byte) (n int, err error) {
70 t.response, err = t.tpm.Send(p)
71 if err != nil {
72 return 0, err
73 }
74 return len(p), nil
75 }
76
77 // Send implements the TPM interface.
78 func (t *wrappedRW) Send(input []byte) ([]byte, error) {
79 return tpmutil.RunCommandRaw(t.transport, input)
80 }
81
82 // Send implements the TPM interface.
83 func (t *wrappedRWC) Send(input []byte) ([]byte, error) {
84 return tpmutil.RunCommandRaw(t.transport, input)
85 }
86
87 // Close implements the TPM interface.
88 func (t *wrappedRWC) Close() error {
89 return t.transport.Close()
90 }