-
Notifications
You must be signed in to change notification settings - Fork 1
/
shell.go
123 lines (107 loc) · 2.26 KB
/
shell.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
package dadb
import (
"encoding/binary"
"fmt"
)
const IdStdin byte = 0
const IdStdout byte = 1
const IdStderr byte = 2
const IdExit byte = 3
const IdCloseStdin byte = 3
type ShellPacket struct {
Id byte
Payload []byte
}
type ShellResponse struct {
Output string
ErrorOutput string
ExitCode int
}
type shellPacketHeader struct {
Id byte
Len uint32
}
type ShellStream struct {
s Stream
}
func Shell(d Dadb, command string) (ShellResponse, error) {
stream, err := OpenShell(d, command)
if err != nil {
return ShellResponse{}, err
}
//goland:noinspection GoUnhandledErrorResult
defer stream.Close()
if err != nil {
return ShellResponse{}, err
}
return stream.ReadAll()
}
func OpenShell(d Dadb, command string) (ShellStream, error) {
stream, err := d.Open(fmt.Sprintf("shell,v2,raw:%s", command))
if err != nil {
return ShellStream{}, err
}
return ShellStream{s: stream}, nil
}
func (s ShellStream) ReadAll() (ShellResponse, error) {
output := make([]byte, 0)
errorOutput := make([]byte, 0)
for {
packet, err := s.Read()
if err != nil {
return ShellResponse{}, err
}
switch packet.Id {
case IdExit:
return ShellResponse{
Output: string(output),
ErrorOutput: string(errorOutput),
ExitCode: int(packet.Payload[0]),
}, nil
case IdStdout:
output = append(output, packet.Payload...)
case IdStderr:
errorOutput = append(errorOutput, packet.Payload...)
}
}
}
func (s ShellStream) Read() (ShellPacket, error) {
header := shellPacketHeader{}
err := binary.Read(s.s, binary.LittleEndian, &header)
if err != nil {
return ShellPacket{}, err
}
payload := make([]byte, header.Len)
_, err = s.s.Read(payload)
if err != nil {
return ShellPacket{}, err
}
return ShellPacket{
Id: header.Id,
Payload: payload,
}, nil
}
func (s ShellStream) WriteString(string string) error {
return s.Write(IdStdin, []byte(string))
}
func (s ShellStream) Write(id byte, payload []byte) error {
err := binary.Write(s.s, binary.LittleEndian, shellPacketHeader{
Id: id,
Len: uint32(len(payload)),
})
if err != nil {
return err
}
_, err = s.s.Write(payload)
if err != nil {
return err
}
return nil
}
func (s ShellStream) Close() error {
err := s.s.Close()
if err != nil {
return err
}
return nil
}