-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathroute.go
78 lines (69 loc) · 1.81 KB
/
route.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
package main
import (
"time"
log "github.com/Sirupsen/logrus"
)
import (
"agent/client_handler"
"agent/misc/packet"
. "agent/types"
"agent/utils"
)
// route client protocol
func route(sess *Session, p []byte) []byte {
start := time.Now()
defer utils.PrintPanicStack(sess, p)
// 解密
if sess.Flag&SESS_ENCRYPT != 0 {
sess.Decoder.XORKeyStream(p, p)
}
// 封装为reader
reader := packet.Reader(p)
// 读客户端数据包序列号(1,2,3...)
// 客户端发送的数据包必须包含一个自增的序号,必须严格递增
// 加密后,可避免重放攻击-REPLAY-ATTACK
seq_id, err := reader.ReadU32()
if err != nil {
log.Error("read client timestamp failed:", err)
sess.Flag |= SESS_KICKED_OUT
return nil
}
// 数据包序列号验证
if seq_id != sess.PacketCount {
log.Errorf("illegal packet sequence id:%v should be:%v size:%v", seq_id, sess.PacketCount, len(p)-6)
sess.Flag |= SESS_KICKED_OUT
return nil
}
// 读协议号
b, err := reader.ReadS16()
if err != nil {
log.Error("read protocol number failed.")
sess.Flag |= SESS_KICKED_OUT
return nil
}
// 根据协议号断做服务划分
// 协议号的划分采用分割协议区间, 用户可以自定义多个区间,用于转发到不同的后端服务
var ret []byte
if b > 1000 {
if err := forward(sess, p[4:]); err != nil {
log.Errorf("service id:%v execute failed, error:%v", b, err)
sess.Flag |= SESS_KICKED_OUT
return nil
}
} else {
if h := client_handler.Handlers[b]; h != nil {
ret = h(sess, reader)
} else {
log.Errorf("service id:%v not bind", b)
sess.Flag |= SESS_KICKED_OUT
return nil
}
}
elasped := time.Now().Sub(start)
if b != 0 { // 排除心跳包日志
log.WithFields(log.Fields{"cost": elasped,
"api": client_handler.RCode[b],
"code": b}).Debug("REQ")
}
return ret
}