mirror of
https://github.com/lwch/natpass.git
synced 2026-10-21 03:23:57 +00:00
修改checksum计算方式
This commit is contained in:
+8
-14
@@ -3,13 +3,16 @@ package network
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/lwch/logging"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -21,7 +24,7 @@ type Conn struct {
|
||||
c net.Conn
|
||||
lockRead sync.Mutex
|
||||
lockWrite sync.Mutex
|
||||
sizeRead [4]byte
|
||||
sizeRead [6]byte
|
||||
}
|
||||
|
||||
// NewConn create connection
|
||||
@@ -34,16 +37,6 @@ func (c *Conn) Close() {
|
||||
c.c.Close()
|
||||
}
|
||||
|
||||
func sum(data []byte) uint16 {
|
||||
tmp := make([]uint16, len(data)/2)
|
||||
binary.Read(bytes.NewReader(data), binary.BigEndian, tmp)
|
||||
var ret uint16
|
||||
for _, v := range tmp {
|
||||
ret += v
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
// ReadMessage read message with timeout
|
||||
func (c *Conn) ReadMessage(timeout time.Duration) (*Msg, error) {
|
||||
c.lockRead.Lock()
|
||||
@@ -54,13 +47,14 @@ func (c *Conn) ReadMessage(timeout time.Duration) (*Msg, error) {
|
||||
return nil, err
|
||||
}
|
||||
size := binary.BigEndian.Uint16(c.sizeRead[:])
|
||||
enc := binary.BigEndian.Uint16(c.sizeRead[2:])
|
||||
enc := binary.BigEndian.Uint32(c.sizeRead[2:])
|
||||
buf := make([]byte, size)
|
||||
_, err = io.ReadFull(c.c, buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if sum(buf) != enc {
|
||||
if crc32.ChecksumIEEE(buf) != enc {
|
||||
logging.Info("sum=%d, enc=%d\n%s", crc32.ChecksumIEEE(buf), enc, hex.Dump(buf))
|
||||
return nil, errChecksum
|
||||
}
|
||||
var msg Msg
|
||||
@@ -84,7 +78,7 @@ func (c *Conn) WriteMessage(m *Msg, timeout time.Duration) error {
|
||||
}
|
||||
buf := make([]byte, len(data)+len(c.sizeRead))
|
||||
binary.BigEndian.PutUint16(buf, uint16(len(data)))
|
||||
binary.BigEndian.PutUint16(buf[2:], sum(data))
|
||||
binary.BigEndian.PutUint32(buf[2:], crc32.ChecksumIEEE(data))
|
||||
copy(buf[len(c.sizeRead):], data)
|
||||
c.c.SetWriteDeadline(time.Now().Add(timeout))
|
||||
_, err = io.Copy(c.c, bytes.NewReader(buf))
|
||||
|
||||
Reference in New Issue
Block a user