-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaway.go
147 lines (128 loc) · 2.22 KB
/
away.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
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
const (
ModeRule rune = 42
ModeAway rune = 126
ModePass rune = 64
ModeDrop rune = 33
)
type Rule struct {
Rule string
Mode rune
}
func NewRule(rule string) (*Rule, error) {
m := []rune(rule[0:1])[0]
if m == ModeRule {
return nil, fmt.Errorf("Rule mode must be in [~, !, @], %s", rule)
}
r := &Rule{
Rule: rule[1:],
Mode: m,
}
return r, nil
}
func (r *Rule) String() string {
return string(r.Mode) + r.Rule
}
type Away struct {
rules sync.Map
mode rune
filename string
}
func NewAway(mode rune, filename string) *Away {
a := &Away{
mode: mode,
filename: filename,
}
return a
}
func (a *Away) Mode() rune {
return a.mode
}
func (a *Away) ChangeMode(m rune) {
a.mode = m
}
func (a *Away) ResloveMode(addr *Addr) rune {
if a.mode == ModeRule {
s := addr.Host()
for {
if r, ok := a.rules.Load(s); ok {
return r.(*Rule).Mode
}
i := strings.IndexRune(s, '.')
if i >= 0 {
s = s[i+1:]
} else {
return ModeRule
}
}
} else {
return a.mode
}
}
func (a *Away) AddRule(r string) error {
nr, err := NewRule(r)
if err != nil {
return err
}
a.rules.Store(nr.Rule, nr)
return nil
}
func (a *Away) DeleteRule(r string) {
a.rules.Delete(r[1:])
}
func (a *Away) SortRules() []string {
rs := make([]string, 0, 30)
a.rules.Range(func(_, r interface{}) bool {
rs = append(rs, r.(*Rule).String())
return true
})
sort.Slice(rs, func(i, j int) bool {
return rs[i][1:] < rs[j][1:]
})
return rs
}
func (a *Away) LoadRules() (int, error) {
file, err := os.Open(a.filename)
if err != nil {
return -1, err
}
defer file.Close()
i := 0
s := bufio.NewScanner(file)
for s.Scan() {
rule := s.Text()
nr, err := NewRule(rule)
if err != nil {
log.Warn(err)
}
a.rules.Store(nr.Rule, nr)
i++
}
return i, nil
}
func (a *Away) WriteRules() error {
tmp := a.filename + "." + strconv.Itoa(time.Now().Nanosecond())
tmpf, err := os.Create(tmp)
if err != nil {
return err
}
defer tmpf.Close()
rs := a.SortRules()
for _, r := range rs {
if _, e := fmt.Fprintln(tmpf, r); e != nil {
return e
}
}
return os.Rename(tmp, a.filename)
}