Steam servers are asked for A2S_INFO like the server browser does, answering the challenge newer servers send. Minecraft Java Edition gets the server list ping, Bedrock Edition a RakNet unconnected ping. A minimum of free slots can be required. The protocols are implemented directly; tested against protocol-accurate test servers and once by hand against public Java and Bedrock servers. Closes #96 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
254 lines
7.6 KiB
Go
254 lines
7.6 KiB
Go
package check
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/binary"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
|
|
)
|
|
|
|
// Game server checks query a server the way game clients list it.
|
|
const (
|
|
Steam Type = "steam"
|
|
Minecraft Type = "minecraft"
|
|
)
|
|
|
|
// GameConfig configures game server checks.
|
|
type GameConfig struct {
|
|
// Edition is "java" or "bedrock" for Minecraft.
|
|
Edition string `json:"edition,omitempty"`
|
|
// MinFreeSlots fails the check when fewer player slots are free.
|
|
MinFreeSlots int `json:"min_free_slots,omitempty"`
|
|
}
|
|
|
|
type gameCheck struct{ typ Type }
|
|
|
|
func (g gameCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
|
if !validHostPort(target) {
|
|
return nil, invalid("invalid_target")
|
|
}
|
|
var c GameConfig
|
|
if err := json.Unmarshal(config, &c); err != nil || c.MinFreeSlots < 0 || c.MinFreeSlots > 10000 {
|
|
return nil, invalid("invalid_config")
|
|
}
|
|
switch {
|
|
case g.typ == Minecraft && c.Edition == "":
|
|
c.Edition = "java"
|
|
case g.typ == Minecraft && c.Edition != "java" && c.Edition != "bedrock",
|
|
g.typ == Steam && c.Edition != "":
|
|
return nil, invalid("invalid_config")
|
|
}
|
|
return encode(c), nil
|
|
}
|
|
|
|
// gameStatus is what a server tells about itself.
|
|
type gameStatus struct {
|
|
Name string
|
|
Players, Max int
|
|
}
|
|
|
|
func (g gameCheck) run(ctx context.Context, s Spec) Outcome {
|
|
c, err := decode[GameConfig](s.Config)
|
|
if err != nil {
|
|
return Outcome{Error: "invalid configuration"}
|
|
}
|
|
d := netguard.Dialer(s.AllowPrivate, s.Timeout)
|
|
var st gameStatus
|
|
switch {
|
|
case g.typ == Steam:
|
|
st, err = queryA2S(ctx, d, s.Target)
|
|
case c.Edition == "bedrock":
|
|
st, err = pingBedrock(ctx, d, s.Target)
|
|
default:
|
|
st, err = pingJava(ctx, d, s.Target)
|
|
}
|
|
var op *net.OpError
|
|
switch {
|
|
case errors.As(err, &op) && op.Timeout(), errors.Is(err, context.DeadlineExceeded):
|
|
return Outcome{Error: "no answer from the game server"}
|
|
case errors.As(err, &op):
|
|
return Outcome{Error: describeNetErr(err)}
|
|
case err != nil:
|
|
return Outcome{Error: truncate(err.Error(), 300)}
|
|
}
|
|
if free := st.Max - st.Players; c.MinFreeSlots > 0 && free < c.MinFreeSlots {
|
|
return Outcome{Error: fmt.Sprintf("%d of %d slots taken", st.Players, st.Max)}
|
|
}
|
|
return Outcome{OK: true}
|
|
}
|
|
|
|
// udpExchange sends req and returns the first answer.
|
|
func udpExchange(ctx context.Context, conn net.Conn, req []byte) ([]byte, error) {
|
|
if _, err := conn.Write(req); err != nil {
|
|
return nil, err
|
|
}
|
|
buf := make([]byte, 1500)
|
|
n, err := conn.Read(buf)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return buf[:n], ctx.Err()
|
|
}
|
|
|
|
func deadlineConn(ctx context.Context, d *net.Dialer, network, target string) (net.Conn, error) {
|
|
conn, err := d.DialContext(ctx, network, target)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if dl, ok := ctx.Deadline(); ok {
|
|
// Leave time to report a silent server before the check's deadline.
|
|
_ = conn.SetDeadline(time.Now().Add(time.Until(dl) * 4 / 5))
|
|
}
|
|
return conn, nil
|
|
}
|
|
|
|
var a2sInfo = append([]byte{0xFF, 0xFF, 0xFF, 0xFF, 'T'}, "Source Engine Query\x00"...)
|
|
|
|
// queryA2S asks a Steam server for A2S_INFO, answering a challenge if the
|
|
// server sends one.
|
|
func queryA2S(ctx context.Context, d *net.Dialer, target string) (gameStatus, error) {
|
|
conn, err := deadlineConn(ctx, d, "udp", target)
|
|
if err != nil {
|
|
return gameStatus{}, err
|
|
}
|
|
defer func() { _ = conn.Close() }()
|
|
resp, err := udpExchange(ctx, conn, a2sInfo)
|
|
if err != nil {
|
|
return gameStatus{}, err
|
|
}
|
|
if len(resp) == 9 && resp[4] == 'A' {
|
|
resp, err = udpExchange(ctx, conn, append(append([]byte{}, a2sInfo...), resp[5:9]...))
|
|
if err != nil {
|
|
return gameStatus{}, err
|
|
}
|
|
}
|
|
if len(resp) < 6 || !bytes.Equal(resp[:4], []byte{0xFF, 0xFF, 0xFF, 0xFF}) || resp[4] != 'I' {
|
|
return gameStatus{}, errors.New("not a Steam server query answer")
|
|
}
|
|
r := bytes.NewReader(resp[6:])
|
|
cstr := func() string {
|
|
var b strings.Builder
|
|
for {
|
|
c, err := r.ReadByte()
|
|
if err != nil || c == 0 {
|
|
return b.String()
|
|
}
|
|
b.WriteByte(c)
|
|
}
|
|
}
|
|
name := cstr()
|
|
_, _, _ = cstr(), cstr(), cstr() // map, folder, game
|
|
var rest struct {
|
|
ID uint16
|
|
Players, Max uint8
|
|
}
|
|
if err := binary.Read(r, binary.LittleEndian, &rest); err != nil {
|
|
return gameStatus{}, errors.New("truncated Steam server answer")
|
|
}
|
|
return gameStatus{Name: name, Players: int(rest.Players), Max: int(rest.Max)}, nil
|
|
}
|
|
|
|
// pingJava does the Minecraft Java Edition server list ping.
|
|
func pingJava(ctx context.Context, d *net.Dialer, target string) (gameStatus, error) {
|
|
conn, err := deadlineConn(ctx, d, "tcp", target)
|
|
if err != nil {
|
|
return gameStatus{}, err
|
|
}
|
|
defer func() { _ = conn.Close() }()
|
|
host, port, _ := net.SplitHostPort(target)
|
|
p, _ := strconv.Atoi(port)
|
|
var hs bytes.Buffer
|
|
hs.WriteByte(0x00)
|
|
hs.Write(binary.AppendUvarint(nil, 767)) // protocol version; servers answer any
|
|
hs.Write(binary.AppendUvarint(nil, uint64(len(host))))
|
|
hs.WriteString(host)
|
|
_ = binary.Write(&hs, binary.BigEndian, uint16(p))
|
|
hs.WriteByte(0x01) // next state: status
|
|
var out []byte
|
|
out = binary.AppendUvarint(out, uint64(hs.Len()))
|
|
out = append(out, hs.Bytes()...)
|
|
out = append(out, 0x01, 0x00) // status request
|
|
if _, err := conn.Write(out); err != nil {
|
|
return gameStatus{}, err
|
|
}
|
|
r := bufio.NewReader(conn)
|
|
length, err := binary.ReadUvarint(r)
|
|
if err != nil {
|
|
return gameStatus{}, err
|
|
}
|
|
// The packet ID is checked first: another protocol's greeting would
|
|
// otherwise leave us waiting for the rest of an imagined packet.
|
|
if id, err := r.ReadByte(); err != nil || id != 0x00 || length < 2 || length > 1<<20 {
|
|
return gameStatus{}, errors.New("not a Minecraft server")
|
|
}
|
|
packet := make([]byte, length-1)
|
|
if _, err := io.ReadFull(r, packet); err != nil {
|
|
return gameStatus{}, err
|
|
}
|
|
pr := bytes.NewReader(packet)
|
|
n, err := binary.ReadUvarint(pr)
|
|
if err != nil || n > uint64(pr.Len()) {
|
|
return gameStatus{}, errors.New("not a Minecraft server")
|
|
}
|
|
var status struct {
|
|
Players struct {
|
|
Max int `json:"max"`
|
|
Online int `json:"online"`
|
|
} `json:"players"`
|
|
Description json.RawMessage `json:"description"`
|
|
}
|
|
if err := json.NewDecoder(io.LimitReader(pr, int64(n))).Decode(&status); err != nil {
|
|
return gameStatus{}, errors.New("not a Minecraft server")
|
|
}
|
|
return gameStatus{Players: status.Players.Online, Max: status.Players.Max}, nil
|
|
}
|
|
|
|
var raknetMagic = []byte{0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78}
|
|
|
|
// pingBedrock sends a RakNet unconnected ping, which Bedrock servers
|
|
// answer with their MOTD line.
|
|
func pingBedrock(ctx context.Context, d *net.Dialer, target string) (gameStatus, error) {
|
|
conn, err := deadlineConn(ctx, d, "udp", target)
|
|
if err != nil {
|
|
return gameStatus{}, err
|
|
}
|
|
defer func() { _ = conn.Close() }()
|
|
req := []byte{0x01}
|
|
req = binary.BigEndian.AppendUint64(req, uint64(time.Now().UnixMilli()))
|
|
req = append(req, raknetMagic...)
|
|
guid := make([]byte, 8)
|
|
_, _ = rand.Read(guid)
|
|
req = append(req, guid...)
|
|
resp, err := udpExchange(ctx, conn, req)
|
|
if err != nil {
|
|
return gameStatus{}, err
|
|
}
|
|
// 0x1C, time (8), server GUID (8), magic (16), length (2), MOTD.
|
|
if len(resp) < 35 || resp[0] != 0x1C || !bytes.Equal(resp[17:33], raknetMagic) {
|
|
return gameStatus{}, errors.New("not a Minecraft Bedrock server")
|
|
}
|
|
motd := resp[35:]
|
|
if n := int(binary.BigEndian.Uint16(resp[33:35])); n < len(motd) {
|
|
motd = motd[:n]
|
|
}
|
|
// MCPE;name;protocol;version;online;max;...
|
|
f := strings.Split(string(motd), ";")
|
|
if len(f) < 6 {
|
|
return gameStatus{}, errors.New("not a Minecraft Bedrock server")
|
|
}
|
|
online, _ := strconv.Atoi(f[4])
|
|
maxPlayers, _ := strconv.Atoi(f[5])
|
|
return gameStatus{Name: f[1], Players: online, Max: maxPlayers}, nil
|
|
}
|