forked from HimbeerserverDE/mt-multiserver-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelnet.go
More file actions
107 lines (86 loc) · 1.98 KB
/
telnet.go
File metadata and controls
107 lines (86 loc) · 1.98 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package proxy
import (
"bufio"
"errors"
"fmt"
"io"
"log"
"math"
"net"
)
// A TelnetWriter can be used to print something at the other end
// of a telnet connection. It implements the io.Writer interface.
type TelnetWriter struct {
conn net.Conn
}
// Write writes its parameter to the telnet connection.
// A trailing newline is always appended.
// It returns the number of bytes written and an error.
func (tw *TelnetWriter) Write(p []byte) (n int, err error) {
return tw.conn.Write(append(p, '\n'))
}
var telnetCh = make(chan struct{})
func telnetServer() error {
ln, err := net.Listen("tcp", Conf().TelnetAddr)
if err != nil {
return err
}
defer ln.Close()
log.Println("listen telnet", ln.Addr())
for {
select {
case <-telnetCh:
return nil
default:
conn, err := ln.Accept()
if err != nil {
log.Print(err)
continue
}
go handleTelnet(conn)
}
}
}
func handleTelnet(conn net.Conn) {
tlog := func(dir string, v ...interface{}) {
prefix := fmt.Sprintf("[telnet %s] ", conn.RemoteAddr())
l := log.New(logWriter, prefix, log.LstdFlags|log.Lmsgprefix)
l.Println(append([]interface{}{dir}, v...)...)
}
tlog("<->", "connect")
defer tlog("<->", "disconnect")
defer conn.Close()
readString := func(delim byte) (string, error) {
s, err := bufio.NewReader(conn).ReadString(delim)
if err != nil || len(s) == 0 {
return s, err
}
i := int(math.Max(float64(len(s)-1), 1))
s = s[:i]
return s, nil
}
writeString := func(s string) (n int, err error) {
return io.WriteString(conn, s)
}
writeString("mt-multiserver-proxy console\n")
writeString("Type \\quit or \\q to disconnect.\n")
for {
writeString(Conf().CmdPrefix)
s, err := readString('\n')
if err != nil {
if errors.Is(err, io.EOF) {
return
}
log.Print(err)
continue
}
tlog("->", "command", s)
if s == "\\quit" || s == "\\q" {
return
}
result := onTelnetMsg(tlog, &TelnetWriter{conn: conn}, s)
if result != "\n" {
writeString(result)
}
}
}