forked from openatx/atx-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
339 lines (306 loc) · 7.16 KB
/
utils.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package main
import (
"bufio"
"bytes"
"crypto/rand"
"encoding/hex"
"fmt"
"image"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/codeskyblue/goreq"
"github.com/codeskyblue/procfs"
shellquote "github.com/kballard/go-shellquote"
"github.com/openatx/androidutils"
"github.com/pkg/errors"
"github.com/shogo82148/androidbinary/apk"
)
// TempFileName generates a temporary filename for use in testing or whatever
func TempFileName(dir, suffix string) string {
randBytes := make([]byte, 16)
rand.Read(randBytes)
return filepath.Join(dir, hex.EncodeToString(randBytes)+suffix)
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// Command add timeout support for os/exec
type Command struct {
Args []string
Timeout time.Duration
Shell bool
ShellQuote bool
Stdout io.Writer
Stderr io.Writer
}
func (c *Command) shellPath() string {
sh := os.Getenv("SHELL")
if sh == "" {
sh, err := exec.LookPath("sh")
if err == nil {
return sh
}
sh = "/system/bin/sh"
}
return sh
}
func (c *Command) computedArgs() (name string, args []string) {
if c.Shell {
var cmdline string
if c.ShellQuote {
cmdline = shellquote.Join(c.Args...)
} else {
cmdline = strings.Join(c.Args, " ") // simple, but works well with ">". eg Args("echo", "hello", ">output.txt")
}
args = append(args, "-c", cmdline)
return c.shellPath(), args
}
return c.Args[0], c.Args[1:]
}
func (c Command) newCommand() *exec.Cmd {
name, args := c.computedArgs()
cmd := exec.Command(name, args...)
if c.Stdout != nil {
cmd.Stdout = c.Stdout
}
if c.Stderr != nil {
cmd.Stderr = c.Stderr
}
return cmd
}
func (c Command) Run() error {
cmd := c.newCommand()
if c.Timeout > 0 {
timer := time.AfterFunc(c.Timeout, func() {
if cmd.Process != nil {
cmd.Process.Kill()
}
})
defer timer.Stop()
}
return cmd.Run()
}
func (c Command) Output() (output []byte, err error) {
var b bytes.Buffer
c.Stdout = &b
c.Stderr = nil
err = c.Run()
return b.Bytes(), err
}
func (c Command) CombinedOutput() (output []byte, err error) {
var b bytes.Buffer
c.Stdout = &b
c.Stderr = &b
err = c.Run()
return b.Bytes(), err
}
func (c Command) CombinedOutputString() (output string, err error) {
bytesOutput, err := c.CombinedOutput()
return string(bytesOutput), err
}
// need add timeout
func runShell(args ...string) (output []byte, err error) {
return Command{
Args: args,
Shell: true,
ShellQuote: false,
Timeout: 10 * time.Minute,
}.CombinedOutput()
}
func runShellOutput(args ...string) (output []byte, err error) {
return Command{
Args: args,
Shell: true,
ShellQuote: false,
Timeout: 10 * time.Minute,
}.Output()
}
func runShellTimeout(duration time.Duration, args ...string) (output []byte, err error) {
return Command{
Args: args,
Shell: true,
Timeout: duration,
}.CombinedOutput()
}
type fakeWriter struct {
writeFunc func([]byte) (int, error)
Err chan error
}
func (w *fakeWriter) Write(data []byte) (int, error) {
n, err := w.writeFunc(data)
if err != nil {
select {
case w.Err <- err:
default:
}
}
return n, err
}
func newFakeWriter(f func([]byte) (int, error)) *fakeWriter {
return &fakeWriter{
writeFunc: f,
Err: make(chan error, 1),
}
}
// pidof
func pidOf(packageName string) (pid int, err error) {
fs, err := procfs.NewFS(procfs.DefaultMountPoint)
if err != nil {
return
}
procs, err := fs.AllProcs()
if err != nil {
return
}
for _, proc := range procs {
cmdline, _ := proc.CmdLine()
if len(cmdline) == 1 && cmdline[0] == packageName {
return proc.PID, nil
}
}
return 0, errors.New("package not found")
}
type PackageInfo struct {
MainActivity string `json:"mainActivity"`
Label string `json:"label"`
VersionName string `json:"versionName"`
VersionCode int `json:"versionCode"`
Size int64 `json:"size"`
Icon image.Image `json:"-"`
}
func pkgInfo(packageName string) (info PackageInfo, err error) {
outbyte, err := runShell("pm", "path", packageName)
output := strings.TrimSpace(string(outbyte))
if !strings.HasPrefix(output, "package:") {
err = errors.New("package " + strconv.Quote(packageName) + " not found")
return
}
apkpath := output[len("package:"):]
finfo, err := os.Stat(apkpath)
if err != nil {
return
}
info.Size = finfo.Size()
pkg, err := apk.OpenFile(apkpath)
if err != nil {
err = errors.Wrap(err, packageName)
return
}
info.Label, _ = pkg.Label(nil)
info.MainActivity, _ = pkg.MainActivity()
info.Icon, _ = pkg.Icon(nil)
info.VersionCode = pkg.Manifest().VersionCode
info.VersionName = pkg.Manifest().VersionName
return
}
func procWalk(fn func(p procfs.Proc)) error {
fs, err := procfs.NewFS(procfs.DefaultMountPoint)
if err != nil {
return err
}
procs, err := fs.AllProcs()
for _, proc := range procs {
fn(proc)
}
return nil
}
// get main activity with packageName
func mainActivityOf(packageName string) (activity string, err error) {
output, err := runShellOutput("pm", "list", "packages", "-f", packageName)
if err != nil {
log.Println("pm list err:", err)
return
}
matches := regexp.MustCompile(`package:(.+)=([.\w]+)`).FindAllStringSubmatch(string(output), -1)
for _, match := range matches {
if match[2] != packageName {
continue
}
pkg, err := apk.OpenFile(match[1])
if err != nil {
return "", err
}
return pkg.MainActivity()
}
return "", errors.New("package not found")
}
// download minicap or minitouch apk, etc...
func httpDownload(path string, urlStr string, perms os.FileMode) (written int64, err error) {
resp, err := goreq.Request{
Uri: urlStr,
RedirectHeaders: true,
MaxRedirects: 10,
}.Do()
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("http download <%s> status %v", urlStr, resp.Status)
return
}
file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, perms)
if err != nil {
return
}
defer file.Close()
written, err = io.Copy(file, resp.Body)
log.Println("http download:", written)
return
}
func hijackHTTPRequest(w http.ResponseWriter) (conn net.Conn, err error) {
hj, ok := w.(http.Hijacker)
if !ok {
err = errors.New("webserver don't support hijacking")
return
}
hjconn, bufrw, err := hj.Hijack()
if err != nil {
return nil, err
}
conn = newHijackReadWriteCloser(hjconn.(*net.TCPConn), bufrw)
return
}
type hijactRW struct {
*net.TCPConn
bufrw *bufio.ReadWriter
}
func (this *hijactRW) Write(data []byte) (int, error) {
nn, err := this.bufrw.Write(data)
this.bufrw.Flush()
return nn, err
}
func (this *hijactRW) Read(p []byte) (int, error) {
return this.bufrw.Read(p)
}
func newHijackReadWriteCloser(conn *net.TCPConn, bufrw *bufio.ReadWriter) net.Conn {
return &hijactRW{
bufrw: bufrw,
TCPConn: conn,
}
}
func getCachedProperty(name string) string {
return androidutils.CachedProperty(name)
}
func getProperty(name string) string {
return androidutils.Property(name)
}
func copyToFile(rd io.Reader, dst string) error {
fd, err := os.Create(dst)
if err != nil {
return err
}
defer fd.Close()
_, err = io.Copy(fd, rd)
return err
}