Skip to content

Commit

Permalink
Leave overflow logic to go-msgio
Browse files Browse the repository at this point in the history
It seems as though go-msgio now implements the message length limit
(currently 8MB), so the logic in secio reader can be simplified.

License: MIT
Signed-off-by: Randall Leeds <randall@bleeds.info>
  • Loading branch information
tilgovi committed Oct 29, 2015
1 parent bf415b0 commit 1c7e286
Showing 1 changed file with 13 additions and 56 deletions.
69 changes: 13 additions & 56 deletions p2p/crypto/secio/rw.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,6 @@ import (
context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
)

const MaxMsgSize = 8 * 1024 * 1024

var ErrMaxMessageSize = errors.New("attempted to read message larger than max size")

// ErrMACInvalid signals that a MAC verification failed
var ErrMACInvalid = errors.New("MAC verification failed")

Expand Down Expand Up @@ -105,66 +101,27 @@ func (r *etmReader) NextMsgLen() (int, error) {
return r.msg.NextMsgLen()
}

func (r *etmReader) drainBuf(buf []byte) int {
if r.buf == nil {
return 0
}

n := copy(buf, r.buf)
r.buf = r.buf[n:]
return n
}

func (r *etmReader) Read(buf []byte) (int, error) {
r.Lock()
defer r.Unlock()

// first, check if we have anything in the buffer
copied := r.drainBuf(buf)
buf = buf[copied:]
if copied > 0 {
return copied, nil
// return here to avoid complicating the rest...
// user can call io.ReadFull.
}

// check the buffer has enough space for the next msg
fullLen, err := r.msg.NextMsgLen()
if err != nil {
return 0, err
}

if fullLen > MaxMsgSize {
return 0, ErrMaxMessageSize
}
if len(r.buf) == 0 {
msg, err := r.msg.ReadMsg()
if err != nil {
return 0, err
}

buf2 := buf
changed := false
// if not enough space, allocate a new buffer.
if cap(buf) < fullLen {
buf2 = make([]byte, fullLen)
changed = true
}
buf2 = buf2[:fullLen]
m, err := r.macCheckThenDecrypt(msg)
if err != nil {
return 0, err
}

n, err := io.ReadFull(r.msg, buf2)
if err != nil {
return n, err
r.buf = msg[:m]
}

m, err := r.macCheckThenDecrypt(buf2)
if err != nil {
return 0, err
}
buf2 = buf2[:m]
if !changed {
return m, nil
}

n = copy(buf, buf2)
if len(buf2) > len(buf) {
r.buf = buf2[len(buf):] // had some left over? save it.
}
n := copy(buf, r.buf)
buf = buf[:n]
r.buf = r.buf[n:]
return n, nil
}

Expand Down

0 comments on commit 1c7e286

Please sign in to comment.