From a936978cd047d41eae0e51c592ce376dfcc9618e Mon Sep 17 00:00:00 2001 From: dreamscached Date: Mon, 12 Feb 2024 17:54:10 +0100 Subject: [PATCH] Backport readAll from later Go --- io.go | 21 +++++++++++++++++++++ query.go | 8 ++++---- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/io.go b/io.go index 4fb7c8e..6bf2955 100644 --- a/io.go +++ b/io.go @@ -33,3 +33,24 @@ func readAllUntilZero(reader io.ByteReader) ([]byte, error) { } } } + +// readAll reads all bytes from reader. +// This is a backport from newer Go stdlib for sake of minequery's compatibility with Go 1.13. +func readAll(r io.Reader) ([]byte, error) { + b := make([]byte, 0, 512) + for { + n, err := r.Read(b[len(b):cap(b)]) + b = b[:len(b)+n] + if err != nil { + if err == io.EOF { + err = nil + } + return b, err + } + + if len(b) == cap(b) { + // Add more capacity (let append pick how much). + b = append(b, 0)[:len(b)] + } + } +} diff --git a/query.go b/query.go index 9d7e402..f911c68 100644 --- a/query.go +++ b/query.go @@ -371,7 +371,7 @@ func (p *Pinger) writeQueryFullStatPacket(conn *net.UDPConn, sessionID int32, to func (p *Pinger) parseQueryHandshakeResponse(reader io.Reader) (int32, error) { // Read all the remaining data in packet and ensure it has NUL terminator (if UseStrict) - token, _ := io.ReadAll(reader) + token, _ := readAll(reader) if len(token) == 0 { return 0, fmt.Errorf("challenge token is empty") } @@ -392,7 +392,7 @@ func (p *Pinger) parseQueryHandshakeResponse(reader io.Reader) (int32, error) { func (p *Pinger) parseQueryBasicStatResponse(reader io.Reader) (*BasicQueryStatus, error) { // Read all the remaining data and ensure it has NUL terminator (if UseStrict) - data, _ := io.ReadAll(reader) + data, _ := readAll(reader) if len(data) == 0 { return nil, fmt.Errorf("%w: empty response body", ErrInvalidStatus) } @@ -437,7 +437,7 @@ func (p *Pinger) parseQueryBasicStatResponse(reader io.Reader) (*BasicQueryStatu } // Read host as byte sequence - hostBytes, err := io.ReadAll(remReader) + hostBytes, err := readAll(remReader) if err != nil { return nil, err } @@ -454,7 +454,7 @@ func (p *Pinger) parseQueryBasicStatResponse(reader io.Reader) (*BasicQueryStatu func (p *Pinger) parseQueryFullStatResponse(reader io.Reader) (*FullQueryStatus, error) { // Read all the remaining data and ensure it has NUL terminator (if UseStrict) - data, _ := io.ReadAll(reader) + data, _ := readAll(reader) if len(data) == 0 { return nil, fmt.Errorf("%w: empty response body", ErrInvalidStatus) }