forked from dolfly/termux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
111 lines (87 loc) · 2.26 KB
/
exec.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
package termux
import (
"context"
"io"
"sync"
"time"
"github.com/stunnel/termux/internal/api"
_io "github.com/stunnel/termux/internal/io"
)
// GlobalTimeout The global timeout to non-persistent and non-time-consuming operations
var GlobalTimeout = 15 * time.Second
func tryCloseReader(c io.Reader) {
if r, ok := c.(_io.CloseReader); ok {
err := r.CloseRead()
if err != nil {
return
}
}
}
func tryCloseWriter(c io.Writer) {
if r, ok := c.(_io.CloseWriter); ok {
err := r.CloseWrite()
if err != nil {
return
}
}
}
func pipe(ctx context.Context, ai io.Reader, ao io.Writer, bi io.Reader, bo io.Writer) (err error) {
wg := sync.WaitGroup{}
if bi != nil && ao != nil {
wg.Add(1)
go func() {
if t, ok := ctx.Deadline(); ok {
_, err = _io.CopyDeadline(t, ao, bi)
} else {
_, err = io.Copy(ao, bi)
}
tryCloseReader(bi)
tryCloseWriter(ao)
wg.Done()
}()
}
if ai != nil && bo != nil {
wg.Add(1)
go func() {
if t, ok := ctx.Deadline(); ok {
_, err = _io.CopyDeadline(t, bo, ai)
} else {
_, err = io.Copy(bo, ai)
}
tryCloseReader(ai)
tryCloseWriter(bo)
wg.Done()
}()
}
wg.Wait()
return
}
func execAction(method string, stdin io.Reader, stdout io.Writer, action string, args map[string]interface{}) error {
ctx, cancel := context.WithTimeout(context.Background(), GlobalTimeout)
defer cancel()
return execActionContext(ctx, stdin, stdout, method, action, args)
}
func execActionContext(ctx context.Context, stdin io.Reader, stdout io.Writer, method string, action string, args map[string]interface{}) error {
call := api.Call{
Method: method,
Action: action,
Args: args,
}
call.Call(ctx)
return pipe(ctx, &call, &call, stdin, stdout)
}
func exec(stdin io.Reader, stdout io.Writer, method string, args map[string]interface{}, data string) error {
ctx, cancel := context.WithTimeout(context.Background(), GlobalTimeout)
defer cancel()
return execContext(ctx, stdin, stdout, method, args, data)
}
func execContext(ctx context.Context, stdin io.Reader, stdout io.Writer, method string, args map[string]interface{}, data string) error {
call := api.Call{
Method: method,
Args: args,
Data: data,
}
call.Call(ctx)
defer call.Close()
return pipe(ctx, &call, &call, stdin, stdout)
}