-
Notifications
You must be signed in to change notification settings - Fork 2
/
tf2RconConnection.go
353 lines (294 loc) · 7.89 KB
/
tf2RconConnection.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package TF2RconWrapper
import (
"errors"
"fmt"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/TF2Stadium/rcon"
)
// TF2RconConnection represents a rcon connection to a TF2 server
type TF2RconConnection struct {
rcLock sync.RWMutex
rc *rcon.RemoteConsole
host string
password string
reconnecting *int32
}
var (
ErrUnknownCommand = errors.New("Unknown Command")
CVarValueRegex = regexp.MustCompile(`^"(?:.*?)" = "(.*?)"`)
//# userid name uniqueid connected ping loss state adr
rePlayerInfo = regexp.MustCompile(`^#\s+(\d+)\s+"(.+)"\s+(\[U:1:\d+\])\s+\d+:\d+\s+\d+\s+\d+\s+\w+\s+(\d+\.+\d+\.\d+\.\d+:\d+)`)
)
type UnknownCommand string
func (c UnknownCommand) Error() string {
return "unknown command: " + string(c)
}
func (c *TF2RconConnection) QueryNoResp(req string) error {
c.rcLock.RLock()
defer c.rcLock.RUnlock()
if c.rc == nil {
return errors.New("RCON connection is nil")
}
_, err := c.rc.Write(req)
return err
}
// Query executes a query and returns the server responses
func (c *TF2RconConnection) Query(req string) (string, error) {
c.rcLock.RLock()
defer c.rcLock.RUnlock()
if c.rc == nil {
return "", errors.New("RCON connection is nil")
}
reqID, reqErr := c.rc.Write(req)
if reqErr != nil {
// log.Println(reqErr)
return "", reqErr
}
resp, respID, respErr := c.rc.Read(5 * time.Second)
if respErr != nil {
// log.Println(respErr)
return "", respErr
}
counter := 10
// retry 10 times
for {
if reqID == respID {
break
} else if counter < 0 {
return "", errors.New("Couldn't get a response.")
} else {
counter--
resp, respID, respErr = c.rc.Read(5 * time.Second)
if respErr != nil {
// log.Println(respErr)
return "", reqErr
}
}
}
if strings.HasPrefix(resp, "Unknown command") {
return resp, UnknownCommand(req)
}
return resp, nil
}
func (c *TF2RconConnection) GetConVar(cvar string) (string, error) {
raw, err := c.Query(cvar)
if err != nil {
return "", err
}
// Querying just a variable's name sends back a message like the
// following:
//
// "cvar_name" = "current value" ( def. "default value" )
// var flags like notify replicated
// - short description of cvar
firstLine := strings.Split(raw, "\n")[0]
matches := CVarValueRegex.FindStringSubmatch(firstLine)
if len(matches) != 2 {
return "", errors.New("Unknown cvar.")
}
return matches[1], nil
}
func (c *TF2RconConnection) SetConVar(cvar string, val string) (string, error) {
return c.Query(fmt.Sprintf("%s \"%s\"", cvar, val))
}
// GetPlayers returns a list of players in the server. Includes bots.
func (c *TF2RconConnection) GetPlayers() ([]Player, error) {
statusString, err := c.Query("status")
if err != nil {
return nil, err
}
index := strings.Index(statusString, "#")
i := 0
for index == -1 {
statusString, _ = c.Query("status")
index = strings.Index(statusString, "#")
i++
if i == 5 {
return nil, errors.New("Couldn't get output of status")
}
}
users := strings.Split(statusString[index:], "\n")
var list []Player
for _, userString := range users {
if !rePlayerInfo.MatchString(userString) {
continue
}
matches := rePlayerInfo.FindStringSubmatch(userString)
player := Player{
UserID: matches[1],
Username: matches[2],
SteamID: matches[3],
Ip: matches[4],
}
list = append(list, player)
}
return list, nil
}
// KickPlayer kicks a player
func (c *TF2RconConnection) KickPlayer(p Player, message string) error {
return c.KickPlayerID(p.UserID, message)
}
// Kicks a player with the given player ID
func (c *TF2RconConnection) KickPlayerID(userID string, message string) error {
query := fmt.Sprintf("kickid %s %s", userID, message)
_, err := c.Query(query)
return err
}
// BanPlayer bans a player
func (c *TF2RconConnection) BanPlayer(minutes int, p Player, message string) error {
query := "banid " + fmt.Sprintf("%v", minutes) + " " + p.UserID
if message != "" {
query += " \"" + message + "\""
}
_, err := c.Query(query)
return err
}
// UnbanPlayer unbans a player
func (c *TF2RconConnection) UnbanPlayer(p Player) error {
query := "unbanid " + p.UserID
_, err := c.Query(query)
return err
}
// Say sends a message to the TF2 server chat
func (c *TF2RconConnection) Say(message string) error {
query := "say " + message
_, err := c.Query(query)
return err
}
func (c *TF2RconConnection) Sayf(format string, a ...interface{}) error {
err := c.Say(fmt.Sprintf(format, a...))
return err
}
// ChangeRconPassword changes the rcon password and updates the current connection
// to use the new password
func (c *TF2RconConnection) ChangeRconPassword(password string) error {
_, err := c.SetConVar("rcon_password", password)
if err == nil {
err = c.Reconnect(1 * time.Minute)
}
return err
}
// ChangeMap changes the map
func (c *TF2RconConnection) ChangeMap(mapname string) error {
query := "changelevel \"" + mapname + "\""
res, err := c.Query(query)
if res != "" {
return errors.New("Map not found.")
}
return err
}
// ChangeServerPassword changes the server password
func (c *TF2RconConnection) ChangeServerPassword(password string) error {
_, err := c.SetConVar("sv_password", password)
return err
}
// GetServerPassword returns the server password
func (c *TF2RconConnection) GetServerPassword() (string, error) {
return c.GetConVar("sv_password")
}
func (c *TF2RconConnection) AddTag(newTag string) error {
tags, err := c.GetConVar("sv_tags")
if err != nil {
return err
}
// Source servers don't auto-remove duplicate tags, and noone
tagExists := false
for _, tag := range strings.Split(tags, ",") {
if tag == newTag {
tagExists = true
break
}
}
if !tagExists {
newTags := strings.Join([]string{tags, newTag}, ",")
_, err := c.SetConVar("sv_tags", newTags)
return err
}
return nil
}
func (c *TF2RconConnection) RemoveTag(tagName string) error {
tags, err := c.GetConVar("sv_tags")
if err != nil {
return err
}
if strings.Contains(tags, tagName) {
// Replace all instances of the given tagName. This may leave
// duplicated or trailing commas in the sv_tags string; however
// Source servers clean up the value of sv_tags to remove those
// anyways
_, err := c.SetConVar("sv_tags", strings.Replace(tags, tagName, "", -1))
return err
}
return nil
}
// RedirectLogs send the logaddress_add command
func (c *TF2RconConnection) RedirectLogs(addr string) error {
query := "logaddress_add " + addr
_, err := c.Query(query)
return err
}
func (c *TF2RconConnection) StopLogRedirection(addr string) {
query := fmt.Sprintf("logaddress_del %s", addr)
c.QueryNoResp(query)
}
// Close closes the connection
func (c *TF2RconConnection) Close() {
c.rcLock.Lock()
if c.rc != nil {
c.rc.Close()
}
c.rcLock.Unlock()
}
// ExecConfig accepts a string and executes its lines one by one. Assumes
// UNiX line endings
func (c *TF2RconConnection) ExecConfig(config string) error {
lines := strings.Split(config, "\n")
for _, line := range lines {
_, err := c.Query(line)
if err != nil {
return err
}
}
return nil
}
// NewTF2RconConnection builds a new TF2RconConnection to a server at address ("ip:port") using
// a rcon_password password
func NewTF2RconConnection(address, password string) (*TF2RconConnection, error) {
rc, err := rcon.Dial(address, password)
if err != nil {
return nil, err
}
return &TF2RconConnection{
rc: rc,
host: address,
password: password,
reconnecting: new(int32),
}, nil
}
func (c *TF2RconConnection) Reconnect(duration time.Duration) error {
if atomic.LoadInt32(c.reconnecting) == 1 {
c.rcLock.RLock()
c.rcLock.RUnlock()
return nil
}
c.rcLock.Lock()
defer c.rcLock.Unlock()
atomic.StoreInt32(c.reconnecting, 1)
defer atomic.StoreInt32(c.reconnecting, 0)
if c.rc != nil {
c.rc.Close()
}
now := time.Now()
var err error
for time.Since(now) <= duration {
c.rc, err = rcon.Dial(c.host, c.password)
if err == nil {
return nil
}
}
return err
}