diff --git a/protocol/bond/conn.go b/protocol/bond/conn.go index 9c8327f9..a2f7cd98 100644 --- a/protocol/bond/conn.go +++ b/protocol/bond/conn.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "errors" "io" + "math" "net" "time" ) @@ -26,8 +27,11 @@ func NewBondedConn(conns []net.Conn, downloadRatios, uploadRatios []uint8) *bond } } -func (c *bondedConn) Read(b []byte) (n int, err error) { - if c.readBuffer.Len() == 0 { +func (c *bondedConn) Read(buffer []byte) (int, error) { + if len(buffer) == 0 { + return 0, nil + } + for c.readBuffer.Len() == 0 { c.readBuffer.Reset() var header [2]byte _, err := io.ReadFull(c.conns[0], header[:]) @@ -35,51 +39,47 @@ func (c *bondedConn) Read(b []byte) (n int, err error) { return 0, err } size := int(binary.BigEndian.Uint16(header[:])) - chunkLens := splitByRatios(size, c.downloadRatios) - total := 0 - for i, chunkLen := range chunkLens { - if chunkLen == 0 { + for i, length := range splitByRatios(size, c.downloadRatios) { + if length == 0 { continue } - n, err := io.CopyN(c.readBuffer, c.conns[i], int64(chunkLen)) - total += int(n) - if err != nil { - return total, err + if _, err = io.CopyN(c.readBuffer, c.conns[i], int64(length)); err != nil { + c.readBuffer.Reset() + return 0, err } } } - return c.readBuffer.Read(b) + return c.readBuffer.Read(buffer) } -func (c *bondedConn) Write(b []byte) (n int, err error) { - chunkLens := splitByRatios(len(b), c.uploadRatios) - var header [2]byte - binary.BigEndian.PutUint16(header[:], uint16(len(b))) - _, err = c.conns[0].Write(header[:]) - if err != nil { - return 0, err - } - total := 0 - for i, chunkLen := range chunkLens { - if chunkLen == 0 { - continue +func (c *bondedConn) Write(buffer []byte) (int, error) { + written := 0 + for written < len(buffer) { + size := min(len(buffer)-written, math.MaxUint16) + var header [2]byte + binary.BigEndian.PutUint16(header[:], uint16(size)) + count, err := c.conns[0].Write(header[:]) + if err != nil { + return written, err } - chunk := b[total : total+chunkLen] - conn := c.conns[i] - subTotal := 0 - for subTotal < len(chunk) { - n, err := conn.Write(chunk[subTotal:]) - subTotal += n - total += n - if err != nil { - return total, err - } - if n == 0 { - return total, io.ErrUnexpectedEOF + if count != len(header) { + return written, io.ErrShortWrite + } + for i, length := range splitByRatios(size, c.uploadRatios) { + for length > 0 { + count, err = c.conns[i].Write(buffer[written : written+length]) + written += count + length -= count + if err != nil { + return written, err + } + if count == 0 { + return written, io.ErrShortWrite + } } } } - return total, err + return written, nil } func (c *bondedConn) Close() error {