Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions agent/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,8 +284,15 @@ func main() {
}
return nil
}(),
Usage: usageReader,
Metrics: m,
PlayerQuery: func() *caps.PlayerQuery {
if playerActions != nil {
return playerActions.Query
}
return nil
}(),
QueryHost: rconHost,
Usage: usageReader,
Metrics: m,
})

go func() {
Expand Down
139 changes: 139 additions & 0 deletions agent/internal/a2s/a2s.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// Package a2s reads a game server's player counts with Valve's A2S_INFO
// query, which most Steam dedicated servers answer on their query port.
//
// Protocol reference: https://developer.valvesoftware.com/wiki/Server_queries
//
// Wire format (UDP, one datagram each way):
//
// request: FF FF FF FF | 'T'(0x54) | "Source Engine Query\x00" [| 4-byte challenge]
// reply: FF FF FF FF | 'I'(0x49) | protocol byte | name\x00 | map\x00 |
// folder\x00 | game\x00 | app ID (2 bytes, little-endian) |
// players byte | max players byte | bots byte | ...
//
// A server may answer the first request with a challenge instead,
// FF FF FF FF | 'A'(0x41) | 4-byte challenge, and then expects the request
// again with the challenge appended. Only the single-packet reply is
// supported: A2S_INFO replies fit in one datagram in practice, and a
// split reply (FE FF FF FF) is reported as an error.
package a2s

import (
"bytes"
"context"
"errors"
"fmt"
"net"
"time"
)

const (
headerInfo = 0x49
headerChallenge = 0x41
// Replies are at most one datagram; 1400 bytes is the protocol's
// maximum single-packet size, with headroom.
maxPacket = 4096
// A server answers at most this many challenges before we give up,
// so a server that keeps issuing new ones can't hold the query open.
maxChallenges = 2
)

var (
singlePacket = []byte{0xFF, 0xFF, 0xFF, 0xFF}
infoRequest = append(append([]byte{}, singlePacket...), append([]byte{'T'}, "Source Engine Query\x00"...)...)
)

// Info is the part of an A2S_INFO reply that the agent reports.
type Info struct {
// Players is the number of players online, bots included.
Players int
// MaxPlayers is the server's player limit.
MaxPlayers int
// Bots is the number of those players that are bots.
Bots int
}

// Humans is the number of online players who aren't bots.
func (i Info) Humans() int {
if i.Bots >= i.Players {
return 0
}
return i.Players - i.Bots
}

// QueryInfo sends A2S_INFO to addr (host:port) and parses the reply. The
// timeout bounds the whole exchange, challenge round trips included; ctx
// bounds the dial.
func QueryInfo(ctx context.Context, addr string, timeout time.Duration) (Info, error) {
dialer := net.Dialer{Timeout: timeout}
conn, err := dialer.DialContext(ctx, "udp", addr)
if err != nil {
return Info{}, fmt.Errorf("a2s dial %s: %w", addr, err)
}
defer func() { _ = conn.Close() }()
if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil {
return Info{}, fmt.Errorf("a2s deadline: %w", err)
}

req := infoRequest
buf := make([]byte, maxPacket)
for range maxChallenges + 1 {
if _, err := conn.Write(req); err != nil {
return Info{}, fmt.Errorf("a2s write: %w", err)
}
n, err := conn.Read(buf)
if err != nil {
return Info{}, fmt.Errorf("a2s read: %w", err)
}
challenge, info, err := parseReply(buf[:n])
if err != nil {
return Info{}, err
}
if challenge == nil {
return info, nil
}
req = append(append([]byte{}, infoRequest...), challenge...)
}
return Info{}, errors.New("a2s: server kept answering with a challenge")
}

// parseReply returns either the challenge to resend the request with, or
// the parsed info.
func parseReply(b []byte) (challenge []byte, info Info, err error) {
if len(b) < 5 || !bytes.Equal(b[:4], singlePacket) {
return nil, Info{}, errors.New("a2s: not a single-packet reply")
}
switch b[4] {
case headerChallenge:
if len(b) < 9 {
return nil, Info{}, errors.New("a2s: short challenge")
}
return append([]byte{}, b[5:9]...), Info{}, nil
case headerInfo:
info, err := parseInfo(b[5:])
return nil, info, err
default:
return nil, Info{}, fmt.Errorf("a2s: unexpected reply header 0x%02x", b[4])
}
}

// parseInfo parses an A2S_INFO payload, after its 0x49 header.
func parseInfo(b []byte) (Info, error) {
// Protocol version byte.
if len(b) < 1 {
return Info{}, errors.New("a2s: short info reply")
}
b = b[1:]
// Name, map, folder and game.
for range 4 {
i := bytes.IndexByte(b, 0)
if i < 0 {
return Info{}, errors.New("a2s: truncated string in info reply")
}
b = b[i+1:]
}
// App ID (2 bytes), then players, max players and bots.
if len(b) < 5 {
return Info{}, errors.New("a2s: short info reply")
}
return Info{Players: int(b[2]), MaxPlayers: int(b[3]), Bots: int(b[4])}, nil
}
131 changes: 131 additions & 0 deletions agent/internal/a2s/a2s_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package a2s

import (
"bytes"
"net"
"strings"
"testing"
"time"
)

// infoReply builds an A2S_INFO reply with the given counts.
func infoReply(players, maxPlayers, bots byte) []byte {
b := append([]byte{}, singlePacket...)
b = append(b, headerInfo, 17)
b = append(b, "My Server\x00Dedicated\x00valheim\x00Valheim\x00"...)
b = append(b, 0x00, 0x00) // app ID
return append(b, players, maxPlayers, bots, 'd', 'l', 0, 1)
}

// serve answers each request on a loopback UDP socket with reply(request).
func serve(t *testing.T, reply func(req []byte) []byte) string {
t.Helper()
pc, err := (&net.ListenConfig{}).ListenPacket(t.Context(), "udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = pc.Close() })
go func() {
buf := make([]byte, maxPacket)
for {
n, addr, err := pc.ReadFrom(buf)
if err != nil {
return
}
if r := reply(append([]byte{}, buf[:n]...)); r != nil {
_, _ = pc.WriteTo(r, addr)
}
}
}()
return pc.LocalAddr().String()
}

func TestQueryInfo(t *testing.T) {
addr := serve(t, func(req []byte) []byte {
if !bytes.Equal(req, infoRequest) {
t.Errorf("request = %q, want %q", req, infoRequest)
}
return infoReply(3, 10, 1)
})
info, err := QueryInfo(t.Context(), addr, time.Second)
if err != nil {
t.Fatal(err)
}
if info != (Info{Players: 3, MaxPlayers: 10, Bots: 1}) {
t.Errorf("info = %+v", info)
}
if info.Humans() != 2 {
t.Errorf("Humans() = %d, want 2", info.Humans())
}
}

func TestQueryInfoChallenge(t *testing.T) {
challenge := []byte{0xDE, 0xAD, 0xBE, 0xEF}
addr := serve(t, func(req []byte) []byte {
if bytes.HasSuffix(req, challenge) {
return infoReply(0, 10, 0)
}
return append(append(append([]byte{}, singlePacket...), headerChallenge), challenge...)
})
info, err := QueryInfo(t.Context(), addr, time.Second)
if err != nil {
t.Fatal(err)
}
if info.Players != 0 || info.MaxPlayers != 10 {
t.Errorf("info = %+v", info)
}
}

func TestQueryInfoEndlessChallenge(t *testing.T) {
addr := serve(t, func([]byte) []byte {
return append(append([]byte{}, singlePacket...), headerChallenge, 1, 2, 3, 4)
})
if _, err := QueryInfo(t.Context(), addr, time.Second); err == nil || !strings.Contains(err.Error(), "challenge") {
t.Errorf("err = %v, want a challenge error", err)
}
}

func TestQueryInfoTimeout(t *testing.T) {
addr := serve(t, func([]byte) []byte { return nil })
if _, err := QueryInfo(t.Context(), addr, 100*time.Millisecond); err == nil {
t.Error("want a timeout error")
}
}

func TestQueryInfoBadAddress(t *testing.T) {
if _, err := QueryInfo(t.Context(), "no-port", time.Second); err == nil || !strings.Contains(err.Error(), "dial") {
t.Errorf("err = %v, want a dial error", err)
}
}

func TestQueryInfoMalformedReply(t *testing.T) {
addr := serve(t, func([]byte) []byte { return []byte{0xFF, 0xFF, 0xFF, 0xFF, 0x6D} })
if _, err := QueryInfo(t.Context(), addr, time.Second); err == nil || !strings.Contains(err.Error(), "header") {
t.Errorf("err = %v, want an unexpected-header error", err)
}
}

func TestParseReplyErrors(t *testing.T) {
cases := map[string][]byte{
"empty": nil,
"split packet": {0xFE, 0xFF, 0xFF, 0xFF, headerInfo},
"unknown header": {0xFF, 0xFF, 0xFF, 0xFF, 0x6D},
"short challenge": {0xFF, 0xFF, 0xFF, 0xFF, headerChallenge, 1},
"no protocol": {0xFF, 0xFF, 0xFF, 0xFF, headerInfo},
"truncated string": append([]byte{0xFF, 0xFF, 0xFF, 0xFF, headerInfo, 17}, "name"...),
"no counts": append([]byte{0xFF, 0xFF, 0xFF, 0xFF, headerInfo, 17}, "a\x00b\x00c\x00d\x00\x00"...),
}
for name, b := range cases {
t.Run(name, func(t *testing.T) {
if _, _, err := parseReply(b); err == nil {
t.Error("want an error")
}
})
}
}

func TestHumansNeverNegative(t *testing.T) {
if got := (Info{Players: 1, Bots: 2}).Humans(); got != 0 {
t.Errorf("Humans() = %d, want 0", got)
}
}
12 changes: 12 additions & 0 deletions agent/internal/caps/caps.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,18 @@ type PlayerActions struct {
BanList *BanList `json:"banList,omitempty"`
Whitelist *Whitelist `json:"whitelist,omitempty"`
List *PlayerList `json:"list,omitempty"`
// Query reads the online player count over a server query protocol
// instead of the console. The heartbeat prefers it when set.
Query *PlayerQuery `json:"query,omitempty"`
}

// PlayerQuery mirrors spec.capabilities.players.query: a server query
// protocol, answered inside the pod, that reports the player count.
type PlayerQuery struct {
// Protocol is the query protocol; "a2s" (Valve's A2S_INFO) is the only one.
Protocol string `json:"protocol"`
// Port is the UDP port that answers the query.
Port int `json:"port"`
}

// BanList reads and parses the game's ban list.
Expand Down
39 changes: 36 additions & 3 deletions agent/internal/heartbeat/heartbeat.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ import (
"encoding/json"
"fmt"
"log/slog"
"net"
"os"
"regexp"
"strconv"
"time"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand All @@ -29,6 +31,7 @@ import (
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"

"github.com/GameplanePanel/gameplane/agent/internal/a2s"
"github.com/GameplanePanel/gameplane/agent/internal/caps"
"github.com/GameplanePanel/gameplane/agent/internal/metrics"
"github.com/GameplanePanel/gameplane/agent/internal/players"
Expand Down Expand Up @@ -59,7 +62,12 @@ type Config struct {
Usage UsageReader
PlayerList *caps.PlayerList
PlayerListRE *regexp.Regexp
Metrics *metrics.Metrics
// PlayerQuery, when set, replaces the console player list as the
// source of player counts. QueryHost is where it is sent (loopback in
// the pod); empty means 127.0.0.1.
PlayerQuery *caps.PlayerQuery
QueryHost string
Metrics *metrics.Metrics
}

var gvr = schema.GroupVersionResource{
Expand Down Expand Up @@ -156,7 +164,7 @@ func sendOnce(ctx context.Context, dyn dynamic.Interface, cfg Config) error {
// with null clears any prior value. playersMax stays null when the game
// reports an online count but no maximum, so the dashboard shows "—"
// rather than a bogus cap of 0.
if online, maxN, err := queryPlayerCounts(cfg); err == nil {
if online, maxN, err := queryPlayerCounts(ctx, cfg); err == nil {
agent["playersOnline"] = online
// Status patch: playersMax is only emitted when maxN > 0 (a real
// finite limit). Unknown (maxN=0) and unlimited (maxN=-1) both patch
Expand Down Expand Up @@ -239,7 +247,10 @@ func nullable(v int64, known bool) any {
// When EntryRegex is configured, the online count is the number of regex
// matches. err is non-nil only when RCON fails or no online count can be
// parsed at all.
func queryPlayerCounts(cfg Config) (online, maxPlayers int, err error) {
func queryPlayerCounts(ctx context.Context, cfg Config) (online, maxPlayers int, err error) {
if cfg.PlayerQuery != nil {
return queryPlayerCountsA2S(ctx, cfg)
}
cmd := "list"
if cfg.PlayerList != nil && cfg.PlayerList.Command != "" {
cmd = cfg.PlayerList.Command
Expand Down Expand Up @@ -274,6 +285,28 @@ func queryPlayerCounts(cfg Config) (online, maxPlayers int, err error) {
return 0, maxPlayers, fmt.Errorf("no player count in %q", raw)
}

// a2sTimeout bounds one player-count query, well inside the heartbeat
// interval.
const a2sTimeout = 2 * time.Second

// queryPlayerCountsA2S reads the player count over the declared query
// protocol. Bots don't count as players, so a server with only bots on it
// reports 0 and can sleep. A server limit of 0 is reported as unknown.
func queryPlayerCountsA2S(ctx context.Context, cfg Config) (online, maxPlayers int, err error) {
if cfg.PlayerQuery.Protocol != "a2s" {
return 0, 0, fmt.Errorf("unsupported player query protocol %q", cfg.PlayerQuery.Protocol)
}
host := cfg.QueryHost
if host == "" {
host = "127.0.0.1"
}
info, err := a2s.QueryInfo(ctx, net.JoinHostPort(host, strconv.Itoa(cfg.PlayerQuery.Port)), a2sTimeout)
if err != nil {
return 0, 0, fmt.Errorf("player query: %w", err)
}
return info.Humans(), info.MaxPlayers, nil
}

// readNamespace reads the SA-projected namespace file written into
// every pod.
func readNamespace() string {
Expand Down
Loading
Loading