From d02b90a511e2f71c758c8ab057164e03673b7013 Mon Sep 17 00:00:00 2001 From: flswld Date: Mon, 28 Aug 2023 14:52:42 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96robot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/robot/application.toml | 3 +- cmd/robot/main.go | 367 +------------------------- common/config/config.go | 1 + protocol/cmd/cmd_id_proto_obj_map.go | 7 +- robot/app/app.go | 375 +++++++++++++++++++++++++++ robot/client/client.go | 52 +++- robot/login/http_login.go | 4 +- robot/net/session.go | 84 +++--- 8 files changed, 482 insertions(+), 411 deletions(-) create mode 100644 robot/app/app.go diff --git a/cmd/robot/application.toml b/cmd/robot/application.toml index bb103d64..8874a9af 100644 --- a/cmd/robot/application.toml +++ b/cmd/robot/application.toml @@ -11,7 +11,7 @@ client_proto_proxy_enable = false # 是否开启客户端协议代理功能 forward_mode_enable = false # 是否开启网关到机器人的转发功能 [hk4e_robot] -region_list_url = "https://hk4e.flswld.com" # 一级dispatch地址 +region_list_url = "https://hk4e.flswld.com/query_region_list" # 一级dispatch地址 region_list_param = "" # 一级dispatch的url参数 select_region_index = 0 # 选择的二级dispatch索引 cur_region_url = "https://hk4e.flswld.com/query_cur_region" # 二级dispatch地址 可强制指定 为空则使用一级dispatch获取的地址 @@ -30,6 +30,7 @@ client_move_speed = 10 # 客户端模拟移动速度 client_move_range_ext = 100 # 客户端模拟移动区域半径 forward_checksum = "" # 转发模式强制指定校验和 forward_checksum_client_version = "" # 转发模式强制指定校验和客户端版本 +register_all_proto_message = true # 注册全部pb消息 [mq] nats_url = "nats://nats:4222" diff --git a/cmd/robot/main.go b/cmd/robot/main.go index 6b6f33c2..75f2f4d6 100644 --- a/cmd/robot/main.go +++ b/cmd/robot/main.go @@ -2,369 +2,22 @@ package main import ( "context" - "encoding/base64" - "encoding/hex" - "encoding/json" - "net/http" + "flag" + "fmt" "os" - "os/signal" - "strconv" - "strings" - "sync" - "syscall" - "time" - "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" - - "github.com/gin-gonic/gin" - "github.com/gorilla/websocket" - pb "google.golang.org/protobuf/proto" + "hk4e/robot/app" ) -var APPID string +var ( + config = flag.String("config", "application.toml", "config file") +) func main() { - config.InitConfig("application.toml") - logger.InitLogger("robot") - defer func() { - logger.CloseLogger() - }() - - 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) - go runPacketCaptureApi() - } else { - go runRobot() - } - - c := make(chan os.Signal, 1) - signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) - for { - s := <-c - switch s { - case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT: - return - case syscall.SIGHUP: - default: - return - } - } -} - -func runPacketCaptureApi() { - if config.GetConfig().Logger.Level == "DEBUG" { - gin.SetMode(gin.DebugMode) - } else { - gin.SetMode(gin.ReleaseMode) - } - e := gin.Default() - e.GET("/packet/capture/ws", packetCaptureWs) - e.GET("/packet/capture/list", packetCaptureList) - port := config.GetConfig().HttpPort - addr := ":" + strconv.Itoa(int(port)) - err := e.Run(addr) + flag.Parse() + err := app.Run(context.TODO(), *config) if err != nil { - logger.Error("gin run error: %v", err) - return + fmt.Println(err) + os.Exit(1) } } - -var ForwardSession *net.Session = nil - -func packetCaptureWs(ctx *gin.Context) { - upgrader := websocket.Upgrader{ - HandshakeTimeout: 10 * time.Second, - ReadBufferSize: 1024, - WriteBufferSize: 1024, - CheckOrigin: func(r *http.Request) bool { - return true - }, - } - wsConn, err := upgrader.Upgrade(ctx.Writer, ctx.Request, nil) - if err != nil { - logger.Error("websocket upgrade error: %v", err) - _, _ = ctx.Writer.WriteString("500") - return - } - if ForwardSession == nil { - _ = wsConn.Close() - _, _ = ctx.Writer.WriteString("500") - return - } - ForwardSession.PktCapWsConn = wsConn -} - -func packetCaptureList(ctx *gin.Context) { - if ForwardSession == nil { - _, _ = ctx.Writer.WriteString("500") - return - } - ForwardSession.PktLock.Lock() - data, _ := json.Marshal(ForwardSession.PktList) - ForwardSession.PktLock.Unlock() - _, _ = ctx.Writer.WriteString(string(data)) -} - -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 - } - ForwardSession = session - 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 - if gameMsg.CmdId == cmd.PlayerLoginReq { - req := gameMsg.PayloadMessage.(*proto.PlayerLoginReq) - data, _ := json.Marshal(req) - logger.Debug("PlayerLoginReq: %v", string(data)) - if config.GetConfig().Hk4eRobot.ForwardChecksum != "" { - req.Checksum = config.GetConfig().Hk4eRobot.ForwardChecksum - } - if config.GetConfig().Hk4eRobot.ForwardChecksumClientVersion != "" { - req.ChecksumClientVersion = config.GetConfig().Hk4eRobot.ForwardChecksumClientVersion - } - } - session.SendMsgFwd(gameMsg.CmdId, gameMsg.ClientSeq, gameMsg.PayloadMessage) - 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 { - wg.Done() - } - }() - accountInfo, err := login.AccountLogin(config.GetConfig().Hk4eRobot.LoginSdkUrl, account, config.GetConfig().Hk4eRobot.Password) - if err != nil { - logger.Error("account login error: %v", err) - return - } - logger.Info("robot http login ok, account: %v", account) - go func() { - for { - gateLogin(account, dispatchInfo, accountInfo) - if !config.GetConfig().Hk4eRobot.DosLoopLogin { - break - } - time.Sleep(time.Second) - continue - } - }() -} - -func gateLogin(account string, dispatchInfo *login.DispatchInfo, accountInfo *login.AccountInfo) { - session, err, _ := login.GateLogin(dispatchInfo, accountInfo, config.GetConfig().Hk4eRobot.KeyId, nil, 1) - if err != nil { - logger.Error("gate login error: %v", err) - return - } - logger.Info("robot gate login ok, account: %v", account) - clientVersionHashData, err := hex.DecodeString( - endec.Sha1Str(config.GetConfig().Hk4eRobot.ClientVersion + session.ClientVersionRandomKey + "mhy2020"), - ) - if err != nil { - logger.Error("gen clientVersionHashData error: %v", err) - return - } - checksumClientVersion := strings.Split(config.GetConfig().Hk4eRobot.ClientVersion, "_")[0] - session.SendMsg(cmd.PlayerLoginReq, &proto.PlayerLoginReq{ - AccountType: 1, - SubChannelId: 1, - LanguageType: 2, - PlatformType: 3, - Checksum: "$008094416f86a051270e64eb0b405a38825", - ChecksumClientVersion: checksumClientVersion, - ClientDataVersion: 11793813, - ClientVerisonHash: base64.StdEncoding.EncodeToString(clientVersionHashData), - ClientVersion: config.GetConfig().Hk4eRobot.ClientVersion, - SecurityCmdReply: session.SecurityCmdBuffer, - SecurityLibraryMd5: "574a507ffee2eb6f997d11f71c8ae1fa", - Token: accountInfo.ComboToken, - }) - client.Logic(account, session) -} diff --git a/common/config/config.go b/common/config/config.go index 5afabc8a..7efc4775 100644 --- a/common/config/config.go +++ b/common/config/config.go @@ -77,6 +77,7 @@ type Hk4eRobot struct { ClientMoveRangeExt int32 `toml:"client_move_range_ext"` // 客户端模拟移动区域半径 ForwardChecksum string `toml:"forward_checksum"` // 转发模式强制指定校验和 ForwardChecksumClientVersion string `toml:"forward_checksum_client_version"` // 转发模式强制指定校验和客户端版本 + RegisterAllProtoMessage bool `toml:"register_all_proto_message"` // 注册全部pb消息 } // MQ 消息队列 diff --git a/protocol/cmd/cmd_id_proto_obj_map.go b/protocol/cmd/cmd_id_proto_obj_map.go index dc75ac4f..05ffa2f8 100644 --- a/protocol/cmd/cmd_id_proto_obj_map.go +++ b/protocol/cmd/cmd_id_proto_obj_map.go @@ -30,10 +30,10 @@ func NewCmdProtoMap() (r *CmdProtoMap) { r.cmdNameCmdIdMap = make(map[string]uint16) r.cmdIdProtoObjCacheMap = make(map[uint16]*sync.Pool) r.cmdIdProtoObjFastNewMap = make(map[uint16]func() any) - if !config.GetConfig().Hk4e.ForwardModeEnable { - r.registerMessage() - } else { + if config.GetConfig().Hk4e.ForwardModeEnable || config.GetConfig().Hk4eRobot.RegisterAllMessage { r.registerAllMessage() + } else { + r.registerMessage() } return r } @@ -384,6 +384,7 @@ func (c *CmdProtoMap) registerMessage() { c.regMsg(GmTalkReq, func() any { return new(proto.GmTalkReq) }) c.regMsg(GmTalkRsp, func() any { return new(proto.GmTalkRsp) }) c.regMsg(GmTalkNotify, func() any { return new(proto.GmTalkNotify) }) + c.regMsg(ServerLogNotify, func() any { return new(proto.ServerLogNotify) }) } func (c *CmdProtoMap) regMsg(cmdId uint16, protoObjNewFunc func() any) { diff --git a/robot/app/app.go b/robot/app/app.go new file mode 100644 index 00000000..1a406e42 --- /dev/null +++ b/robot/app/app.go @@ -0,0 +1,375 @@ +package app + +import ( + "context" + "encoding/base64" + "encoding/hex" + "encoding/json" + "net/http" + "os" + "os/signal" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "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" + + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" + pb "google.golang.org/protobuf/proto" +) + +var APPID string + +func Run(ctx context.Context, configFile string) error { + config.InitConfig(configFile) + + logger.InitLogger("robot") + defer func() { + logger.CloseLogger() + }() + + if config.GetConfig().Hk4e.ForwardModeEnable { + // natsrpc client + discoveryClient, err := rpc.NewDiscoveryClient() + if err != nil { + logger.Error("find discovery service error: %v", err) + return err + } + + // 注册到节点服务器 + rsp, err := discoveryClient.RegisterServer(context.TODO(), &api.RegisterServerReq{ + ServerType: api.ROBOT, + }) + if err != nil { + logger.Error("register to node server error: %v", err) + 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.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 { + go runRobot() + } + + go runPacketCaptureApi() + + c := make(chan os.Signal, 1) + signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) + for { + s := <-c + switch s { + case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT: + return nil + case syscall.SIGHUP: + default: + return nil + } + } +} + +func runPacketCaptureApi() { + if config.GetConfig().Logger.Level == "DEBUG" { + gin.SetMode(gin.DebugMode) + } else { + gin.SetMode(gin.ReleaseMode) + } + e := gin.Default() + e.GET("/packet/capture/ws", packetCaptureWs) + e.GET("/packet/capture/list", packetCaptureList) + port := config.GetConfig().HttpPort + addr := ":" + strconv.Itoa(int(port)) + err := e.Run(addr) + if err != nil { + logger.Error("gin run error: %v", err) + return + } +} + +var PacketCaptureSession *net.Session = nil + +func packetCaptureWs(ctx *gin.Context) { + upgrader := websocket.Upgrader{ + HandshakeTimeout: 10 * time.Second, + ReadBufferSize: 1024, + WriteBufferSize: 1024, + CheckOrigin: func(r *http.Request) bool { + return true + }, + } + wsConn, err := upgrader.Upgrade(ctx.Writer, ctx.Request, nil) + if err != nil { + logger.Error("websocket upgrade error: %v", err) + _, _ = ctx.Writer.WriteString("500") + return + } + if PacketCaptureSession == nil { + _ = wsConn.Close() + _, _ = ctx.Writer.WriteString("500") + return + } + PacketCaptureSession.PktCapWsConn = wsConn +} + +func packetCaptureList(ctx *gin.Context) { + if PacketCaptureSession == nil { + _, _ = ctx.Writer.WriteString("500") + return + } + PacketCaptureSession.PktLock.Lock() + data, _ := json.Marshal(PacketCaptureSession.PktList) + PacketCaptureSession.PktLock.Unlock() + _, _ = ctx.Writer.WriteString(string(data)) +} + +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 + } + PacketCaptureSession = session + 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 + if gameMsg.CmdId == cmd.PlayerLoginReq { + req := gameMsg.PayloadMessage.(*proto.PlayerLoginReq) + data, _ := json.Marshal(req) + logger.Debug("PlayerLoginReq: %v", string(data)) + if config.GetConfig().Hk4eRobot.ForwardChecksum != "" { + req.Checksum = config.GetConfig().Hk4eRobot.ForwardChecksum + } + if config.GetConfig().Hk4eRobot.ForwardChecksumClientVersion != "" { + req.ChecksumClientVersion = config.GetConfig().Hk4eRobot.ForwardChecksumClientVersion + } + } + session.SendMsgFwd(gameMsg.CmdId, gameMsg.ClientSeq, gameMsg.PayloadMessage) + 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 { + wg.Done() + } + }() + accountInfo, err := login.AccountLogin(config.GetConfig().Hk4eRobot.LoginSdkUrl, account, config.GetConfig().Hk4eRobot.Password) + if err != nil { + logger.Error("account login error: %v", err) + return + } + logger.Info("robot http login ok, account: %v", account) + go func() { + for { + gateLogin(account, dispatchInfo, accountInfo) + if !config.GetConfig().Hk4eRobot.DosLoopLogin { + break + } + time.Sleep(time.Second) + continue + } + }() +} + +func gateLogin(account string, dispatchInfo *login.DispatchInfo, accountInfo *login.AccountInfo) { + session, err, _ := login.GateLogin(dispatchInfo, accountInfo, config.GetConfig().Hk4eRobot.KeyId, nil, 1) + if err != nil { + logger.Error("gate login error: %v", err) + return + } + if !config.GetConfig().Hk4eRobot.DosEnable { + PacketCaptureSession = session + } + logger.Info("robot gate login ok, account: %v", account) + clientVersionHashData, err := hex.DecodeString( + endec.Sha1Str(config.GetConfig().Hk4eRobot.ClientVersion + session.ClientVersionRandomKey + "mhy2020"), + ) + if err != nil { + logger.Error("gen clientVersionHashData error: %v", err) + return + } + checksumClientVersion := strings.Split(config.GetConfig().Hk4eRobot.ClientVersion, "_")[0] + session.SendMsg(cmd.PlayerLoginReq, &proto.PlayerLoginReq{ + AccountType: 1, + SubChannelId: 1, + LanguageType: 2, + PlatformType: 3, + Checksum: "$008094416f86a051270e64eb0b405a38825", + ChecksumClientVersion: checksumClientVersion, + ClientDataVersion: 11793813, + ClientVerisonHash: base64.StdEncoding.EncodeToString(clientVersionHashData), + ClientVersion: config.GetConfig().Hk4eRobot.ClientVersion, + SecurityCmdReply: session.SecurityCmdBuffer, + SecurityLibraryMd5: "574a507ffee2eb6f997d11f71c8ae1fa", + Token: accountInfo.ComboToken, + }) + client.Logic(account, session) +} diff --git a/robot/client/client.go b/robot/client/client.go index 24db969e..535d2f55 100644 --- a/robot/client/client.go +++ b/robot/client/client.go @@ -5,6 +5,7 @@ import ( "time" "hk4e/common/config" + "hk4e/common/constant" hk4egatenet "hk4e/gate/net" "hk4e/pkg/logger" "hk4e/pkg/object" @@ -22,8 +23,10 @@ func Logic(account string, session *net.Session) { pingSeq := uint32(0) enterSceneDone := false sceneBeginTime := uint32(0) + sceneTime := uint32(0) bornPos := new(proto.Vector) currPos := new(proto.Vector) + sceneEntityMap := make(map[uint32]struct{}) avatarEntityId := uint32(0) moveRot := random.GetRandomFloat32(0.0, 359.9) moveReliableSeq := uint32(0) @@ -47,10 +50,18 @@ func Logic(account string, session *net.Session) { case cmd.PlayerDataNotify: ntf := protoMsg.PayloadMessage.(*proto.PlayerDataNotify) logger.Info("player name: %v", ntf.NickName) + if ntf.PropMap[constant.PLAYER_PROP_PLAYER_LEVEL].Val == 1 { + session.SendMsg(cmd.GmTalkReq, &proto.GmTalkReq{Msg: "quest accept 30904"}) + session.SendMsg(cmd.GmTalkReq, &proto.GmTalkReq{Msg: "player level 60"}) + } case cmd.PlayerEnterSceneNotify: ntf := protoMsg.PayloadMessage.(*proto.PlayerEnterSceneNotify) + logger.Info("player enter scene, sceneId: %v, account: %v", ntf.SceneId, account) 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 + enterSceneDone = false + sceneEntityMap = make(map[uint32]struct{}) + avatarEntityId = 0 session.SendMsg(cmd.EnterSceneReadyReq, &proto.EnterSceneReadyReq{EnterSceneToken: ntf.EnterSceneToken}) case cmd.EnterSceneReadyRsp: ntf := protoMsg.PayloadMessage.(*proto.EnterSceneReadyRsp) @@ -66,14 +77,47 @@ func Logic(account string, session *net.Session) { if config.GetConfig().Hk4eRobot.DosLoopLogin { session.Close() } + case cmd.SceneTimeNotify: + ntf := protoMsg.PayloadMessage.(*proto.SceneTimeNotify) + sceneTime = uint32(ntf.SceneTime) case cmd.SceneEntityAppearNotify: ntf := protoMsg.PayloadMessage.(*proto.SceneEntityAppearNotify) for _, sceneEntityInfo := range ntf.EntityList { - if sceneEntityInfo.EntityType != proto.ProtEntityType_PROT_ENTITY_AVATAR { - continue + sceneEntityMap[sceneEntityInfo.EntityId] = struct{}{} + if sceneEntityInfo.EntityType == proto.ProtEntityType_PROT_ENTITY_AVATAR { + avatarEntity := sceneEntityInfo.Entity.(*proto.SceneEntityInfo_Avatar).Avatar + if avatarEntity.Uid == session.Uid { + avatarEntityId = sceneEntityInfo.EntityId + moveReliableSeq = sceneEntityInfo.LastMoveReliableSeq + } } - avatarEntityId = sceneEntityInfo.EntityId } + case cmd.SceneEntityDisappearNotify: + ntf := protoMsg.PayloadMessage.(*proto.SceneEntityDisappearNotify) + for _, entityId := range ntf.EntityList { + delete(sceneEntityMap, entityId) + } + case cmd.PlayerApplyEnterMpNotify: + ntf := protoMsg.PayloadMessage.(*proto.PlayerApplyEnterMpNotify) + session.SendMsg(cmd.PlayerApplyEnterMpResultReq, &proto.PlayerApplyEnterMpResultReq{ApplyUid: ntf.SrcPlayerInfo.Uid, IsAgreed: true}) + case cmd.PlayerApplyEnterMpResultNotify: + ntf := protoMsg.PayloadMessage.(*proto.PlayerApplyEnterMpResultNotify) + if ntf.IsAgreed { + session.SendMsg(cmd.JoinPlayerSceneReq, &proto.JoinPlayerSceneReq{TargetUid: ntf.TargetUid}) + } + case cmd.ServerLogNotify: + ntf := protoMsg.PayloadMessage.(*proto.ServerLogNotify) + logger.Debug("[Server Log] %v, account: %v", ntf.ServerLog, account) + case cmd.GetOnlinePlayerListRsp: + rsp := protoMsg.PayloadMessage.(*proto.GetOnlinePlayerListRsp) + for _, onlinePlayerInfo := range rsp.PlayerInfoList { + if onlinePlayerInfo.MpSettingType != 0 { + session.SendMsg(cmd.PlayerApplyEnterMpReq, &proto.PlayerApplyEnterMpReq{TargetUid: onlinePlayerInfo.Uid}) + } + } + case cmd.ClientReconnectNotify: + logger.Info("client reconnect, account: %v", account) + session.Close() } case <-session.DeadEvent: logger.Info("robot exit, account: %v", account) @@ -107,7 +151,7 @@ func Logic(account string, session *net.Session) { State: proto.MotionState_MOTION_RUN, RefPos: new(proto.Vector), }, - SceneTime: uint32(time.Now().UnixMilli()) - sceneBeginTime, + SceneTime: uint32(time.Now().UnixMilli()) - sceneBeginTime + sceneTime, ReliableSeq: moveReliableSeq, IsReliable: true, } diff --git a/robot/login/http_login.go b/robot/login/http_login.go index 3753f237..b54ac5c3 100644 --- a/robot/login/http_login.go +++ b/robot/login/http_login.go @@ -26,8 +26,8 @@ type DispatchInfo struct { } func GetDispatchInfo(regionListUrl string, regionListParam string, curRegionUrl string, curRegionParam string, keyId string) (*DispatchInfo, error) { - logger.Info("http get url: %v", regionListUrl+"/query_region_list"+regionListParam) - regionListBase64, err := httpclient.GetRaw(regionListUrl + "/query_region_list" + regionListParam) + logger.Info("http get url: %v", regionListUrl+regionListParam) + regionListBase64, err := httpclient.GetRaw(regionListUrl + regionListParam) if err != nil { return nil, err } diff --git a/robot/net/session.go b/robot/net/session.go index 2fb372fe..f64ff19f 100644 --- a/robot/net/session.go +++ b/robot/net/session.go @@ -135,29 +135,27 @@ func (s *Session) recvHandle() { protoMsgList := hk4egatenet.ProtoDecode(v, s.ServerCmdProtoMap, s.ClientCmdProtoMap) for _, vv := range protoMsgList { s.RecvChan <- vv - if config.GetConfig().Hk4e.ForwardModeEnable { - cmdName := string(vv.PayloadMessage.ProtoReflect().Descriptor().FullName()) - headMsg, _ := json.Marshal(vv.HeadMessage) - payloadMsg, _ := json.Marshal(vv.PayloadMessage) - packet := &Packet{ - Time: uint64(time.Now().UnixMilli()), - Dir: "RECV", - CmdId: uint32(vv.CmdId), - CmdName: cmdName, - HeadMsg: string(headMsg), - PayloadMsg: string(payloadMsg), - } - packetData, _ := json.Marshal(packet) - s.PktLock.Lock() - s.PktList = append(s.PktList, packet) - if s.PktCapWsConn != nil { - err := s.PktCapWsConn.WriteMessage(websocket.TextMessage, packetData) - if err != nil { - s.PktCapWsConn = nil - } - } - s.PktLock.Unlock() + cmdName := string(vv.PayloadMessage.ProtoReflect().Descriptor().FullName()) + headMsg, _ := json.Marshal(vv.HeadMessage) + payloadMsg, _ := json.Marshal(vv.PayloadMessage) + packet := &Packet{ + Time: uint64(time.Now().UnixMilli()), + Dir: "RECV", + CmdId: uint32(vv.CmdId), + CmdName: cmdName, + HeadMsg: string(headMsg), + PayloadMsg: string(payloadMsg), } + packetData, _ := json.Marshal(packet) + s.PktLock.Lock() + s.PktList = append(s.PktList, packet) + if s.PktCapWsConn != nil { + err := s.PktCapWsConn.WriteMessage(websocket.TextMessage, packetData) + if err != nil { + s.PktCapWsConn = nil + } + } + s.PktLock.Unlock() } } } @@ -187,28 +185,26 @@ func (s *Session) sendHandle() { s.Close() break } - if config.GetConfig().Hk4e.ForwardModeEnable { - cmdName := string(protoMsg.PayloadMessage.ProtoReflect().Descriptor().FullName()) - headMsg, _ := json.Marshal(protoMsg.HeadMessage) - payloadMsg, _ := json.Marshal(protoMsg.PayloadMessage) - packet := &Packet{ - Time: uint64(time.Now().UnixMilli()), - Dir: "SEND", - CmdId: uint32(protoMsg.CmdId), - CmdName: cmdName, - HeadMsg: string(headMsg), - PayloadMsg: string(payloadMsg), - } - packetData, _ := json.Marshal(packet) - s.PktLock.Lock() - s.PktList = append(s.PktList, packet) - if s.PktCapWsConn != nil { - err := s.PktCapWsConn.WriteMessage(websocket.TextMessage, packetData) - if err != nil { - s.PktCapWsConn = nil - } - } - s.PktLock.Unlock() + cmdName := string(protoMsg.PayloadMessage.ProtoReflect().Descriptor().FullName()) + headMsg, _ := json.Marshal(protoMsg.HeadMessage) + payloadMsg, _ := json.Marshal(protoMsg.PayloadMessage) + packet := &Packet{ + Time: uint64(time.Now().UnixMilli()), + Dir: "SEND", + CmdId: uint32(protoMsg.CmdId), + CmdName: cmdName, + HeadMsg: string(headMsg), + PayloadMsg: string(payloadMsg), } + packetData, _ := json.Marshal(packet) + s.PktLock.Lock() + s.PktList = append(s.PktList, packet) + if s.PktCapWsConn != nil { + err := s.PktCapWsConn.WriteMessage(websocket.TextMessage, packetData) + if err != nil { + s.PktCapWsConn = nil + } + } + s.PktLock.Unlock() } }