a2s-protocol 0.1.1

A protocol core for building A2S server query clients
Documentation
//! A parser and packet assembler for the Steam A2S server query protocol.
//!
//! This crate builds A2S request packets, reassembles fragmented UDP responses,
//! decompresses compressed responses, and parses the resulting payloads. It does
//! not open sockets or send requests; networking stays with the calling application.
//!
//! # Typical flow
//!
//! Send a request with [`info_request`], [`players_request`], or [`rules_request`].
//! Pass each received datagram to [`PacketProcessor::process`]. When it returns a
//! complete packet, parse it with [`parse_payload`]. If the response is a
//! [`Response::Challenge`], resend the matching request with the returned challenge.
//!
//! ```no_run
//! use std::net::{SocketAddr, UdpSocket};
//! use a2s_protocol::{PacketProcessor, Response, info_request, parse_payload};
//!
//! # fn query(server: SocketAddr) -> Result<(), Box<dyn std::error::Error>> {
//! let socket = UdpSocket::bind("0.0.0.0:0")?;
//! socket.send_to(&info_request(None), server)?;
//! let mut processor = PacketProcessor::new();
//! let mut datagram = [0; a2s_protocol::MAX_PACKET_SIZE];
//!
//! loop {
//!     let (len, source) = socket.recv_from(&mut datagram)?;
//!     let Some(packet) = processor.process(source, &datagram[..len])? else {
//!         continue;
//!     };
//!     match parse_payload(&packet)? {
//!         Response::Challenge(challenge) => {
//!             socket.send_to(&info_request(Some(challenge)), source)?;
//!         }
//!         response => {
//!             println!("{response:#?}");
//!             break;
//!         }
//!     }
//! }
//! # Ok(())
//! # }
//! ```

use crate::transport::CONNECTIONLESS_HEADER;

use crate::obsolete::{CHALLENGE_RESPONSE_HEADER, PING_RESPONSE_HEADER};
use crate::cursor::{Cursor};

pub use transport::packet_processor::PacketProcessor;
/// Recommended maximum size of one UDP datagram received from a server.
pub use transport::MAX_PACKET_SIZE;
/// Errors produced while validating or reassembling server packets.
pub use transport::Error as TransportError;

// This module was generated with AI assistance.
mod cursor;

mod transport;
mod the_ship;

pub mod info;
pub mod player;
pub mod rules;

pub mod obsolete;

const EMPTY_CHALLENGE: i32 = -1;

#[derive(Debug)]
/// A decoded response returned by [`parse_payload`].
///
/// String fields in response variants borrow from the packet passed to
/// [`parse_payload`]. Keep that packet alive while using the response, or call
/// the relevant `to_owned` method to detach the data.
pub enum Response<'a> {
    /// A challenge that must be included in the corresponding follow-up request.
    Challenge(i32),
    /// A Source engine server information response.
    Info(info::Info<'a>),
    /// A legacy GoldSrc server information response.
    ObsoleteInfo(obsolete::GoldSrcInfo<'a>),
    /// A player list response.
    Players(player::Players<'a>),
    /// A server rules response.
    Rules(rules::Rules<'a>),
    /// A successful response to a legacy ping request.
    Ping,
}

#[derive(Clone, Copy, PartialEq)]
pub(crate) enum RequestType {
    Info,
    Players,
    Rules,
    Ping,
    Challenge,
}

#[derive(thiserror::Error, Debug)]
/// Errors that can occur while decoding a complete connectionless response.
pub enum PayloadError {
    /// The packet ended before a required field was available, or contained invalid UTF-8.
    #[error(transparent)]
    Read(#[from] cursor::Error),
    /// The response header is not recognized.
    #[error("invalid header: {0}")]
    InvalidHeader(u8),
    /// The Source server information payload is malformed.
    #[error(transparent)]
    Info(#[from] info::Error),
    /// The player response payload is malformed.
    #[error(transparent)]
    Players(#[from] player::Error),
    /// The rules response payload is malformed.
    #[error(transparent)]
    Rules(#[from] rules::Error)
}

/// Parses a complete connectionless response packet into its response type.
///
/// For fragmented or compressed responses, first pass datagrams through
/// [`PacketProcessor::process`]. The returned response may borrow string data
/// directly from `payload`.
///
/// # Errors
///
/// Returns [`PayloadError`] if the packet header is unknown, a required field is
/// missing, a string is not valid UTF-8, or a response-specific value is invalid.
pub fn parse_payload(payload: &[u8]) -> Result<Response<'_>, PayloadError> {
    let mut cur = Cursor::new(payload);

    // Skip the CONNECTIONLESS_HEADER invariant.
    // (The MULTI_PACKET payload still contains it)
    cur.read_long()?;

    let header = cur.read_byte()?;
    let payload = cur.as_slice();

    match header {
        CHALLENGE_RESPONSE_HEADER => Ok(Response::Challenge(cur.read_long()?)),
        info::RESPONSE_HEADER => Ok(Response::Info(info::parse(payload)?)),
        player::RESPONSE_HEADER => Ok(Response::Players(player::Players::parse(payload)?)),
        rules::RESPONSE_HEADER => Ok(Response::Rules(rules::Rules::parse(payload)?)),
        obsolete::INFO_RESPONSE_HEADER => Ok(Response::ObsoleteInfo(obsolete::parse_info(payload)?)),
        PING_RESPONSE_HEADER => Ok(Response::Ping),
        other => Err(PayloadError::InvalidHeader(other)),
    }
}

fn request(req: RequestType, challenge: Option<i32>) -> Vec<u8> {
    let challenge = challenge.unwrap_or(EMPTY_CHALLENGE);

    let header = match req {
        RequestType::Info => info::REQUEST_HEADER,
        RequestType::Players => player::REQUEST_HEADER,
        RequestType::Rules => rules::REQUEST_HEADER,
        RequestType::Ping => obsolete::PING_REQUEST_HEADER,
        RequestType::Challenge => obsolete::CHALLENGE_REQUEST_HEADER,
    };

    let mut request = Vec::new();

    // -1 is byte-order agnostic, though
    request.extend_from_slice(&CONNECTIONLESS_HEADER.to_le_bytes());
    request.extend_from_slice(header);

    // `players` and `rules` always contain a challenge, but some GoldSrc
    // servers reject an empty challenge for `info`.
    if req == RequestType::Players || req == RequestType::Rules || (req == RequestType::Info && challenge != EMPTY_CHALLENGE) {
        request.extend_from_slice(&challenge.to_le_bytes());
    }

    request
}

/// Builds an A2S_INFO request packet.
///
/// Pass `None` for the initial request. If the server responds with a challenge,
/// pass it as `Some(challenge)` when sending the follow-up request.
pub fn info_request(challenge: Option<i32>) -> Vec<u8> {
    request(RequestType::Info, challenge)
}

/// Builds an A2S_PLAYER request packet.
///
/// The initial request uses the protocol's empty challenge value. If the server
/// responds with a challenge, pass it as `Some(challenge)` for the follow-up.
pub fn players_request(challenge: Option<i32>) -> Vec<u8> {
    request(RequestType::Players, challenge)
}

/// Builds an A2S_RULES request packet.
///
/// The initial request uses the protocol's empty challenge value. If the server
/// responds with a challenge, pass it as `Some(challenge)` for the follow-up.
pub fn rules_request(challenge: Option<i32>) -> Vec<u8> {
    request(RequestType::Rules, challenge)
}