-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathisr.go
439 lines (355 loc) · 9.42 KB
/
isr.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package main
import (
"bufio"
"bytes"
"encoding/binary"
"fmt"
"log"
"math"
"net"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
)
const (
connectTimeout = 3
version = "0.1"
)
var (
configFile = "./isr.cfg"
hasRules = false
ruleSet []string
)
var conf = struct {
Host string `name:"host"`
QueryPort int `name:"queryport"`
RconPort int `name:"rconport"`
RconPassword string `name:"rconpassword"`
TemplateWelcome string `name:"templatewelcome"`
TemplateFarewell string `name:"templatefarewell"`
RuleFile string `name:"rulefile"`
TellFirstRuleDelay int `name:"tellfirstruledelay"`
TellNextRulesDelay int `name:"tellnextrulesdelay"`
}{
Host: "",
QueryPort: 27131,
RconPort: 27015,
RconPassword: "",
TemplateWelcome: "Welcome, @!",
TemplateFarewell: "Player @ just left.",
RuleFile: "rules.txt",
TellFirstRuleDelay: 30,
TellNextRulesDelay: 10,
}
func main() {
startup()
var playerList = map[string]bool{}
playRules := struct {
doPlay bool
nextRule time.Time
ruleIndex int
}{doPlay: false, nextRule: time.Now(), ruleIndex: 0}
log.Println("Start monitoring")
for {
players, err := readPlayers()
if err != nil {
log.Println(err.Error())
time.Sleep(30 * time.Second)
continue
}
// check for joined players
for name := range players {
if strings.TrimSpace(name) == "" {
continue
}
_, found := playerList[name]
if found {
if hasRules && playerList[name] && players[name].Seconds() > float64(conf.TellFirstRuleDelay) {
playerList[name] = false
if !playRules.doPlay {
playRules.doPlay = true
playRules.nextRule = nextTime(conf.TellNextRulesDelay)
playRules.ruleIndex = 0
}
}
continue
}
playerList[name] = true
rconSay(strings.Replace(conf.TemplateWelcome, "@", name, -1))
}
// check for parted players
for name := range playerList {
_, found := players[name]
if found {
continue
}
delete(playerList, name)
rconSay(strings.Replace(conf.TemplateFarewell, "@", name, -1))
}
if playRules.doPlay && time.Now().After(playRules.nextRule) {
rconSay(ruleSet[playRules.ruleIndex])
playRules.ruleIndex++
playRules.nextRule = nextTime(conf.TellNextRulesDelay)
if playRules.ruleIndex >= len(ruleSet) {
playRules.doPlay = false
}
}
time.Sleep(5 * time.Second)
}
}
func loadRules() {
file, err := os.Open(conf.RuleFile)
hasRules = err == nil && file != nil
if hasRules {
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
ruleSet = append(ruleSet, line)
}
_ = file.Close()
} else {
log.Println("WARNING: Can't find rules file. Rules disabled.")
}
}
type logWriter struct{}
func (writer logWriter) Write(bytes []byte) (int, error) {
return fmt.Print(time.Now().UTC().Format("[2006-01-02T15:04:05.999Z] ") + string(bytes))
}
func startup() {
log.SetFlags(0)
log.SetOutput(new(logWriter))
printHeader()
if len(os.Args) > 1 {
param := strings.ToLower(os.Args[1])
if param == "--help" || param == "-h" {
printUsage("", true)
}
configFile = os.Args[1]
}
configFile, _ = filepath.Abs(configFile)
_, err := os.Stat(configFile)
if os.IsNotExist(err) {
printUsage(fmt.Sprintf("ERROR: Config file \"%s\" doesn't exist!", configFile), false)
}
loadConfig()
loadRules()
}
func loadConfig() {
file, err := os.Open(configFile)
if err != nil || file == nil {
printUsage("ERROR: Can't open config file.", false)
}
defer file.Close()
t := reflect.TypeOf(conf)
confMap := map[string]string{}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
confMap[field.Tag.Get("name")] = field.Name
}
confValues := reflect.ValueOf(&conf).Elem()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || line[0] == '#' {
continue
}
splitLine := strings.Split(line, "=")
if len(splitLine) < 2 {
continue
}
key := strings.ToLower(strings.TrimSpace(splitLine[0]))
val := strings.TrimSpace(strings.Join(splitLine[1:], "="))
fieldName, found := confMap[key]
if !found {
continue
}
fieldValue := confValues.FieldByName(fieldName)
if fieldValue.Kind() == reflect.String {
fieldValue.SetString(val)
}
if fieldValue.Kind() == reflect.Int {
if intVal, err := strconv.Atoi(val); err == nil {
fieldValue.SetInt(int64(intVal))
}
}
}
if conf.Host == "" {
printUsage("ERROR: No host specified in config.", false)
}
}
func printUsage(message string, full bool) {
exitCode := 0
if message != "" {
message = message + "\n"
exitCode = 1
}
fmt.Printf(` %s
Usage:
isr [-h|--help] [configfile]
ISR tries to load a isr.cfg from the current directory
unless the "configfile" argument specifies a different
location.
`, message)
if full {
fmt.Println(" Example config file:")
_, _ = fmt.Fprint(os.Stderr, `
# hostname or ip of your server
host = my.fancy.server
# server's query port
queryPort = 27131
# server's RCON port
rconPort = 27015
# RCON password
rconPassword = supersecret
# welcome message, @ is replaced with players name
templateWelcome = Welcome, @!
# farewell message
templateFarewell = Player @ just left.
# rules file
rulesFile = rules.txt
# delay until first rule is printed in seconds
tellFirstRuleDelay = 30
# delay between every rule in seconds
tellNextRulesDelay = 10
`)
_, exe := filepath.Split(os.Args[0])
fmt.Printf("\n You can use\n\n %s --help 2>isr.cfg\n\n to copy this example into a file.", exe)
} else {
fmt.Println(" Use --help to see a example.")
}
os.Exit(exitCode)
}
func printHeader() {
title := fmt.Sprintf("Insurgency Sandstorm Receptionist v%s", version)
fmt.Printf(`
___ ___________________
| |/ _____/\______ \
| |\_____ \ | _/
| |/ \ | | \
|___/_______ / |____|_ /
\/ \/
%s
%s
`, title, strings.Repeat("~", len(title)))
}
func readPlayers() (map[string]time.Duration, error) {
const (
MaxPacketSize = 1500
)
A2sPlayer := []byte{0xFF, 0xFF, 0xFF, 0xFF, 0x55, 0xFF, 0xFF, 0xFF, 0xFF}
conn, err := net.DialTimeout("udp",
fmt.Sprintf("%s:%d", conf.Host, conf.QueryPort),
time.Duration(connectTimeout)*time.Second)
if err != nil {
return nil, err
}
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(time.Duration(1) * time.Second))
_, _ = conn.Write(A2sPlayer)
var buf [MaxPacketSize]byte
numread, err := conn.Read(buf[:MaxPacketSize])
if err != nil {
return nil, err
}
if 0x41 == buf[4] {
copy(A2sPlayer[5:9], buf[5:9])
_ = conn.SetDeadline(time.Now().Add(time.Duration(1) * time.Second))
_, _ = conn.Write(A2sPlayer)
numread, err = conn.Read(buf[:MaxPacketSize])
if err != nil || 0x44 != buf[4] {
return nil, err
}
}
unparsed := make([]byte, numread)
copy(unparsed, buf[:numread])
unparsed = unparsed[4:]
numplayers := int(unparsed[1])
players := map[string]time.Duration{}
if numplayers == 0 || numplayers > 30 {
return players, nil
}
startidx := 3
var b []byte
for i := 0; i < numplayers; i++ {
// there is no ternary operator in GO
if i == 0 {
b = unparsed[startidx:]
} else {
b = b[startidx+1:]
}
stringTerminator := bytes.IndexByte(b, 0x00)
if stringTerminator < 0 {
return nil, nil
}
playerName := string(b[:stringTerminator]) // string (variable length)
// ignore score
duration := b[stringTerminator+5 : stringTerminator+9] // time, float (4 bytes)
startidx = stringTerminator + 9
onlineTime := time.Duration(int64(math.Float32frombits(binary.LittleEndian.Uint32(duration)))) * time.Second
players[playerName] = onlineTime
}
return players, nil
}
func nextTime(delay int) time.Time {
return time.Now().Add(time.Duration(delay) * time.Second)
}
func rconSay(msg string) {
conn, err := net.DialTimeout("tcp",
fmt.Sprintf("%s:%d", conf.Host, conf.RconPort),
time.Duration(connectTimeout)*time.Second)
if err != nil {
return
}
defer conn.Close()
const (
cmdAuth = 3
cmdExecCommand = 2
authResponse = 2
)
buffer, connectId := makeRconBuffer(conf.RconPassword, cmdAuth)
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
_, err = conn.Write(buffer)
if err != nil {
return
}
recvBuffer := make([]byte, 14)
_ = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
size, err := conn.Read(recvBuffer)
if size < 10 {
s, err := conn.Read(recvBuffer[size:])
if err != nil {
return
}
size += s
}
if err != nil || size != 14 {
return
}
if authResponse != binary.LittleEndian.Uint32(recvBuffer[8:12]) ||
connectId != int32(binary.LittleEndian.Uint32(recvBuffer[4:8])) {
log.Fatalln("ERROR: RCON authentification failed. Password wrong?")
// Fatal = os.Exit(1)
}
buffer, connectId = makeRconBuffer("say "+msg, cmdExecCommand)
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
_, err = conn.Write(buffer)
if err != nil {
return
}
}
func makeRconBuffer(msg string, cmdId int32) ([]byte, int32) {
connectId := int32((time.Now().UnixNano() / 100000) % 100000)
buffer := bytes.NewBuffer(make([]byte, 0, len(msg)+14))
_ = binary.Write(buffer, binary.LittleEndian, int32(10+len(msg)))
_ = binary.Write(buffer, binary.LittleEndian, connectId)
_ = binary.Write(buffer, binary.LittleEndian, cmdId)
buffer.WriteString(msg)
_ = binary.Write(buffer, binary.LittleEndian, uint16(0))
return buffer.Bytes(), connectId
}