forked from k0sproject/rig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signals.go
62 lines (53 loc) · 1.27 KB
/
signals.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
//go:build !windows
// +build !windows
package rig
import (
"encoding/binary"
"fmt"
"io"
"os"
"os/signal"
"syscall"
ssh "golang.org/x/crypto/ssh"
"golang.org/x/term"
)
// captureSignals intercepts interrupt / resize signals and sends them over to the writer
func captureSignals(stdin io.Writer, session *ssh.Session) func() {
stopCh := make(chan struct{})
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTSTP, syscall.SIGWINCH)
go func() {
for sig := range sigCh {
switch sig {
case os.Interrupt:
fmt.Fprintf(stdin, "\x03")
case syscall.SIGTSTP:
fmt.Fprintf(stdin, "\x1a")
case syscall.SIGWINCH:
_, err := session.SendRequest("window-change", false, termSizeWNCH())
if err != nil {
println("failed to relay window-change event: " + err.Error())
}
}
}
}()
go func() {
<-stopCh
signal.Stop(sigCh)
close(sigCh)
}()
return func() { close(stopCh) }
}
func termSizeWNCH() []byte {
size := make([]byte, 16)
fd := int(os.Stdin.Fd())
rows, cols, err := term.GetSize(fd)
if err != nil {
binary.BigEndian.PutUint32(size, 40)
binary.BigEndian.PutUint32(size[4:], 80)
} else {
binary.BigEndian.PutUint32(size, uint32(cols))
binary.BigEndian.PutUint32(size[4:], uint32(rows))
}
return size
}