a2s-protocol 0.1.0

A protocol core for building A2S server query clients
Documentation
//! Types returned when parsing Source engine server information responses.

use borrowme::borrowme;

use crate::{cursor::{self, Cursor}, the_ship};

// A2S_INFO requires a string payload.
pub(crate) const REQUEST_HEADER: &[u8] = b"TSource Engine Query\0";
pub(crate) const RESPONSE_HEADER: u8 = b'I';

const EDF_PORT: u8 = 0x80;
const EDF_STEAM_ID: u8 = 0x10;
const EDF_SOURCE_TV: u8 = 0x40;
const EDF_KEYWORDS: u8 = 0x20;
const EDF_GAME_ID: u8 = 0x01;

#[derive(thiserror::Error, Debug)]
/// Errors found in an A2S_INFO response.
pub enum Error {
    /// A required field could not be read, or a string was not valid UTF-8.
    #[error(transparent)]
    Read(#[from] cursor::Error),
    /// The server type byte was not one of the protocol's recognized values.
    #[error("invalid server type: {0}")]
    InvalidServerType(u8),
    /// The server environment byte was not recognized.
    #[error("invalid server platform: {0}")]
    InvalidPlatform(u8)
}

#[derive(Debug, Clone)]
/// Source server role reported in an A2S_INFO response.
pub enum ServerType {
    /// A dedicated server process.
    Dedicated,
    /// A server hosted by a player's client.
    Listen,
    /// A SourceTV proxy.
    Proxy
}

#[derive(Debug, Clone)]
/// Operating system family reported by the server.
pub enum Environment {
    /// Linux.
    Linux,
    /// Windows.
    Windows,
    /// macOS or an older Mac OS variant.
    Mac
}

impl TryFrom<u8> for ServerType {
    type Error = Error;

    fn try_from(byte: u8) -> Result<Self, Self::Error> {
        Ok(match byte {
            b'd' => Self::Dedicated,
            b'l' => Self::Listen,
            b'p' => Self::Proxy,
            other => return Err(Error::InvalidServerType(other)),
        })
    }
}

#[borrowme]
#[derive(Debug)]
#[owned_attr(derive(Clone))]
#[owned_attr(doc(hidden))]
/// Optional fields included in the extended data section of an A2S_INFO response.
pub struct ExtraData<'a> {
    /// The server's game port, when advertised.
    pub port: Option<u16>,
    /// The server's Steam ID, when advertised.
    pub steam_id: Option<u64>,
    /// SourceTV port and name, when the server advertises SourceTV.
    pub source_tv: Option<SourceTv<'a>>,
    /// Server keywords, when present.
    pub keywords: Option<&'a str>,
    /// The game's Steam application ID, when advertised.
    pub game_id: Option<u64>
}

#[borrowme]
#[derive(Debug)]
#[owned_attr(derive(Clone))]
#[owned_attr(doc(hidden))]
/// SourceTV details reported in the A2S_INFO extended data section.
pub struct SourceTv<'a> {
    /// SourceTV spectator port.
    pub port: u16,
    /// SourceTV server name, borrowed from the response packet.
    pub name: &'a str
}

#[borrowme]
#[derive(Debug)]
#[owned_attr(derive(Clone))]
#[owned_attr(doc(hidden))]
/// Parsed Source engine server information.
///
/// String fields borrow from the response packet. Use [`Info::to_owned`] to
/// create an owned copy that can outlive that packet.
pub struct Info<'a> {
    /// A2S protocol version reported by the server.
    pub protocol: u8,
    /// Human-readable server name.
    pub name: &'a str,
    /// Current map name.
    pub map: &'a str,
    /// Game directory name.
    pub folder: &'a str,
    /// Human-readable game description.
    pub game: &'a str,
    /// Steam application ID of the game.
    pub id: u16,
    /// Number of players currently reported by the server.
    pub players: u8,
    /// Maximum number of players supported by the server.
    pub max_players: u8,
    /// Number of bots reported by the server.
    pub bots: u8,
    /// Whether the server is dedicated, listen-hosted, or a proxy.
    pub server_type: ServerType,
    /// Operating system family reported by the server.
    pub environment: Environment,
    /// Whether the server is password-protected.
    pub is_private: bool,
    /// Whether Valve Anti-Cheat is enabled.
    pub vac: bool,
    /// Additional game mode information, present for The Ship.
    pub the_ship: Option<the_ship::Info>,
    /// Server version string.
    pub version: &'a str,
    /// Optional extended data advertised by the server.
    pub extra_data: Option<ExtraData<'a>>
}

impl Info<'_> {
    /// Copies this parsed response into an owned value.
    ///
    /// The returned value no longer borrows the input packet.
    pub fn to_owned(self) -> OwnedInfo {
        borrowme::to_owned(self)
    }
}

pub(crate) fn parse(raw: &[u8]) -> Result<Info<'_>, Error> {
    let mut cur = Cursor::new(raw);

    let protocol = cur.read_byte()?;
    let name = cur.read_str()?;
    let map = cur.read_str()?;
    let folder = cur.read_str()?;
    let game = cur.read_str()?;
    let id = cur.read_short()?;
    let players = cur.read_byte()?;
    let max_players = cur.read_byte()?;
    let bots = cur.read_byte()?;
    let server_type = ServerType::try_from(cur.read_byte()?)?;
    let environment = match cur.read_byte()? {
        b'l' => Environment::Linux,
        b'w' => Environment::Windows,
        b'm' | b'o' => Environment::Mac,
        other => return Err(Error::InvalidPlatform(other)),
    };
    let is_private = cur.read_byte()? != 0;
    let vac = cur.read_byte()? != 0;

    let the_ship = if id == the_ship::APP_ID {
        Some(the_ship::Info {
            mode: the_ship::Mode::from(cur.read_byte()?),
            witnesses: cur.read_byte()?,
            duration: cur.read_byte()?
        })
    } else {
        None
    };

    let version = cur.read_str()?;

    let extra_data = if cur.is_end() {
        None
    } else {
        let edf = cur.read_byte()?;
        Some(ExtraData {
            port: match edf & EDF_PORT {
                0 => None,
                _ => Some(cur.read_short()?)
            },
            steam_id: match edf & EDF_STEAM_ID {
                0 => None,
                _ => Some(cur.read_longlong()?)
            },
            source_tv: match edf & EDF_SOURCE_TV {
                0 => None,
                _ => Some(SourceTv{
                    port: cur.read_short()?,
                    name: cur.read_str()?
                })
            },
            keywords: match edf & EDF_KEYWORDS {
                0 => None,
                _ => Some(cur.read_str()?)
            },
            game_id: match edf & EDF_GAME_ID {
                0 => None,
                _ => Some(cur.read_longlong()?)
            }
        })
    };

    Ok(Info { protocol, name, map, folder, game, id, players, max_players, bots, server_type, environment, is_private, vac, the_ship, version, extra_data })
}