Compare commits

...

6 Commits

Author SHA1 Message Date
850dd59967 protocol/packet: accept structs by value for encoding
- server/loginServer: no longer sending packets by pointer, except in cases like AcceptLogin(), which operates on a sent structure slice. since these are already allocated, no need to copy them
2023-03-11 00:24:20 -06:00
00fa94162c server: refactoring; start support for variadic packets 2023-03-10 23:59:13 -06:00
d60638d555 loginServer/peer: peer no longer uses panic/recover for error recovery 2023-03-10 20:30:16 -06:00
857250bf33 protocol/packet: don't panic, return errors 2023-03-10 20:07:48 -06:00
f1552830a0 protocol/packet: switch away from allocation
- Packet struct is small enough that allocation for it is really unnecessary, and can be passed around by value fairly easily
2023-03-10 20:00:06 -06:00
985890d351 protocol: packets operate on io.ReadWritter; now use a buffer pool to encode/decode packets 2023-03-10 19:56:05 -06:00
6 changed files with 233 additions and 198 deletions

View File

@ -178,7 +178,7 @@ func (db *DBHandler) GetPlayer(PlayerID int) (*Player, error) {
&plr.SkywayLocationFlag, &plr.CurrentMissionID, &plr.FirstUseFlag, &plr.SkywayLocationFlag, &plr.CurrentMissionID, &plr.FirstUseFlag,
&plr.Body, &plr.EyeColor, &plr.FaceStyle, &plr.Gender, &plr.HairColor, &plr.HairStyle, &plr.Body, &plr.EyeColor, &plr.FaceStyle, &plr.Gender, &plr.HairColor, &plr.HairStyle,
&plr.Height, &plr.SkinColor); err != nil { &plr.Height, &plr.SkinColor); err != nil {
panic(err) return nil, err
} }
} }

View File

@ -4,7 +4,6 @@ import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"io" "io"
"log"
"reflect" "reflect"
"strconv" "strconv"
"unicode/utf16" "unicode/utf16"
@ -16,69 +15,23 @@ import (
*/ */
type Packet struct { type Packet struct {
ByteOrder binary.ByteOrder readWriter io.ReadWriter
Buf []byte
} }
func NewPacket(buf []byte) *Packet { func NewPacket(readWriter io.ReadWriter) Packet {
pkt := &Packet{ return Packet{
ByteOrder: binary.LittleEndian, readWriter: readWriter,
Buf: buf,
} }
return pkt
} }
func (pkt *Packet) writeRaw(data []byte) { func (pkt Packet) encodeStructField(field reflect.StructField, value reflect.Value) error {
pkt.Buf = append(pkt.Buf, data...) // log.Printf("Encoding '%s'", field.Name)
}
func (pkt *Packet) Write(data []byte) (int, error) {
pkt.writeRaw(data)
if len(pkt.Buf) > CN_PACKET_BUFFER_SIZE {
return 0, fmt.Errorf("Failed to write to packet, invalid size!")
}
return len(data), nil
}
func (pkt *Packet) writeByte(data byte) {
pkt.Write([]byte{data})
}
func (pkt *Packet) readRaw(data []byte) (int, error) {
sz := copy(data, pkt.Buf)
pkt.Buf = pkt.Buf[sz:]
if sz != len(data) {
return sz, io.EOF
}
return sz, nil
}
func (pkt *Packet) Read(data []byte) (int, error) {
if len(data) > len(pkt.Buf) {
return 0, fmt.Errorf("Failed to read from packet, invalid size!")
}
return pkt.readRaw(data)
}
func (pkt *Packet) readByte() byte {
data := pkt.Buf[0]
pkt.Buf = pkt.Buf[1:]
return data
}
func (pkt *Packet) encodeStructField(field reflect.StructField, value reflect.Value) {
log.Printf("Encoding '%s'", field.Name)
switch field.Type.Kind() { switch field.Type.Kind() {
case reflect.String: // all strings in fusionfall packets are encoded as utf16, we'll need to encode it case reflect.String: // all strings in fusionfall packets are encoded as utf16, we'll need to encode it
sz, err := strconv.Atoi(field.Tag.Get("size")) sz, err := strconv.Atoi(field.Tag.Get("size"))
if err != nil { if err != nil {
panic(fmt.Errorf("Failed to grab string 'size' tag!!")) return fmt.Errorf("Failed to grab string 'size' tag!!")
} }
buf16 := utf16.Encode([]rune(value.String())) buf16 := utf16.Encode([]rune(value.String()))
@ -89,27 +42,36 @@ func (pkt *Packet) encodeStructField(field reflect.StructField, value reflect.Va
buf16 = buf16[:sz] buf16 = buf16[:sz]
} else { } else {
// grow // grow
// TODO: probably a better way to do this?
for len(buf16) < sz { for len(buf16) < sz {
buf16 = append(buf16, 0) buf16 = append(buf16, 0)
} }
} }
// write // write
binary.Write(pkt, pkt.ByteOrder, buf16) if err := binary.Write(pkt.readWriter, binary.LittleEndian, buf16); err != nil {
return err
}
default: default:
pkt.Encode(value.Addr().Interface()) if err := pkt.Encode(value.Interface()); err != nil {
return err
}
} }
// write padding bytes // write padding bytes
pad, err := strconv.Atoi(field.Tag.Get("pad")) pad, err := strconv.Atoi(field.Tag.Get("pad"))
if err == nil { if err == nil {
for i := 0; i < pad; i++ { for i := 0; i < pad; i++ {
pkt.writeByte(0) if _, err := pkt.readWriter.Write([]byte{0}); err != nil {
return err
}
} }
} }
return nil
} }
func (pkt *Packet) Encode(data interface{}) { func (pkt Packet) Encode(data interface{}) error {
rv := reflect.Indirect(reflect.ValueOf(data)) rv := reflect.Indirect(reflect.ValueOf(data))
switch rv.Kind() { switch rv.Kind() {
@ -117,26 +79,34 @@ func (pkt *Packet) Encode(data interface{}) {
// walk through each struct fields // walk through each struct fields
sz := rv.NumField() sz := rv.NumField()
for i := 0; i < sz; i++ { for i := 0; i < sz; i++ {
pkt.encodeStructField(rv.Type().Field(i), rv.Field(i)) if err := pkt.encodeStructField(rv.Type().Field(i), rv.Field(i)); err != nil {
return err
}
} }
default: default:
// we pass everything else to go's binary package // we pass everything else to go's binary package
binary.Write(pkt, pkt.ByteOrder, data) if err := binary.Write(pkt.readWriter, binary.LittleEndian, data); err != nil {
return err
}
} }
return nil
} }
func (pkt *Packet) decodeStructField(field reflect.StructField, value reflect.Value) { func (pkt Packet) decodeStructField(field reflect.StructField, value reflect.Value) error {
log.Printf("Decoding '%s'", field.Name) // log.Printf("Decoding '%s'", field.Name)
switch field.Type.Kind() { switch field.Type.Kind() {
case reflect.String: // all strings in fusionfall packets are encoded as utf16, we'll need to decode it case reflect.String: // all strings in fusionfall packets are encoded as utf16, we'll need to decode it
sz, err := strconv.Atoi(field.Tag.Get("size")) sz, err := strconv.Atoi(field.Tag.Get("size"))
if err != nil { if err != nil {
panic(fmt.Errorf("Failed to grab string 'size' tag!!")) return fmt.Errorf("Failed to grab string 'size' tag!!")
} }
buf16 := make([]uint16, sz) buf16 := make([]uint16, sz)
binary.Read(pkt, pkt.ByteOrder, buf16) if err := binary.Read(pkt.readWriter, binary.LittleEndian, buf16); err != nil {
return err
}
// find null terminator // find null terminator
var realSize int var realSize int
@ -148,19 +118,25 @@ func (pkt *Packet) decodeStructField(field reflect.StructField, value reflect.Va
value.SetString(string(utf16.Decode(buf16[:realSize]))) value.SetString(string(utf16.Decode(buf16[:realSize])))
default: default:
pkt.Decode(value.Addr().Interface()) if err := pkt.Decode(value.Addr().Interface()); err != nil {
return err
}
} }
// read padding bytes // consume padding bytes
pad, err := strconv.Atoi(field.Tag.Get("pad")) pad, err := strconv.Atoi(field.Tag.Get("pad"))
if err == nil { if err == nil {
for i := 0; i < pad; i++ { for i := 0; i < pad; i++ {
pkt.readByte() if _, err := pkt.readWriter.Read([]byte{0}); err != nil {
return err
}
} }
} }
return nil
} }
func (pkt *Packet) Decode(data interface{}) { func (pkt Packet) Decode(data interface{}) error {
rv := reflect.Indirect(reflect.ValueOf(data)) rv := reflect.Indirect(reflect.ValueOf(data))
switch rv.Kind() { switch rv.Kind() {
@ -168,9 +144,15 @@ func (pkt *Packet) Decode(data interface{}) {
// walk through each struct fields // walk through each struct fields
sz := rv.NumField() sz := rv.NumField()
for i := 0; i < sz; i++ { for i := 0; i < sz; i++ {
pkt.decodeStructField(rv.Type().Field(i), rv.Field(i)) if err := pkt.decodeStructField(rv.Type().Field(i), rv.Field(i)); err != nil {
return err
}
} }
default: default:
binary.Read(pkt, pkt.ByteOrder, data) if err := binary.Read(pkt.readWriter, binary.LittleEndian, data); err != nil {
return err
}
} }
return nil
} }

19
protocol/pool/pool.go Normal file
View File

@ -0,0 +1,19 @@
package pool
import (
"bytes"
"sync"
)
var allocator = sync.Pool{
New: func() any { return new(bytes.Buffer) },
}
func Get() *bytes.Buffer {
return allocator.Get().(*bytes.Buffer)
}
func Put(buf *bytes.Buffer) {
buf.Reset()
allocator.Put(buf)
}

View File

@ -23,10 +23,10 @@ const (
LOGIN_UPDATED_EUALA_REQUIRED = 9 LOGIN_UPDATED_EUALA_REQUIRED = 9
) )
func (server *LoginServer) AcceptLogin(peer *Peer, SzID string, IClientVerC int32, ISlotNum int8, data []protocol.SP_LS2CL_REP_CHAR_INFO) { func (server *LoginServer) AcceptLogin(peer *Peer, SzID string, IClientVerC int32, ISlotNum int8, data []protocol.SP_LS2CL_REP_CHAR_INFO) error {
peer.SzID = SzID peer.SzID = SzID
resp := &protocol.SP_LS2CL_REP_LOGIN_SUCC{ resp := protocol.SP_LS2CL_REP_LOGIN_SUCC{
SzID: SzID, SzID: SzID,
ICharCount: int8(len(data)), ICharCount: int8(len(data)),
ISlotNum: ISlotNum, ISlotNum: ISlotNum,
@ -35,8 +35,11 @@ func (server *LoginServer) AcceptLogin(peer *Peer, SzID string, IClientVerC int3
UiSvrTime: uint64(time.Now().Unix()), UiSvrTime: uint64(time.Now().Unix()),
} }
if err := peer.Send(protocol.P_LS2CL_REP_LOGIN_SUCC, resp); err != nil {
return err
}
// swap keys // swap keys
peer.Send(resp, protocol.P_LS2CL_REP_LOGIN_SUCC)
peer.E_key = protocol.CreateNewKey( peer.E_key = protocol.CreateNewKey(
resp.UiSvrTime, resp.UiSvrTime,
uint64(resp.ICharCount+1), uint64(resp.ICharCount+1),
@ -50,25 +53,29 @@ func (server *LoginServer) AcceptLogin(peer *Peer, SzID string, IClientVerC int3
// send characters (if any) // send characters (if any)
for i := 0; i < len(data); i++ { for i := 0; i < len(data); i++ {
peer.Send(&data[i], protocol.P_LS2CL_REP_CHAR_INFO) if err := peer.Send(protocol.P_LS2CL_REP_CHAR_INFO, &data[i]); err != nil {
return err
}
} }
return nil
} }
func (server *LoginServer) Login(peer *Peer, pkt *protocol.Packet) { func (server *LoginServer) Login(peer *Peer, pkt protocol.Packet) error {
var loginPkt protocol.SP_CL2LS_REQ_LOGIN var loginPkt protocol.SP_CL2LS_REQ_LOGIN
pkt.Decode(&loginPkt) pkt.Decode(&loginPkt)
SendError := func(e int32) { SendError := func(e int32) {
peer.Send(&protocol.SP_LS2CL_REP_LOGIN_FAIL{ peer.Send(protocol.P_LS2CL_REP_LOGIN_FAIL, protocol.SP_LS2CL_REP_LOGIN_FAIL{
IErrorCode: e, IErrorCode: e,
SzID: loginPkt.SzID, SzID: loginPkt.SzID,
}, protocol.P_LS2CL_REP_LOGIN_FAIL) })
} }
// client is resending a login packet?? // client is resending a login packet??
if peer.AccountID != -1 { if peer.AccountID != -1 {
SendError(LOGIN_ERROR) SendError(LOGIN_ERROR)
panic(fmt.Errorf("Out of order P_CL2LS_REQ_LOGIN!")) return fmt.Errorf("Out of order P_CL2LS_REQ_LOGIN!")
} }
// attempt login // attempt login
@ -79,15 +86,15 @@ func (server *LoginServer) Login(peer *Peer, pkt *protocol.Packet) {
if err != nil { if err != nil {
// respond with a dummy login error packet so the client doesn't get softlocked // respond with a dummy login error packet so the client doesn't get softlocked
SendError(LOGIN_DATABASE_ERROR) SendError(LOGIN_DATABASE_ERROR)
panic(err) return err
} }
} else if err == db.LoginErrorInvalidPassword { } else if err == db.LoginErrorInvalidPassword {
// respond with invalid password // respond with invalid password
SendError(LOGIN_ID_AND_PASSWORD_DO_NOT_MATCH) SendError(LOGIN_ID_AND_PASSWORD_DO_NOT_MATCH)
return return nil
} else if err != nil { // wtf? } else if err != nil { // wtf?
SendError(LOGIN_DATABASE_ERROR) SendError(LOGIN_DATABASE_ERROR)
panic(err) return err
} }
// grab player data // grab player data
@ -95,11 +102,11 @@ func (server *LoginServer) Login(peer *Peer, pkt *protocol.Packet) {
plrs, err := db.DefaultDB.GetPlayers(account.AccountID) plrs, err := db.DefaultDB.GetPlayers(account.AccountID)
if err != nil { if err != nil {
SendError(LOGIN_DATABASE_ERROR) SendError(LOGIN_DATABASE_ERROR)
panic(err) return err
} }
// build character list // build character list
charInfo := make([]protocol.SP_LS2CL_REP_CHAR_INFO, 0) charInfo := make([]protocol.SP_LS2CL_REP_CHAR_INFO, 0, 4)
for _, plr := range plrs { for _, plr := range plrs {
PCStyle, PCStyle2 := util.Player2PCStyle(&plr) PCStyle, PCStyle2 := util.Player2PCStyle(&plr)
info := protocol.SP_LS2CL_REP_CHAR_INFO{ info := protocol.SP_LS2CL_REP_CHAR_INFO{
@ -115,50 +122,50 @@ func (server *LoginServer) Login(peer *Peer, pkt *protocol.Packet) {
AEquip, err := db.DefaultDB.GetPlayerInventorySlots(plr.PlayerID, 0, config.AEQUIP_COUNT-1) AEquip, err := db.DefaultDB.GetPlayerInventorySlots(plr.PlayerID, 0, config.AEQUIP_COUNT-1)
if err != nil { if err != nil {
SendError(LOGIN_DATABASE_ERROR) SendError(LOGIN_DATABASE_ERROR)
panic(err) return err
} }
copy(info.AEquip[:], AEquip) copy(info.AEquip[:], AEquip)
charInfo = append(charInfo, info) charInfo = append(charInfo, info)
} }
server.AcceptLogin(peer, loginPkt.SzID, loginPkt.IClientVerC, 1, charInfo) return server.AcceptLogin(peer, loginPkt.SzID, loginPkt.IClientVerC, 1, charInfo)
} }
func (server *LoginServer) CheckCharacterName(peer *Peer, pkt *protocol.Packet) { func (server *LoginServer) CheckCharacterName(peer *Peer, pkt protocol.Packet) error {
var charPkt protocol.SP_CL2LS_REQ_CHECK_CHAR_NAME var charPkt protocol.SP_CL2LS_REQ_CHECK_CHAR_NAME
pkt.Decode(&charPkt) pkt.Decode(&charPkt)
// just auto accept, client resends this data later // just auto accept, client resends this data later
peer.Send(&protocol.SP_LS2CL_REP_CHECK_CHAR_NAME_SUCC{ return peer.Send(protocol.P_LS2CL_REP_CHECK_CHAR_NAME_SUCC, protocol.SP_LS2CL_REP_CHECK_CHAR_NAME_SUCC{
SzFirstName: charPkt.SzFirstName, SzFirstName: charPkt.SzFirstName,
SzLastName: charPkt.SzLastName, SzLastName: charPkt.SzLastName,
}, protocol.P_LS2CL_REP_CHECK_CHAR_NAME_SUCC) })
} }
func (server *LoginServer) SaveCharacterName(peer *Peer, pkt *protocol.Packet) { func (server *LoginServer) SaveCharacterName(peer *Peer, pkt protocol.Packet) error {
var charPkt protocol.SP_CL2LS_REQ_SAVE_CHAR_NAME var charPkt protocol.SP_CL2LS_REQ_SAVE_CHAR_NAME
pkt.Decode(&charPkt) pkt.Decode(&charPkt)
if peer.AccountID == -1 { if peer.AccountID == -1 {
peer.Send(&protocol.SP_LS2CL_REP_SAVE_CHAR_NAME_FAIL{}, protocol.P_LS2CL_REP_SAVE_CHAR_NAME_FAIL) peer.Send(protocol.P_LS2CL_REP_SAVE_CHAR_NAME_FAIL, protocol.SP_LS2CL_REP_SAVE_CHAR_NAME_FAIL{})
panic(fmt.Errorf("Out of order P_LS2CL_REP_SAVE_CHAR_NAME_FAIL!")) return fmt.Errorf("Out of order P_LS2CL_REP_SAVE_CHAR_NAME_FAIL!")
} }
// TODO: sanity check SzFirstName && SzLastName // TODO: sanity check SzFirstName && SzLastName
PlayerID, err := db.DefaultDB.NewPlayer(peer.AccountID, charPkt.SzFirstName, charPkt.SzLastName, int(charPkt.ISlotNum)) PlayerID, err := db.DefaultDB.NewPlayer(peer.AccountID, charPkt.SzFirstName, charPkt.SzLastName, int(charPkt.ISlotNum))
if err != nil { if err != nil {
peer.Send(&protocol.SP_LS2CL_REP_SAVE_CHAR_NAME_FAIL{}, protocol.P_LS2CL_REP_SAVE_CHAR_NAME_FAIL) peer.Send(protocol.P_LS2CL_REP_SAVE_CHAR_NAME_FAIL, protocol.SP_LS2CL_REP_SAVE_CHAR_NAME_FAIL{})
panic(err) return err
} }
peer.Send(&protocol.SP_LS2CL_REP_SAVE_CHAR_NAME_SUCC{ return peer.Send(protocol.P_LS2CL_REP_SAVE_CHAR_NAME_SUCC, protocol.SP_LS2CL_REP_SAVE_CHAR_NAME_SUCC{
IPC_UID: int64(PlayerID), IPC_UID: int64(PlayerID),
ISlotNum: charPkt.ISlotNum, ISlotNum: charPkt.ISlotNum,
IGender: charPkt.IGender, IGender: charPkt.IGender,
SzFirstName: charPkt.SzFirstName, SzFirstName: charPkt.SzFirstName,
SzLastName: charPkt.SzLastName, SzLastName: charPkt.SzLastName,
}, protocol.P_LS2CL_REP_SAVE_CHAR_NAME_SUCC) })
} }
func validateCharacterCreation(character *protocol.SP_CL2LS_REQ_CHAR_CREATE) bool { func validateCharacterCreation(character *protocol.SP_CL2LS_REQ_CHAR_CREATE) bool {
@ -187,58 +194,64 @@ func validateCharacterCreation(character *protocol.SP_CL2LS_REQ_CHAR_CREATE) boo
return true return true
} }
func (server *LoginServer) CharacterCreate(peer *Peer, pkt *protocol.Packet) { func SendFail(peer *Peer) error {
if err := peer.Send(protocol.P_LS2CL_REP_SHARD_SELECT_FAIL, protocol.SP_LS2CL_REP_SHARD_SELECT_FAIL{
IErrorCode: 2,
}); err != nil {
return err
}
return nil
}
func (server *LoginServer) CharacterCreate(peer *Peer, pkt protocol.Packet) error {
var charPkt protocol.SP_CL2LS_REQ_CHAR_CREATE var charPkt protocol.SP_CL2LS_REQ_CHAR_CREATE
pkt.Decode(&charPkt) pkt.Decode(&charPkt)
if !validateCharacterCreation(&charPkt) { if !validateCharacterCreation(&charPkt) {
peer.Send(&protocol.SP_LS2CL_REP_SHARD_SELECT_FAIL{IErrorCode: 2}, protocol.P_LS2CL_REP_SHARD_SELECT_FAIL) return SendFail(peer)
panic(fmt.Errorf("invalid SP_CL2LS_REQ_CHAR_CREATE!"))
} }
if err := db.DefaultDB.FinishPlayer(&charPkt, peer.AccountID); err != nil { if err := db.DefaultDB.FinishPlayer(&charPkt, peer.AccountID); err != nil {
peer.Send(&protocol.SP_LS2CL_REP_SHARD_SELECT_FAIL{IErrorCode: 2}, protocol.P_LS2CL_REP_SHARD_SELECT_FAIL) return SendFail(peer)
panic(err)
} }
plr, err := db.DefaultDB.GetPlayer(int(charPkt.PCStyle.IPC_UID)) plr, err := db.DefaultDB.GetPlayer(int(charPkt.PCStyle.IPC_UID))
if err != nil { if err != nil {
peer.Send(&protocol.SP_LS2CL_REP_SHARD_SELECT_FAIL{IErrorCode: 2}, protocol.P_LS2CL_REP_SHARD_SELECT_FAIL) return SendFail(peer)
panic(err)
} }
PCStyle, PCStyle2 := util.Player2PCStyle(plr) PCStyle, PCStyle2 := util.Player2PCStyle(plr)
peer.Send(&protocol.SP_LS2CL_REP_CHAR_CREATE_SUCC{ return peer.Send(protocol.P_LS2CL_REP_CHAR_CREATE_SUCC, protocol.SP_LS2CL_REP_CHAR_CREATE_SUCC{
ILevel: int16(plr.Level), ILevel: int16(plr.Level),
SPC_Style: PCStyle, SPC_Style: PCStyle,
SPC_Style2: PCStyle2, SPC_Style2: PCStyle2,
SOn_Item: charPkt.SOn_Item, // if items were faked, we don't really care since the db only stores the sanitized fields SOn_Item: charPkt.SOn_Item, // if items were faked, we don't really care since the db only stores the sanitized fields
}, protocol.P_LS2CL_REP_CHAR_CREATE_SUCC) })
} }
func (server *LoginServer) CharacterDelete(peer *Peer, pkt *protocol.Packet) { func (server *LoginServer) CharacterDelete(peer *Peer, pkt protocol.Packet) error {
var charPkt protocol.SP_CL2LS_REQ_CHAR_DELETE var charPkt protocol.SP_CL2LS_REQ_CHAR_DELETE
pkt.Decode(&charPkt) pkt.Decode(&charPkt)
slot, err := db.DefaultDB.DeletePlayer(int(charPkt.IPC_UID), peer.AccountID) slot, err := db.DefaultDB.DeletePlayer(int(charPkt.IPC_UID), peer.AccountID)
if err != nil { if err != nil {
peer.Send(&protocol.SP_LS2CL_REP_SHARD_SELECT_FAIL{IErrorCode: 2}, protocol.P_LS2CL_REP_SHARD_SELECT_FAIL) return SendFail(peer)
panic(err)
} }
peer.Send(&protocol.SP_LS2CL_REP_CHAR_DELETE_SUCC{ return peer.Send(protocol.P_LS2CL_REP_CHAR_DELETE_SUCC, protocol.SP_LS2CL_REP_CHAR_DELETE_SUCC{
ISlotNum: int8(slot), ISlotNum: int8(slot),
}, protocol.P_LS2CL_REP_CHAR_DELETE_SUCC) })
} }
func (server *LoginServer) FinishTutorial(peer *Peer, pkt *protocol.Packet) { func (server *LoginServer) FinishTutorial(peer *Peer, pkt protocol.Packet) error {
var charPkt protocol.SP_CL2LS_REQ_SAVE_CHAR_TUTOR var charPkt protocol.SP_CL2LS_REQ_SAVE_CHAR_TUTOR
pkt.Decode(&charPkt) pkt.Decode(&charPkt)
if err := db.DefaultDB.FinishTutorial(int(charPkt.IPC_UID), peer.AccountID); err != nil { if err := db.DefaultDB.FinishTutorial(int(charPkt.IPC_UID), peer.AccountID); err != nil {
peer.Send(&protocol.SP_LS2CL_REP_SHARD_SELECT_FAIL{IErrorCode: 2}, protocol.P_LS2CL_REP_SHARD_SELECT_FAIL) return SendFail(peer)
panic(err)
} }
// no response // no response
return nil
} }

View File

@ -8,10 +8,13 @@ import (
"github.com/CPunch/gopenfusion/protocol" "github.com/CPunch/gopenfusion/protocol"
) )
type PacketHandler func(peer *Peer, pkt protocol.Packet) error
type LoginServer struct { type LoginServer struct {
listener net.Listener listener net.Listener
peers map[*Peer]bool packetHandlers map[uint32]PacketHandler
peersLock sync.Mutex peers map[*Peer]bool
peersLock sync.Mutex
} }
func NewLoginServer() *LoginServer { func NewLoginServer() *LoginServer {
@ -20,10 +23,32 @@ func NewLoginServer() *LoginServer {
log.Fatal(err) log.Fatal(err)
} }
return &LoginServer{ loginServer := &LoginServer{
listener: listener, listener: listener,
peers: make(map[*Peer]bool), packetHandlers: make(map[uint32]PacketHandler),
peers: make(map[*Peer]bool),
} }
loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_LOGIN, loginServer.Login)
loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_CHECK_CHAR_NAME, loginServer.CheckCharacterName)
loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_SAVE_CHAR_NAME, loginServer.SaveCharacterName)
loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_CHAR_CREATE, loginServer.CharacterCreate)
// loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_CHAR_SELECT, func(_ *Peer, _ protocol.Packet) error { /* stubbed */ return nil })
loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_CHAR_DELETE, loginServer.CharacterDelete)
// loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_SHARD_SELECT, func(_ *Peer, _ protocol.Packet) error { /* stubbed */ return nil })
// loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_SHARD_LIST_INFO, func(_ *Peer, _ protocol.Packet) error { /* stubbed */ return nil })
// loginServer.RegisterPacketHandler(protocol.P_CL2LS_CHECK_NAME_LIST, func(_ *Peer, _ protocol.Packet) error { /* stubbed */ return nil })
loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_SAVE_CHAR_TUTOR, loginServer.FinishTutorial)
// loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_PC_EXIT_DUPLICATE, func(_ *Peer, _ protocol.Packet) error { /* stubbed */ return nil })
// loginServer.RegisterPacketHandler(protocol.P_CL2LS_REP_LIVE_CHECK, func(_ *Peer, _ protocol.Packet) error { /* stubbed */ return nil })
// loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_CHANGE_CHAR_NAME, func(_ *Peer, _ protocol.Packet) error { /* stubbed */ return nil })
// loginServer.RegisterPacketHandler(protocol.P_CL2LS_REQ_SERVER_SELECT, func(_ *Peer, _ protocol.Packet) error { /* stubbed */ return nil })
return loginServer
}
func (server *LoginServer) RegisterPacketHandler(typeID uint32, hndlr PacketHandler) {
server.packetHandlers[typeID] = hndlr
} }
func (server *LoginServer) Start() { func (server *LoginServer) Start() {
@ -38,43 +63,20 @@ func (server *LoginServer) Start() {
client := NewPeer(server, conn) client := NewPeer(server, conn)
server.Connect(client) server.Connect(client)
go client.ClientHandler() go client.Handler()
} }
} }
func (server *LoginServer) HandlePacket(peer *Peer, typeID uint32, pkt *protocol.Packet) { func (server *LoginServer) HandlePacket(peer *Peer, typeID uint32, pkt protocol.Packet) error {
switch typeID { if hndlr, ok := server.packetHandlers[typeID]; ok {
case protocol.P_CL2LS_REQ_LOGIN: if err := hndlr(peer, pkt); err != nil {
server.Login(peer, pkt) return err
case protocol.P_CL2LS_REQ_CHECK_CHAR_NAME: }
server.CheckCharacterName(peer, pkt) } else {
case protocol.P_CL2LS_REQ_SAVE_CHAR_NAME:
server.SaveCharacterName(peer, pkt)
case protocol.P_CL2LS_REQ_CHAR_CREATE:
server.CharacterCreate(peer, pkt)
case protocol.P_CL2LS_REQ_CHAR_SELECT:
/* stubbed */
case protocol.P_CL2LS_REQ_CHAR_DELETE:
server.CharacterDelete(peer, pkt)
case protocol.P_CL2LS_REQ_SHARD_SELECT:
/* stubbed */
case protocol.P_CL2LS_REQ_SHARD_LIST_INFO:
/* stubbed */
case protocol.P_CL2LS_CHECK_NAME_LIST:
/* stubbed */
case protocol.P_CL2LS_REQ_SAVE_CHAR_TUTOR:
server.FinishTutorial(peer, pkt)
case protocol.P_CL2LS_REQ_PC_EXIT_DUPLICATE:
/* stubbed */
case protocol.P_CL2LS_REP_LIVE_CHECK:
/* stubbed */
case protocol.P_CL2LS_REQ_CHANGE_CHAR_NAME:
/* stubbed */
case protocol.P_CL2LS_REQ_SERVER_SELECT:
/* stubbed */
default:
log.Printf("[WARN] unsupported packet ID: %x\n", typeID) log.Printf("[WARN] unsupported packet ID: %x\n", typeID)
} }
return nil
} }
func (server *LoginServer) Disconnect(peer *Peer) { func (server *LoginServer) Disconnect(peer *Peer) {

View File

@ -3,11 +3,13 @@ package server
import ( import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"io"
"log" "log"
"net" "net"
"github.com/CPunch/gopenfusion/db" "github.com/CPunch/gopenfusion/db"
"github.com/CPunch/gopenfusion/protocol" "github.com/CPunch/gopenfusion/protocol"
"github.com/CPunch/gopenfusion/protocol/pool"
) )
const ( const (
@ -16,7 +18,7 @@ const (
) )
type PeerHandler interface { type PeerHandler interface {
HandlePacket(client *Peer, typeID uint32, pkt *protocol.Packet) HandlePacket(client *Peer, typeID uint32, pkt protocol.Packet) error
Connect(client *Peer) Connect(client *Peer)
Disconnect(client *Peer) Disconnect(client *Peer)
} }
@ -47,83 +49,100 @@ func NewPeer(handler PeerHandler, conn net.Conn) *Peer {
} }
} }
func (client *Peer) Send(data interface{}, typeID uint32) { func (peer *Peer) Send(typeID uint32, data ...interface{}) error {
// encode buf := pool.Get()
pkt := protocol.NewPacket(make([]byte, 0)) defer pool.Put(buf) // always return the buffer to the pool
pkt.Encode(data)
log.Printf("Sending %#v, sizeof: %d", data, len(pkt.Buf))
// write packet size // body start
tmp := make([]byte, 4) pkt := protocol.NewPacket(buf)
binary.LittleEndian.PutUint32(tmp, uint32(len(pkt.Buf)+4))
if _, err := client.conn.Write(tmp); err != nil { // encode type id
panic(fmt.Errorf("[FATAL] failed to write packet size! %v", err)) if err := pkt.Encode(uint32(typeID)); err != nil {
return err
} }
// prepend the typeID to the packet body // encode data
binary.LittleEndian.PutUint32(tmp, uint32(typeID)) for _, trailer := range data {
tmp = append(tmp, pkt.Buf...) if err := pkt.Encode(trailer); err != nil {
return err
}
}
// encrypt typeID & body // encrypt body
switch client.whichKey { switch peer.whichKey {
case USE_E: case USE_E:
protocol.EncryptData(tmp, client.E_key) protocol.EncryptData(buf.Bytes(), peer.E_key)
case USE_FE: case USE_FE:
protocol.EncryptData(tmp, client.FE_key) protocol.EncryptData(buf.Bytes(), peer.FE_key)
}
// write packet size
if err := binary.Write(peer.conn, binary.LittleEndian, uint32(buf.Len())); err != nil {
return err
} }
// write packet body // write packet body
if _, err := client.conn.Write(tmp); err != nil { log.Printf("Sending %#v, sizeof: %d", data, buf.Len())
panic(fmt.Errorf("[FATAL] failed to write packet body! %v", err)) if _, err := peer.conn.Write(buf.Bytes()); err != nil {
return fmt.Errorf("[FATAL] failed to write packet body! %v", err)
} }
return nil
} }
func (client *Peer) Kill() { func (peer *Peer) Kill() {
if !client.alive { if !peer.alive {
return return
} }
client.alive = false peer.alive = false
client.conn.Close() peer.conn.Close()
client.handler.Disconnect(client) peer.handler.Disconnect(peer)
} }
func (client *Peer) ClientHandler() { func (peer *Peer) Handler() {
defer func() { defer peer.Kill()
if err := recover(); err != nil {
log.Printf("Client %p panic'd! %v", client, err)
}
client.Kill()
}()
tmp := make([]byte, 4, protocol.CN_PACKET_BUFFER_SIZE)
for { for {
// read packet size // read packet size, the goroutine spends most of it's time parked here
if _, err := client.conn.Read(tmp); err != nil { var sz uint32
panic(fmt.Errorf("[FATAL] failed to read packet size! %v", err)) if err := binary.Read(peer.conn, binary.LittleEndian, &sz); err != nil {
log.Printf("[FATAL] failed to read packet size! %v\n", err)
return
} }
sz := int(binary.LittleEndian.Uint32(tmp))
// client should never send a packet size outside of this range // client should never send a packet size outside of this range
if sz > protocol.CN_PACKET_BUFFER_SIZE || sz < 4 { if sz > protocol.CN_PACKET_BUFFER_SIZE || sz < 4 {
panic(fmt.Errorf("[FATAL] malicious packet size received! %d", sz)) log.Printf("[FATAL] malicious packet size received! %d", sz)
return
} }
// read packet body // read packet body
if _, err := client.conn.Read(tmp[:sz]); err != nil { buf := pool.Get()
panic(fmt.Errorf("[FATAL] failed to read packet body! %v", err)) if _, err := buf.ReadFrom(io.LimitReader(peer.conn, int64(sz))); err != nil {
log.Printf("[FATAL] failed to read packet body! %v", err)
return
} }
// decrypt && grab typeID // decrypt
protocol.DecryptData(tmp[:sz], client.E_key) protocol.DecryptData(buf.Bytes(), peer.E_key)
typeID := uint32(binary.LittleEndian.Uint32(tmp[:4])) pkt := protocol.NewPacket(buf)
// create packet && read typeID
var typeID uint32
if err := pkt.Decode(&typeID); err != nil {
log.Printf("[FATAL] failed to read packet type! %v", err)
return
}
// dispatch packet // dispatch packet
log.Printf("Got packet ID: %x, with a sizeof: %d\n", typeID, sz) log.Printf("Got packet ID: %x, with a sizeof: %d\n", typeID, sz)
pkt := protocol.NewPacket(tmp[4:sz]) if err := peer.handler.HandlePacket(peer, typeID, pkt); err != nil {
client.handler.HandlePacket(client, typeID, pkt) log.Printf("[FATAL] %v", err)
return
}
// reset tmp // restore buffer to pool
tmp = tmp[:4] pool.Put(buf)
} }
} }