-
Notifications
You must be signed in to change notification settings - Fork 181
/
kline.go
357 lines (301 loc) · 8.89 KB
/
kline.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
// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
package irc
import (
"encoding/json"
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/goshuirc/irc-go/ircfmt"
"github.com/goshuirc/irc-go/ircmatch"
"github.com/goshuirc/irc-go/ircmsg"
"github.com/oragono/oragono/irc/custime"
"github.com/oragono/oragono/irc/sno"
"github.com/tidwall/buntdb"
)
const (
keyKlineEntry = "bans.kline %s"
)
// KLineInfo contains the address itself and expiration time for a given network.
type KLineInfo struct {
// Mask that is blocked.
Mask string
// Matcher, to facilitate fast matching.
Matcher ircmatch.Matcher
// Info contains information on the ban.
Info IPBanInfo
}
// KLineManager manages and klines.
type KLineManager struct {
sync.RWMutex
// kline'd entries
entries map[string]*KLineInfo
}
// NewKLineManager returns a new KLineManager.
func NewKLineManager() *KLineManager {
var km KLineManager
km.entries = make(map[string]*KLineInfo)
return &km
}
// AllBans returns all bans (for use with APIs, etc).
func (km *KLineManager) AllBans() map[string]IPBanInfo {
allb := make(map[string]IPBanInfo)
km.RLock()
defer km.RUnlock()
for name, info := range km.entries {
allb[name] = info.Info
}
return allb
}
// AddMask adds to the blocked list.
func (km *KLineManager) AddMask(mask string, length *IPRestrictTime, reason string, operReason string) {
kln := KLineInfo{
Mask: mask,
Matcher: ircmatch.MakeMatch(mask),
Info: IPBanInfo{
Time: length,
Reason: reason,
OperReason: operReason,
},
}
km.Lock()
km.entries[mask] = &kln
km.Unlock()
}
// RemoveMask removes a mask from the blocked list.
func (km *KLineManager) RemoveMask(mask string) {
km.Lock()
delete(km.entries, mask)
km.Unlock()
}
// CheckMasks returns whether or not the hostmask(s) are banned, and how long they are banned for.
func (km *KLineManager) CheckMasks(masks ...string) (isBanned bool, info *IPBanInfo) {
doCleanup := false
defer func() {
// asynchronously remove expired bans
if doCleanup {
go func() {
km.Lock()
defer km.Unlock()
for key, entry := range km.entries {
if entry.Info.Time.IsExpired() {
delete(km.entries, key)
}
}
}()
}
}()
km.RLock()
defer km.RUnlock()
for _, entryInfo := range km.entries {
if entryInfo.Info.Time != nil && entryInfo.Info.Time.IsExpired() {
doCleanup = true
continue
}
matches := false
for _, mask := range masks {
if entryInfo.Matcher.Match(mask) {
matches = true
break
}
}
if matches {
return true, &entryInfo.Info
}
}
// no matches!
return false, nil
}
// KLINE [ANDKILL] [MYSELF] [duration] <mask> [ON <server>] [reason [| oper reason]]
func klineHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
// check oper permissions
if !client.class.Capabilities["oper:local_ban"] {
client.Send(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, "Insufficient oper privs")
return false
}
currentArg := 0
// when setting a ban, if they say "ANDKILL" we should also kill all users who match it
var andKill bool
if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "andkill" {
andKill = true
currentArg++
}
// when setting a ban that covers the oper's current connection, we require them to say
// "KLINE MYSELF" so that we're sure they really mean it.
var klineMyself bool
if len(msg.Params) > currentArg+1 && strings.ToLower(msg.Params[currentArg]) == "myself" {
klineMyself = true
currentArg++
}
// duration
duration, err := custime.ParseDuration(msg.Params[currentArg])
durationIsUsed := err == nil
if durationIsUsed {
currentArg++
}
// get mask
if len(msg.Params) < currentArg+1 {
client.Send(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, "Not enough parameters")
return false
}
mask := strings.ToLower(msg.Params[currentArg])
currentArg++
// check mask
if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
mask = mask + "!*@*"
} else if !strings.Contains(mask, "@") {
mask = mask + "@*"
}
matcher := ircmatch.MakeMatch(mask)
for _, clientMask := range client.AllNickmasks() {
if !klineMyself && matcher.Match(clientMask) {
client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "This ban matches you. To KLINE yourself, you must use the command: /KLINE MYSELF <arguments>")
return false
}
}
// check remote
if len(msg.Params) > currentArg && msg.Params[currentArg] == "ON" {
client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, "Remote servers not yet supported")
return false
}
// get comment(s)
reason := "No reason given"
operReason := "No reason given"
if len(msg.Params) > currentArg {
tempReason := strings.TrimSpace(msg.Params[currentArg])
if len(tempReason) > 0 && tempReason != "|" {
tempReasons := strings.SplitN(tempReason, "|", 2)
if tempReasons[0] != "" {
reason = tempReasons[0]
}
if len(tempReasons) > 1 && tempReasons[1] != "" {
operReason = tempReasons[1]
} else {
operReason = reason
}
}
}
// assemble ban info
var banTime *IPRestrictTime
if durationIsUsed {
banTime = &IPRestrictTime{
Duration: duration,
Expires: time.Now().Add(duration),
}
}
info := IPBanInfo{
Reason: reason,
OperReason: operReason,
Time: banTime,
}
// save in datastore
err = server.store.Update(func(tx *buntdb.Tx) error {
klineKey := fmt.Sprintf(keyKlineEntry, mask)
// assemble json from ban info
b, err := json.Marshal(info)
if err != nil {
return err
}
tx.Set(klineKey, string(b), nil)
return nil
})
if err != nil {
client.Notice(fmt.Sprintf("Could not successfully save new K-LINE: %s", err.Error()))
return false
}
server.klines.AddMask(mask, banTime, reason, operReason)
var snoDescription string
if durationIsUsed {
client.Notice(fmt.Sprintf("Added temporary (%s) K-Line for %s", duration.String(), mask))
snoDescription = fmt.Sprintf(ircfmt.Unescape("%s$r added temporary (%s) K-Line for %s"), client.nick, duration.String(), mask)
} else {
client.Notice(fmt.Sprintf("Added K-Line for %s", mask))
snoDescription = fmt.Sprintf(ircfmt.Unescape("%s$r added K-Line for %s"), client.nick, mask)
}
server.snomasks.Send(sno.LocalXline, snoDescription)
var killClient bool
if andKill {
var clientsToKill []*Client
var killedClientNicks []string
server.clients.ByNickMutex.RLock()
for _, mcl := range server.clients.ByNick {
for _, clientMask := range mcl.AllNickmasks() {
if matcher.Match(clientMask) {
clientsToKill = append(clientsToKill, mcl)
killedClientNicks = append(killedClientNicks, mcl.nick)
}
}
}
server.clients.ByNickMutex.RUnlock()
for _, mcl := range clientsToKill {
mcl.exitedSnomaskSent = true
mcl.Quit(fmt.Sprintf("You have been banned from this server (%s)", reason))
if mcl == client {
killClient = true
} else {
// if mcl == client, we kill them below
mcl.destroy()
}
}
// send snomask
sort.Strings(killedClientNicks)
server.snomasks.Send(sno.LocalKills, fmt.Sprintf(ircfmt.Unescape("%s killed %d clients with a KLINE $c[grey][$r%s$c[grey]]"), client.nick, len(killedClientNicks), strings.Join(killedClientNicks, ", ")))
}
return killClient
}
func unKLineHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
// check oper permissions
if !client.class.Capabilities["oper:local_unban"] {
client.Send(nil, server.name, ERR_NOPRIVS, client.nick, msg.Command, "Insufficient oper privs")
return false
}
// get host
mask := msg.Params[0]
if !strings.Contains(mask, "!") && !strings.Contains(mask, "@") {
mask = mask + "!*@*"
} else if !strings.Contains(mask, "@") {
mask = mask + "@*"
}
// save in datastore
err := server.store.Update(func(tx *buntdb.Tx) error {
klineKey := fmt.Sprintf(keyKlineEntry, mask)
// check if it exists or not
val, err := tx.Get(klineKey)
if val == "" {
return errNoExistingBan
} else if err != nil {
return err
}
tx.Delete(klineKey)
return nil
})
if err != nil {
client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, msg.Command, fmt.Sprintf("Could not remove ban [%s]", err.Error()))
return false
}
server.klines.RemoveMask(mask)
client.Notice(fmt.Sprintf("Removed K-Line for %s", mask))
server.snomasks.Send(sno.LocalXline, fmt.Sprintf(ircfmt.Unescape("%s$r removed K-Line for %s"), client.nick, mask))
return false
}
func (s *Server) loadKLines() {
s.klines = NewKLineManager()
// load from datastore
s.store.View(func(tx *buntdb.Tx) error {
//TODO(dan): We could make this safer
tx.AscendKeys("bans.kline *", func(key, value string) bool {
// get address name
key = key[len("bans.kline "):]
mask := key
// load ban info
var info IPBanInfo
json.Unmarshal([]byte(value), &info)
// add to the server
s.klines.AddMask(mask, info.Time, info.Reason, info.OperReason)
return true // true to continue I guess?
})
return nil
})
}