forked from jumpserver/koko
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal_command.go
More file actions
90 lines (77 loc) · 1.71 KB
/
local_command.go
File metadata and controls
90 lines (77 loc) · 1.71 KB
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
package localcommand
import (
"fmt"
"os"
"os/exec"
"syscall"
"github.com/creack/pty"
)
type LocalCommand struct {
command string
argv []string
env []string
cmdCredential *syscall.Credential
cmd *exec.Cmd
ptyFd *os.File
ptyClosed chan struct{}
ptyWin *pty.Winsize
}
func New(command string, argv []string, options ...Option) (*LocalCommand, error) {
ptyClosed := make(chan struct{})
lcmd := &LocalCommand{
command: command,
argv: argv,
ptyClosed: ptyClosed,
}
for _, option := range options {
option(lcmd)
}
cmd := exec.Command(command, argv...)
if lcmd.env != nil {
cmd.Env = lcmd.env
}
if lcmd.cmdCredential != nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.Credential = lcmd.cmdCredential
}
ptyFd, err := pty.StartWithSize(cmd, lcmd.ptyWin)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
lcmd.cmd = cmd
lcmd.ptyFd = ptyFd
// When the process is closed by the user,
// close pty so that Read() on the pty breaks with an EOF.
go func() {
defer func() {
lcmd.ptyFd.Close()
close(lcmd.ptyClosed)
}()
_ = lcmd.cmd.Wait()
}()
return lcmd, nil
}
func (lcmd *LocalCommand) Read(p []byte) (n int, err error) {
return lcmd.ptyFd.Read(p)
}
func (lcmd *LocalCommand) Write(p []byte) (n int, err error) {
return lcmd.ptyFd.Write(p)
}
func (lcmd *LocalCommand) Close() error {
select {
case <-lcmd.ptyClosed:
return nil
default:
if lcmd.cmd != nil && lcmd.cmd.Process != nil {
return lcmd.cmd.Process.Signal(syscall.SIGKILL)
}
}
return nil
}
func (lcmd *LocalCommand) SetWinSize(width int, height int) error {
win := pty.Winsize{
Rows: uint16(height),
Cols: uint16(width),
}
return pty.Setsize(lcmd.ptyFd, &win)
}