-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbanlist.go
More file actions
119 lines (100 loc) · 2.35 KB
/
banlist.go
File metadata and controls
119 lines (100 loc) · 2.35 KB
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
package banlist
import (
"encoding/json"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"sync/atomic"
"syscall"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type Config struct {
Domains []string
URLs []string
}
type Banlist struct {
domainHolder atomic.Value
urlHolder atomic.Value
mtx sync.Mutex
ch chan os.Signal
log logrus.FieldLogger
path string
}
func New(log logrus.FieldLogger, filepath string) *Banlist {
bl := newBanlist(log, filepath)
bl.listen()
bl.runUpdate()
return bl
}
func newBanlist(log logrus.FieldLogger, path string) *Banlist {
bl := &Banlist{log: log, path: path}
bl.domainHolder.Store(make(map[string]struct{}))
bl.urlHolder.Store(make(map[string]struct{}))
return bl
}
func (b *Banlist) listen() {
b.ch = make(chan os.Signal, 1)
signal.Notify(b.ch, syscall.SIGHUP)
go func() {
for range b.ch {
b.runUpdate()
}
b.log.Info("No longer listening for SIGHUP")
}()
}
func (b *Banlist) runUpdate() {
if err := b.update(); err != nil {
b.log.WithError(err).Warn("error updating banlist")
} else {
b.log.Info("banlist updated")
}
}
func (b *Banlist) update() error {
b.mtx.Lock()
defer b.mtx.Unlock()
f, err := os.Open(b.path)
if err != nil {
return errors.Wrap(err, "error opening banlist config")
}
defer f.Close()
c := new(Config)
if err := json.NewDecoder(f).Decode(c); err != nil {
return errors.Wrap(err, "error decoding banlist config")
}
domains := make(map[string]struct{})
urls := make(map[string]struct{})
for _, el := range c.Domains {
domains[strings.ToLower(el)] = struct{}{}
}
for _, el := range c.URLs {
urls[strings.ToLower(el)] = struct{}{}
}
b.domainHolder.Store(domains)
b.urlHolder.Store(urls)
return nil
}
// CheckRequest will check if the domain is blocked or the path is blocked
func (b *Banlist) CheckRequest(r *http.Request) bool {
domain := strings.SplitN(r.Host, ":", 2)[0]
if _, ok := b.domains()[strings.ToLower(domain)]; ok {
return true
}
url := domain + r.URL.Path
if _, ok := b.urls()[strings.ToLower(url)]; ok {
return true
}
return false
}
func (b *Banlist) Close() {
signal.Stop(b.ch)
close(b.ch)
}
func (b *Banlist) domains() map[string]struct{} {
return b.domainHolder.Load().(map[string]struct{})
}
func (b *Banlist) urls() map[string]struct{} {
return b.urlHolder.Load().(map[string]struct{})
}