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/// Error while parsing an A2S_INFO response.
55pub use info::Error as InfoError;
56/// Error while parsing an A2S_PLAYER response.
57pub use player::Error as PlayersError;
58/// Error while parsing an A2S_RULES response.
59pub use rules::Error as RulesError;
60
61// This module was generated with AI assistance.
62mod cursor;
63
64mod transport;
65mod the_ship;
66
67mod info;
68mod player;
69mod rules;
70
71pub mod obsolete;
72
73const EMPTY_CHALLENGE: i32 = -1;
74
75#[derive(Debug)]
76/// A decoded response returned by [`parse_payload`].
77///
78/// String fields in response variants borrow from the packet passed to
79/// [`parse_payload`]. Keep that packet alive while using the response, or call
80/// the relevant `to_owned` method to detach the data.
81pub enum Response<'a> {
82 /// A challenge that must be included in the corresponding follow-up request.
83 Challenge(i32),
84 /// A Source engine server information response.
85 Info(info::Info<'a>),
86 /// A legacy GoldSrc server information response.
87 ObsoleteInfo(obsolete::GoldSrcInfo<'a>),
88 /// A player list response.
89 Players(player::Players<'a>),
90 /// A server rules response.
91 Rules(rules::Rules<'a>),
92 /// A successful response to a legacy ping request.
93 Ping,
94}
95
96#[derive(Clone, Copy, PartialEq)]
97pub(crate) enum RequestType {
98 Info,
99 Players,
100 Rules,
101 Ping,
102 Challenge,
103}
104
105#[derive(thiserror::Error, Debug)]
106/// Errors that can occur while decoding a complete connectionless response.
107pub enum PayloadError {
108 /// The packet ended before a required field was available, or contained invalid UTF-8.
109 #[error(transparent)]
110 Read(#[from] cursor::Error),
111 /// The response header is not recognized.
112 #[error("invalid header: {0}")]
113 InvalidHeader(u8),
114 /// The Source server information payload is malformed.
115 #[error(transparent)]
116 Info(#[from] info::Error),
117 /// The player response payload is malformed.
118 #[error(transparent)]
119 Players(#[from] player::Error),
120 /// The rules response payload is malformed.
121 #[error(transparent)]
122 Rules(#[from] rules::Error)
123}
124
125/// Parses a complete connectionless response packet into its response type.
126///
127/// For fragmented or compressed responses, first pass datagrams through
128/// [`PacketProcessor::process`]. The returned response may borrow string data
129/// directly from `payload`.
130///
131/// # Errors
132///
133/// Returns [`PayloadError`] if the packet header is unknown, a required field is
134/// missing, a string is not valid UTF-8, or a response-specific value is invalid.
135pub fn parse_payload(payload: &[u8]) -> Result<Response<'_>, PayloadError> {
136 let mut cur = Cursor::new(payload);
137
138 // Skip the CONNECTIONLESS_HEADER invariant.
139 // (The MULTI_PACKET payload still contains it)
140 cur.read_long()?;
141
142 let header = cur.read_byte()?;
143 let payload = cur.as_slice();
144
145 match header {
146 CHALLENGE_RESPONSE_HEADER => Ok(Response::Challenge(cur.read_long()?)),
147 info::RESPONSE_HEADER => Ok(Response::Info(info::parse(payload)?)),
148 player::RESPONSE_HEADER => Ok(Response::Players(player::Players::parse(payload)?)),
149 rules::RESPONSE_HEADER => Ok(Response::Rules(rules::Rules::parse(payload)?)),
150 obsolete::INFO_RESPONSE_HEADER => Ok(Response::ObsoleteInfo(obsolete::parse_info(payload)?)),
151 PING_RESPONSE_HEADER => Ok(Response::Ping),
152 other => Err(PayloadError::InvalidHeader(other)),
153 }
154}
155
156fn request(req: RequestType, challenge: Option<i32>) -> Vec<u8> {
157 let challenge = challenge.unwrap_or(EMPTY_CHALLENGE);
158
159 let header = match req {
160 RequestType::Info => info::REQUEST_HEADER,
161 RequestType::Players => player::REQUEST_HEADER,
162 RequestType::Rules => rules::REQUEST_HEADER,
163 RequestType::Ping => obsolete::PING_REQUEST_HEADER,
164 RequestType::Challenge => obsolete::CHALLENGE_REQUEST_HEADER,
165 };
166
167 let mut request = Vec::new();
168
169 // -1 is byte-order agnostic, though
170 request.extend_from_slice(&CONNECTIONLESS_HEADER.to_le_bytes());
171 request.extend_from_slice(header);
172
173 // `players` and `rules` always contain a challenge, but some GoldSrc
174 // servers reject an empty challenge for `info`.
175 if req == RequestType::Players || req == RequestType::Rules || (req == RequestType::Info && challenge != EMPTY_CHALLENGE) {
176 request.extend_from_slice(&challenge.to_le_bytes());
177 }
178
179 request
180}
181
182/// Builds an A2S_INFO request packet.
183///
184/// Pass `None` for the initial request. If the server responds with a challenge,
185/// pass it as `Some(challenge)` when sending the follow-up request.
186pub fn info_request(challenge: Option<i32>) -> Vec<u8> {
187 request(RequestType::Info, challenge)
188}
189
190/// Builds an A2S_PLAYER request packet.
191///
192/// The initial request uses the protocol's empty challenge value. If the server
193/// responds with a challenge, pass it as `Some(challenge)` for the follow-up.
194pub fn players_request(challenge: Option<i32>) -> Vec<u8> {
195 request(RequestType::Players, challenge)
196}
197
198/// Builds an A2S_RULES request packet.
199///
200/// The initial request uses the protocol's empty challenge value. If the server
201/// responds with a challenge, pass it as `Some(challenge)` for the follow-up.
202pub fn rules_request(challenge: Option<i32>) -> Vec<u8> {
203 request(RequestType::Rules, challenge)
204}