gate到robot转发模式
This commit is contained in:
1 parent
8d039dee06
commit
12a8381c43
34 files changed
+3132
-440
No files matched your search
@@ -2,6 +2,9 @@ http_port = 8080
|
||||
|
||||
[hk4e]
|
||||
dispatch_url = "https://hk4e.flswld.com/query_cur_region" # 二级dispatch地址 将域名改为dispatch的外网地址
|
||||
forward_mode_enable = false
|
||||
forward_region_url = "" # 转发的一级dispatch地址
|
||||
forward_dispatch_url = "" # 转发的二级dispatch地址
|
||||
|
||||
[logger]
|
||||
level = "DEBUG"
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpAIBAAKCAQEAxAde3Gos++LVlw2vvW5OiziD97fVvA3Y6GLY0xMd4d7LpnHr
|
||||
fwuO7+60IZA9zR6QOFkrMrxNMTf2UbEJsnfbnUyhsQJr8bHR6PfUj6d/YUceM8YW
|
||||
cjpCyZGM2mKuVBXYqWO8gU81bwQOKgHSytvIrXtsk+3+g+pfkSKZOakiPzosSXCt
|
||||
GSPrVRJlumCmiXjTiKiwKqR+BBk8tZSuINl+r/aTfgu5xkfcB6YOYIIsNfkhpyZT
|
||||
cO0TNk7A3gRhikySyfxZX/T7lBDqUUKMMoCPy8MPGHvc66YyW1xsf02zdkAHXDzc
|
||||
hj6TrzApvzrUzEcl9rwxzCEtGWh5wjIV1a/sJQIDAQABAoIBAQCzHTD2ISXdOdSD
|
||||
4wOTCPlHiGo8rILlA5oQLFGF+8+wFIzsFudg/ESswuVgTZXKmISamA86mofF0yaE
|
||||
WklMAuxt/Bk5zcan3xy3y8szP47KadsU34ie8tEXsKCM4uH6/sMrc3BIjwF54LC4
|
||||
fVYH+W6R5Va+jBWkn0CXMo/i+cHLFlYV8YScblO+nmhjxI4O9sy8b6grQ1/EMHi8
|
||||
ioOi+4w0VZLD52GVsQ56tAf75EOFAsZgzldMHTNCdvDAy1NeNXgniN6qFv7vrqCf
|
||||
R1DWh4jLyzeLdk6c4zakozSiElnY+PORuzPWu+GABZ6qYMDpDlGAriRG1Y8lG0O4
|
||||
nJK+T4J5AoGBAPx3A8d5MhxXArTl3n2xNdCKDcSZu4MG5BCxmc70yrC4+MUXhMos
|
||||
81vyUtz9s4HRcJlqoI+2tr0JptVaEWjN++VFKYVW4i+nX+YTbqndQ1tgXqXXGuLT
|
||||
g6ffemQtwmKoOmNfq5FXMuCzySG0+YMp+lRuhHaTCDT5mvhFngpkUjWfAoGBAMbG
|
||||
DhT+KcbvJABn1P5/eS2cnDebbcBUEVE0UTF8jWsrGNQdPj6oV2XpjfjlPR5ybRJb
|
||||
eJI8uDdPUUAeyr4TNOwnJvyM7T1sxkm8zmLIUo6vsNXQT/HYyaFFTKftYAA9V3AB
|
||||
37etSALKH4g5UVG6lfZuJlp08wPlGq84zv3/i5+7AoGALFvQ+yxtRJN5M0WsWRNY
|
||||
7EJFdwS38Ka2TcSWzMkwD+sAMskWGNvbCo3CR3gAIVAmY55bhcTJyN84RAZmRq7i
|
||||
kn8bc4U3ir3y2J8Tc58f5Z9CIgtweuhFGqrme1Ga9PCwCaPWplvW4apVLan5qTUn
|
||||
+cvNVHQzHfO5aeP5h8PmuesCgYAzcVR5qGGlg4R8umKMTu9Ml6hyV75qtRcaPgD5
|
||||
XrO21ZuCYeMXEjg0PuKoVKOhuplx08x7hE1kuxlbD90Gni/nIibb25kWeY1DziJX
|
||||
vGJpXRzV6SiXfbSJEUdKeouK5FU5vrJodecaGbdZaQQbs79V3KH+bR/rlSJ30Kr5
|
||||
X2aCOwKBgQCB9Cjp8RPuLEez8ISbsqaar/s1l6XVbPAX77XeVukJjXKXf3SN4Rat
|
||||
Bi/OALSkd9TxcIrqfQ8TJtDicz8CJC379/hhfx9nxN/ZSyAf60qZ4KRc7qEtTTIt
|
||||
GxpdYCz7pAUXR74D5w1T6Ob5TYIyMi2WefdzDx+Io0yZqUjEbqudLw==
|
||||
-----END RSA PRIVATE KEY-----
|
||||
@@ -2,6 +2,7 @@
|
||||
kcp_addr = "127.0.0.1" # 该地址只用来注册到节点服务器 填网关的外网地址 网关本地监听为0.0.0.0
|
||||
kcp_port = 22222
|
||||
client_proto_proxy_enable = false
|
||||
forward_mode_enable = false
|
||||
version = "300,310,320" # 支持的客户端协议版本号 三位数字 多个以逗号分隔 如300,310,320
|
||||
gate_tcp_mq_addr = "127.0.0.1" # 访问网关tcp直连消息队列的地址 填网关的内网地址
|
||||
gate_tcp_mq_port = 33333
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpAIBAAKCAQEAxAde3Gos++LVlw2vvW5OiziD97fVvA3Y6GLY0xMd4d7LpnHr
|
||||
fwuO7+60IZA9zR6QOFkrMrxNMTf2UbEJsnfbnUyhsQJr8bHR6PfUj6d/YUceM8YW
|
||||
cjpCyZGM2mKuVBXYqWO8gU81bwQOKgHSytvIrXtsk+3+g+pfkSKZOakiPzosSXCt
|
||||
GSPrVRJlumCmiXjTiKiwKqR+BBk8tZSuINl+r/aTfgu5xkfcB6YOYIIsNfkhpyZT
|
||||
cO0TNk7A3gRhikySyfxZX/T7lBDqUUKMMoCPy8MPGHvc66YyW1xsf02zdkAHXDzc
|
||||
hj6TrzApvzrUzEcl9rwxzCEtGWh5wjIV1a/sJQIDAQABAoIBAQCzHTD2ISXdOdSD
|
||||
4wOTCPlHiGo8rILlA5oQLFGF+8+wFIzsFudg/ESswuVgTZXKmISamA86mofF0yaE
|
||||
WklMAuxt/Bk5zcan3xy3y8szP47KadsU34ie8tEXsKCM4uH6/sMrc3BIjwF54LC4
|
||||
fVYH+W6R5Va+jBWkn0CXMo/i+cHLFlYV8YScblO+nmhjxI4O9sy8b6grQ1/EMHi8
|
||||
ioOi+4w0VZLD52GVsQ56tAf75EOFAsZgzldMHTNCdvDAy1NeNXgniN6qFv7vrqCf
|
||||
R1DWh4jLyzeLdk6c4zakozSiElnY+PORuzPWu+GABZ6qYMDpDlGAriRG1Y8lG0O4
|
||||
nJK+T4J5AoGBAPx3A8d5MhxXArTl3n2xNdCKDcSZu4MG5BCxmc70yrC4+MUXhMos
|
||||
81vyUtz9s4HRcJlqoI+2tr0JptVaEWjN++VFKYVW4i+nX+YTbqndQ1tgXqXXGuLT
|
||||
g6ffemQtwmKoOmNfq5FXMuCzySG0+YMp+lRuhHaTCDT5mvhFngpkUjWfAoGBAMbG
|
||||
DhT+KcbvJABn1P5/eS2cnDebbcBUEVE0UTF8jWsrGNQdPj6oV2XpjfjlPR5ybRJb
|
||||
eJI8uDdPUUAeyr4TNOwnJvyM7T1sxkm8zmLIUo6vsNXQT/HYyaFFTKftYAA9V3AB
|
||||
37etSALKH4g5UVG6lfZuJlp08wPlGq84zv3/i5+7AoGALFvQ+yxtRJN5M0WsWRNY
|
||||
7EJFdwS38Ka2TcSWzMkwD+sAMskWGNvbCo3CR3gAIVAmY55bhcTJyN84RAZmRq7i
|
||||
kn8bc4U3ir3y2J8Tc58f5Z9CIgtweuhFGqrme1Ga9PCwCaPWplvW4apVLan5qTUn
|
||||
+cvNVHQzHfO5aeP5h8PmuesCgYAzcVR5qGGlg4R8umKMTu9Ml6hyV75qtRcaPgD5
|
||||
XrO21ZuCYeMXEjg0PuKoVKOhuplx08x7hE1kuxlbD90Gni/nIibb25kWeY1DziJX
|
||||
vGJpXRzV6SiXfbSJEUdKeouK5FU5vrJodecaGbdZaQQbs79V3KH+bR/rlSJ30Kr5
|
||||
X2aCOwKBgQCB9Cjp8RPuLEez8ISbsqaar/s1l6XVbPAX77XeVukJjXKXf3SN4Rat
|
||||
Bi/OALSkd9TxcIrqfQ8TJtDicz8CJC379/hhfx9nxN/ZSyAf60qZ4KRc7qEtTTIt
|
||||
GxpdYCz7pAUXR74D5w1T6Ob5TYIyMi2WefdzDx+Io0yZqUjEbqudLw==
|
||||
-----END RSA PRIVATE KEY-----
|
||||
@@ -44,12 +44,15 @@ type Hk4e struct {
|
||||
GameDataConfigPath string `toml:"game_data_config_path"`
|
||||
GachaHistoryServer string `toml:"gacha_history_server"`
|
||||
ClientProtoProxyEnable bool `toml:"client_proto_proxy_enable"`
|
||||
ForwardModeEnable bool `toml:"forward_mode_enable"`
|
||||
Version string `toml:"version"` // 支持的客户端协议版本号 三位数字 多个以逗号分隔 如300,310,320
|
||||
GateTcpMqAddr string `toml:"gate_tcp_mq_addr"` // 访问网关tcp直连消息队列的地址 填网关的内网地址
|
||||
GateTcpMqPort int32 `toml:"gate_tcp_mq_port"`
|
||||
LoginSdkUrl string `toml:"login_sdk_url"` // 网关登录验证token的sdk服务器地址 目前填dispatch的内网地址
|
||||
LoadSceneLuaConfig bool `toml:"load_scene_lua_config"` // 是否加载场景详情LUA配置数据
|
||||
DispatchUrl string `toml:"dispatch_url"` // 二级dispatch地址 将域名改为dispatch的外网地址
|
||||
ForwardRegionUrl string `toml:"forward_region_url"` // 转发的一级dispatch地址
|
||||
ForwardDispatchUrl string `toml:"forward_dispatch_url"` // 转发的二级dispatch地址
|
||||
}
|
||||
|
||||
// Hk4eRobot 原神机器人
|
||||
|
||||
+5
-1
@@ -67,7 +67,7 @@ func NewMessageQueue(serverType string, appId string, discoveryClient *rpc.Disco
|
||||
r.discoveryClient = discoveryClient
|
||||
if serverType == api.GATE {
|
||||
go r.runGateTcpMqServer()
|
||||
} else if serverType == api.GS || serverType == api.ANTICHEAT || serverType == api.PATHFINDING {
|
||||
} else if serverType == api.GS || serverType == api.ANTICHEAT || serverType == api.PATHFINDING || serverType == api.ROBOT {
|
||||
go r.runGateTcpMqClient()
|
||||
}
|
||||
go r.natsMsgRecvHandler()
|
||||
@@ -79,6 +79,7 @@ func (m *MessageQueue) Close() {
|
||||
// 等待所有待发送的消息发送完毕
|
||||
for {
|
||||
if len(m.netMsgInput) == 0 {
|
||||
time.Sleep(time.Millisecond * 100)
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond * 100)
|
||||
@@ -173,6 +174,7 @@ func (m *MessageQueue) sendHandler() {
|
||||
api.GS: make(map[string]*GateTcpMqInst),
|
||||
api.ANTICHEAT: make(map[string]*GateTcpMqInst),
|
||||
api.PATHFINDING: make(map[string]*GateTcpMqInst),
|
||||
api.ROBOT: make(map[string]*GateTcpMqInst),
|
||||
}
|
||||
for {
|
||||
select {
|
||||
@@ -321,6 +323,8 @@ func (m *MessageQueue) gateTcpMqHandshake(conn net.Conn) {
|
||||
inst.serverType = api.ANTICHEAT
|
||||
case api.PATHFINDING:
|
||||
inst.serverType = api.PATHFINDING
|
||||
case api.ROBOT:
|
||||
inst.serverType = api.ROBOT
|
||||
default:
|
||||
logger.Error("invalid server type")
|
||||
return
|
||||
|
||||
+18
-7
@@ -49,13 +49,17 @@ type ConnCtrlMsg struct {
|
||||
}
|
||||
|
||||
const (
|
||||
ServerAppidBindNotify = iota // 玩家连接绑定的各个服务器appid通知
|
||||
ServerUserOnlineStateChangeNotify // 广播玩家上线和离线状态以及所在GS的appid
|
||||
ServerUserGsChangeNotify // 跨服玩家迁移通知
|
||||
ServerUserMpReq // 跨服多人世界相关请求
|
||||
ServerUserMpRsp // 跨服多人世界相关响应
|
||||
ServerChatMsgNotify // 跨服玩家聊天消息通知
|
||||
ServerAddFriendNotify // 跨服添加好友通知
|
||||
ServerAppidBindNotify = iota // 玩家连接绑定的各个服务器appid通知
|
||||
ServerUserOnlineStateChangeNotify // 广播玩家上线和离线状态以及所在GS的appid
|
||||
ServerUserGsChangeNotify // 跨服玩家迁移通知
|
||||
ServerUserMpReq // 跨服多人世界相关请求
|
||||
ServerUserMpRsp // 跨服多人世界相关响应
|
||||
ServerChatMsgNotify // 跨服玩家聊天消息通知
|
||||
ServerAddFriendNotify // 跨服添加好友通知
|
||||
ServerForwardModeClientConnNotify // 转发模式客户端连接通知
|
||||
ServerForwardModeClientCloseNotify // 转发模式客户端断开连接通知
|
||||
ServerForwardModeServerCloseNotify // 转发模式服务器断开连接通知
|
||||
ServerForwardDispatchInfoNotify // 转发模式区服信息通知
|
||||
)
|
||||
|
||||
type ServerMsg struct {
|
||||
@@ -67,6 +71,7 @@ type ServerMsg struct {
|
||||
UserMpInfo *UserMpInfo
|
||||
ChatMsgInfo *ChatMsgInfo
|
||||
AddFriendInfo *AddFriendInfo
|
||||
ForwardDispatchInfo *ForwardDispatchInfo
|
||||
}
|
||||
|
||||
type OriginInfo struct {
|
||||
@@ -112,3 +117,9 @@ type AddFriendInfo struct {
|
||||
TargetUserId uint32
|
||||
ApplyPlayerOnlineInfo *UserBaseInfo
|
||||
}
|
||||
|
||||
type ForwardDispatchInfo struct {
|
||||
GateIp string
|
||||
GatePort uint32
|
||||
DispatchKey []byte
|
||||
}
|
||||
@@ -55,6 +55,26 @@ func (m *MessageQueue) SendToPathfinding(appId string, netMsg *NetMsg) {
|
||||
m.netMsgInput <- netMsg
|
||||
}
|
||||
|
||||
func (m *MessageQueue) SendToRobot(appId string, netMsg *NetMsg) {
|
||||
netMsg.Topic = m.getTopic(api.ROBOT, appId)
|
||||
netMsg.ServerType = api.ROBOT
|
||||
netMsg.AppId = appId
|
||||
originServerType, originServerAppId := m.getOriginServer()
|
||||
netMsg.OriginServerType = originServerType
|
||||
netMsg.OriginServerAppId = originServerAppId
|
||||
m.netMsgInput <- netMsg
|
||||
}
|
||||
|
||||
func (m *MessageQueue) SendToDispatch(appId string, netMsg *NetMsg) {
|
||||
netMsg.Topic = m.getTopic(api.DISPATCH, appId)
|
||||
netMsg.ServerType = api.DISPATCH
|
||||
netMsg.AppId = appId
|
||||
originServerType, originServerAppId := m.getOriginServer()
|
||||
netMsg.OriginServerType = originServerType
|
||||
netMsg.OriginServerAppId = originServerAppId
|
||||
m.netMsgInput <- netMsg
|
||||
}
|
||||
|
||||
func (m *MessageQueue) SendToAll(netMsg *NetMsg) {
|
||||
netMsg.Topic = "ALL_SERVER_HK4E"
|
||||
netMsg.ServerType = "ALL_SERVER_HK4E"
|
||||
|
||||
+2
-24
@@ -1,7 +1,6 @@
|
||||
package region
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"os"
|
||||
|
||||
"hk4e/common/config"
|
||||
@@ -9,8 +8,6 @@ import (
|
||||
"hk4e/pkg/logger"
|
||||
"hk4e/pkg/random"
|
||||
"hk4e/protocol/proto"
|
||||
|
||||
pb "google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func LoadRsaKey() (signRsaKey []byte, encRsaKeyMap map[string][]byte, pwdRsaKey []byte) {
|
||||
@@ -21,7 +18,7 @@ func LoadRsaKey() (signRsaKey []byte, encRsaKeyMap map[string][]byte, pwdRsaKey
|
||||
logger.Error("open region_sign_key.pem error: %v", err)
|
||||
return nil, nil, nil
|
||||
}
|
||||
encKeyIdList := []string{"2", "3", "4", "5"}
|
||||
encKeyIdList := []string{"1", "2", "3", "4", "5"}
|
||||
for _, v := range encKeyIdList {
|
||||
encRsaKeyMap[v], err = os.ReadFile("key/region_enc_key_" + v + ".pem")
|
||||
if err != nil {
|
||||
@@ -82,25 +79,6 @@ func GetRegionCurr(kcpAddr string, kcpPort int32, ec2b *random.Ec2b) *proto.Quer
|
||||
GateserverPort: uint32(kcpPort),
|
||||
SecretKey: dispatchEc2bData,
|
||||
}
|
||||
regionCurr.ClientSecretKey = dispatchEc2bData
|
||||
return regionCurr
|
||||
}
|
||||
|
||||
func GetRegionListBase64(ec2b *random.Ec2b) string {
|
||||
regionList := GetRegionList(ec2b)
|
||||
regionListData, err := pb.Marshal(regionList)
|
||||
if err != nil {
|
||||
logger.Error("pb marshal QueryRegionListHttpRsp error: %v", err)
|
||||
return ""
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(regionListData)
|
||||
}
|
||||
|
||||
func GetRegionCurrBase64(kcpAddr string, kcpPort int32, ec2b *random.Ec2b) string {
|
||||
regionCurr := GetRegionCurr(kcpAddr, kcpPort, ec2b)
|
||||
regionCurrData, err := pb.Marshal(regionCurr)
|
||||
if err != nil {
|
||||
logger.Error("pb marshal QueryCurrRegionHttpRsp error: %v", err)
|
||||
return ""
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(regionCurrData)
|
||||
}
|
||||
+46
-10
@@ -6,33 +6,69 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"hk4e/common/config"
|
||||
"hk4e/common/mq"
|
||||
"hk4e/common/rpc"
|
||||
"hk4e/dispatch/controller"
|
||||
"hk4e/dispatch/dao"
|
||||
"hk4e/node/api"
|
||||
"hk4e/pkg/logger"
|
||||
)
|
||||
|
||||
var APPID string
|
||||
|
||||
func Run(ctx context.Context, configFile string) error {
|
||||
config.InitConfig(configFile)
|
||||
|
||||
logger.InitLogger("dispatch")
|
||||
logger.Warn("dispatch start")
|
||||
defer func() {
|
||||
logger.CloseLogger()
|
||||
}()
|
||||
|
||||
db := dao.NewDao()
|
||||
defer db.CloseDao()
|
||||
|
||||
// natsrpc client
|
||||
discoveryClient, err := rpc.NewDiscoveryClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_ = controller.NewController(db, discoveryClient)
|
||||
// 注册到节点服务器
|
||||
rsp, err := discoveryClient.RegisterServer(context.TODO(), &api.RegisterServerReq{
|
||||
ServerType: api.DISPATCH,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
APPID = rsp.GetAppId()
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Second * 15)
|
||||
for {
|
||||
<-ticker.C
|
||||
_, err := discoveryClient.KeepaliveServer(context.TODO(), &api.KeepaliveServerReq{
|
||||
ServerType: api.DISPATCH,
|
||||
AppId: APPID,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("keepalive error: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
_, _ = discoveryClient.CancelServer(context.TODO(), &api.CancelServerReq{
|
||||
ServerType: api.DISPATCH,
|
||||
AppId: APPID,
|
||||
})
|
||||
}()
|
||||
|
||||
logger.InitLogger("dispatch_" + APPID)
|
||||
logger.Warn("dispatch start, appid: %v", APPID)
|
||||
defer func() {
|
||||
logger.CloseLogger()
|
||||
}()
|
||||
|
||||
messageQueue := mq.NewMessageQueue(api.DISPATCH, APPID, discoveryClient)
|
||||
defer messageQueue.Close()
|
||||
|
||||
db := dao.NewDao()
|
||||
defer db.CloseDao()
|
||||
|
||||
_ = controller.NewController(db, discoveryClient, messageQueue)
|
||||
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strconv"
|
||||
|
||||
"hk4e/common/config"
|
||||
"hk4e/common/mq"
|
||||
"hk4e/common/region"
|
||||
"hk4e/common/rpc"
|
||||
"hk4e/dispatch/dao"
|
||||
@@ -24,9 +25,10 @@ type Controller struct {
|
||||
encRsaKeyMap map[string][]byte
|
||||
pwdRsaKey []byte
|
||||
ec2b *random.Ec2b
|
||||
messageQueue *mq.MessageQueue
|
||||
}
|
||||
|
||||
func NewController(dao *dao.Dao, discovery *rpc.DiscoveryClient) (r *Controller) {
|
||||
func NewController(dao *dao.Dao, discovery *rpc.DiscoveryClient, messageQueue *mq.MessageQueue) (r *Controller) {
|
||||
r = new(Controller)
|
||||
r.dao = dao
|
||||
r.discovery = discovery
|
||||
@@ -42,6 +44,7 @@ func NewController(dao *dao.Dao, discovery *rpc.DiscoveryClient) (r *Controller)
|
||||
return nil
|
||||
}
|
||||
r.ec2b = ec2b
|
||||
r.messageQueue = messageQueue
|
||||
go r.registerRouter()
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -3,19 +3,27 @@ package controller
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"hk4e/common/config"
|
||||
"hk4e/common/mq"
|
||||
"hk4e/common/region"
|
||||
httpapi "hk4e/dispatch/api"
|
||||
"hk4e/node/api"
|
||||
"hk4e/pkg/endec"
|
||||
"hk4e/pkg/httpclient"
|
||||
"hk4e/pkg/logger"
|
||||
"hk4e/pkg/random"
|
||||
"hk4e/protocol/proto"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
pb "google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func (c *Controller) querySecurityFile(context *gin.Context) {
|
||||
@@ -32,7 +40,45 @@ func (c *Controller) querySecurityFile(context *gin.Context) {
|
||||
|
||||
func (c *Controller) queryRegionList(context *gin.Context) {
|
||||
context.Header("Content-type", "text/html; charset=UTF-8")
|
||||
regionListBase64 := region.GetRegionListBase64(c.ec2b)
|
||||
var regionListBase64 = ""
|
||||
if !config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
regionList := region.GetRegionList(c.ec2b)
|
||||
regionListData, err := pb.Marshal(regionList)
|
||||
if err != nil {
|
||||
logger.Error("pb marshal QueryRegionListHttpRsp error: %v", err)
|
||||
_, _ = context.Writer.WriteString("500")
|
||||
return
|
||||
}
|
||||
regionListBase64 = base64.StdEncoding.EncodeToString(regionListData)
|
||||
} else {
|
||||
var err error = nil
|
||||
url := context.Request.RequestURI
|
||||
param := url[strings.Index(url, "?"):]
|
||||
regionListBase64Raw, err := httpclient.GetRaw(config.GetConfig().Hk4e.ForwardRegionUrl + param)
|
||||
if err != nil {
|
||||
_, _ = context.Writer.WriteString("500")
|
||||
return
|
||||
}
|
||||
regionListDataRaw, err := base64.StdEncoding.DecodeString(regionListBase64Raw)
|
||||
if err != nil {
|
||||
_, _ = context.Writer.WriteString("500")
|
||||
return
|
||||
}
|
||||
queryRegionListHttpRsp := new(proto.QueryRegionListHttpRsp)
|
||||
err = pb.Unmarshal(regionListDataRaw, queryRegionListHttpRsp)
|
||||
if err != nil {
|
||||
_, _ = context.Writer.WriteString("500")
|
||||
return
|
||||
}
|
||||
logger.Debug("QueryRegionListHttpRsp: %+v", queryRegionListHttpRsp)
|
||||
queryRegionListHttpRsp.RegionList[0].DispatchUrl = config.GetConfig().Hk4e.DispatchUrl
|
||||
regionListData, err := pb.Marshal(queryRegionListHttpRsp)
|
||||
if err != nil {
|
||||
_, _ = context.Writer.WriteString("500")
|
||||
return
|
||||
}
|
||||
regionListBase64 = base64.StdEncoding.EncodeToString(regionListData)
|
||||
}
|
||||
_, _ = context.Writer.WriteString(regionListBase64)
|
||||
}
|
||||
|
||||
@@ -81,6 +127,13 @@ func (c *Controller) queryCurRegion(context *gin.Context) {
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
keyId := context.Query("key_id")
|
||||
encPubPrivKey, exist := c.encRsaKeyMap[keyId]
|
||||
if !exist {
|
||||
logger.Error("can not found key id: %v", keyId)
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
version, versionStr := c.getClientVersionByName(versionName)
|
||||
if version == 0 {
|
||||
rspError()
|
||||
@@ -94,33 +147,113 @@ func (c *Controller) queryCurRegion(context *gin.Context) {
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
regionCurrBase64 := region.GetRegionCurrBase64(addr.KcpAddr, int32(addr.KcpPort), c.ec2b)
|
||||
var regionCurr *proto.QueryCurrRegionHttpRsp = nil
|
||||
if !config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
regionCurr = region.GetRegionCurr(addr.KcpAddr, int32(addr.KcpPort), c.ec2b)
|
||||
} else {
|
||||
url := context.Request.RequestURI
|
||||
param := url[strings.Index(url, "?"):]
|
||||
regionCurrJson, err := httpclient.GetRaw(config.GetConfig().Hk4e.ForwardDispatchUrl + param)
|
||||
if err != nil {
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
queryCurRegionRspJson := new(httpapi.QueryCurRegionRspJson)
|
||||
err = json.Unmarshal([]byte(regionCurrJson), queryCurRegionRspJson)
|
||||
if err != nil {
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
encryptedRegionInfo, err := base64.StdEncoding.DecodeString(queryCurRegionRspJson.Content)
|
||||
if err != nil {
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
chunkSize := 256
|
||||
regionInfoLength := len(encryptedRegionInfo)
|
||||
numChunks := int(math.Ceil(float64(regionInfoLength) / float64(chunkSize)))
|
||||
regionCurrData := make([]byte, 0)
|
||||
for i := 0; i < numChunks; i++ {
|
||||
from := i * chunkSize
|
||||
to := int(math.Min(float64((i+1)*chunkSize), float64(regionInfoLength)))
|
||||
chunk := encryptedRegionInfo[from:to]
|
||||
privKey, err := endec.RsaParsePrivKey(encPubPrivKey)
|
||||
if err != nil {
|
||||
logger.Error("parse rsa priv key error: %v", err)
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
decrypt, err := endec.RsaDecrypt(chunk, privKey)
|
||||
if err != nil {
|
||||
logger.Error("rsa dec error: %v", err)
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
regionCurrData = append(regionCurrData, decrypt...)
|
||||
}
|
||||
queryCurrRegionHttpRsp := new(proto.QueryCurrRegionHttpRsp)
|
||||
err = pb.Unmarshal(regionCurrData, queryCurrRegionHttpRsp)
|
||||
if err != nil {
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
logger.Debug("QueryCurrRegionHttpRsp: %+v", queryCurrRegionHttpRsp)
|
||||
robotServerAppId, err := c.discovery.GetServerAppId(context, &api.GetServerAppIdReq{
|
||||
ServerType: api.ROBOT,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("get robot server appid error: %v", err)
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
ec2b, err := random.LoadEc2bKey(queryCurrRegionHttpRsp.ClientSecretKey)
|
||||
if err != nil {
|
||||
logger.Error("parse ec2b error: %v", err)
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
c.messageQueue.SendToRobot(robotServerAppId.AppId, &mq.NetMsg{
|
||||
MsgType: mq.MsgTypeServer,
|
||||
EventId: mq.ServerForwardDispatchInfoNotify,
|
||||
ServerMsg: &mq.ServerMsg{
|
||||
ForwardDispatchInfo: &mq.ForwardDispatchInfo{
|
||||
GateIp: queryCurrRegionHttpRsp.RegionInfo.GateserverIp,
|
||||
GatePort: queryCurrRegionHttpRsp.RegionInfo.GateserverPort,
|
||||
DispatchKey: ec2b.XorKey(),
|
||||
},
|
||||
},
|
||||
})
|
||||
regionCurr = queryCurrRegionHttpRsp
|
||||
regionCurr.ClientSecretKey = c.ec2b.Bytes()
|
||||
regionCurr.RegionInfo.GateserverIp = addr.KcpAddr
|
||||
regionCurr.RegionInfo.GateserverPort = addr.KcpPort
|
||||
endec.Xor(regionCurr.RegionCustomConfigEncrypted, ec2b.XorKey())
|
||||
logger.Info("RegionCustomConfigEncrypted: %v", string(regionCurr.RegionCustomConfigEncrypted))
|
||||
endec.Xor(regionCurr.RegionCustomConfigEncrypted, c.ec2b.XorKey())
|
||||
endec.Xor(regionCurr.ClientRegionCustomConfigEncrypted, ec2b.XorKey())
|
||||
logger.Info("ClientRegionCustomConfigEncrypted: %v", string(regionCurr.ClientRegionCustomConfigEncrypted))
|
||||
endec.Xor(regionCurr.ClientRegionCustomConfigEncrypted, c.ec2b.XorKey())
|
||||
}
|
||||
regionCurrData, err := pb.Marshal(regionCurr)
|
||||
if err != nil {
|
||||
logger.Error("pb marshal QueryCurrRegionHttpRsp error: %v", err)
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
if version < 275 {
|
||||
context.Header("Content-type", "text/html; charset=UTF-8")
|
||||
regionCurrBase64 := base64.StdEncoding.EncodeToString(regionCurrData)
|
||||
_, _ = context.Writer.WriteString(regionCurrBase64)
|
||||
return
|
||||
}
|
||||
keyId := context.Query("key_id")
|
||||
encPubPrivKey, exist := c.encRsaKeyMap[keyId]
|
||||
if !exist {
|
||||
logger.Error("can not found key id: %v", keyId)
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
regionInfo, err := base64.StdEncoding.DecodeString(regionCurrBase64)
|
||||
if err != nil {
|
||||
logger.Error("decode region info error: %v", err)
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
chunkSize := 256 - 11
|
||||
regionInfoLength := len(regionInfo)
|
||||
regionInfoLength := len(regionCurrData)
|
||||
numChunks := int(math.Ceil(float64(regionInfoLength) / float64(chunkSize)))
|
||||
encryptedRegionInfo := make([]byte, 0)
|
||||
for i := 0; i < numChunks; i++ {
|
||||
from := i * chunkSize
|
||||
to := int(math.Min(float64((i+1)*chunkSize), float64(regionInfoLength)))
|
||||
chunk := regionInfo[from:to]
|
||||
chunk := regionCurrData[from:to]
|
||||
pubKey, err := endec.RsaParsePubKeyByPrivKey(encPubPrivKey)
|
||||
if err != nil {
|
||||
logger.Error("parse rsa pub key error: %v", err)
|
||||
@@ -158,13 +291,13 @@ func (c *Controller) queryCurRegion(context *gin.Context) {
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
signData, err := endec.RsaSign(regionInfo, signPrivkey)
|
||||
signData, err := endec.RsaSign(regionCurrData, signPrivkey)
|
||||
if err != nil {
|
||||
logger.Error("rsa sign error: %v", err)
|
||||
rspError()
|
||||
return
|
||||
}
|
||||
ok, err := endec.RsaVerify(regionInfo, signData, &signPrivkey.PublicKey)
|
||||
ok, err := endec.RsaVerify(regionCurrData, signData, &signPrivkey.PublicKey)
|
||||
if err != nil {
|
||||
logger.Error("rsa verify error: %v", err)
|
||||
rspError()
|
||||
|
||||
+3
-3
@@ -12,14 +12,14 @@ DropRCEPacket = false
|
||||
;;;;;; 1) replace your own dispatch url;
|
||||
;;;;;; 2) disable the extra log reporters;
|
||||
;;;;;; 3) disable the beta watermark.
|
||||
ConfigChannel = {"ChannelName":"OSRELWin","PreDefines":"GAIA_ADDON_TOOLS;GAIA_MULTI_TERRAINS;CTS_GAIA_RELOCATE;HOTFIX_ENABLE;UNITY_RELEASE_BUILD;AMPLIFY_SHADER_EDITOR;ODIN_INSPECTOR;ODIN_INSPECTOR_3;UNITY_POST_PROCESSING_STACK_V2;PROBUILDER_FBX_ENABLED","DispatchConfigs":[{"DispatchUrls":["https://hk4e.flswld.com/query_region_list"]}],"BaseTextLang":"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15","BaseAudioLang":"Chinese,English(US),Korean,Japanese"}
|
||||
ConfigChannel = {"DispatchConfigs":[{"DispatchUrls":["http://hk4e.flswld.com:8080/query_region_list"]}],"ChannelName":"OSRELWin","PreDefines":"GAIA_ADDON_TOOLS;GAIA_MULTI_TERRAINS;CTS_GAIA_RELOCATE;HOTFIX_ENABLE;UNITY_RELEASE_BUILD;AMPLIFY_SHADER_EDITOR;ODIN_INSPECTOR;ODIN_INSPECTOR_3;UNITY_POST_PROCESSING_STACK_V2;PROBUILDER_FBX_ENABLED","BaseTextLang":"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15","BaseAudioLang":"Chinese,English(US),Korean,Japanese"}
|
||||
;;;;;; here you can customize your own sdk base url:
|
||||
ConfigBaseUrl = https://hk4e.flswld.com
|
||||
ConfigBaseUrl = http://hk4e.flswld.com:8080
|
||||
;;;;;; replace your rsa public key, the default one is from grasscutter.
|
||||
;;;;;; this key is used to 1) verify the signature of the dispatched data, and 2) encrypt your account password.
|
||||
PublicRSAKey = <RSAKeyValue><Modulus>xbbx2m1feHyrQ7jP+8mtDF/pyYLrJWKWAdEv3wZrOtjOZzeLGPzsmkcgncgoRhX4dT+1itSMR9j9m0/OwsH2UoF6U32LxCOQWQD1AMgIZjAkJeJvFTrtn8fMQ1701CkbaLTVIjRMlTw8kNXvNA/A9UatoiDmi4TFG6mrxTKZpIcTInvPEpkK2A7Qsp1E4skFK8jmysy7uRhMaYHtPTsBvxP0zn3lhKB3W+HTqpneewXWHjCDfL7Nbby91jbz5EKPZXWLuhXIvR1Cu4tiruorwXJxmXaP1HQZonytECNU/UOzP6GNLdq0eFDE4b04Wjp396551G99YiFP2nqHVJ5OMQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
|
||||
;;;;;; or, the password encryption key can be set separately.
|
||||
; RSAEncryptKey =
|
||||
RSAEncryptKey = <RSAKeyValue><Modulus>xz5wLxGyXzFMB15kS4jQx9ahXhptFPw+p+wY8xJiZeVbTCgWRYZ8/mirMjKPWgKMIthXv+ollLs3G5wCUvuIi1MWnqjnbz3uS7kd8EMRyhifF7A5B5Ld09aKXqxNa6cPcF98blItAgOWh6qQtIaNMzLJO578VkKIL9RvLqnF5n0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
|
||||
;;;;;; it's not recommended to overwrite the private key, unless you know what you are doing.
|
||||
;;;;;; if you want to use another rsa private key, uncomment the following line and replace it with your own.
|
||||
; PrivateRSAKey =
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ func Run(ctx context.Context, configFile string) error {
|
||||
outputChan := connectManager.GetKcpEventOutputChan()
|
||||
for {
|
||||
kcpEvent := <-outputChan
|
||||
logger.Info("kcpEvent: %v", kcpEvent)
|
||||
logger.Info("kcpEvent: %+v", kcpEvent)
|
||||
}
|
||||
}()
|
||||
|
||||
|
||||
+5
-14
@@ -22,15 +22,6 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// 16-bytes nonce for each packet
|
||||
nonceSize = 16
|
||||
|
||||
// 4-bytes packet checksum
|
||||
crcSize = 4
|
||||
|
||||
// overall crypto header size
|
||||
cryptHeaderSize = nonceSize + crcSize
|
||||
|
||||
// maximum packet size
|
||||
mtuLimit = 1500
|
||||
|
||||
@@ -581,7 +572,7 @@ func (s *UDPSession) GetSRTT() int32 {
|
||||
return s.kcp.rx_srtt
|
||||
}
|
||||
|
||||
// GetRTTVar gets current rtt variance of the session
|
||||
// GetSRTTVar gets current rtt variance of the session
|
||||
func (s *UDPSession) GetSRTTVar() int32 {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
@@ -693,7 +684,7 @@ func (l *Listener) packetInput(data []byte, addr net.Addr, convId uint64) {
|
||||
s.kcpInput(data)
|
||||
} else if sn == 0 { // should replace current connection
|
||||
// 网络切换会话保持改造后 这里的逻辑可能永远也执行不到了
|
||||
s.Close()
|
||||
_ = s.Close()
|
||||
s = nil
|
||||
}
|
||||
}
|
||||
@@ -793,8 +784,8 @@ func (l *Listener) AcceptKCP() (*UDPSession, error) {
|
||||
|
||||
// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
|
||||
func (l *Listener) SetDeadline(t time.Time) error {
|
||||
l.SetReadDeadline(t)
|
||||
l.SetWriteDeadline(t)
|
||||
_ = l.SetReadDeadline(t)
|
||||
_ = l.SetWriteDeadline(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -943,7 +934,7 @@ func NewConn3(convid uint64, raddr net.Addr, conn net.PacketConn) (*UDPSession,
|
||||
// NewConn2 establishes a session and talks KCP protocol over a packet connection.
|
||||
func NewConn2(raddr net.Addr, conn net.PacketConn) (*UDPSession, error) {
|
||||
var convid uint64
|
||||
binary.Read(rand.Reader, binary.LittleEndian, &convid)
|
||||
_ = binary.Read(rand.Reader, binary.LittleEndian, &convid)
|
||||
return NewConn3(convid, raddr, conn)
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ func (s *UDPSession) defaultReadLoop() {
|
||||
continue
|
||||
}
|
||||
if connType == ConnEnetFin {
|
||||
s.Close()
|
||||
_ = s.Close()
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func (s *UDPSession) readLoop() {
|
||||
continue
|
||||
}
|
||||
if connType == ConnEnetFin {
|
||||
s.Close()
|
||||
_ = s.Close()
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -97,13 +96,7 @@ func (k *KcpConnectManager) run() {
|
||||
}
|
||||
regionEc2b := random.NewEc2b()
|
||||
regionEc2b.SetSeed(ec2b.Seed())
|
||||
// 3.7的时候修改了xor 首包无需使用加密密钥
|
||||
if k.getGateMaxVersion() < 370 {
|
||||
k.dispatchKey = regionEc2b.XorKey()
|
||||
} else {
|
||||
// 全部填充为0 不然会出问题
|
||||
k.dispatchKey = make([]byte, 4096)
|
||||
}
|
||||
k.dispatchKey = regionEc2b.XorKey()
|
||||
// kcp
|
||||
port := strconv.Itoa(int(config.GetConfig().Hk4e.KcpPort))
|
||||
listener, err := kcp.ListenWithOptions("0.0.0.0:" + port)
|
||||
@@ -113,7 +106,9 @@ func (k *KcpConnectManager) run() {
|
||||
}
|
||||
go k.enetHandle(listener)
|
||||
go k.eventHandle()
|
||||
go k.sendMsgHandle()
|
||||
if !config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
go k.forwardServerMsgToClientHandle()
|
||||
}
|
||||
go k.acceptHandle(listener)
|
||||
go k.gateNetInfo()
|
||||
k.syncGlobalGsOnlineMap()
|
||||
@@ -124,22 +119,6 @@ func (k *KcpConnectManager) Close() {
|
||||
k.closeAllKcpConn()
|
||||
}
|
||||
|
||||
// getGateMaxVersion 获取gate最大可兼容的版本
|
||||
func (k *KcpConnectManager) getGateMaxVersion() (maxVersion int) {
|
||||
versionSplit := strings.Split(config.GetConfig().Hk4e.Version, ",")
|
||||
for _, verStr := range versionSplit {
|
||||
version, err := strconv.Atoi(verStr)
|
||||
if err != nil {
|
||||
logger.Error("version a to i error: %v", err)
|
||||
return
|
||||
}
|
||||
if version > maxVersion {
|
||||
maxVersion = version
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (k *KcpConnectManager) gateNetInfo() {
|
||||
ticker := time.NewTicker(time.Second * 60)
|
||||
kcpErrorCount := uint64(0)
|
||||
@@ -171,10 +150,17 @@ func (k *KcpConnectManager) acceptHandle(listener *kcp.Listener) {
|
||||
_ = conn.Close()
|
||||
continue
|
||||
}
|
||||
if config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
clientConnNum := atomic.LoadInt32(&CLIENT_CONN_NUM)
|
||||
if clientConnNum != 0 {
|
||||
logger.Error("forward mode only support one client conn now")
|
||||
_ = conn.Close()
|
||||
continue
|
||||
}
|
||||
}
|
||||
conn.SetACKNoDelay(true)
|
||||
conn.SetWriteDelay(false)
|
||||
conn.SetWindowSize(255, 255)
|
||||
atomic.AddInt32(&CLIENT_CONN_NUM, 1)
|
||||
conn.SetWindowSize(256, 256)
|
||||
logger.Info("client connect, convId: %v", convId)
|
||||
kcpRawSendChan := make(chan *ProtoMsg, 1000)
|
||||
session := &Session{
|
||||
@@ -188,16 +174,38 @@ func (k *KcpConnectManager) acceptHandle(listener *kcp.Listener) {
|
||||
gsServerAppId: "",
|
||||
anticheatServerAppId: "",
|
||||
pathfindingServerAppId: "",
|
||||
robotServerAppId: "",
|
||||
useMagicSeed: false,
|
||||
keyId: 0,
|
||||
clientRandKey: "",
|
||||
}
|
||||
if config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
robotServerAppId, err := k.discovery.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
|
||||
ServerType: api.ROBOT,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("get robot server appid error: %v", err)
|
||||
_ = conn.Close()
|
||||
continue
|
||||
}
|
||||
session.robotServerAppId = robotServerAppId.AppId
|
||||
k.messageQueue.SendToRobot(session.robotServerAppId, &mq.NetMsg{
|
||||
MsgType: mq.MsgTypeServer,
|
||||
EventId: mq.ServerForwardModeClientConnNotify,
|
||||
})
|
||||
}
|
||||
go k.recvHandle(session)
|
||||
go k.sendHandle(session)
|
||||
if config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
go k.forwardRobotMsgToClientHandle(session)
|
||||
}
|
||||
// 连接建立成功通知
|
||||
k.kcpEventOutput <- &KcpEvent{
|
||||
ConvId: convId,
|
||||
EventId: KcpConnEstNotify,
|
||||
EventMessage: conn.RemoteAddr().String(),
|
||||
}
|
||||
atomic.AddInt32(&CLIENT_CONN_NUM, 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,7 +310,10 @@ type Session struct {
|
||||
gsServerAppId string
|
||||
anticheatServerAppId string
|
||||
pathfindingServerAppId string
|
||||
robotServerAppId string
|
||||
useMagicSeed bool
|
||||
keyId uint32
|
||||
clientRandKey string
|
||||
}
|
||||
|
||||
// 接收
|
||||
@@ -340,7 +351,11 @@ func (k *KcpConnectManager) recvHandle(session *Session) {
|
||||
for _, v := range kcpMsgList {
|
||||
protoMsgList := ProtoDecode(v, k.serverCmdProtoMap, k.clientCmdProtoMap)
|
||||
for _, vv := range protoMsgList {
|
||||
k.recvMsgHandle(vv, session)
|
||||
if config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
k.forwardClientMsgToRobotHandle(vv, session)
|
||||
} else {
|
||||
k.forwardClientMsgToServerHandle(vv, session)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -433,16 +448,23 @@ func (k *KcpConnectManager) closeKcpConn(session *Session, enetType uint32) {
|
||||
ConvId: convId,
|
||||
EventId: KcpConnCloseNotify,
|
||||
}
|
||||
// 通知GS玩家下线
|
||||
connCtrlMsg := new(mq.ConnCtrlMsg)
|
||||
connCtrlMsg.UserId = session.userId
|
||||
k.messageQueue.SendToGs(session.gsServerAppId, &mq.NetMsg{
|
||||
MsgType: mq.MsgTypeConnCtrl,
|
||||
EventId: mq.UserOfflineNotify,
|
||||
ConnCtrlMsg: connCtrlMsg,
|
||||
})
|
||||
logger.Info("send to gs user offline, ConvId: %v, UserId: %v", convId, connCtrlMsg.UserId)
|
||||
k.destroySessionChan <- session
|
||||
if !config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
// 通知GS玩家下线
|
||||
connCtrlMsg := new(mq.ConnCtrlMsg)
|
||||
connCtrlMsg.UserId = session.userId
|
||||
k.messageQueue.SendToGs(session.gsServerAppId, &mq.NetMsg{
|
||||
MsgType: mq.MsgTypeConnCtrl,
|
||||
EventId: mq.UserOfflineNotify,
|
||||
ConnCtrlMsg: connCtrlMsg,
|
||||
})
|
||||
logger.Info("send to gs user offline, ConvId: %v, UserId: %v", convId, connCtrlMsg.UserId)
|
||||
k.destroySessionChan <- session
|
||||
} else {
|
||||
k.messageQueue.SendToRobot(session.robotServerAppId, &mq.NetMsg{
|
||||
MsgType: mq.MsgTypeServer,
|
||||
EventId: mq.ServerForwardModeClientCloseNotify,
|
||||
})
|
||||
}
|
||||
atomic.AddInt32(&CLIENT_CONN_NUM, -1)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package net
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
|
||||
"hk4e/pkg/endec"
|
||||
"hk4e/pkg/logger"
|
||||
)
|
||||
|
||||
@@ -92,7 +92,7 @@ func ProtoDecode(kcpMsg *KcpMsg,
|
||||
logger.Error("decode proto object is nil")
|
||||
return protoMsgList
|
||||
}
|
||||
if kcpMsg.CmdId == cmd.UnionCmdNotify {
|
||||
if kcpMsg.CmdId == cmd.UnionCmdNotify && !config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
for _, protoMessage := range protoMessageList {
|
||||
msg := new(ProtoMsg)
|
||||
msg.ConvId = kcpMsg.ConvId
|
||||
@@ -129,7 +129,7 @@ func ProtoDecodePayloadLoop(cmdId uint16, protoData []byte, protoMessageList *[]
|
||||
logger.Error("decode proto object is nil")
|
||||
return
|
||||
}
|
||||
if cmdId == cmd.UnionCmdNotify {
|
||||
if cmdId == cmd.UnionCmdNotify && !config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
// 处理聚合消息
|
||||
unionCmdNotify, ok := protoObj.(*proto.UnionCmdNotify)
|
||||
if !ok {
|
||||
|
||||
+229
-102
@@ -6,7 +6,6 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
@@ -34,37 +33,36 @@ const (
|
||||
ConnClose
|
||||
)
|
||||
|
||||
// 发送消息到GS
|
||||
func (k *KcpConnectManager) recvMsgHandle(protoMsg *ProtoMsg, session *Session) {
|
||||
userId := session.userId
|
||||
connState := session.connState
|
||||
// 转发客户端消息到其他服务器 每个连接独立协程
|
||||
func (k *KcpConnectManager) forwardClientMsgToServerHandle(protoMsg *ProtoMsg, session *Session) {
|
||||
if protoMsg.HeadMessage == nil {
|
||||
logger.Error("recv null head msg: %v", protoMsg)
|
||||
return
|
||||
}
|
||||
// 网关服务器本地处理的请求
|
||||
switch protoMsg.CmdId {
|
||||
case cmd.GetPlayerTokenReq:
|
||||
// GATE登录包
|
||||
if connState != ConnEst {
|
||||
if session.connState != ConnEst {
|
||||
return
|
||||
}
|
||||
session.connState = ConnWaitLogin
|
||||
getPlayerTokenReq := protoMsg.PayloadMessage.(*proto.GetPlayerTokenReq)
|
||||
getPlayerTokenRsp := k.getPlayerToken(getPlayerTokenReq, session)
|
||||
if getPlayerTokenRsp == nil {
|
||||
req := protoMsg.PayloadMessage.(*proto.GetPlayerTokenReq)
|
||||
rsp := k.doGateLogin(req, session)
|
||||
if rsp == nil {
|
||||
return
|
||||
}
|
||||
// 返回数据到客户端
|
||||
rsp := &ProtoMsg{
|
||||
msg := &ProtoMsg{
|
||||
ConvId: protoMsg.ConvId,
|
||||
CmdId: cmd.GetPlayerTokenRsp,
|
||||
HeadMessage: k.getHeadMsg(protoMsg.HeadMessage.ClientSequenceId),
|
||||
PayloadMessage: getPlayerTokenRsp,
|
||||
PayloadMessage: rsp,
|
||||
}
|
||||
session.kcpRawSendChan <- rsp
|
||||
session.kcpRawSendChan <- msg
|
||||
case cmd.PlayerForceExitReq:
|
||||
// 退出游戏
|
||||
if connState != ConnActive {
|
||||
if session.connState != ConnActive {
|
||||
return
|
||||
}
|
||||
k.kcpEventInput <- &KcpEvent{
|
||||
@@ -79,22 +77,22 @@ func (k *KcpConnectManager) recvMsgHandle(protoMsg *ProtoMsg, session *Session)
|
||||
// 返回数据到客户端
|
||||
pingRsp := new(proto.PingRsp)
|
||||
pingRsp.ClientTime = pingReq.ClientTime
|
||||
rsp := &ProtoMsg{
|
||||
msg := &ProtoMsg{
|
||||
ConvId: protoMsg.ConvId,
|
||||
CmdId: cmd.PingRsp,
|
||||
HeadMessage: k.getHeadMsg(protoMsg.HeadMessage.ClientSequenceId),
|
||||
PayloadMessage: pingRsp,
|
||||
}
|
||||
session.kcpRawSendChan <- rsp
|
||||
session.kcpRawSendChan <- msg
|
||||
logger.Debug("convId: %v, RTO: %v, SRTT: %v, RTTVar: %v",
|
||||
protoMsg.ConvId, session.conn.GetRTO(), session.conn.GetSRTT(), session.conn.GetSRTTVar())
|
||||
if connState != ConnActive {
|
||||
if session.connState != ConnActive {
|
||||
return
|
||||
}
|
||||
// 通知GS玩家客户端往返时延
|
||||
rtt := session.conn.GetSRTT()
|
||||
connCtrlMsg := &mq.ConnCtrlMsg{
|
||||
UserId: userId,
|
||||
UserId: session.userId,
|
||||
ClientRtt: uint32(rtt),
|
||||
ClientTime: 0,
|
||||
}
|
||||
@@ -105,7 +103,7 @@ func (k *KcpConnectManager) recvMsgHandle(protoMsg *ProtoMsg, session *Session)
|
||||
})
|
||||
// 通知GS玩家客户端的本地时钟
|
||||
connCtrlMsg = &mq.ConnCtrlMsg{
|
||||
UserId: userId,
|
||||
UserId: session.userId,
|
||||
ClientTime: pingReq.ClientTime,
|
||||
}
|
||||
k.messageQueue.SendToGs(session.gsServerAppId, &mq.NetMsg{
|
||||
@@ -115,14 +113,14 @@ func (k *KcpConnectManager) recvMsgHandle(protoMsg *ProtoMsg, session *Session)
|
||||
})
|
||||
case cmd.PlayerLoginReq:
|
||||
// GS登录包
|
||||
if connState != ConnWaitLogin {
|
||||
if session.connState != ConnWaitLogin {
|
||||
return
|
||||
}
|
||||
playerLoginReq := protoMsg.PayloadMessage.(*proto.PlayerLoginReq)
|
||||
playerLoginReq.TargetUid = 0
|
||||
playerLoginReq.TargetHomeOwnerUid = 0
|
||||
gameMsg := &mq.GameMsg{
|
||||
UserId: userId,
|
||||
UserId: session.userId,
|
||||
CmdId: protoMsg.CmdId,
|
||||
ClientSeq: protoMsg.HeadMessage.ClientSequenceId,
|
||||
PayloadMessage: playerLoginReq,
|
||||
@@ -134,12 +132,12 @@ func (k *KcpConnectManager) recvMsgHandle(protoMsg *ProtoMsg, session *Session)
|
||||
GameMsg: gameMsg,
|
||||
})
|
||||
default:
|
||||
if connState != ConnActive {
|
||||
logger.Error("conn not active so drop packet, cmdId: %v, userId: %v, convId: %v", protoMsg.CmdId, userId, protoMsg.ConvId)
|
||||
if session.connState != ConnActive {
|
||||
logger.Error("conn not active so drop packet, cmdId: %v, userId: %v, convId: %v", protoMsg.CmdId, session.userId, protoMsg.ConvId)
|
||||
return
|
||||
}
|
||||
gameMsg := &mq.GameMsg{
|
||||
UserId: userId,
|
||||
UserId: session.userId,
|
||||
CmdId: protoMsg.CmdId,
|
||||
ClientSeq: protoMsg.HeadMessage.ClientSequenceId,
|
||||
PayloadMessageData: nil,
|
||||
@@ -184,9 +182,9 @@ func (k *KcpConnectManager) recvMsgHandle(protoMsg *ProtoMsg, session *Session)
|
||||
}
|
||||
}
|
||||
|
||||
// 接收来自其他服务器的消息
|
||||
func (k *KcpConnectManager) sendMsgHandle() {
|
||||
logger.Debug("send msg handle start")
|
||||
// 转发其他服务器的消息到客户端 所有连接共享一个协程
|
||||
func (k *KcpConnectManager) forwardServerMsgToClientHandle() {
|
||||
logger.Debug("server msg forward handle start")
|
||||
// 函数栈内缓存 添加删除事件走chan 避免频繁加锁
|
||||
convSessionMap := make(map[uint64]*Session)
|
||||
userIdConvMap := make(map[uint32]uint64)
|
||||
@@ -325,8 +323,121 @@ func (k *KcpConnectManager) sendMsgHandle() {
|
||||
}
|
||||
}
|
||||
|
||||
func (k *KcpConnectManager) getHeadMsg(clientSeq uint32) (headMsg *proto.PacketHead) {
|
||||
headMsg = new(proto.PacketHead)
|
||||
// 转发客户端消息到robot
|
||||
func (k *KcpConnectManager) forwardClientMsgToRobotHandle(protoMsg *ProtoMsg, session *Session) {
|
||||
if protoMsg.HeadMessage == nil {
|
||||
logger.Error("recv null head msg: %v", protoMsg)
|
||||
return
|
||||
}
|
||||
// 网关服务器本地处理的请求
|
||||
switch protoMsg.CmdId {
|
||||
case cmd.GetPlayerTokenReq:
|
||||
// GATE登录包
|
||||
if session.connState != ConnEst {
|
||||
return
|
||||
}
|
||||
session.connState = ConnWaitLogin
|
||||
req := protoMsg.PayloadMessage.(*proto.GetPlayerTokenReq)
|
||||
session.keyId = req.KeyId
|
||||
session.clientRandKey = req.ClientRandKey
|
||||
case cmd.PlayerForceExitReq:
|
||||
// 退出游戏
|
||||
if session.connState != ConnActive {
|
||||
return
|
||||
}
|
||||
case cmd.PlayerLoginReq:
|
||||
// GS登录包
|
||||
if session.connState != ConnWaitLogin {
|
||||
return
|
||||
}
|
||||
}
|
||||
gameMsg := &mq.GameMsg{
|
||||
UserId: session.userId,
|
||||
CmdId: protoMsg.CmdId,
|
||||
ClientSeq: protoMsg.HeadMessage.ClientSequenceId,
|
||||
PayloadMessageData: nil,
|
||||
}
|
||||
// 在这里直接序列化成二进制数据 终结PayloadMessage的生命周期并回收进缓存池
|
||||
payloadMessageData, err := pb.Marshal(protoMsg.PayloadMessage)
|
||||
if err != nil {
|
||||
logger.Error("parse payload msg to bin error: %v, stack: %v", err, logger.Stack())
|
||||
return
|
||||
}
|
||||
k.serverCmdProtoMap.PutProtoObjCache(protoMsg.CmdId, protoMsg.PayloadMessage)
|
||||
gameMsg.PayloadMessageData = payloadMessageData
|
||||
// 转发到Robot
|
||||
k.messageQueue.SendToRobot(session.robotServerAppId, &mq.NetMsg{
|
||||
MsgType: mq.MsgTypeGame,
|
||||
EventId: mq.NormalMsg,
|
||||
GameMsg: gameMsg,
|
||||
})
|
||||
}
|
||||
|
||||
// 转发robot的消息到客户端
|
||||
func (k *KcpConnectManager) forwardRobotMsgToClientHandle(session *Session) {
|
||||
logger.Debug("robot msg forward handle start")
|
||||
ticker := time.NewTicker(time.Second)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if session.connState == ConnClose {
|
||||
logger.Debug("robot msg forward handle stop")
|
||||
return
|
||||
}
|
||||
case netMsg := <-k.messageQueue.GetNetMsg():
|
||||
if netMsg.OriginServerType != api.ROBOT {
|
||||
continue
|
||||
}
|
||||
switch netMsg.MsgType {
|
||||
case mq.MsgTypeGame:
|
||||
gameMsg := netMsg.GameMsg
|
||||
switch netMsg.EventId {
|
||||
case mq.NormalMsg:
|
||||
switch gameMsg.CmdId {
|
||||
case cmd.GetPlayerTokenRsp:
|
||||
rsp := gameMsg.PayloadMessage.(*proto.GetPlayerTokenRsp)
|
||||
ok := k.keyExchange(session, rsp.Uid, rsp)
|
||||
if !ok {
|
||||
logger.Error("key exchange error, uid: %v", rsp.Uid)
|
||||
continue
|
||||
}
|
||||
// 关联玩家uid和连接信息
|
||||
session.userId = rsp.Uid
|
||||
k.SetSession(session, session.conn.GetConv(), session.userId)
|
||||
gameMsg.PayloadMessage = rsp
|
||||
case cmd.PlayerLoginRsp:
|
||||
logger.Debug("session active, uid: %v", gameMsg.UserId)
|
||||
session.connState = ConnActive
|
||||
}
|
||||
protoMsg := &ProtoMsg{
|
||||
ConvId: session.conn.GetConv(),
|
||||
CmdId: gameMsg.CmdId,
|
||||
HeadMessage: k.getHeadMsg(gameMsg.ClientSeq),
|
||||
PayloadMessage: gameMsg.PayloadMessage,
|
||||
}
|
||||
kcpRawSendChan := session.kcpRawSendChan
|
||||
if kcpRawSendChan == nil {
|
||||
logger.Error("kcpRawSendChan is nil, convId: %v", protoMsg.ConvId)
|
||||
continue
|
||||
}
|
||||
if len(kcpRawSendChan) == 1000 {
|
||||
logger.Error("kcpRawSendChan is full, convId: %v", protoMsg.ConvId)
|
||||
continue
|
||||
}
|
||||
kcpRawSendChan <- protoMsg
|
||||
}
|
||||
case mq.MsgTypeServer:
|
||||
switch netMsg.EventId {
|
||||
case mq.ServerForwardModeServerCloseNotify:
|
||||
_ = session.conn.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (k *KcpConnectManager) getHeadMsg(clientSeq uint32) *proto.PacketHead {
|
||||
headMsg := new(proto.PacketHead)
|
||||
if clientSeq != 0 {
|
||||
headMsg.ClientSequenceId = clientSeq
|
||||
headMsg.SentMs = uint64(time.Now().UnixMilli())
|
||||
@@ -340,14 +451,29 @@ type RemoteKick struct {
|
||||
kickFinishNotifyChan chan bool
|
||||
}
|
||||
|
||||
func (k *KcpConnectManager) getPlayerToken(req *proto.GetPlayerTokenReq, session *Session) *proto.GetPlayerTokenRsp {
|
||||
loginFailClose := func() {
|
||||
k.kcpEventInput <- &KcpEvent{
|
||||
ConvId: session.conn.GetConv(),
|
||||
EventId: KcpConnForceClose,
|
||||
EventMessage: uint32(kcp.EnetLoginUnfinished),
|
||||
func (k *KcpConnectManager) loginFailClose(session *Session) {
|
||||
k.kcpEventInput <- &KcpEvent{
|
||||
ConvId: session.conn.GetConv(),
|
||||
EventId: KcpConnForceClose,
|
||||
EventMessage: uint32(kcp.EnetLoginUnfinished),
|
||||
}
|
||||
}
|
||||
|
||||
func (k *KcpConnectManager) loginFailRsp(uid uint32, retCode proto.Retcode, isForbid bool, forbidEndTime uint32) *proto.GetPlayerTokenRsp {
|
||||
rsp := new(proto.GetPlayerTokenRsp)
|
||||
rsp.Uid = uid
|
||||
rsp.Retcode = int32(retCode)
|
||||
if isForbid {
|
||||
rsp.Msg = "FORBID_CHEATING_PLUGINS"
|
||||
rsp.BlackUidEndTime = forbidEndTime
|
||||
if rsp.BlackUidEndTime == 0 {
|
||||
rsp.BlackUidEndTime = 2051193600 // 2035-01-01 00:00:00
|
||||
}
|
||||
}
|
||||
return rsp
|
||||
}
|
||||
|
||||
func (k *KcpConnectManager) doGateLogin(req *proto.GetPlayerTokenReq, session *Session) *proto.GetPlayerTokenRsp {
|
||||
tokenVerifyRsp, err := httpclient.PostJson[controller.TokenVerifyRsp](
|
||||
config.GetConfig().Hk4e.LoginSdkUrl+"/gate/token/verify",
|
||||
&controller.TokenVerifyReq{
|
||||
@@ -356,42 +482,23 @@ func (k *KcpConnectManager) getPlayerToken(req *proto.GetPlayerTokenReq, session
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("verify token error: %v, account uid: %v", err, req.AccountUid)
|
||||
loginFailClose()
|
||||
k.loginFailClose(session)
|
||||
return nil
|
||||
}
|
||||
uid := tokenVerifyRsp.PlayerID
|
||||
loginFailRsp := func(retCode int32, isForbid bool, forbidEndTime uint32) *proto.GetPlayerTokenRsp {
|
||||
rsp := new(proto.GetPlayerTokenRsp)
|
||||
rsp.Uid = uid
|
||||
rsp.IsProficientPlayer = true
|
||||
rsp.Retcode = retCode
|
||||
if isForbid {
|
||||
rsp.Msg = "FORBID_CHEATING_PLUGINS"
|
||||
rsp.BlackUidEndTime = forbidEndTime
|
||||
if rsp.BlackUidEndTime == 0 {
|
||||
rsp.BlackUidEndTime = 2051193600 // 2035-01-01 00:00:00
|
||||
}
|
||||
}
|
||||
rsp.RegPlatform = 3
|
||||
rsp.CountryCode = "US"
|
||||
addr := session.conn.RemoteAddr().String()
|
||||
split := strings.Split(addr, ":")
|
||||
rsp.ClientIpStr = split[0]
|
||||
return rsp
|
||||
}
|
||||
if !tokenVerifyRsp.Valid {
|
||||
logger.Error("token error, uid: %v", uid)
|
||||
return loginFailRsp(int32(proto.Retcode_RET_TOKEN_ERROR), false, 0)
|
||||
return k.loginFailRsp(uid, proto.Retcode_RET_TOKEN_ERROR, false, 0)
|
||||
}
|
||||
// comboToken验证成功
|
||||
if tokenVerifyRsp.Forbid {
|
||||
// 封号通知
|
||||
return loginFailRsp(int32(proto.Retcode_RET_BLACK_UID), true, tokenVerifyRsp.ForbidEndTime)
|
||||
return k.loginFailRsp(uid, proto.Retcode_RET_BLACK_UID, true, tokenVerifyRsp.ForbidEndTime)
|
||||
}
|
||||
clientConnNum := atomic.LoadInt32(&CLIENT_CONN_NUM)
|
||||
if clientConnNum > MaxClientConnNumLimit {
|
||||
logger.Error("gate conn num limit, uid: %v", uid)
|
||||
return loginFailRsp(int32(proto.Retcode_RET_MAX_PLAYER), false, 0)
|
||||
return k.loginFailRsp(uid, proto.Retcode_RET_MAX_PLAYER, false, 0)
|
||||
}
|
||||
k.globalGsOnlineMapLock.RLock()
|
||||
_, exist := k.globalGsOnlineMap[uid]
|
||||
@@ -412,7 +519,7 @@ func (k *KcpConnectManager) getPlayerToken(req *proto.GetPlayerTokenReq, session
|
||||
case <-timer.C:
|
||||
logger.Error("global interrupt login reg wait timeout, uid: %v", uid)
|
||||
timer.Stop()
|
||||
loginFailClose()
|
||||
k.loginFailClose(session)
|
||||
return nil
|
||||
case <-regFinishNotifyChan:
|
||||
timer.Stop()
|
||||
@@ -442,7 +549,7 @@ func (k *KcpConnectManager) getPlayerToken(req *proto.GetPlayerTokenReq, session
|
||||
case <-timer.C:
|
||||
logger.Error("global interrupt login kick wait timeout, uid: %v", uid)
|
||||
timer.Stop()
|
||||
loginFailClose()
|
||||
k.loginFailClose(session)
|
||||
return nil
|
||||
case <-kickFinishNotifyChan:
|
||||
timer.Stop()
|
||||
@@ -458,7 +565,7 @@ func (k *KcpConnectManager) getPlayerToken(req *proto.GetPlayerTokenReq, session
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("get gs server appid error: %v, uid: %v", err, uid)
|
||||
loginFailClose()
|
||||
k.loginFailClose(session)
|
||||
return nil
|
||||
}
|
||||
session.gsServerAppId = gsServerAppId.AppId
|
||||
@@ -479,97 +586,117 @@ func (k *KcpConnectManager) getPlayerToken(req *proto.GetPlayerTokenReq, session
|
||||
logger.Debug("session gs appid: %v, uid: %v", session.gsServerAppId, uid)
|
||||
logger.Debug("session anticheat appid: %v, uid: %v", session.anticheatServerAppId, uid)
|
||||
logger.Debug("session pathfinding appid: %v, uid: %v", session.pathfindingServerAppId, uid)
|
||||
// 返回响应
|
||||
rsp := new(proto.GetPlayerTokenRsp)
|
||||
rsp.Uid = uid
|
||||
rsp.AccountUid = req.AccountUid
|
||||
rsp.Token = req.AccountToken
|
||||
data := make([]byte, 16+32)
|
||||
rand.Read(data)
|
||||
rsp.SecurityCmdBuffer = data[16:]
|
||||
rsp.ClientVersionRandomKey = fmt.Sprintf("%03x-%012x", data[:3], data[4:16])
|
||||
rsp.AccountType = 1
|
||||
rsp.IsProficientPlayer = true
|
||||
rsp.PlatformType = 3
|
||||
rsp.ChannelId = 1
|
||||
rsp.SubChannelId = 1
|
||||
rsp.RegPlatform = 2
|
||||
rsp.Birthday = "2000-01-01"
|
||||
// 构造响应
|
||||
rsp := k.buildGateLoginRsp(session, uid, req.AccountUid, req.AccountToken)
|
||||
// 密钥交换
|
||||
session.keyId = req.KeyId
|
||||
session.clientRandKey = req.ClientRandKey
|
||||
ok := k.keyExchange(session, uid, rsp)
|
||||
if !ok {
|
||||
logger.Error("key exchange error, uid: %v", uid)
|
||||
return nil
|
||||
}
|
||||
return rsp
|
||||
}
|
||||
|
||||
func (k *KcpConnectManager) buildGateLoginRsp(session *Session, uid uint32, accountUid string, token string) *proto.GetPlayerTokenRsp {
|
||||
addr := session.conn.RemoteAddr().String()
|
||||
split := strings.Split(addr, ":")
|
||||
rsp.ClientIpStr = split[0]
|
||||
addrSplit := strings.Split(addr, ":")
|
||||
rsp := &proto.GetPlayerTokenRsp{
|
||||
Uid: uid,
|
||||
AccountUid: accountUid,
|
||||
Token: token,
|
||||
AccountType: 1,
|
||||
ChannelId: 1,
|
||||
SubChannelId: 1,
|
||||
PlatformType: 3,
|
||||
RegPlatform: 3,
|
||||
IsProficientPlayer: false,
|
||||
CountryCode: "US",
|
||||
Birthday: "2000-01-01",
|
||||
ClientIpStr: addrSplit[0],
|
||||
SecurityCmdBuffer: random.GetRandomByte(32),
|
||||
ClientVersionRandomKey: fmt.Sprintf("%03x-%012x", random.GetRandomByte(3), random.GetRandomByte(12)),
|
||||
}
|
||||
return rsp
|
||||
}
|
||||
|
||||
func (k *KcpConnectManager) keyExchange(session *Session, uid uint32, rsp *proto.GetPlayerTokenRsp) bool {
|
||||
timeRand := random.GetTimeRand()
|
||||
serverSeedUint64 := timeRand.Uint64()
|
||||
session.seed = serverSeedUint64
|
||||
if req.KeyId != 0 {
|
||||
if session.keyId != 0 {
|
||||
session.useMagicSeed = true
|
||||
keyId := strconv.Itoa(int(req.KeyId))
|
||||
keyId := strconv.Itoa(int(session.keyId))
|
||||
encPubPrivKey, exist := k.encRsaKeyMap[keyId]
|
||||
if !exist {
|
||||
logger.Error("can not found key id: %v, uid: %v", keyId, uid)
|
||||
loginFailClose()
|
||||
return nil
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
pubKey, err := endec.RsaParsePubKeyByPrivKey(encPubPrivKey)
|
||||
if err != nil {
|
||||
logger.Error("parse rsa pub key error: %v, uid: %v", err, uid)
|
||||
loginFailClose()
|
||||
return nil
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
signPrivkey, err := endec.RsaParsePrivKey(k.signRsaKey)
|
||||
if err != nil {
|
||||
logger.Error("parse rsa priv key error: %v, uid: %v", err, uid)
|
||||
loginFailClose()
|
||||
return nil
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
clientSeedBase64 := req.ClientRandKey
|
||||
clientSeedBase64 := session.clientRandKey
|
||||
clientSeedEnc, err := base64.StdEncoding.DecodeString(clientSeedBase64)
|
||||
if err != nil {
|
||||
logger.Error("parse client seed base64 error: %v, uid: %v", err, uid)
|
||||
loginFailClose()
|
||||
return nil
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
clientSeed, err := endec.RsaDecrypt(clientSeedEnc, signPrivkey)
|
||||
if err != nil {
|
||||
logger.Error("rsa dec error: %v, uid: %v", err, uid)
|
||||
loginFailClose()
|
||||
return nil
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
clientSeedUint64 := uint64(0)
|
||||
err = binary.Read(bytes.NewReader(clientSeed), binary.BigEndian, &clientSeedUint64)
|
||||
if err != nil {
|
||||
logger.Error("parse client seed to uint64 error: %v, uid: %v", err, uid)
|
||||
loginFailClose()
|
||||
return nil
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
logger.Debug("clientSeed: %v, clientSeedUint64: %v", clientSeed, clientSeedUint64)
|
||||
logger.Debug("serverSeedUint64: %v", serverSeedUint64)
|
||||
seedUint64 := serverSeedUint64 ^ clientSeedUint64
|
||||
seedBuf := new(bytes.Buffer)
|
||||
err = binary.Write(seedBuf, binary.BigEndian, seedUint64)
|
||||
if err != nil {
|
||||
logger.Error("conv seed uint64 to bytes error: %v, uid: %v", err, uid)
|
||||
loginFailClose()
|
||||
return nil
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
seed := seedBuf.Bytes()
|
||||
logger.Debug("seed: %v, seedUint64: %v", seed, seedUint64)
|
||||
seedEnc, err := endec.RsaEncrypt(seed, pubKey)
|
||||
if err != nil {
|
||||
logger.Error("rsa enc error: %v, uid: %v", err, uid)
|
||||
loginFailClose()
|
||||
return nil
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
seedSign, err := endec.RsaSign(seed, signPrivkey)
|
||||
if err != nil {
|
||||
logger.Error("rsa sign error: %v, uid: %v", err, uid)
|
||||
loginFailClose()
|
||||
return nil
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
rsp.KeyId = req.KeyId
|
||||
rsp.KeyId = session.keyId
|
||||
rsp.ServerRandKey = base64.StdEncoding.EncodeToString(seedEnc)
|
||||
rsp.Sign = base64.StdEncoding.EncodeToString(seedSign)
|
||||
} else {
|
||||
session.useMagicSeed = false
|
||||
rsp.SecretKeySeed = serverSeedUint64
|
||||
rsp.SecretKey = fmt.Sprintf("%03x-%012x", data[:3], data[4:16])
|
||||
rsp.SecretKey = fmt.Sprintf("%03x-%012x", random.GetRandomByte(3), random.GetRandomByte(12))
|
||||
}
|
||||
return rsp
|
||||
return true
|
||||
}
|
||||
@@ -6,4 +6,6 @@ const (
|
||||
ANTICHEAT = "ANTICHEAT"
|
||||
PATHFINDING = "PATHFINDING"
|
||||
NODE = "NODE"
|
||||
ROBOT = "ROBOT"
|
||||
DISPATCH = "DISPATCH"
|
||||
)
|
||||
@@ -66,6 +66,8 @@ func NewDiscoveryService() *DiscoveryService {
|
||||
r.serverInstanceMap[api.GS] = new(sync.Map)
|
||||
r.serverInstanceMap[api.ANTICHEAT] = new(sync.Map)
|
||||
r.serverInstanceMap[api.PATHFINDING] = new(sync.Map)
|
||||
r.serverInstanceMap[api.ROBOT] = new(sync.Map)
|
||||
r.serverInstanceMap[api.DISPATCH] = new(sync.Map)
|
||||
r.serverAppIdMap = new(sync.Map)
|
||||
r.globalGsOnlineMap = make(map[uint32]string)
|
||||
go r.removeDeadServer()
|
||||
|
||||
@@ -79,6 +79,7 @@ func CloseLogger() {
|
||||
// 等待所有日志打印完毕
|
||||
for {
|
||||
if len(LOG.LogInfoChan) == 0 {
|
||||
time.Sleep(time.Millisecond * 100)
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond * 100)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -4,6 +4,7 @@ import (
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"hk4e/common/config"
|
||||
"hk4e/pkg/logger"
|
||||
"hk4e/protocol/proto"
|
||||
|
||||
@@ -29,11 +30,15 @@ func NewCmdProtoMap() (r *CmdProtoMap) {
|
||||
r.cmdNameCmdIdMap = make(map[string]uint16)
|
||||
r.cmdIdProtoObjCacheMap = make(map[uint16]*sync.Pool)
|
||||
r.cmdIdProtoObjFastNewMap = make(map[uint16]func() any)
|
||||
r.registerAllMessage()
|
||||
if !config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
r.registerMessage()
|
||||
} else {
|
||||
r.registerAllMessage()
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (c *CmdProtoMap) registerAllMessage() {
|
||||
func (c *CmdProtoMap) registerMessage() {
|
||||
// 登录
|
||||
c.regMsg(DoSetPlayerBornDataNotify, func() any { return new(proto.DoSetPlayerBornDataNotify) }) // 注册账号通知 新号播放开场动画
|
||||
c.regMsg(SetPlayerBornDataReq, func() any { return new(proto.SetPlayerBornDataReq) }) // 注册账号请求
|
||||
|
||||
@@ -43,6 +43,8 @@ message GetPlayerTokenReq {
|
||||
string country_code = 5;
|
||||
uint32 lang = 892;
|
||||
string psn_id = 13;
|
||||
string gate_ticket = 9998;
|
||||
uint32 un_x = 9999;
|
||||
}
|
||||
|
||||
message GetPlayerTokenRsp {
|
||||
|
||||
@@ -1200,6 +1200,7 @@ message QueryCurrRegionHttpRsp {
|
||||
bytes client_secret_key = 11;
|
||||
bytes region_custom_config_encrypted = 12;
|
||||
bytes client_region_custom_config_encrypted = 13;
|
||||
string gate_ticket = 14;
|
||||
oneof detail {
|
||||
ForceUpdateInfo force_udpate = 4;
|
||||
StopServerInfo stop_server = 5;
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"hk4e/common/config"
|
||||
hk4egatenet "hk4e/gate/net"
|
||||
"hk4e/pkg/logger"
|
||||
"hk4e/pkg/object"
|
||||
"hk4e/pkg/random"
|
||||
"hk4e/protocol/cmd"
|
||||
"hk4e/protocol/proto"
|
||||
"hk4e/robot/net"
|
||||
|
||||
pb "google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func Logic(account string, session *net.Session) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
tickCounter := uint64(0)
|
||||
pingSeq := uint32(0)
|
||||
enterSceneDone := false
|
||||
sceneBeginTime := uint32(0)
|
||||
bornPos := new(proto.Vector)
|
||||
currPos := new(proto.Vector)
|
||||
avatarEntityId := uint32(0)
|
||||
moveRot := random.GetRandomFloat32(0.0, 359.9)
|
||||
moveReliableSeq := uint32(0)
|
||||
for {
|
||||
select {
|
||||
case protoMsg := <-session.RecvChan:
|
||||
// 从这个管道接收服务器发来的消息
|
||||
switch protoMsg.CmdId {
|
||||
case cmd.PlayerLoginRsp:
|
||||
rsp := protoMsg.PayloadMessage.(*proto.PlayerLoginRsp)
|
||||
if rsp.Retcode != 0 {
|
||||
logger.Error("login fail, retCode: %v, account: %v", rsp.Retcode, account)
|
||||
return
|
||||
}
|
||||
logger.Info("robot gs login ok, account: %v", account)
|
||||
case cmd.DoSetPlayerBornDataNotify:
|
||||
session.SendMsg(cmd.SetPlayerBornDataReq, &proto.SetPlayerBornDataReq{
|
||||
AvatarId: 10000007,
|
||||
NickName: account,
|
||||
})
|
||||
case cmd.PlayerDataNotify:
|
||||
ntf := protoMsg.PayloadMessage.(*proto.PlayerDataNotify)
|
||||
logger.Info("player name: %v", ntf.NickName)
|
||||
case cmd.PlayerEnterSceneNotify:
|
||||
ntf := protoMsg.PayloadMessage.(*proto.PlayerEnterSceneNotify)
|
||||
bornPos.X, bornPos.Y, bornPos.Z = ntf.Pos.X, ntf.Pos.Y, ntf.Pos.Z
|
||||
currPos.X, currPos.Y, currPos.Z = ntf.Pos.X, ntf.Pos.Y, ntf.Pos.Z
|
||||
session.SendMsg(cmd.EnterSceneReadyReq, &proto.EnterSceneReadyReq{EnterSceneToken: ntf.EnterSceneToken})
|
||||
case cmd.EnterSceneReadyRsp:
|
||||
ntf := protoMsg.PayloadMessage.(*proto.EnterSceneReadyRsp)
|
||||
session.SendMsg(cmd.SceneInitFinishReq, &proto.SceneInitFinishReq{EnterSceneToken: ntf.EnterSceneToken})
|
||||
case cmd.SceneInitFinishRsp:
|
||||
ntf := protoMsg.PayloadMessage.(*proto.SceneInitFinishRsp)
|
||||
session.SendMsg(cmd.EnterSceneDoneReq, &proto.EnterSceneDoneReq{EnterSceneToken: ntf.EnterSceneToken})
|
||||
case cmd.EnterSceneDoneRsp:
|
||||
ntf := protoMsg.PayloadMessage.(*proto.EnterSceneDoneRsp)
|
||||
enterSceneDone = true
|
||||
sceneBeginTime = uint32(time.Now().UnixMilli())
|
||||
session.SendMsg(cmd.PostEnterSceneReq, &proto.PostEnterSceneReq{EnterSceneToken: ntf.EnterSceneToken})
|
||||
if config.GetConfig().Hk4eRobot.DosLoopLogin {
|
||||
session.Close()
|
||||
}
|
||||
case cmd.SceneEntityAppearNotify:
|
||||
ntf := protoMsg.PayloadMessage.(*proto.SceneEntityAppearNotify)
|
||||
for _, sceneEntityInfo := range ntf.EntityList {
|
||||
if sceneEntityInfo.EntityType != proto.ProtEntityType_PROT_ENTITY_AVATAR {
|
||||
continue
|
||||
}
|
||||
avatarEntityId = sceneEntityInfo.EntityId
|
||||
}
|
||||
}
|
||||
case <-session.DeadEvent:
|
||||
logger.Info("robot exit, account: %v", account)
|
||||
close(session.SendChan)
|
||||
return
|
||||
case <-ticker.C:
|
||||
tickCounter++
|
||||
if config.GetConfig().Hk4eRobot.ClientMoveEnable {
|
||||
if enterSceneDone {
|
||||
for {
|
||||
dx := float32(float64(config.GetConfig().Hk4eRobot.ClientMoveSpeed) * math.Cos(float64(moveRot/360.0*2*math.Pi)))
|
||||
dz := float32(float64(config.GetConfig().Hk4eRobot.ClientMoveSpeed) * math.Sin(float64(moveRot/360.0*2*math.Pi)))
|
||||
if currPos.X-dx > bornPos.X+float32(config.GetConfig().Hk4eRobot.ClientMoveRangeExt) ||
|
||||
currPos.Z-dz > bornPos.Z+float32(config.GetConfig().Hk4eRobot.ClientMoveRangeExt) ||
|
||||
currPos.X-dx < bornPos.X-float32(config.GetConfig().Hk4eRobot.ClientMoveRangeExt) ||
|
||||
currPos.Z-dz < bornPos.Z-float32(config.GetConfig().Hk4eRobot.ClientMoveRangeExt) {
|
||||
moveRot = random.GetRandomFloat32(0.0, 359.9)
|
||||
continue
|
||||
}
|
||||
currPos.X -= dx
|
||||
currPos.Z -= dz
|
||||
break
|
||||
}
|
||||
moveReliableSeq += 100
|
||||
entityMoveInfo := &proto.EntityMoveInfo{
|
||||
EntityId: avatarEntityId,
|
||||
MotionInfo: &proto.MotionInfo{
|
||||
Pos: currPos,
|
||||
Rot: &proto.Vector{X: 0.0, Y: moveRot, Z: 0.0},
|
||||
Speed: new(proto.Vector),
|
||||
State: proto.MotionState_MOTION_RUN,
|
||||
RefPos: new(proto.Vector),
|
||||
},
|
||||
SceneTime: uint32(time.Now().UnixMilli()) - sceneBeginTime,
|
||||
ReliableSeq: moveReliableSeq,
|
||||
IsReliable: true,
|
||||
}
|
||||
logger.Debug("EntityMoveInfo: %v, account: %v", entityMoveInfo, account)
|
||||
combatData, err := pb.Marshal(entityMoveInfo)
|
||||
if err != nil {
|
||||
logger.Error("marshal EntityMoveInfo error: %v, account: %v", err, account)
|
||||
continue
|
||||
}
|
||||
combatInvocationsNotify := &proto.CombatInvocationsNotify{
|
||||
InvokeList: []*proto.CombatInvokeEntry{{
|
||||
CombatData: combatData,
|
||||
ForwardType: proto.ForwardType_FORWARD_TO_ALL_EXCEPT_CUR,
|
||||
ArgumentType: proto.CombatTypeArgument_ENTITY_MOVE,
|
||||
}},
|
||||
}
|
||||
var combatInvocationsNotifyPb pb.Message = combatInvocationsNotify
|
||||
if config.GetConfig().Hk4e.ClientProtoProxyEnable {
|
||||
clientProtoObj := hk4egatenet.GetClientProtoObjByName("CombatInvocationsNotify", session.ClientCmdProtoMap)
|
||||
if clientProtoObj == nil {
|
||||
continue
|
||||
}
|
||||
err := object.CopyProtoBufSameField(clientProtoObj, combatInvocationsNotify)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
hk4egatenet.ConvServerPbDataToClient(clientProtoObj, session.ClientCmdProtoMap)
|
||||
combatInvocationsNotifyPb = clientProtoObj
|
||||
}
|
||||
body, err := pb.Marshal(combatInvocationsNotifyPb)
|
||||
if err != nil {
|
||||
logger.Error("marshal CombatInvocationsNotify error: %v, account: %v", err, account)
|
||||
continue
|
||||
}
|
||||
unionCmdNotify := &proto.UnionCmdNotify{
|
||||
CmdList: []*proto.UnionCmd{{
|
||||
Body: body,
|
||||
MessageId: cmd.CombatInvocationsNotify,
|
||||
}},
|
||||
}
|
||||
if config.GetConfig().Hk4e.ClientProtoProxyEnable {
|
||||
unionCmdNotify.CmdList[0].MessageId = uint32(session.ClientCmdProtoMap.GetClientCmdIdByCmdName("CombatInvocationsNotify"))
|
||||
}
|
||||
session.SendMsg(cmd.UnionCmdNotify, unionCmdNotify)
|
||||
}
|
||||
}
|
||||
if tickCounter%5 != 0 {
|
||||
continue
|
||||
}
|
||||
pingSeq++
|
||||
// 通过这个接口发消息给服务器
|
||||
session.SendMsg(cmd.PingReq, &proto.PingReq{
|
||||
ClientTime: uint32(time.Now().Unix()),
|
||||
Seq: pingSeq,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ max_size = 10485760
|
||||
|
||||
[hk4e]
|
||||
client_proto_proxy_enable = false
|
||||
forward_mode_enable = false
|
||||
|
||||
[hk4e_robot]
|
||||
region_list_url = "https://hk4e.flswld.com" # 一级dispatch地址
|
||||
@@ -25,3 +26,6 @@ dos_loop_login = false # 压力测试是否循环登录退出
|
||||
client_move_enable = false # 是否开启客户端模拟移动
|
||||
client_move_speed = 10 # 客户端模拟移动速度
|
||||
client_move_range_ext = 100 # 客户端模拟移动区域半径
|
||||
|
||||
[mq]
|
||||
nats_url = "nats://nats:4222"
|
||||
+206
-179
@@ -1,9 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"math"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
@@ -12,21 +13,23 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
hk4egatenet "hk4e/gate/net"
|
||||
"hk4e/pkg/endec"
|
||||
"hk4e/pkg/object"
|
||||
"hk4e/pkg/random"
|
||||
"hk4e/robot/net"
|
||||
|
||||
pb "google.golang.org/protobuf/proto"
|
||||
|
||||
"hk4e/common/config"
|
||||
"hk4e/common/mq"
|
||||
"hk4e/common/rpc"
|
||||
"hk4e/node/api"
|
||||
"hk4e/pkg/endec"
|
||||
"hk4e/pkg/logger"
|
||||
"hk4e/protocol/cmd"
|
||||
"hk4e/protocol/proto"
|
||||
"hk4e/robot/client"
|
||||
"hk4e/robot/login"
|
||||
"hk4e/robot/net"
|
||||
|
||||
pb "google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
var APPID string
|
||||
|
||||
func main() {
|
||||
config.InitConfig("application.toml")
|
||||
logger.InitLogger("robot")
|
||||
@@ -42,29 +45,49 @@ func main() {
|
||||
// engine.RunEngine([]int{0, 1, 2, 3}, 4, 1, "0.0.0.0")
|
||||
// time.Sleep(time.Second * 30)
|
||||
|
||||
dispatchInfo, err := login.GetDispatchInfo(config.GetConfig().Hk4eRobot.RegionListUrl,
|
||||
config.GetConfig().Hk4eRobot.RegionListParam,
|
||||
config.GetConfig().Hk4eRobot.CurRegionUrl,
|
||||
config.GetConfig().Hk4eRobot.CurRegionParam,
|
||||
config.GetConfig().Hk4eRobot.KeyId)
|
||||
if err != nil {
|
||||
logger.Error("get dispatch info error: %v", err)
|
||||
time.Sleep(time.Second)
|
||||
return
|
||||
}
|
||||
|
||||
if config.GetConfig().Hk4eRobot.DosEnable {
|
||||
dosBatchNum := int(config.GetConfig().Hk4eRobot.DosBatchNum)
|
||||
for i := 0; i < int(config.GetConfig().Hk4eRobot.DosTotalNum); i += dosBatchNum {
|
||||
wg := new(sync.WaitGroup)
|
||||
wg.Add(dosBatchNum)
|
||||
for j := 0; j < dosBatchNum; j++ {
|
||||
go httpLogin(config.GetConfig().Hk4eRobot.Account+"_"+strconv.Itoa(i+j), dispatchInfo, wg)
|
||||
}
|
||||
wg.Wait()
|
||||
if config.GetConfig().Hk4e.ForwardModeEnable {
|
||||
// natsrpc client
|
||||
discoveryClient, err := rpc.NewDiscoveryClient()
|
||||
if err != nil {
|
||||
logger.Error("find discovery service error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 注册到节点服务器
|
||||
rsp, err := discoveryClient.RegisterServer(context.TODO(), &api.RegisterServerReq{
|
||||
ServerType: api.ROBOT,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("register to node server error: %v", err)
|
||||
return
|
||||
}
|
||||
APPID = rsp.GetAppId()
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Second * 15)
|
||||
for {
|
||||
<-ticker.C
|
||||
_, err := discoveryClient.KeepaliveServer(context.TODO(), &api.KeepaliveServerReq{
|
||||
ServerType: api.ROBOT,
|
||||
AppId: APPID,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("keepalive error: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
_, _ = discoveryClient.CancelServer(context.TODO(), &api.CancelServerReq{
|
||||
ServerType: api.ROBOT,
|
||||
AppId: APPID,
|
||||
})
|
||||
}()
|
||||
|
||||
messageQueue := mq.NewMessageQueue(api.ROBOT, APPID, discoveryClient)
|
||||
defer messageQueue.Close()
|
||||
|
||||
go runForward(messageQueue)
|
||||
} else {
|
||||
httpLogin(config.GetConfig().Hk4eRobot.Account, dispatchInfo, nil)
|
||||
go runRobot()
|
||||
}
|
||||
|
||||
c := make(chan os.Signal, 1)
|
||||
@@ -83,6 +106,157 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
func runForward(messageQueue *mq.MessageQueue) {
|
||||
for {
|
||||
netMsg := <-messageQueue.GetNetMsg()
|
||||
if netMsg.OriginServerType != api.DISPATCH {
|
||||
continue
|
||||
}
|
||||
if netMsg.MsgType != mq.MsgTypeServer || netMsg.EventId != mq.ServerForwardDispatchInfoNotify {
|
||||
continue
|
||||
}
|
||||
serverMsg := netMsg.ServerMsg
|
||||
dispatchInfo := &login.DispatchInfo{
|
||||
GateIp: serverMsg.ForwardDispatchInfo.GateIp,
|
||||
GatePort: serverMsg.ForwardDispatchInfo.GatePort,
|
||||
DispatchKey: serverMsg.ForwardDispatchInfo.DispatchKey,
|
||||
}
|
||||
logger.Info("get forward dispatch info ok, gate addr: %v:%v", dispatchInfo.GateIp, dispatchInfo.GatePort)
|
||||
waitClientConn(messageQueue, dispatchInfo)
|
||||
}
|
||||
}
|
||||
|
||||
func waitClientConn(messageQueue *mq.MessageQueue, dispatchInfo *login.DispatchInfo) {
|
||||
for {
|
||||
netMsg := <-messageQueue.GetNetMsg()
|
||||
if netMsg.OriginServerType != api.GATE {
|
||||
continue
|
||||
}
|
||||
if netMsg.MsgType != mq.MsgTypeServer || netMsg.EventId != mq.ServerForwardModeClientConnNotify {
|
||||
continue
|
||||
}
|
||||
gateAppId := netMsg.OriginServerAppId
|
||||
logger.Info("client connect, gateAppId: %v", gateAppId)
|
||||
for {
|
||||
netMsg = <-messageQueue.GetNetMsg()
|
||||
if netMsg.OriginServerType != api.GATE || netMsg.OriginServerAppId != gateAppId {
|
||||
continue
|
||||
}
|
||||
if netMsg.MsgType != mq.MsgTypeGame || netMsg.EventId != mq.NormalMsg {
|
||||
continue
|
||||
}
|
||||
gameMsg := netMsg.GameMsg
|
||||
if gameMsg.CmdId != cmd.GetPlayerTokenReq {
|
||||
continue
|
||||
}
|
||||
req := gameMsg.PayloadMessage.(*proto.GetPlayerTokenReq)
|
||||
session, err, rsp := login.GateLogin(dispatchInfo, nil, config.GetConfig().Hk4eRobot.KeyId, req, gameMsg.ClientSeq)
|
||||
if err != nil {
|
||||
logger.Error("remote gate login error: %v", err)
|
||||
continue
|
||||
}
|
||||
logger.Info("remote gate login ok, uid: %v", session.Uid)
|
||||
messageQueue.SendToGate(gateAppId, &mq.NetMsg{
|
||||
MsgType: mq.MsgTypeGame,
|
||||
EventId: mq.NormalMsg,
|
||||
GameMsg: &mq.GameMsg{
|
||||
UserId: rsp.Uid,
|
||||
CmdId: cmd.GetPlayerTokenRsp,
|
||||
ClientSeq: gameMsg.ClientSeq,
|
||||
PayloadMessage: rsp,
|
||||
},
|
||||
})
|
||||
forwardLoop(session, messageQueue, gateAppId)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func forwardLoop(session *net.Session, messageQueue *mq.MessageQueue, gateAppId string) {
|
||||
for {
|
||||
select {
|
||||
case netMsg := <-messageQueue.GetNetMsg():
|
||||
if netMsg.OriginServerType != api.GATE || netMsg.OriginServerAppId != gateAppId {
|
||||
continue
|
||||
}
|
||||
switch netMsg.MsgType {
|
||||
case mq.MsgTypeGame:
|
||||
if netMsg.EventId != mq.NormalMsg {
|
||||
continue
|
||||
}
|
||||
gameMsg := netMsg.GameMsg
|
||||
session.SendMsgFwd(gameMsg.CmdId, gameMsg.ClientSeq, gameMsg.PayloadMessage)
|
||||
if gameMsg.CmdId == cmd.PlayerLoginReq {
|
||||
data, _ := json.Marshal(gameMsg.PayloadMessage)
|
||||
logger.Debug("PlayerLoginReq: %v", string(data))
|
||||
}
|
||||
case mq.MsgTypeServer:
|
||||
switch netMsg.EventId {
|
||||
case mq.ServerForwardModeClientCloseNotify:
|
||||
logger.Info("client conn close, uid: %v", session.Uid)
|
||||
session.Close()
|
||||
}
|
||||
}
|
||||
case protoMsg := <-session.RecvChan:
|
||||
gameMsg := new(mq.GameMsg)
|
||||
gameMsg.UserId = session.Uid
|
||||
gameMsg.CmdId = protoMsg.CmdId
|
||||
if protoMsg.HeadMessage != nil {
|
||||
gameMsg.ClientSeq = protoMsg.HeadMessage.ClientSequenceId
|
||||
}
|
||||
// 在这里直接序列化成二进制数据 防止发送的消息内包含各种游戏数据指针 而造成并发读写的问题
|
||||
payloadMessageData, err := pb.Marshal(protoMsg.PayloadMessage)
|
||||
if err != nil {
|
||||
logger.Error("parse payload msg to bin error: %v", err)
|
||||
continue
|
||||
}
|
||||
gameMsg.PayloadMessageData = payloadMessageData
|
||||
messageQueue.SendToGate(gateAppId, &mq.NetMsg{
|
||||
MsgType: mq.MsgTypeGame,
|
||||
EventId: mq.NormalMsg,
|
||||
GameMsg: gameMsg,
|
||||
})
|
||||
if gameMsg.CmdId == cmd.PlayerLoginRsp {
|
||||
data, _ := json.Marshal(protoMsg.PayloadMessage)
|
||||
logger.Debug("PlayerLoginRsp: %v", string(data))
|
||||
}
|
||||
case <-session.DeadEvent:
|
||||
logger.Info("remote gate conn close, uid: %v", session.Uid)
|
||||
close(session.SendChan)
|
||||
messageQueue.SendToGate(gateAppId, &mq.NetMsg{
|
||||
MsgType: mq.MsgTypeServer,
|
||||
EventId: mq.ServerForwardModeServerCloseNotify,
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runRobot() {
|
||||
dispatchInfo, err := login.GetDispatchInfo(config.GetConfig().Hk4eRobot.RegionListUrl,
|
||||
config.GetConfig().Hk4eRobot.RegionListParam,
|
||||
config.GetConfig().Hk4eRobot.CurRegionUrl,
|
||||
config.GetConfig().Hk4eRobot.CurRegionParam,
|
||||
config.GetConfig().Hk4eRobot.KeyId)
|
||||
if err != nil {
|
||||
logger.Error("get dispatch info error: %v", err)
|
||||
return
|
||||
}
|
||||
if config.GetConfig().Hk4eRobot.DosEnable {
|
||||
dosBatchNum := int(config.GetConfig().Hk4eRobot.DosBatchNum)
|
||||
for i := 0; i < int(config.GetConfig().Hk4eRobot.DosTotalNum); i += dosBatchNum {
|
||||
wg := new(sync.WaitGroup)
|
||||
wg.Add(dosBatchNum)
|
||||
for j := 0; j < dosBatchNum; j++ {
|
||||
go httpLogin(config.GetConfig().Hk4eRobot.Account+"_"+strconv.Itoa(i+j), dispatchInfo, wg)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
} else {
|
||||
httpLogin(config.GetConfig().Hk4eRobot.Account, dispatchInfo, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func httpLogin(account string, dispatchInfo *login.DispatchInfo, wg *sync.WaitGroup) {
|
||||
defer func() {
|
||||
if config.GetConfig().Hk4eRobot.DosEnable {
|
||||
@@ -108,7 +282,7 @@ func httpLogin(account string, dispatchInfo *login.DispatchInfo, wg *sync.WaitGr
|
||||
}
|
||||
|
||||
func gateLogin(account string, dispatchInfo *login.DispatchInfo, accountInfo *login.AccountInfo) {
|
||||
session, err := login.GateLogin(dispatchInfo, accountInfo, config.GetConfig().Hk4eRobot.KeyId)
|
||||
session, err, _ := login.GateLogin(dispatchInfo, accountInfo, config.GetConfig().Hk4eRobot.KeyId, nil, 1)
|
||||
if err != nil {
|
||||
logger.Error("gate login error: %v", err)
|
||||
return
|
||||
@@ -136,152 +310,5 @@ func gateLogin(account string, dispatchInfo *login.DispatchInfo, accountInfo *lo
|
||||
SecurityLibraryMd5: "574a507ffee2eb6f997d11f71c8ae1fa",
|
||||
Token: accountInfo.ComboToken,
|
||||
})
|
||||
clientLogic(account, session)
|
||||
}
|
||||
|
||||
func clientLogic(account string, session *net.Session) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
tickCounter := uint64(0)
|
||||
pingSeq := uint32(0)
|
||||
enterSceneDone := false
|
||||
sceneBeginTime := uint32(0)
|
||||
bornPos := new(proto.Vector)
|
||||
currPos := new(proto.Vector)
|
||||
avatarEntityId := uint32(0)
|
||||
moveRot := random.GetRandomFloat32(0.0, 359.9)
|
||||
moveReliableSeq := uint32(0)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
tickCounter++
|
||||
if config.GetConfig().Hk4eRobot.ClientMoveEnable {
|
||||
if enterSceneDone {
|
||||
for {
|
||||
dx := float32(float64(config.GetConfig().Hk4eRobot.ClientMoveSpeed) * math.Cos(float64(moveRot/360.0*2*math.Pi)))
|
||||
dz := float32(float64(config.GetConfig().Hk4eRobot.ClientMoveSpeed) * math.Sin(float64(moveRot/360.0*2*math.Pi)))
|
||||
if currPos.X-dx > bornPos.X+float32(config.GetConfig().Hk4eRobot.ClientMoveRangeExt) ||
|
||||
currPos.Z-dz > bornPos.Z+float32(config.GetConfig().Hk4eRobot.ClientMoveRangeExt) ||
|
||||
currPos.X-dx < bornPos.X-float32(config.GetConfig().Hk4eRobot.ClientMoveRangeExt) ||
|
||||
currPos.Z-dz < bornPos.Z-float32(config.GetConfig().Hk4eRobot.ClientMoveRangeExt) {
|
||||
moveRot = random.GetRandomFloat32(0.0, 359.9)
|
||||
continue
|
||||
}
|
||||
currPos.X -= dx
|
||||
currPos.Z -= dz
|
||||
break
|
||||
}
|
||||
moveReliableSeq += 100
|
||||
entityMoveInfo := &proto.EntityMoveInfo{
|
||||
EntityId: avatarEntityId,
|
||||
MotionInfo: &proto.MotionInfo{
|
||||
Pos: currPos,
|
||||
Rot: &proto.Vector{X: 0.0, Y: moveRot, Z: 0.0},
|
||||
Speed: new(proto.Vector),
|
||||
State: proto.MotionState_MOTION_RUN,
|
||||
RefPos: new(proto.Vector),
|
||||
},
|
||||
SceneTime: uint32(time.Now().UnixMilli()) - sceneBeginTime,
|
||||
ReliableSeq: moveReliableSeq,
|
||||
IsReliable: true,
|
||||
}
|
||||
logger.Debug("EntityMoveInfo: %v, account: %v", entityMoveInfo, account)
|
||||
combatData, err := pb.Marshal(entityMoveInfo)
|
||||
if err != nil {
|
||||
logger.Error("marshal EntityMoveInfo error: %v, account: %v", err, account)
|
||||
continue
|
||||
}
|
||||
combatInvocationsNotify := &proto.CombatInvocationsNotify{
|
||||
InvokeList: []*proto.CombatInvokeEntry{{
|
||||
CombatData: combatData,
|
||||
ForwardType: proto.ForwardType_FORWARD_TO_ALL_EXCEPT_CUR,
|
||||
ArgumentType: proto.CombatTypeArgument_ENTITY_MOVE,
|
||||
}},
|
||||
}
|
||||
var combatInvocationsNotifyPb pb.Message = combatInvocationsNotify
|
||||
if config.GetConfig().Hk4e.ClientProtoProxyEnable {
|
||||
clientProtoObj := hk4egatenet.GetClientProtoObjByName("CombatInvocationsNotify", session.ClientCmdProtoMap)
|
||||
if clientProtoObj == nil {
|
||||
continue
|
||||
}
|
||||
err := object.CopyProtoBufSameField(clientProtoObj, combatInvocationsNotify)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
hk4egatenet.ConvServerPbDataToClient(clientProtoObj, session.ClientCmdProtoMap)
|
||||
combatInvocationsNotifyPb = clientProtoObj
|
||||
}
|
||||
body, err := pb.Marshal(combatInvocationsNotifyPb)
|
||||
if err != nil {
|
||||
logger.Error("marshal CombatInvocationsNotify error: %v, account: %v", err, account)
|
||||
continue
|
||||
}
|
||||
unionCmdNotify := &proto.UnionCmdNotify{
|
||||
CmdList: []*proto.UnionCmd{{
|
||||
Body: body,
|
||||
MessageId: cmd.CombatInvocationsNotify,
|
||||
}},
|
||||
}
|
||||
if config.GetConfig().Hk4e.ClientProtoProxyEnable {
|
||||
unionCmdNotify.CmdList[0].MessageId = uint32(session.ClientCmdProtoMap.GetClientCmdIdByCmdName("CombatInvocationsNotify"))
|
||||
}
|
||||
session.SendMsg(cmd.UnionCmdNotify, unionCmdNotify)
|
||||
}
|
||||
}
|
||||
if tickCounter%5 != 0 {
|
||||
continue
|
||||
}
|
||||
pingSeq++
|
||||
// 通过这个接口发消息给服务器
|
||||
session.SendMsg(cmd.PingReq, &proto.PingReq{
|
||||
ClientTime: uint32(time.Now().Unix()),
|
||||
Seq: pingSeq,
|
||||
})
|
||||
case protoMsg := <-session.RecvChan:
|
||||
// 从这个管道接收服务器发来的消息
|
||||
switch protoMsg.CmdId {
|
||||
case cmd.PlayerLoginRsp:
|
||||
rsp := protoMsg.PayloadMessage.(*proto.PlayerLoginRsp)
|
||||
if rsp.Retcode != 0 {
|
||||
logger.Error("login fail, retCode: %v, account: %v", rsp.Retcode, account)
|
||||
return
|
||||
}
|
||||
logger.Info("robot gs login ok, account: %v", account)
|
||||
case cmd.DoSetPlayerBornDataNotify:
|
||||
session.SendMsg(cmd.SetPlayerBornDataReq, &proto.SetPlayerBornDataReq{
|
||||
AvatarId: 10000007,
|
||||
NickName: account,
|
||||
})
|
||||
case cmd.PlayerEnterSceneNotify:
|
||||
ntf := protoMsg.PayloadMessage.(*proto.PlayerEnterSceneNotify)
|
||||
bornPos.X, bornPos.Y, bornPos.Z = ntf.Pos.X, ntf.Pos.Y, ntf.Pos.Z
|
||||
currPos.X, currPos.Y, currPos.Z = ntf.Pos.X, ntf.Pos.Y, ntf.Pos.Z
|
||||
session.SendMsg(cmd.EnterSceneReadyReq, &proto.EnterSceneReadyReq{EnterSceneToken: ntf.EnterSceneToken})
|
||||
case cmd.EnterSceneReadyRsp:
|
||||
ntf := protoMsg.PayloadMessage.(*proto.EnterSceneReadyRsp)
|
||||
session.SendMsg(cmd.SceneInitFinishReq, &proto.SceneInitFinishReq{EnterSceneToken: ntf.EnterSceneToken})
|
||||
case cmd.SceneInitFinishRsp:
|
||||
ntf := protoMsg.PayloadMessage.(*proto.SceneInitFinishRsp)
|
||||
session.SendMsg(cmd.EnterSceneDoneReq, &proto.EnterSceneDoneReq{EnterSceneToken: ntf.EnterSceneToken})
|
||||
case cmd.EnterSceneDoneRsp:
|
||||
ntf := protoMsg.PayloadMessage.(*proto.EnterSceneDoneRsp)
|
||||
enterSceneDone = true
|
||||
sceneBeginTime = uint32(time.Now().UnixMilli())
|
||||
session.SendMsg(cmd.PostEnterSceneReq, &proto.PostEnterSceneReq{EnterSceneToken: ntf.EnterSceneToken})
|
||||
if config.GetConfig().Hk4eRobot.DosLoopLogin {
|
||||
return
|
||||
}
|
||||
case cmd.SceneEntityAppearNotify:
|
||||
ntf := protoMsg.PayloadMessage.(*proto.SceneEntityAppearNotify)
|
||||
for _, sceneEntityInfo := range ntf.EntityList {
|
||||
if sceneEntityInfo.EntityType != proto.ProtEntityType_PROT_ENTITY_AVATAR {
|
||||
continue
|
||||
}
|
||||
avatarEntityId = sceneEntityInfo.EntityId
|
||||
}
|
||||
}
|
||||
case <-session.DeadEvent:
|
||||
logger.Info("robot exit, account: %v", account)
|
||||
return
|
||||
}
|
||||
}
|
||||
client.Logic(account, session)
|
||||
}
|
||||
+65
-25
@@ -4,93 +4,133 @@ import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"hk4e/common/region"
|
||||
"hk4e/pkg/endec"
|
||||
"hk4e/pkg/logger"
|
||||
"hk4e/pkg/random"
|
||||
"hk4e/pkg/reflection"
|
||||
"hk4e/protocol/cmd"
|
||||
"hk4e/protocol/proto"
|
||||
"hk4e/robot/net"
|
||||
)
|
||||
|
||||
func GateLogin(dispatchInfo *DispatchInfo, accountInfo *AccountInfo, keyId string) (*net.Session, error) {
|
||||
func GateLogin(dispatchInfo *DispatchInfo, accountInfo *AccountInfo, keyId string, req *proto.GetPlayerTokenReq, clientSeq uint32) (*net.Session, error, *proto.GetPlayerTokenRsp) {
|
||||
gateAddr := dispatchInfo.GateIp + ":" + strconv.Itoa(int(dispatchInfo.GatePort))
|
||||
logger.Debug("connect gate addr: %v", gateAddr)
|
||||
session, err := net.NewSession(gateAddr, dispatchInfo.DispatchKey, 30000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, err, nil
|
||||
}
|
||||
logger.Debug("connect gate ok")
|
||||
timeRand := random.GetTimeRand()
|
||||
clientSeedUint64 := timeRand.Uint64()
|
||||
clientSeedBuf := new(bytes.Buffer)
|
||||
err = binary.Write(clientSeedBuf, binary.BigEndian, &clientSeedUint64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, err, nil
|
||||
}
|
||||
clientSeed := clientSeedBuf.Bytes()
|
||||
logger.Debug("clientSeed: %v, clientSeedUint64: %v", clientSeed, clientSeedUint64)
|
||||
signRsaKey, encRsaKeyMap, _ := region.LoadRsaKey()
|
||||
if signRsaKey == nil || encRsaKeyMap == nil {
|
||||
return nil, errors.New("load key error"), nil
|
||||
}
|
||||
signPubkey, err := endec.RsaParsePubKeyByPrivKey(signRsaKey)
|
||||
if err != nil {
|
||||
logger.Error("parse rsa pub key error: %v", err)
|
||||
return nil, err
|
||||
return nil, err, nil
|
||||
}
|
||||
signRsaKey, err = os.ReadFile("key/region_sign_key_pub.pem")
|
||||
if err == nil {
|
||||
logger.Debug("use pub key")
|
||||
signPubkey, err = endec.RsaParsePubKey(signRsaKey)
|
||||
if err != nil {
|
||||
logger.Error("parse rsa pub key error: %v", err)
|
||||
return nil, err, nil
|
||||
}
|
||||
}
|
||||
clientSeedEnc, err := endec.RsaEncrypt(clientSeed, signPubkey)
|
||||
if err != nil {
|
||||
logger.Error("rsa dec error: %v", err)
|
||||
return nil, err
|
||||
logger.Error("rsa enc error: %v", err)
|
||||
return nil, err, nil
|
||||
}
|
||||
clientSeedBase64 := base64.StdEncoding.EncodeToString(clientSeedEnc)
|
||||
getPlayerTokenReq := new(proto.GetPlayerTokenReq)
|
||||
keyIdInt, err := strconv.Atoi(keyId)
|
||||
if err != nil {
|
||||
logger.Error("parse key id error: %v", err)
|
||||
return nil, err
|
||||
return nil, err, nil
|
||||
}
|
||||
session.SendMsg(cmd.GetPlayerTokenReq, &proto.GetPlayerTokenReq{
|
||||
AccountToken: accountInfo.ComboToken,
|
||||
AccountUid: strconv.Itoa(int(accountInfo.AccountId)),
|
||||
KeyId: uint32(keyIdInt),
|
||||
ClientRandKey: clientSeedBase64,
|
||||
AccountType: 1,
|
||||
ChannelId: 1,
|
||||
SubChannelId: 1,
|
||||
PlatformType: 3,
|
||||
})
|
||||
if req == nil {
|
||||
getPlayerTokenReq = &proto.GetPlayerTokenReq{
|
||||
AccountToken: accountInfo.ComboToken,
|
||||
AccountUid: strconv.Itoa(int(accountInfo.AccountId)),
|
||||
KeyId: uint32(keyIdInt),
|
||||
ClientRandKey: clientSeedBase64,
|
||||
AccountType: 1,
|
||||
ChannelId: 1,
|
||||
SubChannelId: 1,
|
||||
PlatformType: 3,
|
||||
}
|
||||
} else {
|
||||
ok := reflection.CopyStructSameField(getPlayerTokenReq, req)
|
||||
if !ok {
|
||||
return nil, errors.New("copy field error"), nil
|
||||
}
|
||||
getPlayerTokenReq.KeyId = uint32(keyIdInt)
|
||||
getPlayerTokenReq.ClientRandKey = clientSeedBase64
|
||||
}
|
||||
session.SendMsgFwd(cmd.GetPlayerTokenReq, clientSeq, getPlayerTokenReq)
|
||||
getPlayerTokenReqJson, _ := json.Marshal(getPlayerTokenReq)
|
||||
logger.Debug("GetPlayerTokenReq: %v", string(getPlayerTokenReqJson))
|
||||
protoMsg := <-session.RecvChan
|
||||
if protoMsg.CmdId != cmd.GetPlayerTokenRsp {
|
||||
return nil, errors.New("recv pkt is not GetPlayerTokenRsp")
|
||||
return nil, errors.New("recv pkt is not GetPlayerTokenRsp"), nil
|
||||
}
|
||||
getPlayerTokenRsp := protoMsg.PayloadMessage.(*proto.GetPlayerTokenRsp)
|
||||
getPlayerTokenRspJson, _ := json.Marshal(getPlayerTokenRsp)
|
||||
logger.Debug("GetPlayerTokenRsp: %v", string(getPlayerTokenRspJson))
|
||||
if getPlayerTokenRsp.Retcode != 0 {
|
||||
return nil, errors.New(fmt.Sprintf("gate login error, retCode: %v", getPlayerTokenRsp.Retcode)), nil
|
||||
}
|
||||
logger.Info("gate login ok, uid: %v", getPlayerTokenRsp.Uid)
|
||||
session.Uid = getPlayerTokenRsp.Uid
|
||||
// XOR密钥切换
|
||||
seedEnc, err := base64.StdEncoding.DecodeString(getPlayerTokenRsp.ServerRandKey)
|
||||
if err != nil {
|
||||
logger.Error("base64 decode error: %v", err)
|
||||
return nil, err
|
||||
return nil, err, nil
|
||||
}
|
||||
encPubPrivKey, exist := encRsaKeyMap[keyId]
|
||||
if !exist {
|
||||
logger.Error("can not found key id: %v", keyId)
|
||||
return nil, err
|
||||
return nil, err, nil
|
||||
}
|
||||
privKey, err := endec.RsaParsePrivKey(encPubPrivKey)
|
||||
if err != nil {
|
||||
logger.Error("parse rsa pub key error: %v", err)
|
||||
return nil, err
|
||||
return nil, err, nil
|
||||
}
|
||||
seed, err := endec.RsaDecrypt(seedEnc, privKey)
|
||||
if err != nil {
|
||||
logger.Error("rsa enc error: %v", err)
|
||||
return nil, err
|
||||
logger.Error("rsa dec error: %v", err)
|
||||
return nil, err, nil
|
||||
}
|
||||
seedUint64 := uint64(0)
|
||||
err = binary.Read(bytes.NewReader(seed), binary.BigEndian, &seedUint64)
|
||||
if err != nil {
|
||||
logger.Error("parse seed error: %v", err)
|
||||
return nil, err
|
||||
return nil, err, nil
|
||||
}
|
||||
serverSeedUint64 := seedUint64 ^ clientSeedUint64
|
||||
logger.Debug("seed: %v, seedUint64: %v", seed, seedUint64)
|
||||
logger.Debug("serverSeedUint64: %v", serverSeedUint64)
|
||||
logger.Info("change session xor key")
|
||||
keyBlock := random.NewKeyBlock(serverSeedUint64, true)
|
||||
xorKey := keyBlock.XorKey()
|
||||
@@ -99,5 +139,5 @@ func GateLogin(dispatchInfo *DispatchInfo, accountInfo *AccountInfo, keyId strin
|
||||
session.XorKey = key
|
||||
session.ClientVersionRandomKey = getPlayerTokenRsp.ClientVersionRandomKey
|
||||
session.SecurityCmdBuffer = getPlayerTokenRsp.SecurityCmdBuffer
|
||||
return session, nil
|
||||
return session, nil, getPlayerTokenRsp
|
||||
}
|
||||
@@ -98,7 +98,7 @@ func GetDispatchInfo(regionListUrl string, regionListParam string, curRegionUrl
|
||||
if regionInfo == nil {
|
||||
return nil, errors.New("region info is nil")
|
||||
}
|
||||
ec2b, err := random.LoadEc2bKey(regionInfo.SecretKey)
|
||||
ec2b, err := random.LoadEc2bKey(queryCurrRegionHttpRsp.ClientSecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+33
-9
@@ -27,6 +27,8 @@ type Session struct {
|
||||
DeadEvent chan bool
|
||||
ClientVersionRandomKey string
|
||||
SecurityCmdBuffer []byte
|
||||
Uid uint32
|
||||
IsClose bool
|
||||
}
|
||||
|
||||
func NewSession(gateAddr string, dispatchKey []byte, localPort int) (*Session, error) {
|
||||
@@ -40,7 +42,7 @@ func NewSession(gateAddr string, dispatchKey []byte, localPort int) (*Session, e
|
||||
}
|
||||
conn.SetACKNoDelay(true)
|
||||
conn.SetWriteDelay(false)
|
||||
conn.SetWindowSize(255, 255)
|
||||
conn.SetWindowSize(256, 256)
|
||||
r := &Session{
|
||||
Conn: conn,
|
||||
XorKey: dispatchKey,
|
||||
@@ -49,9 +51,11 @@ func NewSession(gateAddr string, dispatchKey []byte, localPort int) (*Session, e
|
||||
ServerCmdProtoMap: cmd.NewCmdProtoMap(),
|
||||
ClientCmdProtoMap: nil,
|
||||
ClientSeq: 0,
|
||||
DeadEvent: make(chan bool, 10),
|
||||
DeadEvent: make(chan bool, 1),
|
||||
ClientVersionRandomKey: "",
|
||||
SecurityCmdBuffer: nil,
|
||||
Uid: 0,
|
||||
IsClose: false,
|
||||
}
|
||||
if config.GetConfig().Hk4e.ClientProtoProxyEnable {
|
||||
r.ClientCmdProtoMap = client_proto.NewClientCmdProtoMap()
|
||||
@@ -62,18 +66,40 @@ func NewSession(gateAddr string, dispatchKey []byte, localPort int) (*Session, e
|
||||
}
|
||||
|
||||
func (s *Session) SendMsg(cmdId uint16, msg pb.Message) {
|
||||
atomic.AddUint32(&s.ClientSeq, 1)
|
||||
s.SendChan <- &hk4egatenet.ProtoMsg{
|
||||
ConvId: 0,
|
||||
CmdId: cmdId,
|
||||
HeadMessage: &proto.PacketHead{
|
||||
ClientSequenceId: s.ClientSeq,
|
||||
ClientSequenceId: atomic.AddUint32(&s.ClientSeq, 1),
|
||||
SentMs: uint64(time.Now().UnixMilli()),
|
||||
EnetIsReliable: 1,
|
||||
},
|
||||
PayloadMessage: msg,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) SendMsgFwd(cmdId uint16, clientSeq uint32, msg pb.Message) {
|
||||
s.SendChan <- &hk4egatenet.ProtoMsg{
|
||||
ConvId: 0,
|
||||
CmdId: cmdId,
|
||||
HeadMessage: &proto.PacketHead{
|
||||
ClientSequenceId: clientSeq,
|
||||
SentMs: uint64(time.Now().UnixMilli()),
|
||||
EnetIsReliable: 1,
|
||||
},
|
||||
PayloadMessage: msg,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) Close() {
|
||||
if s.IsClose {
|
||||
return
|
||||
}
|
||||
s.IsClose = true
|
||||
_ = s.Conn.Close()
|
||||
s.DeadEvent <- true
|
||||
}
|
||||
|
||||
func (s *Session) recvHandle() {
|
||||
logger.Info("recv handle start")
|
||||
conn := s.Conn
|
||||
@@ -84,7 +110,7 @@ func (s *Session) recvHandle() {
|
||||
recvLen, err := conn.Read(recvBuf)
|
||||
if err != nil {
|
||||
logger.Error("exit recv loop, conn read err: %v, convId: %v", err, convId)
|
||||
_ = conn.Close()
|
||||
s.Close()
|
||||
break
|
||||
}
|
||||
recvData := recvBuf[:recvLen]
|
||||
@@ -97,7 +123,6 @@ func (s *Session) recvHandle() {
|
||||
}
|
||||
}
|
||||
}
|
||||
s.DeadEvent <- true
|
||||
}
|
||||
|
||||
func (s *Session) sendHandle() {
|
||||
@@ -108,7 +133,7 @@ func (s *Session) sendHandle() {
|
||||
protoMsg, ok := <-s.SendChan
|
||||
if !ok {
|
||||
logger.Error("exit send loop, send chan close, convId: %v", convId)
|
||||
_ = conn.Close()
|
||||
s.Close()
|
||||
break
|
||||
}
|
||||
kcpMsg := hk4egatenet.ProtoEncode(protoMsg, s.ServerCmdProtoMap, s.ClientCmdProtoMap)
|
||||
@@ -121,9 +146,8 @@ func (s *Session) sendHandle() {
|
||||
_, err := conn.Write(bin)
|
||||
if err != nil {
|
||||
logger.Error("exit send loop, conn write err: %v, convId: %v", err, convId)
|
||||
_ = conn.Close()
|
||||
s.Close()
|
||||
break
|
||||
}
|
||||
}
|
||||
s.DeadEvent <- true
|
||||
}
|
||||
Reference in new issue
Block a user