cm

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: 21 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

steamcm

steamcm is a Go client for Steam Connection Manager (CM) WebSocket sessions. It provides CM framing and jobs, Steam authentication, and gameserver query methods.

[!WARNING] CM session and gameserver methods are not a documented, stable Steamworks API. Steam may change or restrict them without notice.

Installation

Add the module to your project:

go get github.com/woozymasta/steamcm@latest

Usage

Authenticate with the auth package or another trusted Steam flow, then use the resulting refresh token to create an individual CM session.

[!NOTE] A Steam Web API key does not authenticate a CM session.

import (
  "context"
  "errors"

  cm "github.com/woozymasta/steamcm"
  "github.com/woozymasta/steamcm/auth"
  "github.com/woozymasta/steamcm/gameservers"
)

func queryServers(
  ctx context.Context,
  token auth.Token,
) ([]gameservers.Endpoint, error) {
  directory := &cm.Directory{}
  endpoints, err := directory.Get(ctx, cm.DirectoryQuery{
    MaxCount: 5,
  })
  if err != nil {
    return nil, err
  }
  if len(endpoints) == 0 {
    return nil, errors.New("Steam CM directory returned no endpoints")
  }

  client, err := cm.New()
  if err != nil {
    return nil, err
  }
  defer client.Close()

  if err := client.Connect(ctx, endpoints[0]); err != nil {
    return nil, err
  }
  session, err := client.LogonToken(ctx, cm.TokenLogonDetails{
    SteamID: token.SteamID, AccountName: token.AccountName,
    RefreshToken: token.RefreshToken,
  })
  if err != nil {
    return nil, err
  }

  servers, err := gameservers.New(session)
  if err != nil {
    return nil, err
  }
  return servers.MasterServerQuery(ctx, gameservers.QueryRequest{
    AppID: 221100, Filter: `\appid\221100`, Limit: 100,
  })
}

LogonAnonymous is available for CM sessions, but gameserver query methods require an authenticated session. The auth package exposes password- and QR-based login steps, Steam Guard code submission, and polling.

Gameserver discovery

gameservers.List requests rich records through the historical GameServers.GetServerList method. Some CM endpoints may reject or ignore that method. Query and MasterServerQuery return server endpoints; use them when addresses are sufficient.

CM does not expose a continuation cursor, and an individual response is limited to about 10,000 entries. Discover partitions an AppID-root query using observed map, version, and game-type metadata, then returns unique endpoints and a reusable plan. Collect runs that plan again on later polls. When callers need server metadata, DiscoverServers and CollectServers return one latest record per address; these methods retain more data in memory and do not require a diagnostics callback. The planner is bounded and may return partial results:

result, err := servers.DiscoverServers(ctx, gameservers.QueryRequest{
  AppID: 221100,
}, gameservers.DiscoveryOptions{MaxRequests: 24})
if err != nil {
  return err
}
if !result.Status.Complete {
  // Inspect Status and retain the plan; this run did not drain every branch.
}

_, err = servers.CollectServers(ctx, result.Plan, gameservers.CollectionOptions{})
if err != nil {
  return err
}

Discovery is unpaced by default. Request pacing and the one-time initial burst are caller-controlled. For repeated polling, the package's suggested starting values are a burst of 3 and 60 seconds between later request starts; observed workloads have varied, so these are not guaranteed Steam limits. A complete result describes sampled filter coverage, not a consistent global snapshot; CM responses can overlap or change between requests.

  • serverlist calls Steam's Web API IGameServersService/GetServerList endpoint and requires a Web API key.
  • msqp implements the legacy UDP Master Server Query Protocol.

These modules use different Steam interfaces and have separate data contracts.

Documentation and tests

Run local tests with:

go test ./...

Authenticated CM integration tests are opt-in. Run them with the cm_auth_live build tag and STEAMCM_AUTH_TOKEN_FILE pointing to an owner-provided refresh-token file.

Documentation

Overview

Package cm implements Steam Connection Manager transport and sessions.

Index

Constants

View Source
const (
	EResultOK           int32 = 1
	EResultFail         int32 = 2
	EResultAccessDenied int32 = 15
)

Common Steam EResult values returned by CM operations.

View Source
const (
	EMsgMulti                        uint32 = 1
	EMsgClientHeartBeat              uint32 = 703
	EMsgClientLoggedOff              uint32 = 757
	EMsgClientLogOnResponse          uint32 = 751
	EMsgClientLogon                  uint32 = 5514
	EMsgClientGMSServerQuery         uint32 = 6403
	EMsgGMSClientServerQueryResponse uint32 = 6404
	EMsgServiceMethod                uint32 = 146
	EMsgServiceMethodResponse        uint32 = 147
	EMsgServiceMethodCallFromClient  uint32 = 151
)

CM message identifiers used by the discovery session.

View Source
const (
	// EMsgClientHello identifies the initial CM client hello message.
	EMsgClientHello uint32 = 9805

	// EMsgServiceMethodCallFromClientNonAuthed identifies a pre-login UM call.
	EMsgServiceMethodCallFromClientNonAuthed uint32 = 9804
)
View Source
const NoJobID uint64 = ^uint64(0)

NoJobID is the reserved Steam value used when a message has no job ID.

Variables

This section is empty.

Functions

func EncodeFrame

func EncodeFrame(frame Frame, limits FrameLimits) ([]byte, error)

EncodeFrame serializes a CM frame using the little-endian CM envelope.

Types

type Client

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

Client manages one CM WebSocket connection.

func New

func New(opts ...ClientOption) (*Client, error)

New creates a disconnected CM client.

func (*Client) CallUnauthenticated

func (c *Client) CallUnauthenticated(ctx context.Context, method string, body []byte) (Message, error)

CallUnauthenticated calls a Steam Unified Messaging method before CM logon. Calls are serialized because this operation owns socket reads.

func (*Client) Close

func (c *Client) Close() error

Close closes the active CM connection.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, endpoint Endpoint) error

Connect opens a WebSocket to endpoint. The client supports one active connection at a time.

func (*Client) LogonAnonymous

func (c *Client) LogonAnonymous(ctx context.Context) (*Session, error)

LogonAnonymous performs the anonymous ClientLogon exchange and starts the session heartbeat when the server supplies a positive interval.

func (*Client) LogonToken

func (c *Client) LogonToken(ctx context.Context, details TokenLogonDetails) (*Session, error)

LogonToken starts an individual SteamClient session using a refresh token.

type ClientOption

type ClientOption func(*clientConfig) error

ClientOption configures a CM client.

func WithFrameLimits

func WithFrameLimits(limits FrameLimits) ClientOption

WithFrameLimits configures CM frame decoding and encoding limits.

func WithWebSocketOption

func WithWebSocketOption(option WebSocketOption) ClientOption

WithWebSocketOption passes an option to the CM WebSocket dialer.

type Directory

type Directory struct {
	HTTPClient *http.Client
	BaseURL    string
}

Directory queries the public Steam CM directory.

func (*Directory) Get

func (d *Directory) Get(ctx context.Context, query DirectoryQuery) ([]Endpoint, error)

Get returns WebSocket-capable CM endpoints matching query.

type DirectoryError

type DirectoryError struct {
	Message string
}

DirectoryError reports an error returned by the directory API.

func (*DirectoryError) Error

func (e *DirectoryError) Error() string

type DirectoryQuery

type DirectoryQuery struct {
	CMType   string
	Realm    string
	CellID   uint32
	MaxCount uint32
	QoSLevel uint32
}

DirectoryQuery contains filters accepted by GetCMListForConnect.

type Endpoint

type Endpoint struct {
	Address      string  `json:"endpoint"                  yaml:"endpoint"`
	Legacy       string  `json:"legacy_endpoint,omitempty" yaml:"legacy_endpoint,omitempty"`
	Type         string  `json:"type,omitempty"            yaml:"type,omitempty"`
	DataCenter   string  `json:"dc,omitempty"              yaml:"dc,omitempty"`
	Realm        string  `json:"realm,omitempty"           yaml:"realm,omitempty"`
	Load         int32   `json:"load,omitempty"            yaml:"load,omitempty"`
	WeightedLoad float64 `json:"wtd_load,omitempty"        yaml:"wtd_load,omitempty"`
}

Endpoint is a CM endpoint returned by the public directory.

type Frame

type Frame struct {
	Header []byte
	Body   []byte
	EMsg   uint32
	Proto  bool
}

Frame is one CM message after WebSocket framing has been removed.

func DecodeFrame

func DecodeFrame(encoded []byte, limits FrameLimits) (Frame, error)

DecodeFrame parses one complete CM envelope and copies its payloads.

func DecodeMulti

func DecodeMulti(frame Frame, limits MultiLimits) ([]Frame, error)

DecodeMulti expands one EMsg.Multi frame into its child frames.

type FrameLimits

type FrameLimits struct {
	MaxFrameSize  int
	MaxHeaderSize int
}

FrameLimits bounds allocations performed by DecodeFrame.

type HTTPError

type HTTPError struct {
	Status     string
	StatusCode int
}

HTTPError reports a non-success response from the CM directory endpoint.

func (*HTTPError) Error

func (e *HTTPError) Error() string
type Header struct {
	TargetJobName   string
	ErrorMessage    string
	SteamID         uint64
	JobIDSource     uint64
	JobIDTarget     uint64
	ClientSessionID int32
	EResult         int32
	HasEResult      bool
}

Header is the public subset of CMsgProtoBufHeader used by CM jobs.

type JobError

type JobError struct {
	Message string
	EResult int32
}

JobError reports a non-success EResult from a correlated CM job.

func (*JobError) Error

func (e *JobError) Error() string

type JobRequest

type JobRequest struct {
	TargetJobName  string
	Body           []byte
	EMsg           uint32
	ExpectedEMsg   uint32
	RequireEResult bool
}

JobRequest describes one protobuf CM job. Body must contain the request protobuf payload; response decoding belongs to the transport-specific package.

type LogoffError

type LogoffError struct {
	EResult    int32
	HasEResult bool
}

LogoffError reports a server-initiated CM session termination.

func (*LogoffError) Error

func (e *LogoffError) Error() string

type LogonError

type LogonError struct {
	Message string
	EResult int32
}

LogonError reports a non-success EResult from ClientLogonResponse.

func (*LogonError) Error

func (e *LogonError) Error() string

type Message

type Message struct {
	Body   []byte
	Header Header
	EMsg   uint32
}

Message is a decoded inbound CM message with an opaque protobuf body.

type MissingEResultError

type MissingEResultError struct{}

MissingEResultError reports a CM job response without an EResult field when the request requires one.

func (MissingEResultError) Error

func (MissingEResultError) Error() string

type MultiLimits

type MultiLimits struct {
	MaxUncompressedBytes int
	MaxMessages          int
	MaxDepth             int
	FrameLimits          FrameLimits
}

MultiLimits bounds decompression and recursive multipart expansion.

type Session

type Session struct {

	// WebSocketConn is the transport used by this authenticated session.
	WebSocketConn *WebSocketConn

	// SessionState exposes the Steam identity and heartbeat settings negotiated at logon.
	SessionState
	// contains filtered or unexported fields
}

Session is an authenticated CM session.

func (*Session) Call

func (s *Session) Call(ctx context.Context, request JobRequest) (Message, error)

Call submits a correlated CM job and returns its opaque protobuf response.

func (*Session) Close

func (s *Session) Close() error

Close stops heartbeat and closes the underlying CM connection.

func (*Session) ReadMessage

func (s *Session) ReadMessage(ctx context.Context) (Message, error)

ReadMessage reads one unmatched inbound CM message from the session event queue. Correlated job responses are consumed by Call.

type SessionState

type SessionState struct {
	SteamID           uint64
	HeartbeatInterval time.Duration
	SessionID         int32
	CellID            uint32
}

SessionState contains the identity and timing values assigned by CM.

type TokenLogonDetails

type TokenLogonDetails struct {
	AccountName  string
	RefreshToken string `json:"-" yaml:"-"`
	SteamID      uint64
	LoginID      uint32
}

TokenLogonDetails contains the identity and SteamClient refresh token for an individual CM logon. LoginID must be unique for concurrent sessions from the same public IP; zero asks the client to generate one.

func (TokenLogonDetails) GoString

func (TokenLogonDetails) GoString() string

GoString redacts the refresh token when details are formatted with %#v.

func (TokenLogonDetails) String

func (TokenLogonDetails) String() string

String redacts the refresh token when details are formatted.

type WebSocketConn

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

WebSocketConn carries framed CM messages over a WebSocket. One goroutine may read while one goroutine writes; writes are serialized internally.

func Dial

func Dial(ctx context.Context, address string, opts ...WebSocketOption) (*WebSocketConn, error)

Dial opens a CM WebSocket. address may be a directory endpoint such as "cmp-fra.steamserver.net:27019" or a complete ws(s) URL.

func (*WebSocketConn) Close

func (c *WebSocketConn) Close() error

Close closes the WebSocket connection.

func (*WebSocketConn) ReadFrame

func (c *WebSocketConn) ReadFrame(ctx context.Context, limits FrameLimits) (Frame, error)

ReadFrame reads and decodes one binary CM WebSocket message.

func (*WebSocketConn) WriteFrame

func (c *WebSocketConn) WriteFrame(ctx context.Context, frame Frame, limits FrameLimits) error

WriteFrame encodes and sends one binary CM WebSocket message.

type WebSocketOption

type WebSocketOption func(*webSocketConfig) error

WebSocketOption configures a CM WebSocket connection.

func WithHandshakeTimeout

func WithHandshakeTimeout(timeout time.Duration) WebSocketOption

WithHandshakeTimeout bounds the WebSocket HTTP handshake.

func WithHeader

func WithHeader(key, value string) WebSocketOption

WithHeader adds a header to the WebSocket handshake.

func WithIOTimeout

func WithIOTimeout(timeout time.Duration) WebSocketOption

WithIOTimeout bounds one WebSocket read or write when the context has no earlier deadline.

func WithMessageSize

func WithMessageSize(size int64) WebSocketOption

WithMessageSize limits one incoming WebSocket message.

Directories

Path Synopsis
Package auth implements SteamClient authentication over a pre-login CM connection.
Package auth implements SteamClient authentication over a pre-login CM connection.
Package gameservers implements Steam CM gameserver discovery methods.
Package gameservers implements Steam CM gameserver discovery methods.
internal

Jump to

Keyboard shortcuts

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