Skip to main content

a2s_protocol/
lib.rs

1//! A parser and packet assembler for the Steam A2S server query protocol.
2//!
3//! This crate builds A2S request packets, reassembles fragmented UDP responses,
4//! decompresses compressed responses, and parses the resulting payloads. It does
5//! not open sockets or send requests; networking stays with the calling application.
6//!
7//! # Typical flow
8//!
9//! Send a request with [`info_request`], [`players_request`], or [`rules_request`].
10//! Pass each received datagram to [`PacketProcessor::process`]. When it returns a
11//! complete packet, parse it with [`parse_payload`]. If the response is a
12//! [`Response::Challenge`], resend the matching request with the returned challenge.
13//!
14//! ```no_run
15//! use std::net::{SocketAddr, UdpSocket};
16//! use a2s_protocol::{PacketProcessor, Response, info_request, parse_payload};
17//!
18//! # fn query(server: SocketAddr) -> Result<(), Box<dyn std::error::Error>> {
19//! let socket = UdpSocket::bind("0.0.0.0:0")?;
20//! socket.send_to(&info_request(None), server)?;
21//! let mut processor = PacketProcessor::new();
22//! let mut datagram = [0; a2s_protocol::MAX_PACKET_SIZE];
23//!
24//! loop {
25//!     let (len, source) = socket.recv_from(&mut datagram)?;
26//!     let Some(packet) = processor.process(source, &datagram[..len])? else {
27//!         continue;
28//!     };
29//!     match parse_payload(&packet)? {
30//!         Response::Challenge(challenge) => {
31//!             socket.send_to(&info_request(Some(challenge)), source)?;
32//!         }
33//!         response => {
34//!             println!("{response:#?}");
35//!             break;
36//!         }
37//!     }
38//! }
39//! # Ok(())
40//! # }
41//! ```
42
43use crate::transport::CONNECTIONLESS_HEADER;
44
45use crate::obsolete::{CHALLENGE_RESPONSE_HEADER, PING_RESPONSE_HEADER};
46use crate::cursor::{Cursor};
47
48pub use transport::packet_processor::PacketProcessor;
49/// Recommended maximum size of one UDP datagram received from a server.
50pub use transport::MAX_PACKET_SIZE;
51/// Errors produced while validating or reassembling server packets.
52pub use transport::Error as TransportError;
53
54// This module was generated with AI assistance.
55mod cursor;
56
57mod transport;
58mod the_ship;
59
60pub mod info;
61pub mod player;
62pub mod rules;
63
64pub mod obsolete;
65
66const EMPTY_CHALLENGE: i32 = -1;
67
68#[derive(Debug)]
69/// A decoded response returned by [`parse_payload`].
70///
71/// String fields in response variants borrow from the packet passed to
72/// [`parse_payload`]. Keep that packet alive while using the response, or call
73/// the relevant `to_owned` method to detach the data.
74pub enum Response<'a> {
75    /// A challenge that must be included in the corresponding follow-up request.
76    Challenge(i32),
77    /// A Source engine server information response.
78    Info(info::Info<'a>),
79    /// A legacy GoldSrc server information response.
80    ObsoleteInfo(obsolete::GoldSrcInfo<'a>),
81    /// A player list response.
82    Players(player::Players<'a>),
83    /// A server rules response.
84    Rules(rules::Rules<'a>),
85    /// A successful response to a legacy ping request.
86    Ping,
87}
88
89#[derive(Clone, Copy, PartialEq)]
90pub(crate) enum RequestType {
91    Info,
92    Players,
93    Rules,
94    Ping,
95    Challenge,
96}
97
98#[derive(thiserror::Error, Debug)]
99/// Errors that can occur while decoding a complete connectionless response.
100pub enum PayloadError {
101    /// The packet ended before a required field was available, or contained invalid UTF-8.
102    #[error(transparent)]
103    Read(#[from] cursor::Error),
104    /// The response header is not recognized.
105    #[error("invalid header: {0}")]
106    InvalidHeader(u8),
107    /// The Source server information payload is malformed.
108    #[error(transparent)]
109    Info(#[from] info::Error),
110    /// The player response payload is malformed.
111    #[error(transparent)]
112    Players(#[from] player::Error),
113    /// The rules response payload is malformed.
114    #[error(transparent)]
115    Rules(#[from] rules::Error)
116}
117
118/// Parses a complete connectionless response packet into its response type.
119///
120/// For fragmented or compressed responses, first pass datagrams through
121/// [`PacketProcessor::process`]. The returned response may borrow string data
122/// directly from `payload`.
123///
124/// # Errors
125///
126/// Returns [`PayloadError`] if the packet header is unknown, a required field is
127/// missing, a string is not valid UTF-8, or a response-specific value is invalid.
128pub fn parse_payload(payload: &[u8]) -> Result<Response<'_>, PayloadError> {
129    let mut cur = Cursor::new(payload);
130
131    // Skip the CONNECTIONLESS_HEADER invariant.
132    // (The MULTI_PACKET payload still contains it)
133    cur.read_long()?;
134
135    let header = cur.read_byte()?;
136    let payload = cur.as_slice();
137
138    match header {
139        CHALLENGE_RESPONSE_HEADER => Ok(Response::Challenge(cur.read_long()?)),
140        info::RESPONSE_HEADER => Ok(Response::Info(info::parse(payload)?)),
141        player::RESPONSE_HEADER => Ok(Response::Players(player::Players::parse(payload)?)),
142        rules::RESPONSE_HEADER => Ok(Response::Rules(rules::Rules::parse(payload)?)),
143        obsolete::INFO_RESPONSE_HEADER => Ok(Response::ObsoleteInfo(obsolete::parse_info(payload)?)),
144        PING_RESPONSE_HEADER => Ok(Response::Ping),
145        other => Err(PayloadError::InvalidHeader(other)),
146    }
147}
148
149fn request(req: RequestType, challenge: Option<i32>) -> Vec<u8> {
150    let challenge = challenge.unwrap_or(EMPTY_CHALLENGE);
151
152    let header = match req {
153        RequestType::Info => info::REQUEST_HEADER,
154        RequestType::Players => player::REQUEST_HEADER,
155        RequestType::Rules => rules::REQUEST_HEADER,
156        RequestType::Ping => obsolete::PING_REQUEST_HEADER,
157        RequestType::Challenge => obsolete::CHALLENGE_REQUEST_HEADER,
158    };
159
160    let mut request = Vec::new();
161
162    // -1 is byte-order agnostic, though
163    request.extend_from_slice(&CONNECTIONLESS_HEADER.to_le_bytes());
164    request.extend_from_slice(header);
165
166    // `players` and `rules` always contain a challenge, but some GoldSrc
167    // servers reject an empty challenge for `info`.
168    if req == RequestType::Players || req == RequestType::Rules || (req == RequestType::Info && challenge != EMPTY_CHALLENGE) {
169        request.extend_from_slice(&challenge.to_le_bytes());
170    }
171
172    request
173}
174
175/// Builds an A2S_INFO request packet.
176///
177/// Pass `None` for the initial request. If the server responds with a challenge,
178/// pass it as `Some(challenge)` when sending the follow-up request.
179pub fn info_request(challenge: Option<i32>) -> Vec<u8> {
180    request(RequestType::Info, challenge)
181}
182
183/// Builds an A2S_PLAYER request packet.
184///
185/// The initial request uses the protocol's empty challenge value. If the server
186/// responds with a challenge, pass it as `Some(challenge)` for the follow-up.
187pub fn players_request(challenge: Option<i32>) -> Vec<u8> {
188    request(RequestType::Players, challenge)
189}
190
191/// Builds an A2S_RULES request packet.
192///
193/// The initial request uses the protocol's empty challenge value. If the server
194/// responds with a challenge, pass it as `Some(challenge)` for the follow-up.
195pub fn rules_request(challenge: Option<i32>) -> Vec<u8> {
196    request(RequestType::Rules, challenge)
197}