-
Notifications
You must be signed in to change notification settings - Fork 10
/
f2b.go
89 lines (73 loc) · 1.36 KB
/
f2b.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
package main
import (
"fmt"
"log"
"net/http"
"sync"
"time"
)
var (
f2b = newf2b()
)
type f2bDBentr struct {
banUntil time.Time
noTries int
}
type f2bDB struct {
entr map[string]f2bDBentr
sync.Mutex
}
func newf2b() *f2bDB {
l := new(f2bDB)
l.entr = make(map[string]f2bDBentr)
return l
}
func (db *f2bDB) check(ip string) bool {
if !*f2bEnabled {
return false
}
db.Lock()
defer db.Unlock()
// TODO: purge old entries
l, ok := db.entr[ip]
if !ok {
return false
}
return time.Now().Before(l.banUntil)
}
func (db *f2bDB) ban(ip string) {
if !*f2bEnabled {
return
}
db.Lock()
defer db.Unlock()
l, ok := db.entr[ip]
if !ok {
l = f2bDBentr{noTries: 0}
}
l.banUntil = time.Now().Add(time.Minute * time.Duration(l.noTries))
l.noTries++
db.entr[ip] = l
log.Printf("auth: Banning ip=%v for=%v no#tries=%v", ip, time.Until(l.banUntil), l.noTries)
}
func (db *f2bDB) unban(ip string) {
if !*f2bEnabled {
return
}
db.Lock()
defer db.Unlock()
delete(db.entr, ip)
}
func (db *f2bDB) dump(w http.ResponseWriter) {
db.Lock()
defer db.Unlock()
for i, l := range db.entr {
fmt.Fprintf(w, "ip=%v for=%v tries=%v\n", i, time.Until(l.banUntil), l.noTries)
}
}
func dumpf2b(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Cache-Control", "no-cache")
fmt.Fprintf(w, "F2BDB\n\n")
f2b.dump(w)
}