/
telnet.go
94 lines (84 loc) · 1.77 KB
/
telnet.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
82
83
84
85
86
87
88
89
90
91
92
93
94
package pufferpanel
import (
"errors"
"github.com/pufferpanel/pufferpanel/v3/logging"
"github.com/spf13/cast"
"io"
"net"
"time"
)
type TelnetConnection struct {
io.WriteCloser
IP string
Port string
Password string
Reconnect bool
connection *net.TCPConn
ready bool
}
func (tc *TelnetConnection) Write(p []byte) (n int, err error) {
if !tc.ready {
time.Sleep(1 * time.Second)
if !tc.ready {
return 0, errors.New("telnet not available")
}
}
if tc.connection != nil {
return tc.connection.Write(p)
}
return 0, errors.New("telnet not available")
}
func (tc *TelnetConnection) Start() {
tc.Reconnect = true
if tc.IP == "" {
tc.IP = "127.0.0.1"
}
go tc.reconnector()
}
func (tc *TelnetConnection) Close() error {
tc.Reconnect = false
if tc.connection == nil {
return nil
}
return tc.connection.Close()
}
func (tc *TelnetConnection) reconnector() {
init := true
for tc.Reconnect {
tc.ready = false
if !init {
time.Sleep(5 * time.Second)
} else {
init = false
}
ipAddr := &net.TCPAddr{
IP: net.ParseIP(tc.IP),
Port: cast.ToInt(tc.Port),
}
conn, err := net.DialTCP("tcp", nil, ipAddr)
if err != nil {
logging.Debug.Printf("Error waiting for TCP TELNET socket: %s", err.Error())
continue
}
_ = conn.SetKeepAlive(true)
//wait a second for the prompt for passwords/other delays
time.Sleep(1 * time.Second)
if tc.Password != "" {
_, err = conn.Write([]byte(tc.Password + "\n"))
if err != nil {
logging.Debug.Printf("Error sending password for TCP TELNET socket: %s", err.Error())
continue
}
}
tc.connection = conn
tc.ready = true
listening := true
for listening {
buf := make([]byte, 1024)
_, err = conn.Read(buf)
if err != nil {
listening = false
}
}
}
}