mt-multiserver-proxy/telnet.go

108 lines
2.0 KiB
Go
Raw Normal View History

2021-09-12 03:03:20 -07:00
package proxy
import (
"bufio"
"errors"
2021-09-13 03:14:11 -07:00
"fmt"
2021-09-12 03:03:20 -07:00
"io"
"log"
2021-09-12 04:38:40 -07:00
"math"
2021-09-12 03:03:20 -07:00
"net"
)
2021-09-12 04:38:40 -07:00
// 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'))
}
2021-09-12 03:03:20 -07:00
var telnetCh = make(chan struct{})
func telnetServer() error {
ln, err := net.Listen("tcp", Conf().TelnetAddr)
if err != nil {
return err
}
defer ln.Close()
2021-09-13 03:14:11 -07:00
log.Println("listen telnet", ln.Addr())
2021-09-12 04:38:40 -07:00
2021-09-12 03:03:20 -07:00
for {
select {
case <-telnetCh:
return nil
default:
conn, err := ln.Accept()
if err != nil {
2021-09-13 03:14:11 -07:00
log.Print(err)
2021-09-12 03:03:20 -07:00
continue
}
go handleTelnet(conn)
}
}
}
func handleTelnet(conn net.Conn) {
2021-09-12 04:38:40 -07:00
tlog := func(dir string, v ...interface{}) {
2021-09-13 03:14:11 -07:00
prefix := fmt.Sprintf("[telnet %s] ", conn.RemoteAddr())
l := log.New(logWriter, prefix, log.LstdFlags|log.Lmsgprefix)
l.Println(append([]interface{}{dir}, v...)...)
2021-09-12 04:38:40 -07:00
}
2021-09-13 07:12:16 -07:00
tlog("<->", "connect")
2021-09-12 04:38:40 -07:00
2021-09-13 07:12:16 -07:00
defer tlog("<->", "disconnect")
2021-09-12 03:03:20 -07:00
defer conn.Close()
2021-09-12 04:38:40 -07:00
readString := func(delim byte) (string, error) {
s, err := bufio.NewReader(conn).ReadString(delim)
if err != nil || len(s) == 0 {
2022-04-21 10:59:40 -07:00
return s, err
}
i := int(math.Max(float64(len(s)-1), 1))
2021-09-12 04:38:40 -07:00
s = s[:i]
return s, nil
2021-09-12 04:38:40 -07:00
}
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")
2021-09-12 03:03:20 -07:00
for {
2021-09-12 04:38:40 -07:00
writeString(Conf().CmdPrefix)
2021-09-12 03:03:20 -07:00
2021-09-12 04:38:40 -07:00
s, err := readString('\n')
2021-09-12 03:03:20 -07:00
if err != nil {
if errors.Is(err, io.EOF) {
return
}
2021-09-13 03:14:11 -07:00
log.Print(err)
2021-09-12 03:03:20 -07:00
continue
}
2021-09-12 04:38:40 -07:00
2021-09-13 07:12:16 -07:00
tlog("->", "command", s)
2021-09-12 04:38:40 -07:00
if s == "\\quit" || s == "\\q" {
return
}
result := onTelnetMsg(tlog, &TelnetWriter{conn: conn}, s)
2021-09-12 05:53:08 -07:00
if result != "\n" {
2021-09-12 04:38:40 -07:00
writeString(result)
}
2021-09-12 03:03:20 -07:00
}
}