Skip to main content

a2s_protocol/
info.rs

1//! Types returned when parsing Source engine server information responses.
2
3use borrowme::borrowme;
4
5use crate::{cursor::{self, Cursor}, the_ship};
6
7// A2S_INFO requires a string payload.
8pub(crate) const REQUEST_HEADER: &[u8] = b"TSource Engine Query\0";
9pub(crate) const RESPONSE_HEADER: u8 = b'I';
10
11const EDF_PORT: u8 = 0x80;
12const EDF_STEAM_ID: u8 = 0x10;
13const EDF_SOURCE_TV: u8 = 0x40;
14const EDF_KEYWORDS: u8 = 0x20;
15const EDF_GAME_ID: u8 = 0x01;
16
17#[derive(thiserror::Error, Debug)]
18/// Errors found in an A2S_INFO response.
19pub enum Error {
20    /// A required field could not be read, or a string was not valid UTF-8.
21    #[error(transparent)]
22    Read(#[from] cursor::Error),
23    /// The server type byte was not one of the protocol's recognized values.
24    #[error("invalid server type: {0}")]
25    InvalidServerType(u8),
26    /// The server environment byte was not recognized.
27    #[error("invalid server platform: {0}")]
28    InvalidPlatform(u8)
29}
30
31#[derive(Debug, Clone)]
32/// Source server role reported in an A2S_INFO response.
33pub enum ServerType {
34    /// A dedicated server process.
35    Dedicated,
36    /// A server hosted by a player's client.
37    Listen,
38    /// A SourceTV proxy.
39    Proxy
40}
41
42#[derive(Debug, Clone)]
43/// Operating system family reported by the server.
44pub enum Environment {
45    /// Linux.
46    Linux,
47    /// Windows.
48    Windows,
49    /// macOS or an older Mac OS variant.
50    Mac
51}
52
53impl TryFrom<u8> for ServerType {
54    type Error = Error;
55
56    fn try_from(byte: u8) -> Result<Self, Self::Error> {
57        Ok(match byte {
58            b'd' => Self::Dedicated,
59            b'l' => Self::Listen,
60            b'p' => Self::Proxy,
61            other => return Err(Error::InvalidServerType(other)),
62        })
63    }
64}
65
66#[borrowme]
67#[derive(Debug)]
68#[owned_attr(derive(Clone))]
69#[owned_attr(doc(hidden))]
70/// Optional fields included in the extended data section of an A2S_INFO response.
71pub struct ExtraData<'a> {
72    /// The server's game port, when advertised.
73    pub port: Option<u16>,
74    /// The server's Steam ID, when advertised.
75    pub steam_id: Option<u64>,
76    /// SourceTV port and name, when the server advertises SourceTV.
77    pub source_tv: Option<SourceTv<'a>>,
78    /// Server keywords, when present.
79    pub keywords: Option<&'a str>,
80    /// The game's Steam application ID, when advertised.
81    pub game_id: Option<u64>
82}
83
84#[borrowme]
85#[derive(Debug)]
86#[owned_attr(derive(Clone))]
87#[owned_attr(doc(hidden))]
88/// SourceTV details reported in the A2S_INFO extended data section.
89pub struct SourceTv<'a> {
90    /// SourceTV spectator port.
91    pub port: u16,
92    /// SourceTV server name, borrowed from the response packet.
93    pub name: &'a str
94}
95
96#[borrowme]
97#[derive(Debug)]
98#[owned_attr(derive(Clone))]
99#[owned_attr(doc(hidden))]
100/// Parsed Source engine server information.
101///
102/// String fields borrow from the response packet. Use [`Info::to_owned`] to
103/// create an owned copy that can outlive that packet.
104pub struct Info<'a> {
105    /// A2S protocol version reported by the server.
106    pub protocol: u8,
107    /// Human-readable server name.
108    pub name: &'a str,
109    /// Current map name.
110    pub map: &'a str,
111    /// Game directory name.
112    pub folder: &'a str,
113    /// Human-readable game description.
114    pub game: &'a str,
115    /// Steam application ID of the game.
116    pub id: u16,
117    /// Number of players currently reported by the server.
118    pub players: u8,
119    /// Maximum number of players supported by the server.
120    pub max_players: u8,
121    /// Number of bots reported by the server.
122    pub bots: u8,
123    /// Whether the server is dedicated, listen-hosted, or a proxy.
124    pub server_type: ServerType,
125    /// Operating system family reported by the server.
126    pub environment: Environment,
127    /// Whether the server is password-protected.
128    pub is_private: bool,
129    /// Whether Valve Anti-Cheat is enabled.
130    pub vac: bool,
131    /// Additional game mode information, present for The Ship.
132    pub the_ship: Option<the_ship::Info>,
133    /// Server version string.
134    pub version: &'a str,
135    /// Optional extended data advertised by the server.
136    pub extra_data: Option<ExtraData<'a>>
137}
138
139impl Info<'_> {
140    /// Copies this parsed response into an owned value.
141    ///
142    /// The returned value no longer borrows the input packet.
143    pub fn to_owned(self) -> OwnedInfo {
144        borrowme::to_owned(self)
145    }
146}
147
148pub(crate) fn parse(raw: &[u8]) -> Result<Info<'_>, Error> {
149    let mut cur = Cursor::new(raw);
150
151    let protocol = cur.read_byte()?;
152    let name = cur.read_str()?;
153    let map = cur.read_str()?;
154    let folder = cur.read_str()?;
155    let game = cur.read_str()?;
156    let id = cur.read_short()?;
157    let players = cur.read_byte()?;
158    let max_players = cur.read_byte()?;
159    let bots = cur.read_byte()?;
160    let server_type = ServerType::try_from(cur.read_byte()?)?;
161    let environment = match cur.read_byte()? {
162        b'l' => Environment::Linux,
163        b'w' => Environment::Windows,
164        b'm' | b'o' => Environment::Mac,
165        other => return Err(Error::InvalidPlatform(other)),
166    };
167    let is_private = cur.read_byte()? != 0;
168    let vac = cur.read_byte()? != 0;
169
170    let the_ship = if id == the_ship::APP_ID {
171        Some(the_ship::Info {
172            mode: the_ship::Mode::from(cur.read_byte()?),
173            witnesses: cur.read_byte()?,
174            duration: cur.read_byte()?
175        })
176    } else {
177        None
178    };
179
180    let version = cur.read_str()?;
181
182    let extra_data = if cur.is_end() {
183        None
184    } else {
185        let edf = cur.read_byte()?;
186        Some(ExtraData {
187            port: match edf & EDF_PORT {
188                0 => None,
189                _ => Some(cur.read_short()?)
190            },
191            steam_id: match edf & EDF_STEAM_ID {
192                0 => None,
193                _ => Some(cur.read_longlong()?)
194            },
195            source_tv: match edf & EDF_SOURCE_TV {
196                0 => None,
197                _ => Some(SourceTv{
198                    port: cur.read_short()?,
199                    name: cur.read_str()?
200                })
201            },
202            keywords: match edf & EDF_KEYWORDS {
203                0 => None,
204                _ => Some(cur.read_str()?)
205            },
206            game_id: match edf & EDF_GAME_ID {
207                0 => None,
208                _ => Some(cur.read_longlong()?)
209            }
210        })
211    };
212
213    Ok(Info { protocol, name, map, folder, game, id, players, max_players, bots, server_type, environment, is_private, vac, the_ship, version, extra_data })
214}