-
Notifications
You must be signed in to change notification settings - Fork 24
/
statistics.go
92 lines (79 loc) · 2.06 KB
/
statistics.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
package statistic
import (
"context"
"io"
"strings"
"sync"
"github.com/Potterli20/trojan-go-fork/common"
"github.com/Potterli20/trojan-go-fork/log"
)
const Name = "STATISTICS"
type Metadata interface {
GetHash() string
GetKeyShare() string
GetTraffic() (sent, recv uint64)
GetSpeedLimit() (sent, recv int)
GetIPLimit() int
}
type TrafficMeter interface {
io.Closer
AddSentTraffic(sent int)
AddRecvTraffic(recv int)
ResetTraffic() (sent, recv uint64)
GetSpeed() (sent, recv uint64)
}
type IPRecorder interface {
AddIP(string) bool
DelIP(string) bool
GetIP() int
}
type User interface {
Metadata
TrafficMeter
IPRecorder
}
type Persistencer interface {
SaveUser(Metadata) error
LoadUser(hash string) (Metadata, error)
DeleteUser(hash string) error
ListUser(func(hash string, u Metadata) bool) error
UpdateUserTraffic(hash string, sent, recv uint64) error
}
type Authenticator interface {
io.Closer
AuthUser(hash string) (valid bool, user User)
AddUser(hash string) error
DelUser(hash string) error
SetUserTraffic(hash string, sent, recv uint64) error
SetUserSpeedLimit(hash string, send, recv int) error
SetUserIPLimit(hash string, limit int) error
ListUsers() []User
}
type Creator func(ctx context.Context) (Authenticator, error)
var (
createdAuthLock sync.Mutex
authCreators = make(map[string]Creator)
createdAuth = make(map[context.Context]Authenticator)
)
func RegisterAuthenticatorCreator(name string, creator Creator) {
authCreators[name] = creator
}
func NewAuthenticator(ctx context.Context, name string) (Authenticator, error) {
// allocate a unique authenticator for each context
createdAuthLock.Lock() // avoid concurrent map read/write
defer createdAuthLock.Unlock()
if auth, found := createdAuth[ctx]; found {
log.Debug("authenticator has been created:", name)
return auth, nil
}
creator, found := authCreators[strings.ToUpper(name)]
if !found {
return nil, common.NewError("auth driver name " + name + " not found")
}
auth, err := creator(ctx)
if err != nil {
return nil, err
}
createdAuth[ctx] = auth
return auth, err
}