/
user.go
347 lines (312 loc) · 8.98 KB
/
user.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package xray
import (
"context"
"fmt"
"net/http"
"strconv"
"sync"
"time"
proxy "github.com/xtls/xray-core/app/proxyman/command"
stats "github.com/xtls/xray-core/app/stats/command"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/proxy/shadowsocks"
"github.com/xtls/xray-core/proxy/trojan"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type User struct {
running bool
ID int `json:"user_id"`
Method string `json:"method"`
Password string `json:"password"`
Level int `json:"level"`
Enable bool `json:"enable"`
UploadTraffic int64 `json:"upload_traffic"`
DownloadTraffic int64 `json:"download_traffic"`
Protocol string `json:"protocol"`
}
type UserTraffic struct {
ID int `json:"user_id"`
UploadTraffic int64 `json:"upload_traffic"`
DownloadTraffic int64 `json:"download_traffic"`
IPList []string `json:"ip_list"`
TcpCount int64 `json:"tcp_conn_num"`
}
type SyncTrafficReq struct {
Data []*UserTraffic `json:"data"`
UploadBandwidth int64 `json:"upload_bandwidth"`
DownloadBandwidth int64 `json:"download_bandwidth"`
}
func (s *SyncTrafficReq) GetTotalTraffic() int64 {
var total int64
for _, u := range s.Data {
total += u.UploadTraffic + u.DownloadTraffic
}
return total
}
type SyncUserConfigsResp struct {
Users []*User `json:"users"`
}
// NOTE we use user id as email
func (u *User) GetEmail() string {
return fmt.Sprintf("%d", u.ID)
}
func (u *User) ResetTraffic() {
u.DownloadTraffic = 0
u.UploadTraffic = 0
}
func (u *User) GenTraffic() *UserTraffic {
return &UserTraffic{
ID: u.ID,
UploadTraffic: u.UploadTraffic,
DownloadTraffic: u.DownloadTraffic,
IPList: []string{},
TcpCount: 0,
}
}
func (u *User) UpdateFromServer(serverSideUser *User) {
u.Method = serverSideUser.Method
u.Enable = serverSideUser.Enable
u.Password = serverSideUser.Password
}
func (u *User) Equal(new *User) bool {
return u.Method == new.Method && u.Enable == new.Enable && u.Password == new.Password
}
func (u *User) ToXrayUser() *protocol.User {
var account *serial.TypedMessage
switch u.Protocol {
case ProtocolTrojan:
account = serial.ToTypedMessage(&trojan.Account{Password: u.Password})
case ProtocolSS:
account = serial.ToTypedMessage(&shadowsocks.Account{CipherType: mappingCipher(u.Method), Password: u.Password})
default:
zap.S().DPanicf("unknown protocol %s", u.Protocol)
return nil
}
return &protocol.User{Level: uint32(u.Level), Email: u.GetEmail(), Account: account}
}
type UserPool struct {
l *zap.Logger
sync.RWMutex
// map key : ID
users map[int]*User
httpClient *http.Client
proxyClient proxy.HandlerServiceClient
statsClient stats.StatsServiceClient
br *bandwidthRecorder
proxyTags []string
cancel context.CancelFunc
grpcEndPoint string
remoteConfigURL string
}
func NewUserPool(grpcEndPoint, remoteConfigURL, metricURL string, proxyTags []string) *UserPool {
up := &UserPool{
l: zap.L().Named("user_pool"),
users: make(map[int]*User),
proxyTags: proxyTags,
grpcEndPoint: grpcEndPoint,
remoteConfigURL: remoteConfigURL,
}
if metricURL != "" {
up.br = NewBandwidthRecorder(metricURL)
}
return up
}
func (up *UserPool) CreateUser(userId, level int, password, method, protocol string, enable bool) *User {
up.Lock()
defer up.Unlock()
u := &User{
running: false,
ID: userId,
Password: password,
Level: level,
Enable: enable,
Method: method,
Protocol: protocol,
}
up.users[u.ID] = u
return u
}
func (up *UserPool) GetUser(id int) (*User, bool) {
up.RLock()
defer up.RUnlock()
user, ok := up.users[id]
return user, ok
}
func (up *UserPool) RemoveUser(id int) {
up.Lock()
defer up.Unlock()
delete(up.users, id)
}
func (up *UserPool) GetAllUsers() []*User {
up.RLock()
defer up.RUnlock()
users := make([]*User, 0, len(up.users))
for _, user := range up.users {
users = append(users, user)
}
return users
}
func (up *UserPool) syncTrafficToServer(ctx context.Context, proxyTag string) error {
// sync traffic from xray server
// V2ray的stats的统计模块设计的非常奇怪,具体规则如下
// 上传流量:"user>>>" + user.Email + ">>>traffic>>>uplink"
// 下载流量:"user>>>" + user.Email + ">>>traffic>>>downlink"
resp, err := up.statsClient.QueryStats(ctx, &stats.QueryStatsRequest{Pattern: "user>>>", Reset_: true})
if err != nil {
return err
}
for _, stat := range resp.Stat {
userIDStr, trafficType := getEmailAndTrafficType(stat.Name)
userID, err := strconv.Atoi(userIDStr)
if err != nil {
return err
}
user, found := up.GetUser(userID)
if !found {
up.l.Sugar().Warnf(
"user in xray not found in user pool this user maybe out of traffic, user id: %d, leak traffic: %d",
userID, stat.Value)
fakeUser := &User{ID: userID}
if err := RemoveInboundUser(ctx, up.proxyClient, proxyTag, fakeUser); err != nil {
up.l.Warn("tring remove leak user failed, user id: %d err: %s",
zap.Int("user_id", userID), zap.Error(err))
}
continue
}
// Note v2ray 只会统计 inbound 的流量,所以这里乘 2 以补偿 outbound 的流量
switch trafficType {
case "uplink":
user.UploadTraffic = stat.Value * 2
case "downlink":
user.DownloadTraffic = stat.Value * 2
}
}
tfs := make([]*UserTraffic, 0, len(up.users))
for _, user := range up.GetAllUsers() {
tf := user.DownloadTraffic + user.UploadTraffic
if tf > 0 {
up.l.Sugar().Infof("User: %v Now Used Total Traffic: %v", user.ID, tf)
tfs = append(tfs, user.GenTraffic())
user.ResetTraffic()
}
}
req := &SyncTrafficReq{Data: tfs}
if up.br != nil {
// record bandwidth
uploadIncr, downloadIncr, err := up.br.RecordOnce(ctx)
if err != nil {
return err
}
ub := up.br.GetUploadBandwidth()
req.UploadBandwidth = int64(ub)
db := up.br.GetDownloadBandwidth()
req.DownloadBandwidth = int64(db)
up.l.Sugar().Debug(
"Upload Bandwidth :", PrettyByteSize(ub),
"Download Bandwidth :", PrettyByteSize(db),
"Total Bandwidth :", PrettyByteSize(ub+db),
"Total Increment By BR", PrettyByteSize(uploadIncr+downloadIncr),
"Total Increment By Xray :", PrettyByteSize(float64(req.GetTotalTraffic())),
)
}
if err := postJson(up.httpClient, up.remoteConfigURL, req); err != nil {
return err
}
up.l.Sugar().Infof("Call syncTrafficToServer ONLINE USER COUNT: %d", len(tfs))
return nil
}
func (up *UserPool) syncUserConfigsFromServer(ctx context.Context, proxyTag string) error {
resp := SyncUserConfigsResp{}
if err := getJson(up.httpClient, up.remoteConfigURL, &resp); err != nil {
return err
}
userM := make(map[int]struct{})
for _, newUser := range resp.Users {
oldUser, found := up.GetUser(newUser.ID)
if !found {
newUser := up.CreateUser(
newUser.ID, newUser.Level, newUser.Password, newUser.Method, newUser.Protocol, newUser.Enable)
if newUser.Enable {
if err := AddInboundUser(ctx, up.proxyClient, proxyTag, newUser); err != nil {
return err
}
}
} else {
// update user configs
if !oldUser.Equal(newUser) {
oldUser.UpdateFromServer(newUser)
if oldUser.running {
if err := RemoveInboundUser(ctx, up.proxyClient, proxyTag, oldUser); err != nil {
return err
}
}
}
if oldUser.Enable && !oldUser.running {
if err := AddInboundUser(ctx, up.proxyClient, proxyTag, oldUser); err != nil {
return err
}
}
}
userM[newUser.ID] = struct{}{}
}
// remove user not in server
for _, user := range up.GetAllUsers() {
if _, ok := userM[user.ID]; !ok {
if err := RemoveInboundUser(ctx, up.proxyClient, proxyTag, user); err != nil {
return err
}
up.RemoveUser(user.ID)
}
}
return nil
}
func (up *UserPool) Start(ctx context.Context) error {
conn, err := grpc.DialContext(
context.Background(), up.grpcEndPoint, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock())
if err != nil {
return err
}
up.proxyClient = proxy.NewHandlerServiceClient(conn)
up.statsClient = stats.NewStatsServiceClient(conn)
up.httpClient = &http.Client{Timeout: time.Second * 10}
syncOnce := func() error {
for _, tag := range up.proxyTags {
if err := up.syncUserConfigsFromServer(ctx, tag); err != nil {
up.l.Sugar().Errorf("Sync User Configs From Server Error: %v", err)
return err
}
if err := up.syncTrafficToServer(ctx, tag); err != nil {
up.l.Sugar().Errorf("Sync Traffic From Server Error: %v", err)
return err
}
}
return nil
}
if err := syncOnce(); err != nil {
return err
}
ctx2, cancel := context.WithCancel(ctx)
up.cancel = cancel
go func() {
ticker := time.NewTicker(time.Second * SyncTime)
for {
select {
case <-ctx2.Done():
return
case <-ticker.C:
if err := syncOnce(); err != nil {
up.l.Error("Sync User Configs From Server Error: %v", zap.Error(err))
}
}
}
}()
return nil
}
func (up *UserPool) Stop() {
if up.cancel != nil {
up.cancel()
}
}