Bugfix framerwc

This commit is contained in:
9seconds
2018-07-03 14:08:01 +03:00
parent daddf50390
commit 4c4671ad3b
2 changed files with 26 additions and 14 deletions
+18 -9
View File
@@ -6,6 +6,7 @@ import (
"encoding/binary"
"hash/crc32"
"io"
"io/ioutil"
"net"
"github.com/juju/errors"
@@ -56,9 +57,13 @@ func (f *FrameRWC) Write(buf []byte) (int, error) {
func (f *FrameRWC) Read(p []byte) (int, error) {
return f.BufferedRead(p, func() error {
buf := &bytes.Buffer{}
sum := crc32.NewIEEE()
writer := io.MultiWriter(buf, sum)
for {
buf.Reset()
if _, err := io.CopyN(buf, f.conn, 4); err != nil {
sum.Reset()
if _, err := io.CopyN(writer, f.conn, 4); err != nil {
return errors.Annotate(err, "Cannot read frame padding")
}
if !bytes.Equal(buf.Bytes(), frameRWCPadding[:]) {
@@ -70,25 +75,29 @@ func (f *FrameRWC) Read(p []byte) (int, error) {
if messageLength%4 != 0 || messageLength < frameRWCMinMessageLength || messageLength > frameRWCMaxMessageLength {
return errors.Errorf("Incorrect frame message length %d", messageLength)
}
sum := crc32.NewIEEE()
sum.Write(buf.Bytes())
buf.Reset()
buf.Grow(int(messageLength) - 4) // -4 because we already read the first number
if _, err := io.CopyN(buf, f.conn, int64(messageLength)-4); err != nil {
buf.Grow(int(messageLength) - 4 - 4)
if _, err := io.CopyN(writer, f.conn, int64(messageLength)-4-4); err != nil {
return errors.Annotate(err, "Cannot read the message frame")
}
sum.Write(buf.Bytes())
var seqNo int32
binary.Read(buf, binary.LittleEndian, seqNo)
binary.Read(buf, binary.LittleEndian, &seqNo)
if seqNo != f.readSeqNo {
return errors.Errorf("Unexpected sequence number %d (wait for %d)", seqNo, f.readSeqNo)
}
f.readSeqNo++
data := buf.Bytes()[:int(messageLength)-4-4-4]
checksum := binary.LittleEndian.Uint32(buf.Bytes()[int(messageLength)-4-4-4:])
data, _ := ioutil.ReadAll(buf)
buf.Reset()
// write to buf, not to writer. This is because we are going to fetch
// crc32 checksum.
if _, err := io.CopyN(buf, f.conn, 4); err != nil {
return errors.Annotate(err, "Cannot read checksum")
}
checksum := binary.LittleEndian.Uint32(buf.Bytes())
if checksum != sum.Sum32() {
return errors.Errorf("CRC32 checksum mismatch. Wait for %d, got %d", sum.Sum32(), checksum)