forked from shadowsocks/go-shadowsocks2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
saltfilter.go
80 lines (73 loc) · 1.66 KB
/
saltfilter.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
package internal
import (
"fmt"
"os"
"strconv"
)
// Those suggest value are all set according to
// https://github.com/shadowsocks/shadowsocks-org/issues/44#issuecomment-281021054
// Due to this package contains various internal implementation so const named with DefaultBR prefix
const (
DefaultSFCapacity = 1e6
// FalsePositiveRate
DefaultSFFPR = 1e-6
DefaultSFSlot = 10
)
const EnvironmentPrefix = "SHADOWSOCKS_"
// A shared instance used for checking salt repeat
var saltfilter *BloomRing
func init() {
var (
finalCapacity = DefaultSFCapacity
finalFPR = DefaultSFFPR
finalSlot = float64(DefaultSFSlot)
)
for _, opt := range []struct {
ENVName string
Target *float64
}{
{
ENVName: "CAPACITY",
Target: &finalCapacity,
},
{
ENVName: "FPR",
Target: &finalFPR,
},
{
ENVName: "SLOT",
Target: &finalSlot,
},
} {
envKey := EnvironmentPrefix + "SF_" + opt.ENVName
env := os.Getenv(envKey)
if env != "" {
p, err := strconv.ParseFloat(env, 64)
if err != nil {
panic(fmt.Sprintf("Invalid envrionment `%s` setting in saltfilter: %s", envKey, env))
}
*opt.Target = p
}
}
// Support disable saltfilter by given a negative capacity
if finalCapacity <= 0 {
return
}
saltfilter = NewBloomRing(int(finalSlot), int(finalCapacity), finalFPR)
}
// TestSalt returns true if salt is repeated
func TestSalt(b []byte) bool {
// If nil means feature disabled, return false to bypass salt repeat detection
if saltfilter == nil {
return false
}
return saltfilter.Test(b)
}
// AddSalt salt to filter
func AddSalt(b []byte) {
// If nil means feature disabled
if saltfilter == nil {
return
}
saltfilter.Add(b)
}