-
Notifications
You must be signed in to change notification settings - Fork 2
/
session.go
296 lines (270 loc) · 7.62 KB
/
session.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// Copyright 2024 The ChromiumOS Authors
// Use of this source code is governed by a MIT License that can be
// found in the LICENSE file.
package adb
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"github.com/prife/goadb/wire"
)
// A Session represents a connection to a remote command or shell.
type Session struct {
// Stdin specifies the remote process's standard input.
// If Stdin is nil, the remote process reads from an empty
// bytes.Buffer.
Stdin io.Reader
// Stdout and Stderr specify the remote process's standard
// output and error.
//
// If either is nil, Run connects the corresponding file
// descriptor to an instance of io.Discard. There is a
// fixed amount of buffering that is shared for the two streams.
// If either blocks it may eventually cause the remote
// command to block.
Stdout io.Writer
Stderr io.Writer
transport *wire.Conn
errorChan chan error
abort bool
handlesToClose []io.Closer
}
// ExitMissingError is returned if a session is torn down cleanly, but the server sends no confirmation of the exit status.
type ExitMissingError struct{}
// Error returns error message.
func (e *ExitMissingError) Error() string {
return "command exited without exit status"
}
// An ExitError reports unsuccessful completion of a remote command.
type ExitError struct {
Waitmsg
}
func (e *ExitError) Error() string {
return fmt.Sprintf("unexpected error code %d", e.exitStatus)
}
// Waitmsg stores the information about an exited remote command as reported by Wait.
type Waitmsg struct {
exitStatus int
}
// ExitStatus returns the exit status of the remote command.
func (w Waitmsg) ExitStatus() int {
return w.exitStatus
}
// NewSession opens a new Session for this client. (A session is a remote execution of a program.)
func (d *Device) NewSession() (*Session, error) {
conn, err := d.dialDevice(d.CmdTimeoutShort)
if err != nil {
return nil, fmt.Errorf("failed to create transport: %w", err)
}
return &Session{transport: conn.(*wire.Conn)}, nil
}
// Close frees resources associated with this Session, and aborts any running command.
func (s *Session) Close() error {
var err error
s.abort = true
if s.transport != nil {
err = s.transport.Close()
}
s.transport = nil
err = errors.Join(err, s.closeFiles())
return err
}
func (s *Session) closeFiles() error {
var err error
for _, f := range s.handlesToClose {
fErr := f.Close()
err = errors.Join(err, fErr)
}
s.handlesToClose = nil
return err
}
// CombinedOutput runs cmd on the remote host and returns its combined standard output and standard error.
func (s *Session) CombinedOutput(cmd string) ([]byte, error) {
if s.Stdout != nil {
return nil, errors.New("can't set Stdout and call CombinedOutput()")
}
if s.Stderr != nil {
return nil, errors.New("can't set Stdout and call CombinedOutput()")
}
var output bytes.Buffer
s.Stdout = &output
s.Stderr = &output
if err := s.Run(cmd); err != nil {
return output.Bytes(), err
}
return output.Bytes(), nil
}
// Output runs cmd on the remote host and returns its standard output.
func (s *Session) Output(cmd string) ([]byte, error) {
if s.Stdout != nil {
return nil, errors.New("can't set Stdout and call Output()")
}
var output bytes.Buffer
s.Stdout = &output
if err := s.Run(cmd); err != nil {
return output.Bytes(), err
}
return output.Bytes(), nil
}
// Run runs cmd on the remote host.
func (s *Session) Run(cmd string) error {
if err := s.Start(cmd); err != nil {
return err
}
if err := s.Wait(); err != nil {
return err
}
return nil
}
// Start runs cmd on the remote host.
func (s *Session) Start(cmd string) error {
if s.errorChan != nil {
return errors.New("Start() already called")
}
req := fmt.Sprintf("shell,v2,raw:%s", cmd)
if err := s.transport.SendMessage([]byte(req)); err != nil {
return fmt.Errorf("failed to send shell cmd: %w", err)
}
if _, err := readStatusWithTimeout(s.transport, req, CommandTimeoutShortDefault); err != nil {
s.transport.Close()
return fmt.Errorf("failed to verify shell cmd: %w", err)
}
shellTp := newShellTransport(s.transport.Conn, 0)
s.errorChan = make(chan error)
s.abort = false
// Copy stdin to remote command
if s.Stdin != nil {
go func() {
buffer := make([]byte, 1024)
for !s.abort {
n, err := s.Stdin.Read(buffer)
if err == io.EOF {
if err := shellTp.Send(shellCloseStdin, []byte{}); err != nil {
s.errorChan <- fmt.Errorf("failed to close stdin: %w", err)
}
return
}
if err != nil {
s.errorChan <- fmt.Errorf("failed to copy stdin: %w", err)
return
}
shellTp.Send(shellStdin, buffer[0:n])
}
}()
} else {
if err := shellTp.Send(shellCloseStdin, []byte{}); err != nil {
return fmt.Errorf("failed to close stdin: %w", err)
}
}
go func() {
for !s.abort {
msgType, msg, err := shellTp.Read()
if err == io.EOF {
break
}
if err != nil {
s.errorChan <- fmt.Errorf("failed to read shell msg: %w", err)
return
}
switch msgType {
case shellStdout: // stdout
if s.Stdout != nil {
if _, err := s.Stdout.Write(msg); err != nil {
s.errorChan <- fmt.Errorf("failed to write stdout: %w", err)
return
}
}
case shellStderr: // stderr
if s.Stderr != nil {
if _, err := s.Stderr.Write(msg); err != nil {
s.errorChan <- fmt.Errorf("failed to write stderr: %w", err)
return
}
}
case shellExit: // exit
exitCode := int(msg[0])
err := s.closeFiles()
if err != nil {
s.errorChan <- fmt.Errorf("failed to close files: %w", err)
}
if exitCode == 0 {
s.errorChan <- nil
} else {
s.errorChan <- &ExitError{
Waitmsg: Waitmsg{exitStatus: exitCode},
}
}
return
default:
s.errorChan <- fmt.Errorf("unexpected shell message %d: %w", msgType, err)
return
}
}
s.errorChan <- &ExitMissingError{}
}()
return nil
}
// StderrPipe returns a pipe that will be connected to the remote command's standard error when the command starts.
func (s *Session) StderrPipe() (io.Reader, error) {
if s.Stderr != nil {
return nil, errors.New("can't set Stderr and call StderrPipe()")
}
if s.errorChan != nil {
return nil, errors.New("StderrPipe called after Start()")
}
pr, pw, err := os.Pipe()
if err != nil {
return nil, err
}
s.Stderr = pw
s.handlesToClose = append(s.handlesToClose, pw)
return pr, nil
}
// StdinPipe returns a pipe that will be connected to the remote command's standard input when the command starts.
func (s *Session) StdinPipe() (io.WriteCloser, error) {
if s.Stdin != nil {
return nil, errors.New("can't set Stdin and call StdinPipe()")
}
if s.errorChan != nil {
return nil, errors.New("StdinPipe called after Start()")
}
pr, pw, err := os.Pipe()
if err != nil {
return nil, err
}
s.Stdin = pr
s.handlesToClose = append(s.handlesToClose, pr)
return pw, nil
}
// StdoutPipe returns a pipe that will be connected to the remote command's standard output when the command starts.
func (s *Session) StdoutPipe() (io.Reader, error) {
if s.Stdout != nil {
return nil, errors.New("can't set Stdout and call StdoutPipe()")
}
if s.errorChan != nil {
return nil, errors.New("StdoutPipe called after Start()")
}
pr, pw, err := os.Pipe()
if err != nil {
return nil, err
}
s.Stdout = pw
s.handlesToClose = append(s.handlesToClose, pw)
return pr, nil
}
// Wait waits for the remote command to exit.
func (s *Session) Wait() error {
if s.errorChan == nil {
return errors.New("Wait() called before Start()")
}
if s.abort {
return errors.New("Wait() called twice or after Close()")
}
backgroundErr := <-s.errorChan
if err := s.Close(); err != nil {
return errors.Join(backgroundErr, err)
}
return backgroundErr
}