-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
pty_x11.go
256 lines (237 loc) · 5.88 KB
/
pty_x11.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
//go:build unix && !windows && !android && !darwin && !js
package pty
import (
"fmt"
"log"
"os"
"os/exec"
"runtime"
"strings"
"time"
"github.com/jezek/xgb/xproto"
"github.com/shirou/gopsutil/process"
"github.com/srlehn/termimg/internal/environ"
"github.com/srlehn/termimg/internal/errors"
"github.com/srlehn/termimg/wm"
"github.com/srlehn/termimg/wm/wmimpl"
)
func ptyRun(termCmd []string, f PTYRunFunc) (errRet error) {
// TODO fix domterm (orphans)
if len(termCmd) == 0 {
return errors.New(`no command`)
}
cmd := exec.Command(termCmd[0], termCmd[1:]...)
// cmd.Stdout = os.Stdout
// cmd.Stderr = os.Stderr
cmd.Env = []string{
`DISPLAY=` + os.Getenv(`DISPLAY`),
`XAUTHORITY=` + os.Getenv(`XAUTHORITY`),
`SHELL=` + os.Getenv(`SHELL`),
`HOME=` + os.Getenv(`HOME`), // required by mlterm
`PATH=` + os.Getenv(`PATH`), // required by domterm
}
if err := cmd.Start(); err != nil {
return err
}
if cmd.Process == nil {
return errors.New(`nil process`)
}
defer func() {
// TODO multiple domterm instances
if err := cmd.Process.Kill(); err != nil && errRet == nil {
errRet = err
}
}()
proc, err := process.NewProcess(int32(cmd.Process.Pid))
if err != nil {
return err
}
wm.SetImpl(wmimpl.Impl())
conn, err := wm.NewConn(environ.EnvToProperties(cmd.Env))
if err != nil {
return err
}
windowsStart, err := conn.Windows()
if err != nil {
return err
}
mapWindowsStart := make(map[xproto.Window]wm.Window)
for _, window := range windowsStart {
if window == nil {
continue
}
mapWindowsStart[xproto.Window(window.WindowID())] = window
}
var (
windowsNew []wm.Window
newWindowAppeared bool
timeFirstNewWindow time.Time
tickDurationCheckProcChildren = 25 * time.Millisecond
tickDurationCheckNewWindows = 330 * time.Millisecond
waitingTimeAfterFirstNewWindow = 3000 * time.Millisecond
timeoutWaitingShell = 8000 * time.Millisecond
)
// wait for the start of the shell of the pseudo terminal
ticker := time.NewTicker(tickDurationCheckProcChildren)
defer ticker.Stop()
tickerWindows := time.NewTicker(tickDurationCheckNewWindows)
defer tickerWindows.Stop()
var children []*process.Process
var procSh *process.Process
waitForShell:
for {
select {
case <-ticker.C:
children, _ = proc.Children()
// printProcWithChildren(proc)
if len(children) == 0 {
if newWindowAppeared &&
time.Since(timeFirstNewWindow) > waitingTimeAfterFirstNewWindow {
// probably orphaned process
break waitForShell
}
} else {
ps, err := findShellProc(proc)
if err != nil {
return err
}
if ps != nil {
procSh = ps
break waitForShell
}
}
case <-tickerWindows.C:
windows, err := conn.Windows()
if err != nil {
return err
}
for _, window := range windows {
if window == nil {
continue
}
if _, exists := mapWindowsStart[xproto.Window(window.WindowID())]; exists {
continue
}
if len(windowsNew) == 0 {
newWindowAppeared = true
timeFirstNewWindow = time.Now()
}
windowsNew = append(windowsNew, window)
mapWindowsStart[xproto.Window(window.WindowID())] = window
}
case <-time.After(timeoutWaitingShell):
return errors.New(`timeout while waiting for shell`)
}
}
if procSh == nil {
// process probably orphaned after double fork, etc
// fallback to window change detection
if len(windowsNew) == 0 {
return errors.New(`unable to detect spawned window`)
}
for _, w := range windowsNew {
pr, _ := process.NewProcess(int32(w.WindowPID()))
printProc(pr)
}
window := windowsNew[0]
procWin, err := process.NewProcess(int32(window.WindowPID()))
if err != nil {
return err
}
ps, err := findShellProc(procWin)
if err != nil {
return err
}
if ps == nil {
return errors.New(`found no shell contained in newly appeared window`)
}
procSh = ps
}
// printProc(procSh)
pty, err := procSh.Terminal()
if err != nil {
return err
}
if len(pty) == 0 {
return errors.New(`found no tty for assumed shell process`)
}
ptyStr := `/dev/` + strings.TrimPrefix(string(pty), `/`) // TODO
// execute passed function on the pty of the pseudo terminal.
if err := f(ptyStr, uint(cmd.Process.Pid)); err != nil {
errRet = err
}
return
}
func findShellProc(pr *process.Process) (*process.Process, error) {
if pr == nil {
return nil, errors.NilParam()
}
children, err := pr.Children()
if err != nil {
return nil, err
}
prTerm, err := pr.Terminal()
if err != nil {
return nil, err
}
sh := os.Getenv(`SHELL`)
for _, child := range children {
if isRunning, err := child.IsRunning(); err != nil {
continue
} else if !isRunning {
continue
}
exe, err := child.Exe()
if err != nil {
// defunct?
continue
}
childTerm, err := child.Terminal()
if err != nil {
return nil, err
}
if len(childTerm) > 0 && childTerm != prTerm {
return child, nil
}
cmdAbs, err := exec.LookPath(exe)
if err != nil {
return nil, err
}
// might fail if containerised, etc
if cmdAbs == sh {
return child, nil
}
}
return nil, nil
}
func printProc(pr *process.Process) {
if pr == nil {
return
}
_, file, line, _ := runtime.Caller(1)
name, _ := pr.Name()
term, _ := pr.Terminal()
ppid, _ := pr.Ppid()
fmt.Printf("%s:%d: pid:%d ppid:%d %q %q\n", file, line, pr.Pid, ppid, name, term)
}
var _ = printProcWithChildren
func printProcWithChildren(pr *process.Process) {
if pr == nil {
return
}
_, file, line, _ := runtime.Caller(1)
name, _ := pr.Name()
term, _ := pr.Terminal()
ppid, _ := pr.Ppid()
fmt.Printf("%s:%d: pid:%d ppid:%d %q %q\n", file, line, pr.Pid, ppid, name, term)
children, err := pr.Children()
if err != nil {
log.Println(err)
}
for _, child := range children {
name, _ := child.Name()
term, _ := child.Terminal()
ppid, _ := child.Ppid()
fmt.Printf(" %s:%d: pid:%d ppid:%d %q %q\n", file, line, child.Pid, ppid, name, term)
}
}