Skip to content

Commit

Permalink
set read deadline for inbound packets
Browse files Browse the repository at this point in the history
  • Loading branch information
Sch8ill committed Feb 8, 2024
1 parent 4cafd45 commit 6d46ac9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
5 changes: 3 additions & 2 deletions slp/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ func (c *Client) recvResponse() (string, error) {
//
// https://wiki.vg/Server_List_Ping#Status_Response

res, err := packet.NewInboundPacket(c.conn)
res, err := packet.NewInboundPacket(c.conn, c.timeout)
if err != nil {
return "", fmt.Errorf("failed to read status response: %w", err)
}
Expand Down Expand Up @@ -250,7 +250,7 @@ func (c *Client) recvPong() (int64, error) {
//
// https://wiki.vg/Server_List_Ping#Pong_Response

pong, err := packet.NewInboundPacket(c.conn)
pong, err := packet.NewInboundPacket(c.conn, c.timeout)
if err != nil {
return 0, fmt.Errorf("failed to read pong: %w", err)
}
Expand Down Expand Up @@ -280,6 +280,7 @@ func (c *Client) connectAndHandshake() error {
return err
}
}

return nil
}

Expand Down
21 changes: 15 additions & 6 deletions slp/packet/inbound.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"io"
"net"
"time"
)

// InboundPacket represents a packet received from a connection.
Expand All @@ -18,7 +19,11 @@ type InboundPacket struct {
}

// NewInboundPacket creates a new InboundPacket from a network connection.
func NewInboundPacket(conn net.Conn) (*InboundPacket, error) {
func NewInboundPacket(conn net.Conn, timeout time.Duration) (*InboundPacket, error) {
if err := conn.SetReadDeadline(time.Now().Add(timeout)); err != nil {
return nil, fmt.Errorf("failed to set read deadline: %w", err)
}

p := &InboundPacket{}
connReader := bufio.NewReader(conn)

Expand Down Expand Up @@ -48,6 +53,11 @@ func NewInboundPacket(conn net.Conn) (*InboundPacket, error) {
return p, nil
}

// ID returns the id of the packet.
func (p *InboundPacket) ID() int32 {
return p.id
}

// ReadInt reads a 32-bit integer from the packet.
func (p *InboundPacket) ReadInt() (int32, error) {
buf := make([]byte, 4)
Expand Down Expand Up @@ -157,13 +167,12 @@ func (p *InboundPacket) ReadBytes(length int) ([]byte, error) {
return b, nil
}

// ID returns the id of the packet.
func (p *InboundPacket) ID() int32 {
return p.id
}

// readBytes reads a specified number of bytes from a buffered reader.
func readBytes(reader *bufio.Reader, length int) ([]byte, error) {
if length < 0 {
return nil, fmt.Errorf("read length cannot be negative: %d", length)
}

data := make([]byte, length)
var received int
for received < length {
Expand Down

0 comments on commit 6d46ac9

Please sign in to comment.