-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
316 lines (248 loc) · 7.42 KB
/
server.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
package main
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
/*
*/
var (
// ErrPlayerNotFound is returned by the ip matching player search function if no player was found.
ErrPlayerNotFound = errors.New("player not found")
// 0: full 1: ID 2: IP 3: port 4: version 5: name 6: clan 7: country
playerEnteredRegex = regexp.MustCompile(`id=([\d]+) addr=([a-fA-F0-9\.\:\[\]]+):([\d]+) version=(\d+) name='(.{0,20})' clan='(.{0,16})' country=([-\d]+)$`)
// 0: full 1: ID 2: IP 3: reason
playerLeftRegex = regexp.MustCompile(`id=([\d]+) addr=([a-fA-F0-9\.\:\[\]]+) reason='(.*)'$`)
// logLevel: net_ban
banAddRegex = regexp.MustCompile(`^banned '(.*)' for ([\d]+) minute[s]? \((.*)\)$`)
banAddIPRegex = regexp.MustCompile(`^'(.*)' banned for ([\d]+) minute[s]? \((.*)\)$`)
banRemoveIndexRegex = regexp.MustCompile(`^unbanned index [\d]+ \('(.+)'\)`)
banRemoveIPRegex = regexp.MustCompile(`^unbanned '(.+)'`)
banExpiredRegex = regexp.MustCompile(`^ban '(.+)' expired$`)
banRemoveAll = regexp.MustCompile(`^unbanned all entries$`)
)
// Player represents an ingame player.
type Player struct {
ID int
Name string
Clan string
Country int
IP string
Port int
Version int
}
// Valid returns true if the player's ID is valid.
func (p *Player) Valid() bool {
return p.ID >= 0 && len(p.IP) > 0 && p.Port > 0
}
// Clear resets the player to default values except for its ID
func (p *Player) Clear() {
id := p.ID
*p = Player{}
p.ID = id //ID stays the same
}
// Server represents a tracked Teeworlds server
type Server struct {
sync.RWMutex // guards slots object
players [64]Player
BanServer BanServer
JoinCallbacks []PlayerCallback
LeaveCallbacks []PlayerCallback
}
// PlayerCallback is a function that takes a player as parameter.
type PlayerCallback func(Player)
// NewServer creates a new empty server
func NewServer() *Server {
srv := &Server{
BanServer: newBanServer(),
JoinCallbacks: make([]PlayerCallback, 0, 1),
LeaveCallbacks: make([]PlayerCallback, 0, 1),
}
for idx := range srv.players {
srv.Lock()
srv.players[idx].ID = idx
srv.Unlock()
}
return srv
}
// ParseLine parses a line from econ or logs, which affects the internal server state.
func (s *Server) ParseLine(logLevel, logLine string, notify *NotifyMap) (consumed bool, formatedString string) {
switch logLevel {
case "client_enter":
match := playerEnteredRegex.FindStringSubmatch(logLine)
if len(match) == 8 {
id, _ := strconv.Atoi(match[1])
port, _ := strconv.Atoi(match[3])
version, _ := strconv.Atoi(match[4])
country, _ := strconv.Atoi(match[7])
player := Player{
ID: id,
Name: match[5],
Clan: match[6],
Country: country,
IP: match[2],
Port: port,
Version: version,
}
s.Lock()
s.players[id] = player
s.Unlock()
s.handleJoin(player)
// notification requested
if notify != nil {
var sb strings.Builder
mentions := notify.Tracked(player.Name)
if len(mentions) > 0 {
for idx, mention := range mentions {
sb.WriteString(mention)
if idx < len(mentions)-1 {
sb.WriteString(" ")
}
}
return true, fmt.Sprintf("[server]: '%s' joined the server with id %d\n%s", Escape(player.Name), id, sb.String())
}
}
if config.LogLevel >= 2 {
return true, fmt.Sprintf("[server]: '%s' joined the server with id %d", player.Name, id)
}
return true, ""
}
case "client_drop":
// player leaves
match := playerLeftRegex.FindStringSubmatch(logLine)
if len(match) == 4 {
id, _ := strconv.Atoi(match[1])
s.Lock()
// make copy
player := s.players[id]
// clear player slot
s.players[id].Clear()
s.Unlock()
s.handleLeave(player)
if config.LogLevel >= 2 {
return true, fmt.Sprintf("[server]: '%s' left the server, id was %d", Escape(player.Name), id)
}
return true, ""
}
case "net_ban":
matches := banAddRegex.FindStringSubmatch(logLine)
if len(matches) == (1 + 3) {
ip := matches[1]
minutes, _ := strconv.Atoi(matches[2])
reason := matches[3]
// returns (unknown) dummy if player was not found
p := s.PlayerByIP(ip)
duration := time.Minute * time.Duration(minutes)
s.BanServer.Ban(p, duration, reason)
// player found, send nickname
return true, fmt.Sprintf("**[bans]**: '%s' banned for %9s with reason: '%s'", p.Name, duration.Round(time.Second), reason)
}
matches = banAddIPRegex.FindStringSubmatch(logLine)
if len(matches) == (1 + 3) {
ip := matches[1]
minutes, _ := strconv.Atoi(matches[2])
reason := matches[3]
p := s.PlayerByIP(ip)
duration := time.Minute * time.Duration(minutes)
s.BanServer.Ban(p, duration, reason)
// player found, send nickname
return true, fmt.Sprintf("**[bans]**: '%s' banned for %9s with reason: '%s'", p.Name, duration.Round(time.Second), reason)
}
matches = banExpiredRegex.FindStringSubmatch(logLine)
if len(matches) == (1 + 1) {
ip := matches[1]
ban, err := s.BanServer.UnbanIP(ip)
if err != nil {
return true, fmt.Sprintf("[bans]: ban of '%s' expired", ban.Player.Name)
}
return true, fmt.Sprintf("[bans]: ban of '%s' expired (%s)", ban.Player.Name, ban.Reason)
}
matches = banRemoveIndexRegex.FindStringSubmatch(logLine)
if len(matches) == (1 + 1) {
ip := matches[1]
ban, err := s.BanServer.UnbanIP(ip)
if err != nil {
return true, fmt.Sprintf("[bans]: unbanned '%s'", ban.Player.Name)
}
return true, fmt.Sprintf("[bans]: unbanned '%s' (%s)", ban.Player.Name, ban.Reason)
}
matches = banRemoveIPRegex.FindStringSubmatch(logLine)
if len(matches) == (1 + 1) {
ip := matches[1]
ban, err := s.BanServer.UnbanIP(ip)
if err != nil {
return true, fmt.Sprintf("[bans]: unbanned '%s'", ban.Player.Name)
}
return true, fmt.Sprintf("[bans]: unbanned '%s' (%s)", ban.Player.Name, ban.Reason)
}
matches = banRemoveAll.FindStringSubmatch(logLine)
if len(matches) == 1 {
s.BanServer.UnbanAll()
return true, fmt.Sprintf("[bans]: unbanned all players.")
}
}
return false, ""
}
// Player returns the player by its ID.
func (s *Server) Player(id int) Player {
if id < 0 || 63 < id {
return Player{
Name: "(unknown)",
ID: -1,
}
}
s.Lock()
defer s.Unlock()
return s.players[id]
}
// PlayerByIP returns a dummy player with a negative ID if no player with expected IP was found.
func (s *Server) PlayerByIP(ip string) Player {
s.Lock()
defer s.Unlock()
for _, p := range &s.players {
if p.IP == ip {
return p
}
}
return Player{
Name: "(unknown)",
ID: -1,
IP: ip,
}
}
// Status returns a list of all online players
func (s *Server) Status() []Player {
playerList := make([]Player, 0, 32)
s.RLock()
defer s.RUnlock()
for _, p := range &s.players {
if p.Valid() {
playerList = append(playerList, p)
}
}
return playerList
}
// AddJoinHandler add a new player join handler.
func (s *Server) AddJoinHandler(handler PlayerCallback) {
s.JoinCallbacks = append(s.JoinCallbacks, handler)
}
// AddLeaveHandler add a new player leaving handler.
func (s *Server) AddLeaveHandler(handler PlayerCallback) {
s.LeaveCallbacks = append(s.LeaveCallbacks, handler)
}
// calls all callbacks asyncronously, when a player joins.
func (s *Server) handleJoin(p Player) {
for _, cb := range s.JoinCallbacks {
cb(p)
}
}
// calls all callbacks asyncronously, when a player leaves.
func (s *Server) handleLeave(p Player) {
for _, cb := range s.LeaveCallbacks {
cb(p)
}
}