msqp

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

msqp

msqp is a Go implementation of Valve's legacy Master Server Query Protocol (MSQP), UDP protocol used by older Steam game browsers to retrieve server addresses. The module provides a client, packet codec, filter builder, and a small server implementation.

[!WARNING] MSQP is a historical protocol, not a current Steam server-discovery API.

For current Steam server discovery, see the Steam Web API server-list client or the Steam Connection Manager (CM) client.

When to use it

Use this module when maintaining an old game or compatible client that still speaks MSQP, or when implementing a private/community master server for such a client. A game must support configuring or redirecting its master-server endpoint; this package does not change a game's configuration or replace Steam's infrastructure.

For current Steamworks server browsing, see the official ISteamMatchmakingServers documentation. That API and MSQP are different interfaces.

Installation

Add the dependency with:

go get github.com/woozymasta/msqp@latest

Use

Query a reachable MSQP master. Replace the example endpoint with one you operate or have verified; the placeholder is not a public service.

func run() error {
  ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  defer cancel()

  client, err := msqp.NewClient("127.0.0.1:27011")
  if err != nil {
    return err
  }
  defer client.Close()

  request := msqp.Request{
    Region: msqp.Region(0xff), // all regions
    Filter: `\appid\730\secure\1`,
  }
  for result := range client.Stream(ctx, request) {
    if result.Err != nil {
      return result.Err
    }
    for _, address := range result.Page.Servers {
      fmt.Println(address)
    }
  }
  return nil
}

The msqp/server package can serve an address list or a custom handler:

func serve() error {
  addresses := []netip.AddrPort{
    netip.MustParseAddrPort("192.0.2.10:27015"),
  }
  handler := server.NewStaticHandler(addresses)
  master, err := server.NewServer(handler)
  if err != nil {
    return err
  }

  conn, err := net.ListenPacket("udp4", ":27011")
  if err != nil {
    return err
  }
  defer conn.Close()
  return master.Serve(conn)
}

Protocol details

  • Client.Query fetches one page. Client.Stream follows continuation cursors until completion or error; receive from the channel until it closes, or cancel the context if stopping early.
  • MSQP carries IPv4 server addresses over UDP. It does not provide encryption, authentication, or reliable delivery.
  • Region is the raw one-byte legacy region code; 0xff requests all regions. Filter can be built with msqp.Filter or supplied as a raw expression.
  • The server applies request/response size limits and caps concurrent handlers.

[!CAUTION] The UDP server has no built-in authentication or rate limiting.
Restrict who can reach it with network controls before exposing it to untrusted clients.

Documentation and tests

Run local tests with go test ./.... The opt-in msqp_live tests send UDP queries to uncommented addresses in testdata/masters.txt:

go test -tags msqp_live ./... -count=1

[!NOTE] testdata/masters.txt keeps historical Valve endpoints for reference and a separately marked community endpoint for opt-in testing. The historical Valve entries are commented out and are not expected to be live.
Community endpoint availability can change.

Documentation

Overview

Package msqp implements the Steam Master Server Query Protocol.

Package msqp implements Steam master-server query protocol support.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrClientUninitialized indicates that a client is nil or was not initialized.
	ErrClientUninitialized = errors.New("master client is nil or uninitialized")
	// ErrNilQueryContext indicates that Query received a nil context.
	ErrNilQueryContext = errors.New("master query context is nil")
	// ErrNilStreamContext indicates that Stream received a nil context.
	ErrNilStreamContext = errors.New("master stream context is nil")
	// ErrResolveMasterAddress marks failures resolving a master endpoint.
	ErrResolveMasterAddress = errors.New("resolve master address")
	// ErrDialMasterAddress marks failures opening a connection to a master.
	ErrDialMasterAddress = errors.New("dial master address")
	// ErrConfigureMasterClient marks failures applying client options.
	ErrConfigureMasterClient = errors.New("configure master client")
	// ErrEncodeMasterRequest marks failures encoding a client request.
	ErrEncodeMasterRequest = errors.New("encode master request")
	// ErrWriteMasterRequest marks failures writing a client request.
	ErrWriteMasterRequest = errors.New("write master request")
	// ErrReadMasterResponse marks failures reading a client response.
	ErrReadMasterResponse = errors.New("read master response")
	// ErrResponseExceedsDatagramLimit indicates a response exceeded the client limit.
	ErrResponseExceedsDatagramLimit = errors.New("master response exceeds configured datagram size")
	// ErrDecodeMasterResponse marks failures decoding a client response.
	ErrDecodeMasterResponse = errors.New("decode master response")
	// ErrCloseMasterClient marks failures closing the client socket.
	ErrCloseMasterClient = errors.New("close master client")
	// ErrMissingContinuationCursor indicates a continued response has no cursor.
	ErrMissingContinuationCursor = errors.New("master response has no continuation cursor")
	// ErrCursorDidNotAdvance indicates that a continued response repeats its cursor.
	ErrCursorDidNotAdvance = errors.New("master response cursor did not advance")

	// ErrMasterFilterContainsNUL indicates a wire filter contains a NUL byte.
	ErrMasterFilterContainsNUL = errors.New("master filter must not contain NUL")
	// ErrFilterKeyValueContainsNUL indicates a filter key or value contains NUL.
	ErrFilterKeyValueContainsNUL = errors.New("filter key and value must not contain NUL")
	// ErrInvalidRequestHeader indicates a request packet has an invalid header.
	ErrInvalidRequestHeader = errors.New("invalid master request header")
	// ErrUnterminatedRequestCursor indicates a request cursor lacks a terminator.
	ErrUnterminatedRequestCursor = errors.New("master cursor is not NUL-terminated")
	// ErrInvalidRequestCursor indicates a request cursor is not an IPv4 endpoint.
	ErrInvalidRequestCursor = errors.New("master request cursor is not a valid IPv4 address")
	// ErrUnterminatedRequestFilter indicates a request filter lacks a terminator.
	ErrUnterminatedRequestFilter = errors.New("master filter is not NUL-terminated")
	// ErrTrailingRequestData indicates bytes follow the request filter terminator.
	ErrTrailingRequestData = errors.New("trailing bytes after master filter")
	// ErrTerminalMarkerAsServer indicates a response lists the protocol terminator as a server.
	ErrTerminalMarkerAsServer = errors.New("master response servers must not contain the terminal marker")
	// ErrInvalidResponseHeader indicates a response packet has an invalid header.
	ErrInvalidResponseHeader = errors.New("invalid master response header")
	// ErrTruncatedAddressEntry indicates a response ends in a partial address entry.
	ErrTruncatedAddressEntry = errors.New("master response has truncated address entry")
	// ErrDecodeServerAddress marks failures decoding one response address.
	ErrDecodeServerAddress = errors.New("decode master server address")
	// ErrDataAfterTerminalMarker indicates bytes follow the terminal response entry.
	ErrDataAfterTerminalMarker = errors.New("master response contains data after terminal entry")
	// ErrInvalidCursorAddress indicates a cursor has no valid address.
	ErrInvalidCursorAddress = errors.New("master cursor address is invalid")
	// ErrCursorMustBeIPv4 indicates a cursor uses a non-IPv4 address.
	ErrCursorMustBeIPv4 = errors.New("legacy master cursor must be IPv4")
	// ErrCursorPortMustBeNonzero indicates a non-initial cursor has port zero.
	ErrCursorPortMustBeNonzero = errors.New("master cursor port must be non-zero for a non-zero address")
	// ErrServerAddressMustBeIPv4 indicates a server uses a non-IPv4 address.
	ErrServerAddressMustBeIPv4 = errors.New("legacy master server address must be IPv4")
	// ErrServerPortMustBeNonzero indicates a server address uses port zero.
	ErrServerPortMustBeNonzero = errors.New("master server port must be non-zero")

	// ErrConflictingFilterGroups indicates a filter combines NOR and NAND groups.
	ErrConflictingFilterGroups = errors.New("cannot use both nor and nand conditions in the same filter")
	// ErrFilterContainsDelimiter indicates a filter key or value contains a delimiter.
	ErrFilterContainsDelimiter = errors.New("filter key and value must not contain the backslash delimiter")
	// ErrEmptyFilterKey indicates a filter clause has an empty key.
	ErrEmptyFilterKey = errors.New("filter key must not be empty")

	// ErrMaxDatagramSizeMustBePositive indicates a non-positive client buffer limit.
	ErrMaxDatagramSizeMustBePositive = errors.New("max datagram size must be positive")
	// ErrMaxDatagramSizeExceedsUDP indicates a client limit exceeds UDP capacity.
	ErrMaxDatagramSizeExceedsUDP = errors.New("max datagram size exceeds the UDP payload limit")
	// ErrIOTimeoutMustBePositive indicates a non-positive client I/O timeout.
	ErrIOTimeoutMustBePositive = errors.New("I/O timeout must be positive")

	// ErrNilMasterHandler indicates that NewServer received a nil handler.
	ErrNilMasterHandler = errors.New("master handler is nil")
	// ErrNilPacketConnection indicates that Serve received a nil connection.
	ErrNilPacketConnection = errors.New("master packet connection is nil")
	// ErrMasterServerAlreadyServing indicates Serve was called more than once.
	ErrMasterServerAlreadyServing = errors.New("master server is already serving")
	// ErrNilShutdownContext indicates that Shutdown received a nil context.
	ErrNilShutdownContext = errors.New("master shutdown context is nil")
	// ErrConfigureMasterServer marks failures applying server options.
	ErrConfigureMasterServer = errors.New("configure master server")
	// ErrReadMasterRequest marks failures receiving a request packet.
	ErrReadMasterRequest = errors.New("read master request")
	// ErrMasterHandlerPanicked indicates the request handler panicked.
	ErrMasterHandlerPanicked = errors.New("master request handler panic")
	// ErrHandleMasterRequest marks errors returned by a request handler.
	ErrHandleMasterRequest = errors.New("handle master request")
	// ErrBoundMasterResponse marks failures limiting a response to packet size.
	ErrBoundMasterResponse = errors.New("bound master response")
	// ErrEncodeMasterResponse marks failures encoding a server response.
	ErrEncodeMasterResponse = errors.New("encode master response")
	// ErrEncodedResponseExceedsLimit indicates the encoded response exceeds its limit.
	ErrEncodedResponseExceedsLimit = errors.New("encoded master response exceeds configured limit")
	// ErrWriteMasterResponse marks failures sending a response packet.
	ErrWriteMasterResponse = errors.New("write master response")
	// ErrResponseCannotFitAddress indicates the configured limit cannot fit one address.
	ErrResponseCannotFitAddress = errors.New("response limit cannot fit an address")
	// ErrNonTerminalResponseEmpty indicates a continued response has no servers.
	ErrNonTerminalResponseEmpty = errors.New("non-terminal master response has no servers")
	// ErrMaxRequestSizeOutOfRange indicates a server request limit is invalid.
	ErrMaxRequestSizeOutOfRange = errors.New("max request size is outside the UDP payload limit")
	// ErrMaxResponseSizeOutOfRange indicates a server response limit is invalid.
	ErrMaxResponseSizeOutOfRange = errors.New("max response size is outside the supported UDP payload range")
	// ErrMaxConcurrentWorkersMustBePositive indicates a non-positive worker limit.
	ErrMaxConcurrentWorkersMustBePositive = errors.New("max concurrent workers must be positive")
)

Functions

func EncodeRequest

func EncodeRequest(req Request) ([]byte, error)

EncodeRequest encodes a legacy master-server query packet.

func EncodeResponse

func EncodeResponse(response Response) ([]byte, error)

EncodeResponse encodes a master-server page. Done adds the terminal 0.0.0.0:0 entry required by the protocol.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client queries a legacy Steam master server over UDP.

func NewClient

func NewClient(address string, opts ...Option) (*Client, error)

NewClient creates a client connected to address, which must be a UDP endpoint such as "master.example.net:27011".

func (*Client) Close

func (c *Client) Close() error

Close closes the client's UDP socket.

func (*Client) Query

func (c *Client) Query(ctx context.Context, req Request) (Response, error)

Query retrieves one page from the configured master server.

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, req Request) <-chan Result

Stream follows sequential master-server cursors until a terminal page or an error is received. The caller must receive until the channel closes or cancel ctx to stop the producer when abandoning the stream.

type Cursor

type Cursor struct {
	// Addr is the cursor endpoint;
	// the unspecified IPv4 address with port zero starts a query.
	Addr netip.AddrPort `json:"addr"`
}

Cursor identifies the last IPv4 endpoint returned by a master server.

func InitialCursor

func InitialCursor() Cursor

InitialCursor returns the cursor used for the first query page.

type Filter

type Filter struct {
	// contains filtered or unexported fields
}

Filter builds the canonical Steam master-server filter string.

func (*Filter) Add

func (f *Filter) Add(key FilterKey, value string)

Add appends a regular key/value clause.

func (*Filter) AddNand

func (f *Filter) AddNand(key FilterKey, value string)

AddNand appends a clause to the NAND group.

func (*Filter) AddNor

func (f *Filter) AddNor(key FilterKey, value string)

AddNor appends a clause to the NOR group.

func (Filter) String

func (f Filter) String() (string, error)

String returns the canonical filter string without modifying the builder.

type FilterKey

type FilterKey string

FilterKey is a Steam master-server filter key. Custom keys are supported.

const (
	// KeyDedicated filters for dedicated servers.
	KeyDedicated FilterKey = "dedicated"
	// KeySecure filters for secure servers.
	KeySecure FilterKey = "secure"
	// KeyGameDir filters by game directory.
	KeyGameDir FilterKey = "gamedir"
	// KeyMap filters by map name.
	KeyMap FilterKey = "map"
	// KeyLinux filters by Linux server support.
	KeyLinux FilterKey = "linux"
	// KeyPassword filters by password protection.
	KeyPassword FilterKey = "password"
	// KeyEmpty filters empty servers.
	KeyEmpty FilterKey = "empty"
	// KeyFull filters full servers.
	KeyFull FilterKey = "full"
	// KeyProxy filters proxy servers.
	KeyProxy FilterKey = "proxy"
	// KeyAppID filters by application ID.
	KeyAppID FilterKey = "appid"
	// KeyNotAppID excludes an application ID.
	KeyNotAppID FilterKey = "napp"
	// KeyNoPlayers filters servers without players.
	KeyNoPlayers FilterKey = "noplayers"
	// KeyWhite filters whitelist state.
	KeyWhite FilterKey = "white"
	// KeyGameType filters by game type.
	KeyGameType FilterKey = "gametype"
	// KeyGameData filters by game data.
	KeyGameData FilterKey = "gamedata"
	// KeyGameDataOr filters by any matching game data tag.
	KeyGameDataOr FilterKey = "gamedataor"
	// KeyName filters by server name.
	KeyName FilterKey = "name_match"
	// KeyVersion filters by version.
	KeyVersion FilterKey = "version_match"
	// KeySingleAddr collapses servers by address hash.
	KeySingleAddr FilterKey = "collapse_addr_hash"
	// KeyGameAddr filters by game address.
	KeyGameAddr FilterKey = "gameaddr"
)

type Option

type Option func(*clientConfig) error

Option configures a legacy master client.

func WithIOTimeout

func WithIOTimeout(timeout time.Duration) Option

WithIOTimeout bounds individual UDP I/O attempts when the context has no earlier deadline.

func WithMaxDatagramSize

func WithMaxDatagramSize(size int) Option

WithMaxDatagramSize limits the receive buffer allocated by the client.

type Region

type Region uint8

Region is the legacy master-server geographic region code.

type Request

type Request struct {
	// Cursor resumes after this endpoint; an invalid address starts from the first page.
	Cursor Cursor `json:"cursor"`
	// Filter is the Steam master-server filter expression, without a trailing NUL.
	Filter string `json:"filter"`
	// Region selects a legacy Steam master-server region code.
	Region Region `json:"region"`
}

Request is a legacy master-server query.

Example
package main

import (
	"encoding/json"
	"fmt"
	"net/netip"

	"github.com/woozymasta/msqp"
)

func main() {
	addr := netip.MustParseAddrPort("192.0.2.10:27015")
	request := msqp.Request{
		Cursor: msqp.Cursor{Addr: addr},
		Filter: `\appid\221100\secure\1`,
		Region: 3,
	}
	requestJSON, err := json.Marshal(request)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(requestJSON))

	var decodedRequest msqp.Request
	if err := json.Unmarshal(requestJSON, &decodedRequest); err != nil {
		panic(err)
	}
	fmt.Println(decodedRequest.Cursor.Addr, decodedRequest.Filter, decodedRequest.Region)

	response := msqp.Response{
		NextCursor: msqp.Cursor{Addr: addr},
		Servers:    []netip.AddrPort{addr},
		Done:       true,
	}
	responseJSON, err := json.Marshal(response)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(responseJSON))

	var decodedResponse msqp.Response
	if err := json.Unmarshal(responseJSON, &decodedResponse); err != nil {
		panic(err)
	}
	fmt.Println(decodedResponse.NextCursor.Addr, decodedResponse.Servers, decodedResponse.Done)

}
Output:
{"cursor":{"addr":"192.0.2.10:27015"},"filter":"\\appid\\221100\\secure\\1","region":3}
192.0.2.10:27015 \appid\221100\secure\1 3
{"next_cursor":{"addr":"192.0.2.10:27015"},"servers":["192.0.2.10:27015"],"done":true}
192.0.2.10:27015 [192.0.2.10:27015] true

func DecodeRequest

func DecodeRequest(packet []byte) (Request, error)

DecodeRequest decodes a legacy master-server query packet.

type Response

type Response struct {
	// NextCursor identifies the last returned endpoint for the next page.
	NextCursor Cursor `json:"next_cursor"`
	// Servers contains the endpoints returned in this page.
	Servers []netip.AddrPort `json:"servers"`
	// Done reports whether the page carries the protocol's terminal marker.
	Done bool `json:"done"`
}

Response contains one decoded master-server page.

func DecodeResponse

func DecodeResponse(packet []byte) (Response, error)

DecodeResponse decodes a master-server page. A page without a terminal marker is considered continued and uses its last address as the cursor.

type Result

type Result struct {
	// Err is non-nil when the stream stopped because of an error.
	Err error
	// Page contains the successfully queried server page when Err is nil.
	Page Response
}

Result is one item emitted by Client.Stream. Exactly one of Err or Page is meaningful: Err reports a failed stream, while Page contains a successful page.

Directories

Path Synopsis
Package server implements the MSQP UDP server.
Package server implements the MSQP UDP server.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL