/
rcon.go
85 lines (76 loc) · 1.5 KB
/
rcon.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
package pufferpanel
import (
"errors"
"fmt"
"github.com/gorcon/rcon"
"github.com/pufferpanel/pufferpanel/v3/logging"
"io"
"time"
)
type RCONConnection struct {
io.WriteCloser
IP string
Port string
Password string
Reconnect bool
connection *rcon.Conn
ready bool
closer chan error
}
func (tc *RCONConnection) Write(p []byte) (n int, err error) {
if !tc.ready {
time.Sleep(1 * time.Second)
if !tc.ready {
return 0, errors.New("rcon not available")
}
}
if tc.connection != nil {
var res string
res, err = tc.connection.Execute(string(p))
if err != nil {
tc.closer <- err
}
logging.Debug.Printf("RCON Response: %s\n", res)
return len(p), err
}
return 0, errors.New("rcon not available")
}
func (tc *RCONConnection) Start() {
tc.Reconnect = true
if tc.IP == "" {
tc.IP = "127.0.0.1"
}
go tc.reconnector()
}
func (tc *RCONConnection) Close() error {
tc.Reconnect = false
if tc.connection == nil {
return nil
}
return tc.connection.Close()
}
func (tc *RCONConnection) reconnector() {
init := true
for tc.Reconnect {
tc.recon(init)
if init {
init = false
}
}
}
func (tc *RCONConnection) recon(init bool) {
tc.ready = false
if !init {
time.Sleep(5 * time.Second)
}
var err error
tc.connection, err = rcon.Dial(fmt.Sprintf("%s:%s", tc.IP, tc.Port), tc.Password)
if err != nil {
logging.Debug.Printf("Error connecting to RCON: %s", err.Error())
return
}
tc.ready = true
defer tc.connection.Close()
<-tc.closer
tc.ready = false
}