ssq 0.7.0

Rust implementation of Source Server Query (A2S)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use std::convert::TryFrom;
use std::io::Cursor;
use std::io::ErrorKind;
use std::io::Read;
use std::io::Write;
use std::net::ToSocketAddrs;

#[cfg(feature = "serde")]
use serde::Deserialize;
#[cfg(feature = "serde")]
use serde::Serialize;

use bstr::BString;
use bstr::ByteSlice;
use byteorder::LittleEndian;
use byteorder::ReadBytesExt;
use byteorder::WriteBytesExt;

use crate::AppId;
use crate::Client;
use crate::GameId;
use crate::HEADER_CHALLENGE;
use crate::HEADER_INFO;
use crate::ReadCString;
use crate::SteamId;
use crate::errors::Error;
use crate::errors::Result;

#[doc(hidden)]
pub const INFO_REQUEST: [u8; 25] = [
    0xFF, 0xFF, 0xFF, 0xFF, 0x54, 0x53, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x20, 0x45, 0x6E, 0x67, 0x69,
    0x6E, 0x65, 0x20, 0x51, 0x75, 0x65, 0x72, 0x79, 0x00,
];

#[derive(Debug, Clone)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[non_exhaustive]
pub struct TheShip {
    /// Indicates the game mode
    pub mode: TheShipMode,

    /// The number of witnesses necessary to have a player arrested.
    pub witnesses: u8,

    /// Time (in seconds) before a player is arrested while being witnessed.
    pub duration: u8,
}

#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[non_exhaustive]
#[repr(u8)]
pub enum TheShipMode {
    Hunt = 0,
    Elimination = 1,
    Duel = 2,
    Deathmatch = 3,
    VIPTeam = 4,
    TeamElimination = 5,
    Unknown = 255,
}

impl From<u8> for TheShipMode {
    fn from(v: u8) -> Self {
        match v {
            0 => Self::Hunt,
            1 => Self::Elimination,
            2 => Self::Duel,
            3 => Self::Deathmatch,
            4 => Self::VIPTeam,
            5 => Self::TeamElimination,
            _ => Self::Unknown,
        }
    }
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[non_exhaustive]
pub struct ExtendedServerInfo {
    /// The server's game port number.
    /// Available if edf & 0x80 is true
    pub port: Option<u16>,

    /// Server's SteamID.
    /// Available if edf & 0x10 is true
    pub steam_id: Option<SteamId>,

    /// Tags that describe the game according to the server (for future use.)
    /// Available if edf & 0x20 is true
    #[cfg_attr(feature = "arbitrary", arbitrary(with = crate::arbitrary_option_bstring))]
    pub keywords: Option<BString>,

    /// The server's 64-bit GameID. If this is present, a more accurate AppID is present in the low 24 bits.
    /// The earlier AppID could have been truncated as it was forced into 16-bit storage.
    /// Available if edf & 0x01 is true
    pub game_id: Option<GameId>,
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[non_exhaustive]
pub struct SourceTVInfo {
    /// Spectator port number for SourceTV.
    pub port: u16,

    /// Name of the spectator server for SourceTV.
    #[cfg_attr(feature = "arbitrary", arbitrary(with = crate::arbitrary_bstring))]
    pub name: BString,
}

#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[non_exhaustive]
#[repr(u8)]
pub enum ServerType {
    Dedicated = b'd',
    NonDedicated = b'i',
    SourceTV = b'p',
}

impl TryFrom<u8> for ServerType {
    type Error = Error;
    fn try_from(val: u8) -> Result<Self> {
        match val {
            b'd' => Ok(Self::Dedicated),
            b'i' => Ok(Self::NonDedicated),
            b'p' => Ok(Self::SourceTV),
            other => Err(Self::Error::UnexpectedHeader {
                expected: b'd',
                actual: other,
            }),
        }
    }
}

#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[non_exhaustive]
#[repr(u8)]
pub enum ServerOS {
    Linux = b'l',
    Windows = b'w',
    Mac = b'm',
}

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

    fn try_from(val: u8) -> Result<Self> {
        match val {
            b'l' => Ok(Self::Linux),
            b'w' => Ok(Self::Windows),
            b'm' | b'o' => Ok(Self::Mac),
            other => Err(Self::Error::UnexpectedHeader {
                expected: b'l',
                actual: other,
            }),
        }
    }
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[non_exhaustive]
pub struct Info {
    /// Protocol version used by the server.
    pub protocol: u8,

    /// Name of the server.
    #[cfg_attr(feature = "arbitrary", arbitrary(with = crate::arbitrary_bstring))]
    pub name: BString,

    /// Map the server has currently loaded.
    #[cfg_attr(feature = "arbitrary", arbitrary(with = crate::arbitrary_bstring))]
    pub map: BString,

    /// Name of the folder containing the game files.
    #[cfg_attr(feature = "arbitrary", arbitrary(with = crate::arbitrary_bstring))]
    pub folder: BString,

    /// Full name of the game.
    #[cfg_attr(feature = "arbitrary", arbitrary(with = crate::arbitrary_bstring))]
    pub game: BString,

    /// Steam Application ID of game.
    pub app_id: AppId,

    /// Number of players on the server.
    pub players: u8,

    /// Maximum number of players the server reports it can hold.
    pub max_players: u8,

    /// Number of bots on the server.
    pub bots: u8,

    /// Indicates the type of server
    /// Rag Doll Kung Fu servers always return 0 for "Server type."
    pub server_type: ServerType,

    /// Indicates the operating system of the server
    pub server_os: ServerOS,

    /// Indicates whether the server requires a password
    pub visibility: bool,

    /// Specifies whether the server uses VAC
    pub vac: bool,

    /// These fields only exist in a response if the server is running The Ship
    pub the_ship: Option<TheShip>,

    /// Version of the game installed on the server.
    #[cfg_attr(feature = "arbitrary", arbitrary(with = crate::arbitrary_bstring))]
    pub version: BString,

    /// If present, this specifies which additional data fields will be included.
    pub edf: u8,

    pub extended_server_info: ExtendedServerInfo,

    /// Available if edf & 0x40 is true
    pub source_tv: Option<SourceTVInfo>,
}

impl Info {
    pub fn size_hint(&self) -> usize {
        // header(5) + protocol(1) + name+nul + map+nul + folder+nul + game+nul
        // + app_id(2) + players(1) + max_players(1) + bots(1) + server_type(1) + server_os(1)
        // + visibility(1) + vac(1) + version+nul
        let mut size = 5
            + 1
            + self.name.len()
            + 1
            + self.map.len()
            + 1
            + self.folder.len()
            + 1
            + self.game.len()
            + 1
            + 2
            + 1
            + 1
            + 1
            + 1
            + 1
            + 1
            + 1
            + self.version.len()
            + 1;

        if self.the_ship.is_some() {
            size += 3;
        }

        if self.edf != 0 {
            size += 1; // edf byte
        }
        if self.extended_server_info.port.is_some() {
            size += 2;
        }
        if self.extended_server_info.steam_id.is_some() {
            size += 8;
        }
        if let Some(keywords) = &self.extended_server_info.keywords {
            size += keywords.len() + 1;
        }
        if self.extended_server_info.game_id.is_some() {
            size += 8;
        }
        if let Some(source_tv) = &self.source_tv {
            size += 2 + source_tv.name.len() + 1;
        }

        size
    }

    pub fn write<W: Write>(&self, mut w: W) -> Result<()> {
        w.write_all(&[0xff, 0xff, 0xff, 0xff, HEADER_INFO])?;
        w.write_all(&[self.protocol])?;
        w.write_all(self.name.as_bytes())?;
        w.write_all(&[0])?;
        w.write_all(self.map.as_bytes())?;
        w.write_all(&[0])?;
        w.write_all(self.folder.as_bytes())?;
        w.write_all(&[0])?;
        w.write_all(self.game.as_bytes())?;
        w.write_all(&[0])?;
        w.write_all(&self.app_id.0.to_le_bytes())?;
        w.write_all(&[self.players, self.max_players, self.bots])?;
        w.write_all(&[self.server_type as u8])?;
        w.write_all(&[self.server_os as u8])?;
        w.write_all(&[if self.visibility { 1 } else { 0 }])?;
        w.write_all(&[if self.vac { 1 } else { 0 }])?;

        if let Some(the_ship) = &self.the_ship {
            w.write_all(&[the_ship.mode as u8, the_ship.witnesses, the_ship.duration])?;
        }

        w.write_all(self.version.as_bytes())?;
        w.write_all(&[0])?;

        if self.edf != 0 {
            w.write_all(&[self.edf])?;
        }

        if let Some(port) = &self.extended_server_info.port {
            w.write_all(&port.to_le_bytes())?;
        }
        if let Some(steam_id) = &self.extended_server_info.steam_id {
            w.write_all(&steam_id.0.to_le_bytes())?;
        }
        if let Some(source_tv) = &self.source_tv {
            w.write_all(&source_tv.port.to_le_bytes())?;
            w.write_all(source_tv.name.as_bytes())?;
            w.write_all(&[0])?;
        }
        if let Some(keywords) = &self.extended_server_info.keywords {
            w.write_all(keywords.as_bytes())?;
            w.write_all(&[0])?;
        }
        if let Some(game_id) = &self.extended_server_info.game_id {
            w.write_all(&game_id.0.to_le_bytes())?;
        }

        Ok(())
    }

    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(self.size_hint());
        self.write(&mut bytes)
            .expect("writing to Vec should not fail");
        bytes
    }

    #[deprecated(since = "0.6.2", note = "use from_reader")]
    pub fn from_cursor(data: Cursor<Vec<u8>>) -> Result<Self> {
        Self::from_reader(data)
    }

    pub fn from_reader<R: Read>(mut data: R) -> Result<Self> {
        let header = data.read_u8()?;
        if header != HEADER_INFO {
            return Err(Error::UnexpectedHeader {
                expected: HEADER_INFO,
                actual: header,
            });
        }

        let protocol = data.read_u8()?;
        let name = data.read_cstring()?;
        let map = data.read_cstring()?;
        let folder = data.read_cstring()?;
        let game = data.read_cstring()?;
        let app_id = AppId(data.read_u16::<LittleEndian>()?);
        let players = data.read_u8()?;
        let max_players = data.read_u8()?;
        let bots = data.read_u8()?;
        let server_type = ServerType::try_from(data.read_u8()?)?;
        let server_os = ServerOS::try_from(data.read_u8()?)?;
        let visibility = read_bool(&mut data, "visibility")?;
        let vac = read_bool(&mut data, "vac")?;
        let the_ship = if app_id == AppId::THE_SHIP {
            Some(TheShip {
                mode: TheShipMode::from(data.read_u8()?),
                witnesses: data.read_u8()?,
                duration: data.read_u8()?,
            })
        } else {
            None
        };
        let version = data.read_cstring()?;
        let edf = match data.read_u8() {
            Ok(val) => val,
            Err(err) => {
                if err.kind() != ErrorKind::UnexpectedEof {
                    return Err(Error::Io(err));
                } else {
                    0
                }
            }
        };
        let port = if edf & 0x80 != 0 {
            Some(data.read_u16::<LittleEndian>()?)
        } else {
            None
        };
        let steam_id = if edf & 0x10 != 0 {
            Some(SteamId(data.read_u64::<LittleEndian>()?))
        } else {
            None
        };
        let source_tv = if edf & 0x40 != 0 {
            Some(SourceTVInfo {
                port: data.read_u16::<LittleEndian>()?,
                name: data.read_cstring()?,
            })
        } else {
            None
        };
        let keywords = if edf & 0x20 != 0 {
            Some(data.read_cstring()?)
        } else {
            None
        };
        let game_id = if edf & 0x01 != 0 {
            Some(GameId(data.read_u64::<LittleEndian>()?))
        } else {
            None
        };
        let extended_server_info = ExtendedServerInfo {
            port,
            steam_id,
            keywords,
            game_id,
        };

        Ok(Info {
            protocol,
            name,
            map,
            folder,
            game,
            app_id,
            players,
            max_players,
            bots,
            server_type,
            server_os,
            visibility,
            vac,
            the_ship,
            version,
            edf,
            extended_server_info,
            source_tv,
        })
    }
}

fn read_bool<R: Read>(data: &mut R, field: &'static str) -> Result<bool> {
    let value = data.read_u8()?;
    match value {
        0 => Ok(false),
        1 => Ok(true),
        _ => Err(Error::InvalidBool { field, value }),
    }
}

impl Client {
    pub fn info<A: ToSocketAddrs>(&self, addr: A) -> Result<Info> {
        let response = self.send(&INFO_REQUEST, &addr)?;

        let mut packet = Cursor::new(&response);

        let header = packet.read_u8()?;
        if header == HEADER_CHALLENGE {
            let challenge = packet.read_i32::<LittleEndian>()?;

            let mut query = Vec::with_capacity(29);
            query.write_all(&INFO_REQUEST)?;
            query.write_i32::<LittleEndian>(challenge)?;

            let data = self.send(&query, addr)?;
            Info::from_reader(data.as_slice())
        } else {
            Info::from_reader(response.as_slice())
        }
    }
}