blob: a1a305a36400fb55682a5ba1dfc03d39d9875b64 [file] [log] [blame]
Serge Bazanskicaa12082023-02-16 14:54:04 +01001package manager
2
3import (
4 "bytes"
5 "context"
6 "fmt"
7 "io"
8 "net"
9 "time"
10
11 "github.com/pkg/sftp"
12 "golang.org/x/crypto/ssh"
13)
14
15// SSHClient defines a simple interface to an abstract SSH client. Usually this
16// would be PlainSSHClient, but tests can use this interface to dependency-inject
17// fake SSH connections.
18type SSHClient interface {
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020019 // Dial returns an SSHConnection to a given address (host:port pair) with
20 // a timeout for connection.
21 Dial(ctx context.Context, address string, connectTimeout time.Duration) (SSHConnection, error)
Serge Bazanskicaa12082023-02-16 14:54:04 +010022}
23
24type SSHConnection interface {
25 // Execute a given command on a remote host synchronously, passing in stdin as
26 // input, and returning a captured stdout/stderr. The returned data might be
27 // valid even when err != nil, which might happen if the remote side returned a
28 // non-zero exit code.
29 Execute(ctx context.Context, command string, stdin []byte) (stdout []byte, stderr []byte, err error)
30 // Upload a given blob to a targetPath on the system and make executable.
31 Upload(ctx context.Context, targetPath string, data []byte) error
32 // Close this connection.
33 Close() error
34}
35
36// PlainSSHClient implements SSHClient (and SSHConnection) using
37// golang.org/x/crypto/ssh.
38type PlainSSHClient struct {
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020039 AuthMethod ssh.AuthMethod
40 Username string
Serge Bazanskicaa12082023-02-16 14:54:04 +010041}
42
43type plainSSHConn struct {
44 cl *ssh.Client
45}
46
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020047func (p *PlainSSHClient) Dial(ctx context.Context, address string, connectTimeout time.Duration) (SSHConnection, error) {
Serge Bazanskicaa12082023-02-16 14:54:04 +010048 d := net.Dialer{
49 Timeout: connectTimeout,
50 }
51 conn, err := d.DialContext(ctx, "tcp", address)
52 if err != nil {
53 return nil, err
54 }
55 conf := &ssh.ClientConfig{
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020056 User: p.Username,
Serge Bazanskicaa12082023-02-16 14:54:04 +010057 Auth: []ssh.AuthMethod{
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020058 p.AuthMethod,
Serge Bazanskicaa12082023-02-16 14:54:04 +010059 },
60 // Ignore the host key, since it's likely the first time anything logs into
61 // this device, and also because there's no way of knowing its fingerprint.
62 HostKeyCallback: ssh.InsecureIgnoreHostKey(),
63 // Timeout sets a bound on the time it takes to set up the connection, but
64 // not on total session time.
65 Timeout: connectTimeout,
66 }
67 conn2, chanC, reqC, err := ssh.NewClientConn(conn, address, conf)
68 if err != nil {
69 return nil, err
70 }
71 cl := ssh.NewClient(conn2, chanC, reqC)
72 return &plainSSHConn{
73 cl: cl,
74 }, nil
75}
76
77func (p *plainSSHConn) Execute(ctx context.Context, command string, stdin []byte) (stdout []byte, stderr []byte, err error) {
78 sess, err := p.cl.NewSession()
79 if err != nil {
80 return nil, nil, fmt.Errorf("while creating SSH session: %w", err)
81 }
82 stdoutBuf := bytes.NewBuffer(nil)
83 stderrBuf := bytes.NewBuffer(nil)
84 sess.Stdin = bytes.NewBuffer(stdin)
85 sess.Stdout = stdoutBuf
86 sess.Stderr = stderrBuf
87 defer sess.Close()
88
89 if err := sess.Start(command); err != nil {
90 return nil, nil, err
91 }
92 doneC := make(chan error, 1)
93 go func() {
94 doneC <- sess.Wait()
95 }()
96 select {
97 case <-ctx.Done():
98 return nil, nil, ctx.Err()
99 case err := <-doneC:
100 return stdoutBuf.Bytes(), stderrBuf.Bytes(), err
101 }
102}
103
104func (p *plainSSHConn) Upload(ctx context.Context, targetPath string, data []byte) error {
105 sc, err := sftp.NewClient(p.cl)
106 if err != nil {
107 return fmt.Errorf("while building sftp client: %w", err)
108 }
109 defer sc.Close()
110
111 acrdr := bytes.NewReader(data)
112 df, err := sc.Create(targetPath)
113 if err != nil {
114 return fmt.Errorf("while creating file on the host: %w", err)
115 }
116
117 doneC := make(chan error, 1)
118
119 go func() {
120 _, err := io.Copy(df, acrdr)
121 df.Close()
122 doneC <- err
123 }()
124
125 select {
126 case err := <-doneC:
127 if err != nil {
128 return fmt.Errorf("while copying file: %w", err)
129 }
130 case <-ctx.Done():
131 df.Close()
132 return ctx.Err()
133 }
134
135 if err := sc.Chmod(targetPath, 0755); err != nil {
136 return fmt.Errorf("while setting file permissions: %w", err)
137 }
138 return nil
139}
140
141func (p *plainSSHConn) Close() error {
142 return p.cl.Close()
143}