-
Notifications
You must be signed in to change notification settings - Fork 176
/
kline.go
240 lines (198 loc) · 5.1 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
// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
package irc
import (
"encoding/json"
"fmt"
"strings"
"sync"
"time"
"github.com/goshuirc/irc-go/ircmatch"
"github.com/tidwall/buntdb"
)
const (
keyKlineEntry = "bans.klinev2 %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 // tier 1
persistenceMutex sync.Mutex // tier 2
// kline'd entries
entries map[string]KLineInfo
expirationTimers map[string]*time.Timer
server *Server
}
// NewKLineManager returns a new KLineManager.
func NewKLineManager(s *Server) *KLineManager {
var km KLineManager
km.entries = make(map[string]KLineInfo)
km.expirationTimers = make(map[string]*time.Timer)
km.server = s
km.loadFromDatastore()
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, duration time.Duration, reason, operReason, operName string) error {
km.persistenceMutex.Lock()
defer km.persistenceMutex.Unlock()
info := IPBanInfo{
Reason: reason,
OperReason: operReason,
OperName: operName,
TimeCreated: time.Now().UTC(),
Duration: duration,
}
km.addMaskInternal(mask, info)
return km.persistKLine(mask, info)
}
func (km *KLineManager) addMaskInternal(mask string, info IPBanInfo) {
kln := KLineInfo{
Mask: mask,
Matcher: ircmatch.MakeMatch(mask),
Info: info,
}
var timeLeft time.Duration
if info.Duration > 0 {
timeLeft = info.timeLeft()
if timeLeft <= 0 {
return
}
}
km.Lock()
defer km.Unlock()
km.entries[mask] = kln
km.cancelTimer(mask)
if info.Duration == 0 {
return
}
// set up new expiration timer
timeCreated := info.TimeCreated
processExpiration := func() {
km.Lock()
defer km.Unlock()
maskBan, ok := km.entries[mask]
if ok && maskBan.Info.TimeCreated.Equal(timeCreated) {
delete(km.entries, mask)
delete(km.expirationTimers, mask)
}
}
km.expirationTimers[mask] = time.AfterFunc(timeLeft, processExpiration)
}
func (km *KLineManager) cancelTimer(id string) {
oldTimer := km.expirationTimers[id]
if oldTimer != nil {
oldTimer.Stop()
delete(km.expirationTimers, id)
}
}
func (km *KLineManager) persistKLine(mask string, info IPBanInfo) error {
// save in datastore
klineKey := fmt.Sprintf(keyKlineEntry, mask)
// assemble json from ban info
b, err := json.Marshal(info)
if err != nil {
return err
}
bstr := string(b)
var setOptions *buntdb.SetOptions
if info.Duration != 0 {
setOptions = &buntdb.SetOptions{Expires: true, TTL: info.Duration}
}
err = km.server.store.Update(func(tx *buntdb.Tx) error {
_, _, err := tx.Set(klineKey, bstr, setOptions)
return err
})
return err
}
func (km *KLineManager) unpersistKLine(mask string) error {
// save in datastore
klineKey := fmt.Sprintf(keyKlineEntry, mask)
return km.server.store.Update(func(tx *buntdb.Tx) error {
_, err := tx.Delete(klineKey)
return err
})
}
// RemoveMask removes a mask from the blocked list.
func (km *KLineManager) RemoveMask(mask string) error {
km.persistenceMutex.Lock()
defer km.persistenceMutex.Unlock()
present := func() bool {
km.Lock()
defer km.Unlock()
_, ok := km.entries[mask]
if ok {
delete(km.entries, mask)
}
km.cancelTimer(mask)
return ok
}()
if !present {
return errNoExistingBan
}
return km.unpersistKLine(mask)
}
// 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) {
km.RLock()
defer km.RUnlock()
for _, entryInfo := range km.entries {
for _, mask := range masks {
if entryInfo.Matcher.Match(mask) {
return true, entryInfo.Info
}
}
}
// no matches!
isBanned = false
return
}
func (km *KLineManager) loadFromDatastore() {
// load from datastore
klinePrefix := fmt.Sprintf(keyKlineEntry, "")
km.server.store.View(func(tx *buntdb.Tx) error {
tx.AscendGreaterOrEqual("", klinePrefix, func(key, value string) bool {
if !strings.HasPrefix(key, klinePrefix) {
return false
}
// get address name
mask := strings.TrimPrefix(key, klinePrefix)
// load ban info
var info IPBanInfo
err := json.Unmarshal([]byte(value), &info)
if err != nil {
km.server.logger.Error("internal", "couldn't unmarshal kline", err.Error())
return true
}
// add oper name if it doesn't exist already
if info.OperName == "" {
info.OperName = km.server.name
}
// add to the server
km.addMaskInternal(mask, info)
return true
})
return nil
})
}
func (s *Server) loadKLines() {
s.klines = NewKLineManager(s)
}