/
termios.go
81 lines (69 loc) · 2.11 KB
/
termios.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
//+build linux
/*
Maddy Mail Server - Composable all-in-one email server.
Copyright © 2019-2020 Max Mazurov <fox.cpp@disroot.org>, Maddy Mail Server contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package clitools
// Copied from github.com/foxcpp/ttyprompt
// Commit 087a574, terminal/termios.go
import (
"errors"
"os"
"syscall"
"unsafe"
)
type Termios struct {
Iflag uint32
Oflag uint32
Cflag uint32
Lflag uint32
Cc [20]byte
Ispeed uint32
Ospeed uint32
}
/*
TurnOnRawIO sets flags suitable for raw I/O (no echo, per-character input, etc)
and returns original flags.
*/
func TurnOnRawIO(tty *os.File) (orig Termios, err error) {
termios, err := TcGetAttr(tty.Fd())
if err != nil {
return Termios{}, errors.New("TurnOnRawIO: failed to get flags: " + err.Error())
}
termiosOrig := *termios
termios.Lflag &^= syscall.ECHO
termios.Lflag &^= syscall.ICANON
termios.Iflag &^= syscall.IXON
termios.Lflag &^= syscall.ISIG
termios.Iflag |= syscall.IUTF8
err = TcSetAttr(tty.Fd(), termios)
if err != nil {
return Termios{}, errors.New("TurnOnRawIO: flags to set flags: " + err.Error())
}
return termiosOrig, nil
}
func TcSetAttr(fd uintptr, termios *Termios) error {
_, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, syscall.TCSETS, uintptr(unsafe.Pointer(termios)))
if err != 0 {
return err
}
return nil
}
func TcGetAttr(fd uintptr) (*Termios, error) {
termios := &Termios{}
_, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, syscall.TCGETS, uintptr(unsafe.Pointer(termios)))
if err != 0 {
return nil, err
}
return termios, nil
}