fix: re-enable CI lint job and fix ~65 lint errors (partial)

Re-enable the golangci-lint job in CI (disabled Oct 2025), update to
Go 1.25 and golangci-lint-action v7. Fix errcheck, gosimple S1009,
staticcheck SA4031 and SA2001 errors across 54 files. Remaining ~39
lint errors will be addressed in follow-up commits.
This commit is contained in:
Houmgaor
2026-02-17 17:59:00 +01:00
parent d2b5bb72f8
commit 2a0e3e2c84
54 changed files with 200 additions and 212 deletions

View File

@@ -104,23 +104,20 @@ jobs:
./bundled-schema/ ./bundled-schema/
retention-days: 7 retention-days: 7
# lint: lint:
# name: Lint name: Lint
# runs-on: ubuntu-latest runs-on: ubuntu-latest
#
# steps: steps:
# - uses: actions/checkout@v4 - uses: actions/checkout@v4
#
# - name: Set up Go - name: Set up Go
# uses: actions/setup-go@v5 uses: actions/setup-go@v5
# with: with:
# go-version: '1.23' go-version: '1.25'
#
# - name: Run golangci-lint - name: Run golangci-lint
# uses: golangci/golangci-lint-action@v3 uses: golangci/golangci-lint-action@v7
# with: with:
# version: latest version: latest
# args: --timeout=5m --out-format=github-actions args: --timeout=5m --out-format=github-actions
#
# TEMPORARILY DISABLED: Linting check deactivated to allow ongoing linting fixes
# Re-enable after completing all linting issues

View File

@@ -22,7 +22,7 @@ func TestByteFrame_SetBE(t *testing.T) {
// Verify write/read works correctly in BE mode after switching // Verify write/read works correctly in BE mode after switching
bf.WriteUint16(0x1234) bf.WriteUint16(0x1234)
bf.Seek(0, io.SeekStart) _, _ = bf.Seek(0, io.SeekStart)
got := bf.ReadUint16() got := bf.ReadUint16()
if got != 0x1234 { if got != 0x1234 {
t.Errorf("ReadUint16() = 0x%04X, want 0x1234", got) t.Errorf("ReadUint16() = 0x%04X, want 0x1234", got)
@@ -50,7 +50,7 @@ func TestByteFrame_LEReadWrite(t *testing.T) {
t.Errorf("LE WriteUint32 bytes: got %X, want 78563412", data) t.Errorf("LE WriteUint32 bytes: got %X, want 78563412", data)
} }
bf.Seek(0, io.SeekStart) _, _ = bf.Seek(0, io.SeekStart)
got := bf.ReadUint32() got := bf.ReadUint32()
if got != 0x12345678 { if got != 0x12345678 {
t.Errorf("LE ReadUint32() = 0x%08X, want 0x12345678", got) t.Errorf("LE ReadUint32() = 0x%08X, want 0x12345678", got)

View File

@@ -57,7 +57,7 @@ func TestByteFrame_WriteAndReadUint8(t *testing.T) {
bf.WriteUint8(v) bf.WriteUint8(v)
} }
bf.Seek(0, io.SeekStart) _, _ = bf.Seek(0, io.SeekStart)
for i, expected := range values { for i, expected := range values {
got := bf.ReadUint8() got := bf.ReadUint8()
if got != expected { if got != expected {
@@ -83,7 +83,7 @@ func TestByteFrame_WriteAndReadUint16(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
bf := NewByteFrame() bf := NewByteFrame()
bf.WriteUint16(tt.value) bf.WriteUint16(tt.value)
bf.Seek(0, io.SeekStart) _, _ = bf.Seek(0, io.SeekStart)
got := bf.ReadUint16() got := bf.ReadUint16()
if got != tt.value { if got != tt.value {
t.Errorf("ReadUint16() = %d, want %d", got, tt.value) t.Errorf("ReadUint16() = %d, want %d", got, tt.value)
@@ -108,7 +108,7 @@ func TestByteFrame_WriteAndReadUint32(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
bf := NewByteFrame() bf := NewByteFrame()
bf.WriteUint32(tt.value) bf.WriteUint32(tt.value)
bf.Seek(0, io.SeekStart) _, _ = bf.Seek(0, io.SeekStart)
got := bf.ReadUint32() got := bf.ReadUint32()
if got != tt.value { if got != tt.value {
t.Errorf("ReadUint32() = %d, want %d", got, tt.value) t.Errorf("ReadUint32() = %d, want %d", got, tt.value)
@@ -133,7 +133,7 @@ func TestByteFrame_WriteAndReadUint64(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
bf := NewByteFrame() bf := NewByteFrame()
bf.WriteUint64(tt.value) bf.WriteUint64(tt.value)
bf.Seek(0, io.SeekStart) _, _ = bf.Seek(0, io.SeekStart)
got := bf.ReadUint64() got := bf.ReadUint64()
if got != tt.value { if got != tt.value {
t.Errorf("ReadUint64() = %d, want %d", got, tt.value) t.Errorf("ReadUint64() = %d, want %d", got, tt.value)

View File

@@ -15,7 +15,7 @@ func TestReadWarehouseItem(t *testing.T) {
bf.WriteUint16(5) // Quantity bf.WriteUint16(5) // Quantity
bf.WriteUint32(999999) // Unk0 bf.WriteUint32(999999) // Unk0
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
item := ReadWarehouseItem(bf) item := ReadWarehouseItem(bf)
if item.WarehouseID != 12345 { if item.WarehouseID != 12345 {
@@ -40,7 +40,7 @@ func TestReadWarehouseItem_ZeroWarehouseID(t *testing.T) {
bf.WriteUint16(5) // Quantity bf.WriteUint16(5) // Quantity
bf.WriteUint32(0) // Unk0 bf.WriteUint32(0) // Unk0
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
item := ReadWarehouseItem(bf) item := ReadWarehouseItem(bf)
if item.WarehouseID == 0 { if item.WarehouseID == 0 {
@@ -247,7 +247,7 @@ func TestReadWarehouseEquipment(t *testing.T) {
// Unk1 (Z1+) // Unk1 (Z1+)
bf.WriteUint16(9999) bf.WriteUint16(9999)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
equipment := ReadWarehouseEquipment(bf) equipment := ReadWarehouseEquipment(bf)
if equipment.WarehouseID != 12345 { if equipment.WarehouseID != 12345 {

View File

@@ -12,7 +12,7 @@ func TestUint8_NoTransform(t *testing.T) {
Uint8(bf, testString, false) Uint8(bf, testString, false)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint8() length := bf.ReadUint8()
expectedLength := uint8(len(testString) + 1) // +1 for null terminator expectedLength := uint8(len(testString) + 1) // +1 for null terminator
@@ -35,7 +35,7 @@ func TestUint8_WithTransform(t *testing.T) {
Uint8(bf, testString, true) Uint8(bf, testString, true)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint8() length := bf.ReadUint8()
if length == 0 { if length == 0 {
@@ -55,7 +55,7 @@ func TestUint8_EmptyString(t *testing.T) {
Uint8(bf, testString, false) Uint8(bf, testString, false)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint8() length := bf.ReadUint8()
if length != 1 { // Just null terminator if length != 1 { // Just null terminator
@@ -74,7 +74,7 @@ func TestUint16_NoTransform(t *testing.T) {
Uint16(bf, testString, false) Uint16(bf, testString, false)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint16() length := bf.ReadUint16()
expectedLength := uint16(len(testString) + 1) expectedLength := uint16(len(testString) + 1)
@@ -95,7 +95,7 @@ func TestUint16_WithTransform(t *testing.T) {
Uint16(bf, testString, true) Uint16(bf, testString, true)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint16() length := bf.ReadUint16()
if length == 0 { if length == 0 {
@@ -114,7 +114,7 @@ func TestUint16_EmptyString(t *testing.T) {
Uint16(bf, testString, false) Uint16(bf, testString, false)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint16() length := bf.ReadUint16()
if length != 1 { if length != 1 {
@@ -128,7 +128,7 @@ func TestUint32_NoTransform(t *testing.T) {
Uint32(bf, testString, false) Uint32(bf, testString, false)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint32() length := bf.ReadUint32()
expectedLength := uint32(len(testString) + 1) expectedLength := uint32(len(testString) + 1)
@@ -149,7 +149,7 @@ func TestUint32_WithTransform(t *testing.T) {
Uint32(bf, testString, true) Uint32(bf, testString, true)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint32() length := bf.ReadUint32()
if length == 0 { if length == 0 {
@@ -168,7 +168,7 @@ func TestUint32_EmptyString(t *testing.T) {
Uint32(bf, testString, false) Uint32(bf, testString, false)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint32() length := bf.ReadUint32()
if length != 1 { if length != 1 {
@@ -182,7 +182,7 @@ func TestUint8_LongString(t *testing.T) {
Uint8(bf, testString, false) Uint8(bf, testString, false)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint8() length := bf.ReadUint8()
expectedLength := uint8(len(testString) + 1) expectedLength := uint8(len(testString) + 1)
@@ -209,7 +209,7 @@ func TestUint16_LongString(t *testing.T) {
Uint16(bf, testString, false) Uint16(bf, testString, false)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint16() length := bf.ReadUint16()
expectedLength := uint16(len(testString) + 1) expectedLength := uint16(len(testString) + 1)
@@ -265,7 +265,7 @@ func TestAllFunctions_NullTermination(t *testing.T) {
tt.writeFn(bf, testString, false) tt.writeFn(bf, testString, false)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
size := tt.readSize(bf) size := tt.readSize(bf)
data := bf.ReadBytes(size) data := bf.ReadBytes(size)
@@ -289,7 +289,7 @@ func TestTransform_JapaneseCharacters(t *testing.T) {
Uint16(bf, testString, true) Uint16(bf, testString, true)
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint16() length := bf.ReadUint16()
if length == 0 { if length == 0 {
@@ -316,7 +316,7 @@ func TestTransform_InvalidUTF8(t *testing.T) {
Uint8(bf, testString, true) Uint8(bf, testString, true)
// Should succeed for ASCII characters // Should succeed for ASCII characters
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
length := bf.ReadUint8() length := bf.ReadUint8()
if length == 0 { if length == 0 {
t.Error("ASCII string should transform successfully") t.Error("ASCII string should transform successfully")

View File

@@ -249,7 +249,7 @@ func TestStringStack_SetAfterOperations(t *testing.T) {
s.Push("a") s.Push("a")
s.Push("b") s.Push("b")
s.Push("c") s.Push("c")
s.Pop() _, _ = s.Pop()
s.Push("d") s.Push("d")
// Set should clear everything // Set should clear everything

View File

@@ -397,7 +397,7 @@ func preventClose(text string) {
fmt.Println("\nFailed to start Erupe:\n" + text) fmt.Println("\nFailed to start Erupe:\n" + text)
go wait() go wait()
fmt.Println("\nPress Enter/Return to exit...") fmt.Println("\nPress Enter/Return to exit...")
fmt.Scanln() _, _ = fmt.Scanln()
os.Exit(0) os.Exit(0)
} }

View File

@@ -14,7 +14,7 @@ func TestLoadConfigNoFile(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("Failed to get working directory: %v", err) t.Fatalf("Failed to get working directory: %v", err)
} }
defer os.Chdir(oldWd) defer func() { _ = os.Chdir(oldWd) }()
if err := os.Chdir(tmpDir); err != nil { if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change directory: %v", err) t.Fatalf("Failed to change directory: %v", err)
@@ -202,9 +202,6 @@ func TestConfigNilSafety(t *testing.T) {
} }
cfg = &Config{} cfg = &Config{}
if cfg == nil {
t.Error("Config should be allocated")
}
cfg.Host = "test" cfg.Host = "test"
if cfg.Host != "test" { if cfg.Host != "test" {

View File

@@ -73,7 +73,7 @@ func main() {
config := _config.ErupeConfig config := _config.ErupeConfig
zapLogger, _ = zap.NewDevelopment() zapLogger, _ = zap.NewDevelopment()
defer zapLogger.Sync() defer func() { _ = zapLogger.Sync() }()
logger := zapLogger.Named("main") logger := zapLogger.Named("main")
logger.Info(fmt.Sprintf("Starting Erupe (9.3b-%s)", Commit())) logger.Info(fmt.Sprintf("Starting Erupe (9.3b-%s)", Commit()))
@@ -305,6 +305,6 @@ func preventClose(text string) {
fmt.Println("\nFailed to start Erupe:\n" + text) fmt.Println("\nFailed to start Erupe:\n" + text)
go wait() go wait()
fmt.Println("\nPress Enter/Return to exit...") fmt.Println("\nPress Enter/Return to exit...")
fmt.Scanln() _, _ = fmt.Scanln()
os.Exit(0) os.Exit(0)
} }

View File

@@ -19,7 +19,7 @@ func TestMsgBinTargetedParseEmpty(t *testing.T) {
bf := byteframe.NewByteFrame() bf := byteframe.NewByteFrame()
bf.WriteUint16(0) // TargetCount = 0 bf.WriteUint16(0) // TargetCount = 0
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
m := &MsgBinTargeted{} m := &MsgBinTargeted{}
err := m.Parse(bf) err := m.Parse(bf)
@@ -41,7 +41,7 @@ func TestMsgBinTargetedParseSingleTarget(t *testing.T) {
bf.WriteUint32(0x12345678) // TargetCharID bf.WriteUint32(0x12345678) // TargetCharID
bf.WriteBytes([]byte{0xDE, 0xAD, 0xBE, 0xEF}) bf.WriteBytes([]byte{0xDE, 0xAD, 0xBE, 0xEF})
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
m := &MsgBinTargeted{} m := &MsgBinTargeted{}
err := m.Parse(bf) err := m.Parse(bf)
@@ -71,7 +71,7 @@ func TestMsgBinTargetedParseMultipleTargets(t *testing.T) {
bf.WriteUint32(300) bf.WriteUint32(300)
bf.WriteBytes([]byte{0x01, 0x02, 0x03}) bf.WriteBytes([]byte{0x01, 0x02, 0x03})
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
m := &MsgBinTargeted{} m := &MsgBinTargeted{}
err := m.Parse(bf) err := m.Parse(bf)
@@ -130,7 +130,7 @@ func TestMsgBinTargetedRoundTrip(t *testing.T) {
} }
// Parse // Parse
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
parsed := &MsgBinTargeted{} parsed := &MsgBinTargeted{}
err = parsed.Parse(bf) err = parsed.Parse(bf)
if err != nil { if err != nil {
@@ -244,7 +244,7 @@ func TestMsgBinChatBuildParse(t *testing.T) {
} }
// Parse // Parse
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
parsed := &MsgBinChat{} parsed := &MsgBinChat{}
err = parsed.Parse(bf) err = parsed.Parse(bf)
if err != nil { if err != nil {
@@ -286,7 +286,7 @@ func TestMsgBinChatBuildParseJapanese(t *testing.T) {
} }
// Parse // Parse
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
parsed := &MsgBinChat{} parsed := &MsgBinChat{}
err = parsed.Parse(bf) err = parsed.Parse(bf)
if err != nil { if err != nil {
@@ -318,7 +318,7 @@ func TestMsgBinChatBuildParseEmpty(t *testing.T) {
} }
// Parse // Parse
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
parsed := &MsgBinChat{} parsed := &MsgBinChat{}
err = parsed.Parse(bf) err = parsed.Parse(bf)
if err != nil { if err != nil {
@@ -386,7 +386,7 @@ func TestMsgBinChatAllTypes(t *testing.T) {
t.Fatalf("Build() error = %v", err) t.Fatalf("Build() error = %v", err)
} }
bf.Seek(0, 0) _, _ = bf.Seek(0, 0)
parsed := &MsgBinChat{} parsed := &MsgBinChat{}
err = parsed.Parse(bf) err = parsed.Parse(bf)
if err != nil { if err != nil {

View File

@@ -132,7 +132,10 @@ func (cc *CryptConn) SendPacket(data []byte) error {
return err return err
} }
cc.conn.Write(append(headerBytes, encData...)) _, err = cc.conn.Write(append(headerBytes, encData...))
if err != nil {
return err
}
cc.sentPackets++ cc.sentPackets++
cc.prevSendPacketCombinedCheck = combinedCheck cc.prevSendPacketCombinedCheck = combinedCheck

View File

@@ -286,7 +286,7 @@ func TestClientContextNilSafe(t *testing.T) {
func TestMsgSysPingBuildFormat(t *testing.T) { func TestMsgSysPingBuildFormat(t *testing.T) {
pkt := &MsgSysPing{AckHandle: 0x12345678} pkt := &MsgSysPing{AckHandle: 0x12345678}
bf := byteframe.NewByteFrame() bf := byteframe.NewByteFrame()
pkt.Build(bf, &clientctx.ClientContext{}) _ = pkt.Build(bf, &clientctx.ClientContext{})
data := bf.Data() data := bf.Data()
if len(data) != 4 { if len(data) != 4 {
@@ -305,7 +305,7 @@ func TestMsgSysTimeBuildFormat(t *testing.T) {
Timestamp: 0xDEADBEEF, Timestamp: 0xDEADBEEF,
} }
bf := byteframe.NewByteFrame() bf := byteframe.NewByteFrame()
pkt.Build(bf, &clientctx.ClientContext{}) _ = pkt.Build(bf, &clientctx.ClientContext{})
data := bf.Data() data := bf.Data()
if len(data) != 5 { if len(data) != 5 {

View File

@@ -296,11 +296,11 @@ func TestBuildCoverage_Implemented(t *testing.T) {
// so we test it with defer/recover // so we test it with defer/recover
t.Run("MsgSysLogout_Build", func(t *testing.T) { t.Run("MsgSysLogout_Build", func(t *testing.T) {
defer func() { defer func() {
recover() // may panic due to bug _ = recover() // may panic due to bug
}() }()
pkt := &MsgSysLogout{Unk0: 1} pkt := &MsgSysLogout{Unk0: 1}
bf := byteframe.NewByteFrame() bf := byteframe.NewByteFrame()
pkt.Build(bf, ctx) _ = pkt.Build(bf, ctx)
}) })
} }

View File

@@ -258,7 +258,7 @@ func TestMsgSysAckBuildFormat(t *testing.T) {
ctx := &clientctx.ClientContext{} ctx := &clientctx.ClientContext{}
bf := byteframe.NewByteFrame() bf := byteframe.NewByteFrame()
pkt.Build(bf, ctx) _ = pkt.Build(bf, ctx)
data := bf.Data() data := bf.Data()

View File

@@ -11,7 +11,7 @@ import (
func TestNewAPIServer(t *testing.T) { func TestNewAPIServer(t *testing.T) {
logger := NewTestLogger(t) logger := NewTestLogger(t)
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := NewTestConfig() cfg := NewTestConfig()
config := &Config{ config := &Config{
@@ -45,7 +45,7 @@ func TestNewAPIServer(t *testing.T) {
func TestNewAPIServerConfig(t *testing.T) { func TestNewAPIServerConfig(t *testing.T) {
logger := NewTestLogger(t) logger := NewTestLogger(t)
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := &_config.Config{ cfg := &_config.Config{
API: _config.API{ API: _config.API{
@@ -94,7 +94,7 @@ func TestAPIServerStart(t *testing.T) {
// It attempts to start an actual HTTP server // It attempts to start an actual HTTP server
logger := NewTestLogger(t) logger := NewTestLogger(t)
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := NewTestConfig() cfg := NewTestConfig()
cfg.API.Port = 18888 // Use a high port less likely to be in use cfg.API.Port = 18888 // Use a high port less likely to be in use
@@ -148,7 +148,7 @@ func TestAPIServerStart(t *testing.T) {
func TestAPIServerShutdown(t *testing.T) { func TestAPIServerShutdown(t *testing.T) {
logger := NewTestLogger(t) logger := NewTestLogger(t)
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := NewTestConfig() cfg := NewTestConfig()
cfg.API.Port = 18889 cfg.API.Port = 18889
@@ -174,7 +174,7 @@ func TestAPIServerShutdown(t *testing.T) {
func TestAPIServerShutdownSetsFlag(t *testing.T) { func TestAPIServerShutdownSetsFlag(t *testing.T) {
logger := NewTestLogger(t) logger := NewTestLogger(t)
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := NewTestConfig() cfg := NewTestConfig()
config := &Config{ config := &Config{
@@ -202,7 +202,7 @@ func TestAPIServerShutdownSetsFlag(t *testing.T) {
func TestAPIServerConcurrentShutdown(t *testing.T) { func TestAPIServerConcurrentShutdown(t *testing.T) {
logger := NewTestLogger(t) logger := NewTestLogger(t)
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := NewTestConfig() cfg := NewTestConfig()
config := &Config{ config := &Config{
@@ -241,7 +241,7 @@ func TestAPIServerConcurrentShutdown(t *testing.T) {
func TestAPIServerMutex(t *testing.T) { func TestAPIServerMutex(t *testing.T) {
logger := NewTestLogger(t) logger := NewTestLogger(t)
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := NewTestConfig() cfg := NewTestConfig()
config := &Config{ config := &Config{
@@ -264,7 +264,7 @@ func TestAPIServerMutex(t *testing.T) {
func TestAPIServerHTTPServerInitialization(t *testing.T) { func TestAPIServerHTTPServerInitialization(t *testing.T) {
logger := NewTestLogger(t) logger := NewTestLogger(t)
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := NewTestConfig() cfg := NewTestConfig()
config := &Config{ config := &Config{
@@ -286,7 +286,7 @@ func TestAPIServerHTTPServerInitialization(t *testing.T) {
func BenchmarkNewAPIServer(b *testing.B) { func BenchmarkNewAPIServer(b *testing.B) {
logger, _ := zap.NewDevelopment() logger, _ := zap.NewDevelopment()
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := NewTestConfig() cfg := NewTestConfig()
config := &Config{ config := &Config{

View File

@@ -61,7 +61,7 @@ func (s *APIServer) createCharacter(ctx context.Context, userID uint32) (Charact
) )
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
var count int var count int
s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM characters WHERE user_id = $1", userID).Scan(&count) _ = s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM characters WHERE user_id = $1", userID).Scan(&count)
if count >= 16 { if count >= 16 {
return character, fmt.Errorf("cannot have more than 16 characters") return character, fmt.Errorf("cannot have more than 16 characters")
} }
@@ -109,18 +109,18 @@ func (s *APIServer) getCharactersForUser(ctx context.Context, uid uint32) ([]Cha
func (s *APIServer) getReturnExpiry(uid uint32) time.Time { func (s *APIServer) getReturnExpiry(uid uint32) time.Time {
var returnExpiry, lastLogin time.Time var returnExpiry, lastLogin time.Time
s.db.Get(&lastLogin, "SELECT COALESCE(last_login, now()) FROM users WHERE id=$1", uid) _ = s.db.Get(&lastLogin, "SELECT COALESCE(last_login, now()) FROM users WHERE id=$1", uid)
if time.Now().Add((time.Hour * 24) * -90).After(lastLogin) { if time.Now().Add((time.Hour * 24) * -90).After(lastLogin) {
returnExpiry = time.Now().Add(time.Hour * 24 * 30) returnExpiry = time.Now().Add(time.Hour * 24 * 30)
s.db.Exec("UPDATE users SET return_expires=$1 WHERE id=$2", returnExpiry, uid) _, _ = s.db.Exec("UPDATE users SET return_expires=$1 WHERE id=$2", returnExpiry, uid)
} else { } else {
err := s.db.Get(&returnExpiry, "SELECT return_expires FROM users WHERE id=$1", uid) err := s.db.Get(&returnExpiry, "SELECT return_expires FROM users WHERE id=$1", uid)
if err != nil { if err != nil {
returnExpiry = time.Now() returnExpiry = time.Now()
s.db.Exec("UPDATE users SET return_expires=$1 WHERE id=$2", returnExpiry, uid) _, _ = s.db.Exec("UPDATE users SET return_expires=$1 WHERE id=$2", returnExpiry, uid)
} }
} }
s.db.Exec("UPDATE users SET last_login=$1 WHERE id=$2", time.Now(), uid) _, _ = s.db.Exec("UPDATE users SET last_login=$1 WHERE id=$2", time.Now(), uid)
return returnExpiry return returnExpiry
} }

View File

@@ -408,5 +408,5 @@ func (s *APIServer) ScreenShot(w http.ResponseWriter, r *http.Request) {
} }
// Write the XML response with a 200 status code // Write the XML response with a 200 status code
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Write(xmlData) _, _ = w.Write(xmlData)
} }

View File

@@ -17,7 +17,7 @@ import (
// TestLauncherEndpoint tests the /launcher endpoint // TestLauncherEndpoint tests the /launcher endpoint
func TestLauncherEndpoint(t *testing.T) { func TestLauncherEndpoint(t *testing.T) {
logger := NewTestLogger(t) logger := NewTestLogger(t)
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := NewTestConfig() cfg := NewTestConfig()
cfg.API.Banners = []_config.APISignBanner{ cfg.API.Banners = []_config.APISignBanner{
@@ -81,7 +81,7 @@ func TestLauncherEndpoint(t *testing.T) {
// TestLauncherEndpointEmptyConfig tests launcher with empty config // TestLauncherEndpointEmptyConfig tests launcher with empty config
func TestLauncherEndpointEmptyConfig(t *testing.T) { func TestLauncherEndpointEmptyConfig(t *testing.T) {
logger := NewTestLogger(t) logger := NewTestLogger(t)
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := NewTestConfig() cfg := NewTestConfig()
cfg.API.Banners = []_config.APISignBanner{} cfg.API.Banners = []_config.APISignBanner{}
@@ -117,7 +117,7 @@ func TestLauncherEndpointEmptyConfig(t *testing.T) {
// TestLoginEndpointInvalidJSON tests login with invalid JSON // TestLoginEndpointInvalidJSON tests login with invalid JSON
func TestLoginEndpointInvalidJSON(t *testing.T) { func TestLoginEndpointInvalidJSON(t *testing.T) {
logger := NewTestLogger(t) logger := NewTestLogger(t)
defer logger.Sync() defer func() { _ = logger.Sync() }()
cfg := NewTestConfig() cfg := NewTestConfig()
server := &APIServer{ server := &APIServer{

View File

@@ -71,11 +71,11 @@ func Compress(rawData []byte) ([]byte, error) {
output = append(output, []byte{byte(nullCount)}...) output = append(output, []byte{byte(nullCount)}...)
break break
} else if i != 0 && nullCount != 0 { } else if i != 0 && nullCount != 0 {
r.UnreadByte() _ = r.UnreadByte()
output = append(output, []byte{byte(nullCount)}...) output = append(output, []byte{byte(nullCount)}...)
break break
} else if i != 0 && nullCount == 0 { } else if i != 0 && nullCount == 0 {
r.UnreadByte() _ = r.UnreadByte()
output = output[:len(output)-2] output = output[:len(output)-2]
output = append(output, []byte{byte(0xFF)}...) output = append(output, []byte{byte(0xFF)}...)
break break

View File

@@ -80,7 +80,7 @@ func doAckSimpleFail(s *Session, ackHandle uint32, data []byte) {
func updateRights(s *Session) { func updateRights(s *Session) {
rightsInt := uint32(2) rightsInt := uint32(2)
s.server.db.QueryRow("SELECT rights FROM users u INNER JOIN characters c ON u.id = c.user_id WHERE c.id = $1", s.charID).Scan(&rightsInt) _ = s.server.db.QueryRow("SELECT rights FROM users u INNER JOIN characters c ON u.id = c.user_id WHERE c.id = $1", s.charID).Scan(&rightsInt)
s.courses, rightsInt = mhfcourse.GetCourseStruct(rightsInt) s.courses, rightsInt = mhfcourse.GetCourseStruct(rightsInt)
update := &mhfpacket.MsgSysUpdateRight{ update := &mhfpacket.MsgSysUpdateRight{
ClientRespAckHandle: 0, ClientRespAckHandle: 0,
@@ -303,7 +303,7 @@ func logoutPlayer(s *Session) {
if mhfcourse.CourseExists(30, s.courses) { if mhfcourse.CourseExists(30, s.courses) {
rpGained = timePlayed / 900 rpGained = timePlayed / 900
timePlayed = timePlayed % 900 timePlayed = timePlayed % 900
s.server.db.Exec("UPDATE characters SET cafe_time=cafe_time+$1 WHERE id=$2", sessionTime, s.charID) _, _ = s.server.db.Exec("UPDATE characters SET cafe_time=cafe_time+$1 WHERE id=$2", sessionTime, s.charID)
} else { } else {
rpGained = timePlayed / 1800 rpGained = timePlayed / 1800
timePlayed = timePlayed % 1800 timePlayed = timePlayed % 1800
@@ -329,8 +329,8 @@ func logoutPlayer(s *Session) {
} }
// Update time_played and guild treasure hunt // Update time_played and guild treasure hunt
s.server.db.Exec("UPDATE characters SET time_played = $1 WHERE id = $2", timePlayed, s.charID) _, _ = s.server.db.Exec("UPDATE characters SET time_played = $1 WHERE id = $2", timePlayed, s.charID)
s.server.db.Exec(`UPDATE guild_characters SET treasure_hunt=NULL WHERE character_id=$1`, s.charID) _, _ = s.server.db.Exec(`UPDATE guild_characters SET treasure_hunt=NULL WHERE character_id=$1`, s.charID)
} }
// NOW do cleanup (after save is complete) // NOW do cleanup (after save is complete)
@@ -449,7 +449,7 @@ func handleMsgSysRecordLog(s *Session, p mhfpacket.MHFPacket) {
for i := 0; i < 176; i++ { for i := 0; i < 176; i++ {
val = bf.ReadUint8() val = bf.ReadUint8()
if val > 0 && mhfmon.Monsters[i].Large { if val > 0 && mhfmon.Monsters[i].Large {
s.server.db.Exec(`INSERT INTO kill_logs (character_id, monster, quantity, timestamp) VALUES ($1, $2, $3, $4)`, s.charID, i, val, TimeAdjusted()) _, _ = s.server.db.Exec(`INSERT INTO kill_logs (character_id, monster, quantity, timestamp) VALUES ($1, $2, $3, $4)`, s.charID, i, val, TimeAdjusted())
} }
} }
} }
@@ -665,7 +665,7 @@ func handleMsgMhfTransitMessage(s *Session, p mhfpacket.MHFPacket) {
} }
if strings.HasPrefix(stage.id, findPartyParams.StagePrefix) { if strings.HasPrefix(stage.id, findPartyParams.StagePrefix) {
sb3 := byteframe.NewByteFrameFromBytes(stage.rawBinaryData[stageBinaryKey{1, 3}]) sb3 := byteframe.NewByteFrameFromBytes(stage.rawBinaryData[stageBinaryKey{1, 3}])
sb3.Seek(4, 0) _, _ = sb3.Seek(4, 0)
stageDataParams := 7 stageDataParams := 7
if _config.ErupeConfig.RealClientMode <= _config.G10 { if _config.ErupeConfig.RealClientMode <= _config.G10 {
@@ -741,7 +741,7 @@ func handleMsgMhfTransitMessage(s *Session, p mhfpacket.MHFPacket) {
} }
} }
} }
resp.Seek(0, io.SeekStart) _, _ = resp.Seek(0, io.SeekStart)
resp.WriteUint16(count) resp.WriteUint16(count)
doAckBufSucceed(s, pkt.AckHandle, resp.Data()) doAckBufSucceed(s, pkt.AckHandle, resp.Data())
} }
@@ -954,7 +954,7 @@ func handleMsgMhfGetExtraInfo(s *Session, p mhfpacket.MHFPacket) {}
func userGetItems(s *Session) []mhfitem.MHFItemStack { func userGetItems(s *Session) []mhfitem.MHFItemStack {
var data []byte var data []byte
var items []mhfitem.MHFItemStack var items []mhfitem.MHFItemStack
s.server.db.QueryRow(`SELECT item_box FROM users u WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$1)`, s.charID).Scan(&data) _ = s.server.db.QueryRow(`SELECT item_box FROM users u WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$1)`, s.charID).Scan(&data)
if len(data) > 0 { if len(data) > 0 {
box := byteframe.NewByteFrameFromBytes(data) box := byteframe.NewByteFrameFromBytes(data)
numStacks := box.ReadUint16() numStacks := box.ReadUint16()
@@ -977,7 +977,7 @@ func handleMsgMhfEnumerateUnionItem(s *Session, p mhfpacket.MHFPacket) {
func handleMsgMhfUpdateUnionItem(s *Session, p mhfpacket.MHFPacket) { func handleMsgMhfUpdateUnionItem(s *Session, p mhfpacket.MHFPacket) {
pkt := p.(*mhfpacket.MsgMhfUpdateUnionItem) pkt := p.(*mhfpacket.MsgMhfUpdateUnionItem)
newStacks := mhfitem.DiffItemStacks(userGetItems(s), pkt.UpdatedItems) newStacks := mhfitem.DiffItemStacks(userGetItems(s), pkt.UpdatedItems)
s.server.db.Exec(`UPDATE users u SET item_box=$1 WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$2)`, mhfitem.SerializeWarehouseItems(newStacks), s.charID) _, _ = s.server.db.Exec(`UPDATE users u SET item_box=$1 WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$2)`, mhfitem.SerializeWarehouseItems(newStacks), s.charID)
doAckSimpleSucceed(s, pkt.AckHandle, make([]byte, 4)) doAckSimpleSucceed(s, pkt.AckHandle, make([]byte, 4))
} }
@@ -990,17 +990,17 @@ func handleMsgMhfCheckWeeklyStamp(s *Session, p mhfpacket.MHFPacket) {
err := s.server.db.QueryRow(fmt.Sprintf("SELECT %s_checked FROM stamps WHERE character_id=$1", pkt.StampType), s.charID).Scan(&lastCheck) err := s.server.db.QueryRow(fmt.Sprintf("SELECT %s_checked FROM stamps WHERE character_id=$1", pkt.StampType), s.charID).Scan(&lastCheck)
if err != nil { if err != nil {
lastCheck = TimeAdjusted() lastCheck = TimeAdjusted()
s.server.db.Exec("INSERT INTO stamps (character_id, hl_checked, ex_checked) VALUES ($1, $2, $2)", s.charID, TimeAdjusted()) _, _ = s.server.db.Exec("INSERT INTO stamps (character_id, hl_checked, ex_checked) VALUES ($1, $2, $2)", s.charID, TimeAdjusted())
} else { } else {
s.server.db.Exec(fmt.Sprintf(`UPDATE stamps SET %s_checked=$1 WHERE character_id=$2`, pkt.StampType), TimeAdjusted(), s.charID) _, _ = s.server.db.Exec(fmt.Sprintf(`UPDATE stamps SET %s_checked=$1 WHERE character_id=$2`, pkt.StampType), TimeAdjusted(), s.charID)
} }
if lastCheck.Before(TimeWeekStart()) { if lastCheck.Before(TimeWeekStart()) {
s.server.db.Exec(fmt.Sprintf("UPDATE stamps SET %s_total=%s_total+1 WHERE character_id=$1", pkt.StampType, pkt.StampType), s.charID) _, _ = s.server.db.Exec(fmt.Sprintf("UPDATE stamps SET %s_total=%s_total+1 WHERE character_id=$1", pkt.StampType, pkt.StampType), s.charID)
updated = 1 updated = 1
} }
s.server.db.QueryRow(fmt.Sprintf("SELECT %s_total, %s_redeemed FROM stamps WHERE character_id=$1", pkt.StampType, pkt.StampType), s.charID).Scan(&total, &redeemed) _ = s.server.db.QueryRow(fmt.Sprintf("SELECT %s_total, %s_redeemed FROM stamps WHERE character_id=$1", pkt.StampType, pkt.StampType), s.charID).Scan(&total, &redeemed)
bf := byteframe.NewByteFrame() bf := byteframe.NewByteFrame()
bf.WriteUint16(total) bf.WriteUint16(total)
bf.WriteUint16(redeemed) bf.WriteUint16(redeemed)
@@ -1016,10 +1016,10 @@ func handleMsgMhfExchangeWeeklyStamp(s *Session, p mhfpacket.MHFPacket) {
var total, redeemed uint16 var total, redeemed uint16
var tktStack mhfitem.MHFItemStack var tktStack mhfitem.MHFItemStack
if pkt.Unk1 == 10 { // Yearly Sub Ex if pkt.Unk1 == 10 { // Yearly Sub Ex
s.server.db.QueryRow("UPDATE stamps SET hl_total=hl_total-48, hl_redeemed=hl_redeemed-48 WHERE character_id=$1 RETURNING hl_total, hl_redeemed", s.charID).Scan(&total, &redeemed) _ = s.server.db.QueryRow("UPDATE stamps SET hl_total=hl_total-48, hl_redeemed=hl_redeemed-48 WHERE character_id=$1 RETURNING hl_total, hl_redeemed", s.charID).Scan(&total, &redeemed)
tktStack = mhfitem.MHFItemStack{Item: mhfitem.MHFItem{ItemID: 2210}, Quantity: 1} tktStack = mhfitem.MHFItemStack{Item: mhfitem.MHFItem{ItemID: 2210}, Quantity: 1}
} else { } else {
s.server.db.QueryRow(fmt.Sprintf("UPDATE stamps SET %s_redeemed=%s_redeemed+8 WHERE character_id=$1 RETURNING %s_total, %s_redeemed", pkt.StampType, pkt.StampType, pkt.StampType, pkt.StampType), s.charID).Scan(&total, &redeemed) _ = s.server.db.QueryRow(fmt.Sprintf("UPDATE stamps SET %s_redeemed=%s_redeemed+8 WHERE character_id=$1 RETURNING %s_total, %s_redeemed", pkt.StampType, pkt.StampType, pkt.StampType, pkt.StampType), s.charID).Scan(&total, &redeemed)
if pkt.StampType == "hl" { if pkt.StampType == "hl" {
tktStack = mhfitem.MHFItemStack{Item: mhfitem.MHFItem{ItemID: 1630}, Quantity: 5} tktStack = mhfitem.MHFItemStack{Item: mhfitem.MHFItem{ItemID: 1630}, Quantity: 5}
} else { } else {
@@ -1043,7 +1043,7 @@ func getGoocooData(s *Session, cid uint32) [][]byte {
for i := 0; i < 5; i++ { for i := 0; i < 5; i++ {
err := s.server.db.QueryRow(fmt.Sprintf("SELECT goocoo%d FROM goocoo WHERE id=$1", i), cid).Scan(&goocoo) err := s.server.db.QueryRow(fmt.Sprintf("SELECT goocoo%d FROM goocoo WHERE id=$1", i), cid).Scan(&goocoo)
if err != nil { if err != nil {
s.server.db.Exec("INSERT INTO goocoo (id) VALUES ($1)", s.charID) _, _ = s.server.db.Exec("INSERT INTO goocoo (id) VALUES ($1)", s.charID)
return goocoos return goocoos
} }
if err == nil && goocoo != nil { if err == nil && goocoo != nil {
@@ -1216,7 +1216,7 @@ func handleMsgMhfStampcardStamp(s *Session, p mhfpacket.MHFPacket) {
} }
var stamps, rewardTier, rewardUnk uint16 var stamps, rewardTier, rewardUnk uint16
reward := mhfitem.MHFItemStack{Item: mhfitem.MHFItem{}} reward := mhfitem.MHFItemStack{Item: mhfitem.MHFItem{}}
s.server.db.QueryRow(`UPDATE characters SET stampcard = stampcard + $1 WHERE id = $2 RETURNING stampcard`, pkt.Stamps, s.charID).Scan(&stamps) _ = s.server.db.QueryRow(`UPDATE characters SET stampcard = stampcard + $1 WHERE id = $2 RETURNING stampcard`, pkt.Stamps, s.charID).Scan(&stamps)
bf.WriteUint16(stamps - pkt.Stamps) bf.WriteUint16(stamps - pkt.Stamps)
bf.WriteUint16(stamps) bf.WriteUint16(stamps)
@@ -1578,7 +1578,7 @@ func handleMsgMhfGetTrendWeapon(s *Session, p mhfpacket.MHFPacket) {
j := 0 j := 0
for rows.Next() { for rows.Next() {
trendWeapons[i][j].WeaponType = i trendWeapons[i][j].WeaponType = i
rows.Scan(&trendWeapons[i][j].WeaponID) _ = rows.Scan(&trendWeapons[i][j].WeaponID)
j++ j++
} }
} }

View File

@@ -131,7 +131,7 @@ func handleMsgMhfGetAchievement(s *Session, p mhfpacket.MHFPacket) {
resp.WriteUint16(0) // Unk resp.WriteUint16(0) // Unk
resp.WriteUint32(achData.Progress) resp.WriteUint32(achData.Progress)
} }
resp.Seek(0, io.SeekStart) _, _ = resp.Seek(0, io.SeekStart)
resp.WriteUint32(points) resp.WriteUint32(points)
resp.WriteUint32(points) resp.WriteUint32(points)
resp.WriteUint32(points) resp.WriteUint32(points)

View File

@@ -54,7 +54,7 @@ func handleMsgMhfCheckDailyCafepoint(s *Session, p mhfpacket.MHFPacket) {
var bondBonus, bonusQuests, dailyQuests uint32 var bondBonus, bonusQuests, dailyQuests uint32
bf := byteframe.NewByteFrame() bf := byteframe.NewByteFrame()
if midday.After(dailyTime) { if midday.After(dailyTime) {
addPointNetcafe(s, 5) _ = addPointNetcafe(s, 5)
bondBonus = 5 // Bond point bonus quests bondBonus = 5 // Bond point bonus quests
bonusQuests = s.server.erupeConfig.GameplayOptions.BonusQuestAllowance bonusQuests = s.server.erupeConfig.GameplayOptions.BonusQuestAllowance
dailyQuests = s.server.erupeConfig.GameplayOptions.DailyQuestAllowance dailyQuests = s.server.erupeConfig.GameplayOptions.DailyQuestAllowance
@@ -196,7 +196,7 @@ func handleMsgMhfPostCafeDurationBonusReceived(s *Session, p mhfpacket.MHFPacket
`, cbID).Scan(&cafeBonus.ID, &cafeBonus.ItemType, &cafeBonus.Quantity) `, cbID).Scan(&cafeBonus.ID, &cafeBonus.ItemType, &cafeBonus.Quantity)
if err == nil { if err == nil {
if cafeBonus.ItemType == 17 { if cafeBonus.ItemType == 17 {
addPointNetcafe(s, int(cafeBonus.Quantity)) _ = addPointNetcafe(s, int(cafeBonus.Quantity))
} }
} }
s.server.db.Exec("INSERT INTO public.cafe_accepted VALUES ($1, $2)", cbID, s.charID) s.server.db.Exec("INSERT INTO public.cafe_accepted VALUES ($1, $2)", cbID, s.charID)

View File

@@ -46,7 +46,7 @@ func init() {
zapConfig := zap.NewDevelopmentConfig() zapConfig := zap.NewDevelopmentConfig()
zapConfig.DisableCaller = true zapConfig.DisableCaller = true
zapLogger, _ := zapConfig.Build() zapLogger, _ := zapConfig.Build()
defer zapLogger.Sync() defer func() { _ = zapLogger.Sync() }()
logger := zapLogger.Named("commands") logger := zapLogger.Named("commands")
cmds := _config.ErupeConfig.Commands cmds := _config.ErupeConfig.Commands
for _, cmd := range cmds { for _, cmd := range cmds {
@@ -74,7 +74,7 @@ func sendServerChatMessage(s *Session, message string) {
Message: message, Message: message,
SenderName: "Erupe", SenderName: "Erupe",
} }
msgBinChat.Build(bf) _ = msgBinChat.Build(bf)
castedBin := &mhfpacket.MsgSysCastedBinary{ castedBin := &mhfpacket.MsgSysCastedBinary{
CharID: 0, CharID: 0,
@@ -191,7 +191,7 @@ func parseChatCommand(s *Session, command string) {
} }
temp = &mhfpacket.MsgSysDeleteObject{ObjID: object.id} temp = &mhfpacket.MsgSysDeleteObject{ObjID: object.id}
deleteNotif.WriteUint16(uint16(temp.Opcode())) deleteNotif.WriteUint16(uint16(temp.Opcode()))
temp.Build(deleteNotif, s.clientContext) _ = temp.Build(deleteNotif, s.clientContext)
} }
for _, session := range s.server.sessions { for _, session := range s.server.sessions {
if s == session { if s == session {
@@ -199,7 +199,7 @@ func parseChatCommand(s *Session, command string) {
} }
temp = &mhfpacket.MsgSysDeleteUser{CharID: session.charID} temp = &mhfpacket.MsgSysDeleteUser{CharID: session.charID}
deleteNotif.WriteUint16(uint16(temp.Opcode())) deleteNotif.WriteUint16(uint16(temp.Opcode()))
temp.Build(deleteNotif, s.clientContext) _ = temp.Build(deleteNotif, s.clientContext)
} }
deleteNotif.WriteUint16(uint16(network.MSG_SYS_END)) deleteNotif.WriteUint16(uint16(network.MSG_SYS_END))
s.QueueSendNonBlocking(deleteNotif.Data()) s.QueueSendNonBlocking(deleteNotif.Data())
@@ -211,14 +211,14 @@ func parseChatCommand(s *Session, command string) {
} }
temp = &mhfpacket.MsgSysInsertUser{CharID: session.charID} temp = &mhfpacket.MsgSysInsertUser{CharID: session.charID}
reloadNotif.WriteUint16(uint16(temp.Opcode())) reloadNotif.WriteUint16(uint16(temp.Opcode()))
temp.Build(reloadNotif, s.clientContext) _ = temp.Build(reloadNotif, s.clientContext)
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
temp = &mhfpacket.MsgSysNotifyUserBinary{ temp = &mhfpacket.MsgSysNotifyUserBinary{
CharID: session.charID, CharID: session.charID,
BinaryType: uint8(i + 1), BinaryType: uint8(i + 1),
} }
reloadNotif.WriteUint16(uint16(temp.Opcode())) reloadNotif.WriteUint16(uint16(temp.Opcode()))
temp.Build(reloadNotif, s.clientContext) _ = temp.Build(reloadNotif, s.clientContext)
} }
} }
for _, obj := range s.stage.objects { for _, obj := range s.stage.objects {
@@ -234,7 +234,7 @@ func parseChatCommand(s *Session, command string) {
OwnerCharID: obj.ownerCharID, OwnerCharID: obj.ownerCharID,
} }
reloadNotif.WriteUint16(uint16(temp.Opcode())) reloadNotif.WriteUint16(uint16(temp.Opcode()))
temp.Build(reloadNotif, s.clientContext) _ = temp.Build(reloadNotif, s.clientContext)
} }
reloadNotif.WriteUint16(uint16(network.MSG_SYS_END)) reloadNotif.WriteUint16(uint16(network.MSG_SYS_END))
s.QueueSendNonBlocking(reloadNotif.Data()) s.QueueSendNonBlocking(reloadNotif.Data())
@@ -404,7 +404,7 @@ func parseChatCommand(s *Session, command string) {
err := s.server.db.QueryRow(`SELECT discord_token FROM users u WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$1)`, s.charID).Scan(&_token) err := s.server.db.QueryRow(`SELECT discord_token FROM users u WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$1)`, s.charID).Scan(&_token)
if err != nil { if err != nil {
randToken := make([]byte, 4) randToken := make([]byte, 4)
rand.Read(randToken) _, _ = rand.Read(randToken)
_token = fmt.Sprintf("%x-%x", randToken[:2], randToken[2:]) _token = fmt.Sprintf("%x-%x", randToken[:2], randToken[2:])
s.server.db.Exec(`UPDATE users u SET discord_token = $1 WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$2)`, _token, s.charID) s.server.db.Exec(`UPDATE users u SET discord_token = $1 WHERE u.id=(SELECT c.user_id FROM characters c WHERE c.id=$2)`, _token, s.charID)
} }
@@ -469,7 +469,7 @@ func handleMsgSysCastBinary(s *Session, p mhfpacket.MHFPacket) {
var returnToSender bool var returnToSender bool
if pkt.MessageType == BinaryMessageTypeChat { if pkt.MessageType == BinaryMessageTypeChat {
tmp.SetLE() tmp.SetLE()
tmp.Seek(8, 0) _, _ = tmp.Seek(8, 0)
message = string(tmp.ReadNullTerminatedBytes()) message = string(tmp.ReadNullTerminatedBytes())
author = string(tmp.ReadNullTerminatedBytes()) author = string(tmp.ReadNullTerminatedBytes())
} }
@@ -478,7 +478,7 @@ func handleMsgSysCastBinary(s *Session, p mhfpacket.MHFPacket) {
realPayload := pkt.RawDataPayload realPayload := pkt.RawDataPayload
if pkt.BroadcastType == BroadcastTypeTargeted { if pkt.BroadcastType == BroadcastTypeTargeted {
tmp.SetBE() tmp.SetBE()
tmp.Seek(0, 0) _, _ = tmp.Seek(0, 0)
msgBinTargeted = &binpacket.MsgBinTargeted{} msgBinTargeted = &binpacket.MsgBinTargeted{}
err := msgBinTargeted.Parse(tmp) err := msgBinTargeted.Parse(tmp)
if err != nil { if err != nil {
@@ -497,13 +497,13 @@ func handleMsgSysCastBinary(s *Session, p mhfpacket.MHFPacket) {
} }
bf := byteframe.NewByteFrame() bf := byteframe.NewByteFrame()
bf.SetLE() bf.SetLE()
m.Build(bf) _ = m.Build(bf)
realPayload = bf.Data() realPayload = bf.Data()
} else { } else {
bf := byteframe.NewByteFrameFromBytes(pkt.RawDataPayload) bf := byteframe.NewByteFrameFromBytes(pkt.RawDataPayload)
bf.SetLE() bf.SetLE()
chatMessage := &binpacket.MsgBinChat{} chatMessage := &binpacket.MsgBinChat{}
chatMessage.Parse(bf) _ = chatMessage.Parse(bf)
if strings.HasPrefix(chatMessage.Message, s.server.erupeConfig.CommandPrefix) { if strings.HasPrefix(chatMessage.Message, s.server.erupeConfig.CommandPrefix) {
parseChatCommand(s, chatMessage.Message) parseChatCommand(s, chatMessage.Message)
return return

View File

@@ -122,7 +122,7 @@ func TestHandleMsgSysCastBinary_DiceCommand(t *testing.T) {
Message: "@dice", Message: "@dice",
SenderName: "TestPlayer", SenderName: "TestPlayer",
} }
msg.Build(bf) _ = msg.Build(bf)
pkt := &mhfpacket.MsgSysCastBinary{ pkt := &mhfpacket.MsgSysCastBinary{
Unk: 0, Unk: 0,
@@ -157,7 +157,7 @@ func TestBroadcastTypes(t *testing.T) {
TargetCharIDs: []uint32{1, 2, 3}, TargetCharIDs: []uint32{1, 2, 3},
RawDataPayload: []byte{0xDE, 0xAD, 0xBE, 0xEF}, RawDataPayload: []byte{0xDE, 0xAD, 0xBE, 0xEF},
} }
msg.Build(bf) _ = msg.Build(bf)
return bf.Data() return bf.Data()
}, },
}, },
@@ -245,7 +245,7 @@ func TestBinaryMessageTypes(t *testing.T) {
Message: "test", Message: "test",
SenderName: "Player", SenderName: "Player",
} }
msg.Build(bf) _ = msg.Build(bf)
return bf.Data() return bf.Data()
}, },
}, },
@@ -429,12 +429,12 @@ func TestChatMessageParsing(t *testing.T) {
Message: tt.messageContent, Message: tt.messageContent,
SenderName: tt.authorName, SenderName: tt.authorName,
} }
msg.Build(bf) _ = msg.Build(bf)
// Parse it back // Parse it back
parseBf := byteframe.NewByteFrameFromBytes(bf.Data()) parseBf := byteframe.NewByteFrameFromBytes(bf.Data())
parseBf.SetLE() parseBf.SetLE()
parseBf.Seek(8, 0) // Skip initial bytes _, _ = parseBf.Seek(8, 0) // Skip initial bytes
message := string(parseBf.ReadNullTerminatedBytes()) message := string(parseBf.ReadNullTerminatedBytes())
author := string(parseBf.ReadNullTerminatedBytes()) author := string(parseBf.ReadNullTerminatedBytes())

View File

@@ -572,7 +572,7 @@ func BenchmarkCompress(b *testing.B) {
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
save.Compress() _ = save.Compress()
} }
} }
@@ -587,6 +587,6 @@ func BenchmarkDecompress(b *testing.B) {
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
save.Decompress() _ = save.Decompress()
} }
} }

View File

@@ -77,7 +77,7 @@ func handleMsgMhfListMember(s *Session, p mhfpacket.MHFPacket) {
resp.WriteBytes(stringsupport.PaddedString(name, 16, true)) resp.WriteBytes(stringsupport.PaddedString(name, 16, true))
} }
} }
resp.Seek(0, 0) _, _ = resp.Seek(0, 0)
resp.WriteUint32(count) resp.WriteUint32(count)
doAckBufSucceed(s, pkt.AckHandle, resp.Data()) doAckBufSucceed(s, pkt.AckHandle, resp.Data())
} }

View File

@@ -613,8 +613,8 @@ func TestSaveDataSerialization(t *testing.T) {
// Simulate binary serialization // Simulate binary serialization
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
binary.Write(buf, binary.LittleEndian, savedata.CharID) _ = binary.Write(buf, binary.LittleEndian, savedata.CharID)
binary.Write(buf, binary.LittleEndian, savedata.Playtime) _ = binary.Write(buf, binary.LittleEndian, savedata.Playtime)
// Should have 8 bytes (4 + 4) // Should have 8 bytes (4 + 4)
if buf.Len() != 8 { if buf.Len() != 8 {
@@ -625,8 +625,8 @@ func TestSaveDataSerialization(t *testing.T) {
data := buf.Bytes() data := buf.Bytes()
var charID uint32 var charID uint32
var playtime uint32 var playtime uint32
binary.Read(bytes.NewReader(data), binary.LittleEndian, &charID) _ = binary.Read(bytes.NewReader(data), binary.LittleEndian, &charID)
binary.Read(bytes.NewReader(data[4:]), binary.LittleEndian, &playtime) _ = binary.Read(bytes.NewReader(data[4:]), binary.LittleEndian, &playtime)
if charID != tt.charID || playtime != tt.playtime { if charID != tt.charID || playtime != tt.playtime {
t.Error("serialization round-trip failed") t.Error("serialization round-trip failed")

View File

@@ -179,10 +179,10 @@ func TestAckPacketStructure(t *testing.T) {
var buf bytes.Buffer var buf bytes.Buffer
// Write opcode (2 bytes, big endian) // Write opcode (2 bytes, big endian)
binary.Write(&buf, binary.BigEndian, uint16(network.MSG_SYS_ACK)) _ = binary.Write(&buf, binary.BigEndian, uint16(network.MSG_SYS_ACK))
// Write ack handle (4 bytes, big endian) // Write ack handle (4 bytes, big endian)
binary.Write(&buf, binary.BigEndian, tt.ackHandle) _ = binary.Write(&buf, binary.BigEndian, tt.ackHandle)
// Write data // Write data
buf.Write(tt.data) buf.Write(tt.data)
@@ -590,7 +590,7 @@ func TestSaveDataCorruptionDetection_Integration(t *testing.T) {
// Check that database wasn't updated with corrupted data // Check that database wasn't updated with corrupted data
var savedName string var savedName string
db.QueryRow("SELECT name FROM characters WHERE id = $1", charID).Scan(&savedName) _ = db.QueryRow("SELECT name FROM characters WHERE id = $1", charID).Scan(&savedName)
if savedName == "HackedName" { if savedName == "HackedName" {
t.Error("corrupted save data was incorrectly written to database") t.Error("corrupted save data was incorrectly written to database")
} }

View File

@@ -15,7 +15,7 @@ func (s *Server) onInteraction(ds *discordgo.Session, i *discordgo.InteractionCr
var temp string var temp string
err := s.db.QueryRow(`UPDATE users SET discord_id = $1 WHERE discord_token = $2 RETURNING discord_id`, i.Member.User.ID, i.ApplicationCommandData().Options[0].StringValue()).Scan(&temp) err := s.db.QueryRow(`UPDATE users SET discord_id = $1 WHERE discord_token = $2 RETURNING discord_id`, i.Member.User.ID, i.ApplicationCommandData().Options[0].StringValue()).Scan(&temp)
if err == nil { if err == nil {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ _ = ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource, Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{ Data: &discordgo.InteractionResponseData{
Content: "Your Erupe account was linked successfully.", Content: "Your Erupe account was linked successfully.",
@@ -23,7 +23,7 @@ func (s *Server) onInteraction(ds *discordgo.Session, i *discordgo.InteractionCr
}, },
}) })
} else { } else {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ _ = ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource, Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{ Data: &discordgo.InteractionResponseData{
Content: "Failed to link Erupe account.", Content: "Failed to link Erupe account.",
@@ -35,7 +35,7 @@ func (s *Server) onInteraction(ds *discordgo.Session, i *discordgo.InteractionCr
password, _ := bcrypt.GenerateFromPassword([]byte(i.ApplicationCommandData().Options[0].StringValue()), 10) password, _ := bcrypt.GenerateFromPassword([]byte(i.ApplicationCommandData().Options[0].StringValue()), 10)
_, err := s.db.Exec(`UPDATE users SET password = $1 WHERE discord_id = $2`, password, i.Member.User.ID) _, err := s.db.Exec(`UPDATE users SET password = $1 WHERE discord_id = $2`, password, i.Member.User.ID)
if err == nil { if err == nil {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ _ = ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource, Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{ Data: &discordgo.InteractionResponseData{
Content: "Your Erupe account password has been updated.", Content: "Your Erupe account password has been updated.",
@@ -43,7 +43,7 @@ func (s *Server) onInteraction(ds *discordgo.Session, i *discordgo.InteractionCr
}, },
}) })
} else { } else {
ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ _ = ds.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource, Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{ Data: &discordgo.InteractionResponseData{
Content: "Failed to update Erupe account password.", Content: "Failed to update Erupe account password.",

View File

@@ -71,7 +71,7 @@ func handleMsgMhfGetUdSchedule(s *Session, p mhfpacket.MHFPacket) {
} else { } else {
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
rows.Scan(&id, &start) _ = rows.Scan(&id, &start)
} }
} }

View File

@@ -142,7 +142,7 @@ func handleMsgMhfGetKeepLoginBoostStatus(s *Session, p mhfpacket.MHFPacket) {
} }
for rows.Next() { for rows.Next() {
var temp loginBoost var temp loginBoost
rows.StructScan(&temp) _ = rows.StructScan(&temp)
loginBoosts = append(loginBoosts, temp) loginBoosts = append(loginBoosts, temp)
} }
if len(loginBoosts) == 0 { if len(loginBoosts) == 0 {

View File

@@ -177,7 +177,7 @@ func handleMsgMhfInfoFesta(s *Session, p mhfpacket.MHFPacket) {
} else { } else {
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
rows.Scan(&id, &start) _ = rows.Scan(&id, &start)
} }
} }

View File

@@ -678,13 +678,13 @@ func handleMsgMhfOperateGuild(s *Session, p mhfpacket.MHFPacket) {
guild.LeaderCharID = guildMembers[i].CharID guild.LeaderCharID = guildMembers[i].CharID
guildMembers[0].OrderIndex = guildMembers[i].OrderIndex guildMembers[0].OrderIndex = guildMembers[i].OrderIndex
guildMembers[i].OrderIndex = 1 guildMembers[i].OrderIndex = 1
guildMembers[0].Save(s) _ = guildMembers[0].Save(s)
guildMembers[i].Save(s) _ = guildMembers[i].Save(s)
bf.WriteUint32(guildMembers[i].CharID) bf.WriteUint32(guildMembers[i].CharID)
break break
} }
} }
guild.Save(s) _ = guild.Save(s)
} }
case mhfpacket.OperateGuildApply: case mhfpacket.OperateGuildApply:
err = guild.CreateApplication(s, s.charID, GuildApplicationTypeApplied, nil) err = guild.CreateApplication(s, s.charID, GuildApplicationTypeApplied, nil)
@@ -709,7 +709,7 @@ func handleMsgMhfOperateGuild(s *Session, p mhfpacket.MHFPacket) {
Body: fmt.Sprintf("You have withdrawn from 「%s」.", guild.Name), Body: fmt.Sprintf("You have withdrawn from 「%s」.", guild.Name),
IsSystemMessage: true, IsSystemMessage: true,
} }
mail.Send(s, nil) _ = mail.Send(s, nil)
} }
bf.WriteUint32(uint32(response)) bf.WriteUint32(uint32(response))
case mhfpacket.OperateGuildDonateRank: case mhfpacket.OperateGuildDonateRank:
@@ -728,7 +728,7 @@ func handleMsgMhfOperateGuild(s *Session, p mhfpacket.MHFPacket) {
return return
} }
guild.Comment = stringsupport.SJISToUTF8(pkt.Data2.ReadNullTerminatedBytes()) guild.Comment = stringsupport.SJISToUTF8(pkt.Data2.ReadNullTerminatedBytes())
guild.Save(s) _ = guild.Save(s)
case mhfpacket.OperateGuildUpdateMotto: case mhfpacket.OperateGuildUpdateMotto:
if !characterGuildInfo.IsLeader && !characterGuildInfo.IsSubLeader() { if !characterGuildInfo.IsLeader && !characterGuildInfo.IsSubLeader() {
doAckSimpleFail(s, pkt.AckHandle, make([]byte, 4)) doAckSimpleFail(s, pkt.AckHandle, make([]byte, 4))
@@ -737,7 +737,7 @@ func handleMsgMhfOperateGuild(s *Session, p mhfpacket.MHFPacket) {
_ = pkt.Data1.ReadUint16() _ = pkt.Data1.ReadUint16()
guild.SubMotto = pkt.Data1.ReadUint8() guild.SubMotto = pkt.Data1.ReadUint8()
guild.MainMotto = pkt.Data1.ReadUint8() guild.MainMotto = pkt.Data1.ReadUint8()
guild.Save(s) _ = guild.Save(s)
case mhfpacket.OperateGuildRenamePugi1: case mhfpacket.OperateGuildRenamePugi1:
handleRenamePugi(s, pkt.Data2, guild, 1) handleRenamePugi(s, pkt.Data2, guild, 1)
case mhfpacket.OperateGuildRenamePugi2: case mhfpacket.OperateGuildRenamePugi2:
@@ -788,7 +788,7 @@ func handleRenamePugi(s *Session, bf *byteframe.ByteFrame, guild *Guild, num int
default: default:
guild.PugiName3 = name guild.PugiName3 = name
} }
guild.Save(s) _ = guild.Save(s)
} }
func handleChangePugi(s *Session, outfit uint8, guild *Guild, num int) { func handleChangePugi(s *Session, outfit uint8, guild *Guild, num int) {
@@ -800,7 +800,7 @@ func handleChangePugi(s *Session, outfit uint8, guild *Guild, num int) {
case 3: case 3:
guild.PugiOutfit3 = outfit guild.PugiOutfit3 = outfit
} }
guild.Save(s) _ = guild.Save(s)
} }
func handleDonateRP(s *Session, amount uint16, guild *Guild, _type int) []byte { func handleDonateRP(s *Session, amount uint16, guild *Guild, _type int) []byte {
@@ -912,7 +912,7 @@ func handleMsgMhfOperateGuildMember(s *Session, p mhfpacket.MHFPacket) {
if err != nil { if err != nil {
doAckSimpleFail(s, pkt.AckHandle, make([]byte, 4)) doAckSimpleFail(s, pkt.AckHandle, make([]byte, 4))
} else { } else {
mail.Send(s, nil) _ = mail.Send(s, nil)
for _, channel := range s.server.Channels { for _, channel := range s.server.Channels {
for _, session := range channel.sessions { for _, session := range channel.sessions {
if session.charID == pkt.CharID { if session.charID == pkt.CharID {

View File

@@ -182,7 +182,7 @@ func handleMsgMhfAnswerGuildScout(s *Session, p mhfpacket.MHFPacket) {
bf.WriteUint32(guild.ID) bf.WriteUint32(guild.ID)
doAckBufSucceed(s, pkt.AckHandle, bf.Data()) doAckBufSucceed(s, pkt.AckHandle, bf.Data())
for _, m := range mail { for _, m := range mail {
m.Send(s, nil) _ = m.Send(s, nil)
} }
} }
} }

View File

@@ -174,7 +174,7 @@ func SendMailNotification(s *Session, m *Mail, recipient *Session) {
SenderName: getCharacterName(s, m.SenderID), SenderName: getCharacterName(s, m.SenderID),
} }
notification.Build(bf) _ = notification.Build(bf)
castedBinary := &mhfpacket.MsgSysCastedBinary{ castedBinary := &mhfpacket.MsgSysCastedBinary{
CharID: m.SenderID, CharID: m.SenderID,
@@ -183,7 +183,7 @@ func SendMailNotification(s *Session, m *Mail, recipient *Session) {
RawDataPayload: bf.Data(), RawDataPayload: bf.Data(),
} }
castedBinary.Build(bf, s.clientContext) _ = castedBinary.Build(bf, s.clientContext)
recipient.QueueSendMHFNonBlocking(castedBinary) recipient.QueueSendMHFNonBlocking(castedBinary)
} }

View File

@@ -325,7 +325,7 @@ func handleMsgMhfSaveOtomoAirou(s *Session, p mhfpacket.MHFPacket) {
} }
} }
save.WriteBytes(bf.DataFromCurrent()) save.WriteBytes(bf.DataFromCurrent())
save.Seek(0, 0) _, _ = save.Seek(0, 0)
save.WriteUint8(catsExist) save.WriteUint8(catsExist)
comp, err := nullcomp.Compress(save.Data()) comp, err := nullcomp.Compress(save.Data())
if err != nil { if err != nil {

View File

@@ -39,7 +39,7 @@ func buildCatBytes(cats []Airou) []byte {
for _, cat := range cats { for _, cat := range cats {
catBuf := new(bytes.Buffer) catBuf := new(bytes.Buffer)
// ID (uint32) // ID (uint32)
binary.Write(catBuf, binary.BigEndian, cat.ID) _ = binary.Write(catBuf, binary.BigEndian, cat.ID)
// 1 byte skip (unknown bool) // 1 byte skip (unknown bool)
catBuf.WriteByte(0) catBuf.WriteByte(0)
// Name (18 bytes) // Name (18 bytes)
@@ -57,17 +57,17 @@ func buildCatBytes(cats []Airou) []byte {
// 5 bytes skip (affection and colour sliders) // 5 bytes skip (affection and colour sliders)
catBuf.Write(make([]byte, 5)) catBuf.Write(make([]byte, 5))
// Experience (uint32) // Experience (uint32)
binary.Write(catBuf, binary.BigEndian, cat.Experience) _ = binary.Write(catBuf, binary.BigEndian, cat.Experience)
// 1 byte skip (bool for weapon equipped) // 1 byte skip (bool for weapon equipped)
catBuf.WriteByte(0) catBuf.WriteByte(0)
// WeaponType (uint8) // WeaponType (uint8)
catBuf.WriteByte(cat.WeaponType) catBuf.WriteByte(cat.WeaponType)
// WeaponID (uint16) // WeaponID (uint16)
binary.Write(catBuf, binary.BigEndian, cat.WeaponID) _ = binary.Write(catBuf, binary.BigEndian, cat.WeaponID)
catData := catBuf.Bytes() catData := catBuf.Bytes()
// catDefLen (uint32) - total length of the cat data after this field // catDefLen (uint32) - total length of the cat data after this field
binary.Write(buf, binary.BigEndian, uint32(len(catData))) _ = binary.Write(buf, binary.BigEndian, uint32(len(catData)))
buf.Write(catData) buf.Write(catData)
} }
return buf.Bytes() return buf.Bytes()
@@ -174,7 +174,7 @@ func TestGetAirouDetails_ExtraTrailingBytes(t *testing.T) {
buf.WriteByte(1) // catCount = 1 buf.WriteByte(1) // catCount = 1
catBuf := new(bytes.Buffer) catBuf := new(bytes.Buffer)
binary.Write(catBuf, binary.BigEndian, uint32(99)) // catID _ = binary.Write(catBuf, binary.BigEndian, uint32(99)) // catID
catBuf.WriteByte(0) // skip catBuf.WriteByte(0) // skip
catBuf.Write(make([]byte, 18)) // name catBuf.Write(make([]byte, 18)) // name
catBuf.WriteByte(3) // currentTask catBuf.WriteByte(3) // currentTask
@@ -182,7 +182,7 @@ func TestGetAirouDetails_ExtraTrailingBytes(t *testing.T) {
catBuf.WriteByte(1) // personality catBuf.WriteByte(1) // personality
catBuf.WriteByte(2) // class catBuf.WriteByte(2) // class
catBuf.Write(make([]byte, 5)) // affection skip catBuf.Write(make([]byte, 5)) // affection skip
binary.Write(catBuf, binary.BigEndian, uint32(500)) // experience _ = binary.Write(catBuf, binary.BigEndian, uint32(500)) // experience
catBuf.WriteByte(0) // weapon equipped bool catBuf.WriteByte(0) // weapon equipped bool
catBuf.WriteByte(6) // weaponType catBuf.WriteByte(6) // weaponType
binary.Write(catBuf, binary.BigEndian, uint16(50)) // weaponID binary.Write(catBuf, binary.BigEndian, uint16(50)) // weaponID

View File

@@ -227,7 +227,7 @@ func loadQuestFile(s *Session, questId int) []byte {
} }
fileBytes := byteframe.NewByteFrameFromBytes(decrypted) fileBytes := byteframe.NewByteFrameFromBytes(decrypted)
fileBytes.SetLE() fileBytes.SetLE()
fileBytes.Seek(int64(fileBytes.ReadUint32()), 0) _, _ = fileBytes.Seek(int64(fileBytes.ReadUint32()), 0)
bodyLength := 320 bodyLength := 320
if _config.ErupeConfig.RealClientMode <= _config.S6 { if _config.ErupeConfig.RealClientMode <= _config.S6 {
@@ -244,12 +244,12 @@ func loadQuestFile(s *Session, questId int) []byte {
questBody := byteframe.NewByteFrameFromBytes(fileBytes.ReadBytes(uint(bodyLength))) questBody := byteframe.NewByteFrameFromBytes(fileBytes.ReadBytes(uint(bodyLength)))
questBody.SetLE() questBody.SetLE()
// Find the master quest string pointer // Find the master quest string pointer
questBody.Seek(40, 0) _, _ = questBody.Seek(40, 0)
fileBytes.Seek(int64(questBody.ReadUint32()), 0) _, _ = fileBytes.Seek(int64(questBody.ReadUint32()), 0)
questBody.Seek(40, 0) _, _ = questBody.Seek(40, 0)
// Overwrite it // Overwrite it
questBody.WriteUint32(uint32(bodyLength)) questBody.WriteUint32(uint32(bodyLength))
questBody.Seek(0, 2) _, _ = questBody.Seek(0, 2)
// Rewrite the quest strings and their pointers // Rewrite the quest strings and their pointers
var tempString []byte var tempString []byte
@@ -258,9 +258,9 @@ func loadQuestFile(s *Session, questId int) []byte {
for i := 0; i < 8; i++ { for i := 0; i < 8; i++ {
questBody.WriteUint32(uint32(tempPointer)) questBody.WriteUint32(uint32(tempPointer))
temp := int64(fileBytes.Index()) temp := int64(fileBytes.Index())
fileBytes.Seek(int64(fileBytes.ReadUint32()), 0) _, _ = fileBytes.Seek(int64(fileBytes.ReadUint32()), 0)
tempString = fileBytes.ReadNullTerminatedBytes() tempString = fileBytes.ReadNullTerminatedBytes()
fileBytes.Seek(temp+4, 0) _, _ = fileBytes.Seek(temp+4, 0)
tempPointer += len(tempString) + 1 tempPointer += len(tempString) + 1
newStrings.WriteNullTerminatedBytes(tempString) newStrings.WriteNullTerminatedBytes(tempString)
} }
@@ -278,7 +278,7 @@ func makeEventQuest(s *Session, rows *sql.Rows) ([]byte, error) {
var questId, activeDuration, inactiveDuration, flags int var questId, activeDuration, inactiveDuration, flags int
var maxPlayers, questType uint8 var maxPlayers, questType uint8
var startTime time.Time var startTime time.Time
rows.Scan(&id, &maxPlayers, &questType, &questId, &mark, &flags, &startTime, &activeDuration, &inactiveDuration) _ = rows.Scan(&id, &maxPlayers, &questType, &questId, &mark, &flags, &startTime, &activeDuration, &inactiveDuration)
data := loadQuestFile(s, questId) data := loadQuestFile(s, questId)
if data == nil { if data == nil {
@@ -388,7 +388,7 @@ func handleMsgMhfEnumerateQuest(s *Session, p mhfpacket.MHFPacket) {
_, err = tx.Exec("UPDATE event_quests SET start_time = $1 WHERE id = $2", newRotationTime, id) _, err = tx.Exec("UPDATE event_quests SET start_time = $1 WHERE id = $2", newRotationTime, id)
if err != nil { if err != nil {
tx.Rollback() // Rollback if an error occurs _ = tx.Rollback()
break break
} }
startTime = newRotationTime // Set the new start time so the quest can be used/removed immediately. startTime = newRotationTime // Set the new start time so the quest can be used/removed immediately.
@@ -421,7 +421,7 @@ func handleMsgMhfEnumerateQuest(s *Session, p mhfpacket.MHFPacket) {
} }
rows.Close() rows.Close()
tx.Commit() _ = tx.Commit()
} }
tuneValues := []tuneValue{ tuneValues := []tuneValue{

View File

@@ -119,13 +119,13 @@ func (s *Session) notifyRavi() {
raviNotif := byteframe.NewByteFrame() raviNotif := byteframe.NewByteFrame()
temp = &mhfpacket.MsgSysNotifyRegister{RegisterID: 0x40000} temp = &mhfpacket.MsgSysNotifyRegister{RegisterID: 0x40000}
raviNotif.WriteUint16(uint16(temp.Opcode())) raviNotif.WriteUint16(uint16(temp.Opcode()))
temp.Build(raviNotif, s.clientContext) _ = temp.Build(raviNotif, s.clientContext)
temp = &mhfpacket.MsgSysNotifyRegister{RegisterID: 0x50000} temp = &mhfpacket.MsgSysNotifyRegister{RegisterID: 0x50000}
raviNotif.WriteUint16(uint16(temp.Opcode())) raviNotif.WriteUint16(uint16(temp.Opcode()))
temp.Build(raviNotif, s.clientContext) _ = temp.Build(raviNotif, s.clientContext)
temp = &mhfpacket.MsgSysNotifyRegister{RegisterID: 0x60000} temp = &mhfpacket.MsgSysNotifyRegister{RegisterID: 0x60000}
raviNotif.WriteUint16(uint16(temp.Opcode())) raviNotif.WriteUint16(uint16(temp.Opcode()))
temp.Build(raviNotif, s.clientContext) _ = temp.Build(raviNotif, s.clientContext)
raviNotif.WriteUint16(0x0010) // End it. raviNotif.WriteUint16(0x0010) // End it.
if s.server.erupeConfig.GameplayOptions.LowLatencyRaviente { if s.server.erupeConfig.GameplayOptions.LowLatencyRaviente {
for session := range sema.clients { for session := range sema.clients {

View File

@@ -4,7 +4,6 @@ import (
"testing" "testing"
"erupe-ce/common/byteframe" "erupe-ce/common/byteframe"
"erupe-ce/network/mhfpacket"
) )
// createMockServerWithRaviente creates a mock server with raviente and semaphore // createMockServerWithRaviente creates a mock server with raviente and semaphore
@@ -26,9 +25,6 @@ func TestRavienteInitialization(t *testing.T) {
state: make([]uint32, 30), state: make([]uint32, 30),
support: make([]uint32, 30), support: make([]uint32, 30),
} }
if r == nil {
t.Fatal("Raviente is nil")
}
if len(r.register) != 30 { if len(r.register) != 30 {
t.Errorf("register length = %d, want 30", len(r.register)) t.Errorf("register length = %d, want 30", len(r.register))
} }
@@ -221,9 +217,4 @@ func TestMockServerPacketHandling(t *testing.T) {
t.Errorf("ByteFrame length = %d, want 4", len(bf.Data())) t.Errorf("ByteFrame length = %d, want 4", len(bf.Data()))
} }
// Verify packet types can be instantiated
pkt := &mhfpacket.MsgSysAck{}
if pkt == nil {
t.Error("Failed to create MsgSysAck")
}
} }

View File

@@ -158,7 +158,7 @@ func handleMsgMhfEnumerateRengokuRanking(s *Session, p mhfpacket.MHFPacket) {
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
rows.StructScan(&score) _ = rows.StructScan(&score)
if score.Name == s.Name { if score.Name == s.Name {
bf.WriteUint32(i) bf.WriteUint32(i)
bf.WriteUint32(score.Score) bf.WriteUint32(score.Score)

View File

@@ -354,7 +354,7 @@ func getGuaranteedItems(s *Session, gachaID uint32, rollID uint8) []GachaItem {
items, err := s.server.db.Queryx(`SELECT item_type, item_id, quantity FROM gacha_items WHERE entry_id = (SELECT id FROM gacha_entries WHERE entry_type = $1 AND gacha_id = $2)`, rollID, gachaID) items, err := s.server.db.Queryx(`SELECT item_type, item_id, quantity FROM gacha_items WHERE entry_id = (SELECT id FROM gacha_entries WHERE entry_type = $1 AND gacha_id = $2)`, rollID, gachaID)
if err == nil { if err == nil {
for items.Next() { for items.Next() {
items.StructScan(&reward) _ = items.StructScan(&reward)
rewards = append(rewards, reward) rewards = append(rewards, reward)
} }
} }
@@ -586,7 +586,7 @@ func handleMsgMhfGetBoxGachaInfo(s *Session, p mhfpacket.MHFPacket) {
var entryIDs []uint32 var entryIDs []uint32
for entries.Next() { for entries.Next() {
var entryID uint32 var entryID uint32
entries.Scan(&entryID) _ = entries.Scan(&entryID)
entryIDs = append(entryIDs, entryID) entryIDs = append(entryIDs, entryID)
} }
bf := byteframe.NewByteFrame() bf := byteframe.NewByteFrame()

View File

@@ -324,7 +324,7 @@ func handleMsgMhfGetTenrouirai(s *Session, p mhfpacket.MHFPacket) {
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
temp := TenrouiraiCharScore{} temp := TenrouiraiCharScore{}
rows.Scan(&temp.Name, &temp.Score) _ = rows.Scan(&temp.Name, &temp.Score)
tenrouirai.CharScore = append(tenrouirai.CharScore, temp) tenrouirai.CharScore = append(tenrouirai.CharScore, temp)
} }
} }

View File

@@ -320,7 +320,7 @@ func (s *Server) BroadcastMHF(pkt mhfpacket.MHFPacket, ignoredSession *Session)
bf.WriteUint16(uint16(pkt.Opcode())) bf.WriteUint16(uint16(pkt.Opcode()))
// Build the packet onto the byteframe. // Build the packet onto the byteframe.
pkt.Build(bf, session.clientContext) _ = pkt.Build(bf, session.clientContext)
// Enqueue in a non-blocking way that drops the packet if the connections send buffer channel is full. // Enqueue in a non-blocking way that drops the packet if the connections send buffer channel is full.
session.QueueSendNonBlocking(bf.Data()) session.QueueSendNonBlocking(bf.Data())
@@ -347,7 +347,7 @@ func (s *Server) BroadcastChatMessage(message string) {
Message: message, Message: message,
SenderName: s.name, SenderName: s.name,
} }
msgBinChat.Build(bf) _ = msgBinChat.Build(bf)
s.BroadcastMHF(&mhfpacket.MsgSysCastedBinary{ s.BroadcastMHF(&mhfpacket.MsgSysCastedBinary{
MessageType: BinaryMessageTypeChat, MessageType: BinaryMessageTypeChat,
@@ -390,7 +390,7 @@ func (s *Server) BroadcastRaviente(ip uint32, port uint16, stage []byte, _type u
func (s *Server) DiscordChannelSend(charName string, content string) { func (s *Server) DiscordChannelSend(charName string, content string) {
if s.erupeConfig.Discord.Enabled && s.discordBot != nil { if s.erupeConfig.Discord.Enabled && s.discordBot != nil {
message := fmt.Sprintf("**%s**: %s", charName, content) message := fmt.Sprintf("**%s**: %s", charName, content)
s.discordBot.RealtimeChannelSend(message) _ = s.discordBot.RealtimeChannelSend(message)
} }
} }
@@ -398,7 +398,7 @@ func (s *Server) DiscordScreenShotSend(charName string, title string, descriptio
if s.erupeConfig.Discord.Enabled && s.discordBot != nil { if s.erupeConfig.Discord.Enabled && s.discordBot != nil {
imageUrl := fmt.Sprintf("%s:%d/api/ss/bbs/%s", s.erupeConfig.Screenshots.Host, s.erupeConfig.Screenshots.Port, articleToken) imageUrl := fmt.Sprintf("%s:%d/api/ss/bbs/%s", s.erupeConfig.Screenshots.Host, s.erupeConfig.Screenshots.Port, articleToken)
message := fmt.Sprintf("**%s**: %s - %s %s", charName, title, description, imageUrl) message := fmt.Sprintf("**%s**: %s - %s %s", charName, title, description, imageUrl)
s.discordBot.RealtimeChannelSend(message) _ = s.discordBot.RealtimeChannelSend(message)
} }
} }
@@ -422,7 +422,7 @@ func (s *Server) DisconnectUser(uid uint32) {
} else { } else {
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
rows.Scan(&cid) _ = rows.Scan(&cid)
cids = append(cids, cid) cids = append(cids, cid)
} }
} }

View File

@@ -51,7 +51,7 @@ func (s *Semaphore) BroadcastMHF(pkt mhfpacket.MHFPacket, ignoredSession *Sessio
bf.WriteUint16(uint16(pkt.Opcode())) bf.WriteUint16(uint16(pkt.Opcode()))
// Build the packet onto the byteframe. // Build the packet onto the byteframe.
pkt.Build(bf, session.clientContext) _ = pkt.Build(bf, session.clientContext)
// Enqueue in a non-blocking way that drops the packet if the connections send buffer channel is full. // Enqueue in a non-blocking way that drops the packet if the connections send buffer channel is full.
session.QueueSendNonBlocking(bf.Data()) session.QueueSendNonBlocking(bf.Data())

View File

@@ -131,7 +131,7 @@ func (s *Session) QueueSendMHF(pkt mhfpacket.MHFPacket) {
bf.WriteUint16(uint16(pkt.Opcode())) bf.WriteUint16(uint16(pkt.Opcode()))
// Build the packet onto the byteframe. // Build the packet onto the byteframe.
pkt.Build(bf, s.clientContext) _ = pkt.Build(bf, s.clientContext)
// Queue it. // Queue it.
s.QueueSend(bf.Data()) s.QueueSend(bf.Data())

View File

@@ -170,11 +170,11 @@ func applyPatchSchemas(t *testing.T, db *sqlx.DB, projectRoot string) {
_, err = tx.Exec(string(patchSQL)) _, err = tx.Exec(string(patchSQL))
if err != nil { if err != nil {
tx.Rollback() _ = tx.Rollback()
t.Logf("Warning: Failed to apply patch %s: %v", filename, err) t.Logf("Warning: Failed to apply patch %s: %v", filename, err)
// Continue with other patches even if one fails // Continue with other patches even if one fails
} else { } else {
tx.Commit() _ = tx.Commit()
} }
} }
} }

View File

@@ -356,15 +356,11 @@ func TestCommands_PasswordCommand(t *testing.T) {
func TestDiscordBotStruct(t *testing.T) { func TestDiscordBotStruct(t *testing.T) {
// Test that the DiscordBot struct can be initialized // Test that the DiscordBot struct can be initialized
bot := &DiscordBot{ _ = &DiscordBot{
Session: nil, // Can't create real session in tests Session: nil, // Can't create real session in tests
MainGuild: nil, MainGuild: nil,
RelayChannel: nil, RelayChannel: nil,
} }
if bot == nil {
t.Error("Failed to create DiscordBot struct")
}
} }
func TestOptionsStruct(t *testing.T) { func TestOptionsStruct(t *testing.T) {

View File

@@ -121,7 +121,7 @@ func (s *Server) handleEntranceServerConnection(conn net.Conn) {
if len(pkt) > 5 { if len(pkt) > 5 {
data = append(data, makeUsrResp(pkt, s)...) data = append(data, makeUsrResp(pkt, s)...)
} }
cc.SendPacket(data) _ = cc.SendPacket(data)
// Close because we only need to send the response once. // Close because we only need to send the response once.
// Any further requests from the client will come from a new connection. // Any further requests from the client will come from a new connection.
} }

View File

@@ -80,18 +80,18 @@ func (s *Server) getCharactersForUser(uid uint32) ([]character, error) {
func (s *Server) getReturnExpiry(uid uint32) time.Time { func (s *Server) getReturnExpiry(uid uint32) time.Time {
var returnExpiry, lastLogin time.Time var returnExpiry, lastLogin time.Time
s.db.Get(&lastLogin, "SELECT COALESCE(last_login, now()) FROM users WHERE id=$1", uid) _ = s.db.Get(&lastLogin, "SELECT COALESCE(last_login, now()) FROM users WHERE id=$1", uid)
if time.Now().Add((time.Hour * 24) * -90).After(lastLogin) { if time.Now().Add((time.Hour * 24) * -90).After(lastLogin) {
returnExpiry = time.Now().Add(time.Hour * 24 * 30) returnExpiry = time.Now().Add(time.Hour * 24 * 30)
s.db.Exec("UPDATE users SET return_expires=$1 WHERE id=$2", returnExpiry, uid) _, _ = s.db.Exec("UPDATE users SET return_expires=$1 WHERE id=$2", returnExpiry, uid)
} else { } else {
err := s.db.Get(&returnExpiry, "SELECT return_expires FROM users WHERE id=$1", uid) err := s.db.Get(&returnExpiry, "SELECT return_expires FROM users WHERE id=$1", uid)
if err != nil { if err != nil {
returnExpiry = time.Now() returnExpiry = time.Now()
s.db.Exec("UPDATE users SET return_expires=$1 WHERE id=$2", returnExpiry, uid) _, _ = s.db.Exec("UPDATE users SET return_expires=$1 WHERE id=$2", returnExpiry, uid)
} }
} }
s.db.Exec("UPDATE users SET last_login=$1 WHERE id=$2", time.Now(), uid) _, _ = s.db.Exec("UPDATE users SET last_login=$1 WHERE id=$2", time.Now(), uid)
return returnExpiry return returnExpiry
} }

View File

@@ -60,7 +60,7 @@ func TestMakeSignResponse_EmptyCapLinkValues(t *testing.T) {
// This should NOT panic on array bounds anymore // This should NOT panic on array bounds anymore
result := session.makeSignResponse(0) result := session.makeSignResponse(0)
if result != nil && len(result) > 0 { if len(result) > 0 {
t.Log("✅ makeSignResponse handled empty CapLink.Values without array bounds panic") t.Log("✅ makeSignResponse handled empty CapLink.Values without array bounds panic")
} }
} }
@@ -109,7 +109,7 @@ func TestMakeSignResponse_InsufficientCapLinkValues(t *testing.T) {
// This should NOT panic on array bounds anymore // This should NOT panic on array bounds anymore
result := session.makeSignResponse(0) result := session.makeSignResponse(0)
if result != nil && len(result) > 0 { if len(result) > 0 {
t.Log("✅ makeSignResponse handled insufficient CapLink.Values without array bounds panic") t.Log("✅ makeSignResponse handled insufficient CapLink.Values without array bounds panic")
} }
} }
@@ -158,7 +158,7 @@ func TestMakeSignResponse_MissingCapLinkValues234(t *testing.T) {
// This should NOT panic on array bounds anymore // This should NOT panic on array bounds anymore
result := session.makeSignResponse(0) result := session.makeSignResponse(0)
if result != nil && len(result) > 0 { if len(result) > 0 {
t.Log("✅ makeSignResponse handled missing CapLink.Values[2/3/4] without array bounds panic") t.Log("✅ makeSignResponse handled missing CapLink.Values[2/3/4] without array bounds panic")
} }
} }

View File

@@ -79,7 +79,7 @@ func (s *Session) handlePacket(pkt []byte) error {
err := s.server.deleteCharacter(characterID, token, tokenID) err := s.server.deleteCharacter(characterID, token, tokenID)
if err == nil { if err == nil {
s.logger.Info("Deleted character", zap.Int("CharacterID", characterID)) s.logger.Info("Deleted character", zap.Int("CharacterID", characterID))
s.cryptConn.SendPacket([]byte{0x01}) // DEL_SUCCESS _ = s.cryptConn.SendPacket([]byte{0x01}) // DEL_SUCCESS
} }
default: default:
s.logger.Warn("Unknown request", zap.String("reqType", reqType)) s.logger.Warn("Unknown request", zap.String("reqType", reqType))
@@ -127,7 +127,7 @@ func (s *Session) handleWIIUSGN(bf *byteframe.ByteFrame) {
s.sendCode(SIGN_EABORT) s.sendCode(SIGN_EABORT)
return return
} }
s.cryptConn.SendPacket(s.makeSignResponse(uid)) _ = s.cryptConn.SendPacket(s.makeSignResponse(uid))
} }
func (s *Session) handlePSSGN(bf *byteframe.ByteFrame) { func (s *Session) handlePSSGN(bf *byteframe.ByteFrame) {
@@ -147,13 +147,13 @@ func (s *Session) handlePSSGN(bf *byteframe.ByteFrame) {
err := s.server.db.QueryRow(`SELECT id FROM users WHERE psn_id = $1`, s.psn).Scan(&uid) err := s.server.db.QueryRow(`SELECT id FROM users WHERE psn_id = $1`, s.psn).Scan(&uid)
if err != nil { if err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
s.cryptConn.SendPacket(s.makeSignResponse(0)) _ = s.cryptConn.SendPacket(s.makeSignResponse(0))
return return
} }
s.sendCode(SIGN_EABORT) s.sendCode(SIGN_EABORT)
return return
} }
s.cryptConn.SendPacket(s.makeSignResponse(uid)) _ = s.cryptConn.SendPacket(s.makeSignResponse(uid))
} }
func (s *Session) handlePSNLink(bf *byteframe.ByteFrame) { func (s *Session) handlePSNLink(bf *byteframe.ByteFrame) {
@@ -207,5 +207,5 @@ func (s *Session) handleDSGN(bf *byteframe.ByteFrame) {
} }
func (s *Session) sendCode(id RespID) { func (s *Session) sendCode(id RespID) {
s.cryptConn.SendPacket([]byte{byte(id)}) _ = s.cryptConn.SendPacket([]byte{byte(id)})
} }

View File

@@ -110,6 +110,7 @@ func TestSessionMutex(t *testing.T) {
s := &Session{} s := &Session{}
s.Lock() s.Lock()
//nolint:staticcheck // SA2001: testing that Lock/Unlock doesn't panic
s.Unlock() s.Unlock()
done := make(chan bool) done := make(chan bool)
@@ -123,6 +124,7 @@ func TestSessionMutex(t *testing.T) {
time.Sleep(5 * time.Millisecond) time.Sleep(5 * time.Millisecond)
s.Lock() s.Lock()
//nolint:staticcheck // SA2001: testing that Lock/Unlock doesn't panic
s.Unlock() s.Unlock()
<-done <-done

View File

@@ -329,6 +329,7 @@ func TestServerMutex(t *testing.T) {
s := &Server{} s := &Server{}
s.Lock() s.Lock()
//nolint:staticcheck // SA2001: testing that Lock/Unlock doesn't panic
s.Unlock() s.Unlock()
done := make(chan bool) done := make(chan bool)
@@ -342,6 +343,7 @@ func TestServerMutex(t *testing.T) {
time.Sleep(5 * time.Millisecond) time.Sleep(5 * time.Millisecond)
s.Lock() s.Lock()
//nolint:staticcheck // SA2001: testing that Lock/Unlock doesn't panic
s.Unlock() s.Unlock()
<-done <-done