-
Notifications
You must be signed in to change notification settings - Fork 0
/
port.go
69 lines (61 loc) · 1.33 KB
/
port.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
package rcom
import (
"os"
"github.com/creack/pty"
"golang.org/x/crypto/ssh/terminal"
)
type port struct {
pty *os.File
tty *os.File
linkName string
}
func (p *port) Read(buf []byte) (n int, err error) {
return p.pty.Read(buf)
}
func (p *port) Write(buf []byte) (n int, err error) {
return p.pty.Write(buf)
}
func newPort(device string) (p *port, err error) {
p = &port{}
if _, err = os.Stat(device); err != nil {
if os.IsNotExist(err) {
err = nil
p.pty, p.tty, err = pty.Open()
_, err = terminal.MakeRaw(int(p.pty.Fd()))
if err != nil {
Logger.Printf("Failed to activate RAW mode on pty: %v", err)
return nil, err
}
if err == nil {
err = os.Symlink(p.tty.Name(), device)
if err == nil {
p.linkName = device
} else {
Logger.Printf("Failed to link %s to %s", p.tty.Name(), device)
}
} else {
Logger.Printf("Failed to open pty")
}
}
} else {
p.pty, err = os.OpenFile(device, os.O_RDWR, 0)
}
return p, err
}
func (p *port) ClosePTY() error {
if p.linkName != "" {
Logger.Printf("Removing symlink %s", p.linkName)
os.Remove(p.linkName)
}
return p.pty.Close()
}
func (p *port) CloseTTY() error {
if p.linkName != "" {
Logger.Printf("Removing symlink %s", p.linkName)
os.Remove(p.linkName)
}
if p.tty != nil {
return p.tty.Close()
}
return nil
}