refator: copy cli into mono

This commit is contained in:
Cain 2023-10-16 23:20:47 +01:00
parent 66ae3c296e
commit 80f6b87991
63 changed files with 244 additions and 34 deletions

View file

@ -0,0 +1,60 @@
/// The implementation.
pub mod protocol;
/// All types used by the implementation.
pub mod types;
pub use protocol::*;
pub use types::*;
/// Generate a module containing a query function for a valve game.
///
/// * `mod_name` - The name to be given to the game module (see ID naming
/// conventions in CONTRIBUTING.md).
/// * `pretty_name` - The full name of the game, will be used as the
/// documentation for the created module.
/// * `steam_app`, `default_port` - Passed through to [game_query_fn].
macro_rules! game_query_mod {
($mod_name: ident, $pretty_name: expr, $steam_app: ident, $default_port: literal) => {
#[doc = $pretty_name]
pub mod $mod_name {
crate::protocols::valve::game_query_fn!($steam_app, $default_port);
}
};
}
pub(crate) use game_query_mod;
// Allow generating doc comments:
// https://users.rust-lang.org/t/macros-filling-text-in-comments/20473
/// Generate a query function for a valve game.
///
/// * `steam_app` - The entry in the [SteamApp] enum that the game uses.
/// * `default_port` - The default port the game uses.
///
/// ```rust,ignore
/// use crate::protocols::valve::game_query_fn;
/// game_query_fn!(TEAMFORTRESS2, 27015);
/// ```
macro_rules! game_query_fn {
($steam_app: ident, $default_port: literal) => {
crate::protocols::valve::game_query_fn!{@gen $steam_app, $default_port, concat!(
"Make a valve query for ", stringify!($steam_app), " with default timeout settings and default extra request settings.\n\n",
"If port is `None`, then the default port (", stringify!($default_port), ") will be used.")}
};
(@gen $steam_app: ident, $default_port: literal, $doc: expr) => {
#[doc = $doc]
pub fn query(address: &std::net::IpAddr, port: Option<u16>) -> crate::GDResult<crate::protocols::valve::game::Response> {
let valve_response = crate::protocols::valve::query(
&std::net::SocketAddr::new(*address, port.unwrap_or($default_port)),
crate::protocols::valve::SteamApp::$steam_app.as_engine(),
None,
None,
)?;
Ok(crate::protocols::valve::game::Response::new_from_valve_response(valve_response))
}
};
}
pub(crate) use game_query_fn;

View file

@ -0,0 +1,483 @@
use crate::{
buffer::Buffer,
protocols::{
types::TimeoutSettings,
valve::{
types::{
Environment,
ExtraData,
GatheringSettings,
Request,
Response,
Server,
ServerInfo,
ServerPlayer,
TheShip,
},
Engine,
ModData,
SteamApp,
},
},
socket::{Socket, UdpSocket},
utils::{retry_on_timeout, u8_lower_upper},
GDErrorKind::{BadGame, Decompress, UnknownEnumCast},
GDResult,
};
use bzip2_rs::decoder::Decoder;
use crate::buffer::Utf8Decoder;
use crate::protocols::valve::Packet;
use byteorder::LittleEndian;
use std::collections::HashMap;
use std::net::SocketAddr;
#[derive(Debug)]
#[allow(dead_code)] //remove this later on
struct SplitPacket {
pub header: u32,
pub id: u32,
pub total: u8,
pub number: u8,
pub size: u16,
/// None means its not compressed, Some means it is
/// and it contains (size and crc32)
pub decompressed: Option<(u32, u32)>,
payload: Vec<u8>,
}
impl SplitPacket {
fn new(engine: &Engine, protocol: u8, buffer: &mut Buffer<LittleEndian>) -> GDResult<Self> {
let header = buffer.read()?; //buffer.get_u32()?;
let id = buffer.read()?;
let (total, number, size, decompressed) = match engine {
Engine::GoldSrc(_) => {
let (lower, upper) = u8_lower_upper(buffer.read()?);
(lower, upper, 0, None)
}
Engine::Source(_) => {
let total = buffer.read()?;
let number = buffer.read()?;
let size = match protocol == 7 && (*engine == SteamApp::CSS.as_engine()) {
// certain apps with protocol = 7 dont have this field
false => buffer.read()?,
true => 1248,
};
let is_compressed = ((id >> 31) & 1u32) == 1u32;
let decompressed = match is_compressed {
false => None,
true => Some((buffer.read()?, buffer.read()?)),
};
(total, number, size, decompressed)
}
};
Ok(Self {
header,
id,
total,
number,
size,
decompressed,
payload: buffer.remaining_bytes().to_vec(),
})
}
fn get_payload(&self) -> GDResult<Vec<u8>> {
if let Some(decompressed) = self.decompressed {
let mut decoder = Decoder::new();
decoder
.write(&self.payload)
.map_err(|e| Decompress.context(e))?;
let decompressed_size = decompressed.0 as usize;
let mut decompressed_payload = vec![0; decompressed_size];
decoder
.read(&mut decompressed_payload)
.map_err(|e| Decompress.context(e))?;
if decompressed_payload.len() != decompressed_size
|| crc32fast::hash(&decompressed_payload) != decompressed.1
{
Err(Decompress.context(format!(
"Decompressed size {} was not expected {}",
decompressed_payload.len(),
decompressed_size
)))
} else {
Ok(decompressed_payload)
}
} else {
Ok(self.payload.clone())
}
}
}
pub(crate) struct ValveProtocol {
socket: UdpSocket,
retry_count: usize,
}
static PACKET_SIZE: usize = 6144;
impl ValveProtocol {
pub fn new(address: &SocketAddr, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> {
let socket = UdpSocket::new(address)?;
let retry_count = timeout_settings
.as_ref()
.map(|t| t.get_retries())
.unwrap_or_else(|| TimeoutSettings::default().get_retries());
socket.apply_timeout(&timeout_settings)?;
Ok(Self {
socket,
retry_count,
})
}
fn receive(&mut self, engine: &Engine, protocol: u8, buffer_size: usize) -> GDResult<Packet> {
let data = self.socket.receive(Some(buffer_size))?;
let mut buffer = Buffer::<LittleEndian>::new(&data);
let header: u8 = buffer.read()?;
buffer.move_cursor(-1)?;
if header == 0xFE {
// the packet is split
let mut main_packet = SplitPacket::new(engine, protocol, &mut buffer)?;
let mut chunk_packets = Vec::with_capacity((main_packet.total - 1) as usize);
for _ in 1 .. main_packet.total {
let new_data = self.socket.receive(Some(buffer_size))?;
buffer = Buffer::<LittleEndian>::new(&new_data);
let chunk_packet = SplitPacket::new(engine, protocol, &mut buffer)?;
chunk_packets.push(chunk_packet);
}
chunk_packets.sort_by(|a, b| a.number.cmp(&b.number));
for chunk_packet in chunk_packets {
main_packet.payload.extend(chunk_packet.payload);
}
let payload = main_packet.get_payload()?; // Creating a non-temporary value here
let mut new_packet_buffer = Buffer::<LittleEndian>::new(&payload); // Using the non-temporary value here
Ok(Packet::new_from_bufferer(&mut new_packet_buffer)?)
} else {
Packet::new_from_bufferer(&mut buffer)
}
}
pub fn get_kind_request_data(&mut self, engine: &Engine, protocol: u8, kind: Request) -> GDResult<Vec<u8>> {
let data = self.get_request_data(engine, protocol, kind as u8, kind.get_default_payload())?;
Ok(data)
}
/// Ask for a specific request only.
/// This function will retry fetch on timeouts.
pub fn get_request_data(&mut self, engine: &Engine, protocol: u8, kind: u8, payload: Vec<u8>) -> GDResult<Vec<u8>> {
retry_on_timeout(self.retry_count, || {
self.get_request_data_impl(engine, protocol, kind, payload.clone())
})
}
/// Ask for a specific request only (without retry logic).
fn get_request_data_impl(
&mut self,
engine: &Engine,
protocol: u8,
kind: u8,
payload: Vec<u8>,
) -> GDResult<Vec<u8>> {
let request_initial_packet = Packet::new(kind, payload).to_bytes();
self.socket.send(&request_initial_packet)?;
let mut packet = self.receive(engine, protocol, PACKET_SIZE)?;
while packet.kind == 0x41 {
// 'A'
let challenge = packet.payload;
const INFO: u8 = Request::Info as u8;
let challenge_packet = Packet::new(
kind,
match kind {
INFO => [Request::Info.get_default_payload(), challenge].concat(),
_ => challenge,
},
)
.to_bytes();
self.socket.send(&challenge_packet)?;
packet = self.receive(engine, protocol, PACKET_SIZE)?;
}
Ok(packet.payload)
}
fn get_goldsrc_server_info(buffer: &mut Buffer<LittleEndian>) -> GDResult<ServerInfo> {
let _header: u8 = buffer.read()?; //get the header (useless info)
let _address: String = buffer.read_string::<Utf8Decoder>(None)?; //get the server address (useless info)
let name = buffer.read_string::<Utf8Decoder>(None)?;
let map = buffer.read_string::<Utf8Decoder>(None)?;
let folder = buffer.read_string::<Utf8Decoder>(None)?;
let game_mode = buffer.read_string::<Utf8Decoder>(None)?;
let players = buffer.read()?;
let max_players = buffer.read()?;
let protocol = buffer.read()?;
let server_type = match buffer.read::<u8>()? {
68 => Server::Dedicated, //'D'
76 => Server::NonDedicated, //'L'
80 => Server::TV, //'P'
_ => Err(UnknownEnumCast)?,
};
let environment_type = match buffer.read::<u8>()? {
76 => Environment::Linux, //'L'
87 => Environment::Windows, //'W'
_ => Err(UnknownEnumCast)?,
};
let has_password = buffer.read::<u8>()? == 1;
let is_mod = buffer.read::<u8>()? == 1;
let mod_data = match is_mod {
false => None,
true => {
Some(ModData {
link: buffer.read_string::<Utf8Decoder>(None)?,
download_link: buffer.read_string::<Utf8Decoder>(None)?,
version: buffer.read()?,
size: buffer.read()?,
multiplayer_only: buffer.read::<u8>()? == 1,
has_own_dll: buffer.read::<u8>()? == 1,
})
}
};
let vac_secured = buffer.read::<u8>()? == 1;
let bots = buffer.read::<u8>()?;
Ok(ServerInfo {
protocol_version: protocol,
name,
map,
folder,
game_mode,
appid: 0, // not present in the obsolete response
players_online: players,
players_maximum: max_players,
players_bots: bots,
server_type,
environment_type,
has_password,
vac_secured,
the_ship: None,
game_version: "".to_string(), // a version field only for the mod
extra_data: None,
is_mod,
mod_data,
})
}
/// Get the server information's.
fn get_server_info(&mut self, engine: &Engine) -> GDResult<ServerInfo> {
let data = self.get_kind_request_data(engine, 0, Request::Info)?;
let mut buffer = Buffer::<LittleEndian>::new(&data);
if let Engine::GoldSrc(force) = engine {
if *force {
return Self::get_goldsrc_server_info(&mut buffer);
}
}
let protocol = buffer.read()?;
let name = buffer.read_string::<Utf8Decoder>(None)?;
let map = buffer.read_string::<Utf8Decoder>(None)?;
let folder = buffer.read_string::<Utf8Decoder>(None)?;
let game_mode = buffer.read_string::<Utf8Decoder>(None)?;
let mut appid = buffer.read::<u16>()? as u32;
let players = buffer.read()?;
let max_players = buffer.read()?;
let bots = buffer.read()?;
let server_type = Server::from_gldsrc(buffer.read()?)?;
let environment_type = Environment::from_gldsrc(buffer.read()?)?;
let has_password = buffer.read::<u8>()? == 1;
let vac_secured = buffer.read::<u8>()? == 1;
let the_ship = match *engine == SteamApp::THESHIP.as_engine() {
false => None,
true => {
Some(TheShip {
mode: buffer.read()?,
witnesses: buffer.read()?,
duration: buffer.read()?,
})
}
};
let game_version = buffer.read_string::<Utf8Decoder>(None)?;
let extra_data = match buffer.read::<u8>() {
Err(_) => None,
Ok(value) => {
Some(ExtraData {
port: match (value & 0x80) > 0 {
false => None,
true => Some(buffer.read()?),
},
steam_id: match (value & 0x10) > 0 {
false => None,
true => Some(buffer.read()?),
},
tv_port: match (value & 0x40) > 0 {
false => None,
true => Some(buffer.read()?),
},
tv_name: match (value & 0x40) > 0 {
false => None,
true => Some(buffer.read_string::<Utf8Decoder>(None)?),
},
keywords: match (value & 0x20) > 0 {
false => None,
true => Some(buffer.read_string::<Utf8Decoder>(None)?),
},
game_id: match (value & 0x01) > 0 {
false => None,
true => {
let gid = buffer.read()?;
appid = (gid & ((1 << 24) - 1)) as u32;
Some(gid)
}
},
})
}
};
Ok(ServerInfo {
protocol_version: protocol,
name,
map,
folder,
game_mode,
appid,
players_online: players,
players_maximum: max_players,
players_bots: bots,
server_type,
environment_type,
has_password,
vac_secured,
the_ship,
game_version,
extra_data,
is_mod: false,
mod_data: None,
})
}
/// Get the server player's.
fn get_server_players(&mut self, engine: &Engine, protocol: u8) -> GDResult<Vec<ServerPlayer>> {
let data = self.get_kind_request_data(engine, protocol, Request::Players)?;
let mut buffer = Buffer::<LittleEndian>::new(&data);
let count = buffer.read::<u8>()? as usize;
let mut players: Vec<ServerPlayer> = Vec::with_capacity(count);
for _ in 0 .. count {
buffer.move_cursor(1)?; //skip the index byte
players.push(ServerPlayer {
name: buffer.read_string::<Utf8Decoder>(None)?,
score: buffer.read()?,
duration: buffer.read()?,
deaths: match *engine == SteamApp::THESHIP.as_engine() {
false => None,
true => Some(buffer.read()?),
},
money: match *engine == SteamApp::THESHIP.as_engine() {
false => None,
true => Some(buffer.read()?),
},
});
}
Ok(players)
}
/// Get the server's rules.
fn get_server_rules(&mut self, engine: &Engine, protocol: u8) -> GDResult<HashMap<String, String>> {
let data = self.get_kind_request_data(engine, protocol, Request::Rules)?;
let mut buffer = Buffer::<LittleEndian>::new(&data);
let count = buffer.read::<u16>()? as usize;
let mut rules: HashMap<String, String> = HashMap::with_capacity(count);
for _ in 0 .. count {
let name = buffer.read_string::<Utf8Decoder>(None)?;
let value = buffer.read_string::<Utf8Decoder>(None)?;
rules.insert(name, value);
}
if *engine == SteamApp::ROR2.as_engine() {
rules.remove("Test");
}
Ok(rules)
}
}
/// Query a server by providing the address, the port, the app, gather and
/// timeout settings. Providing None to the settings results in using the
/// default values for them
/// (GatherSettings::[default](GatheringSettings::default),
/// TimeoutSettings::[default](TimeoutSettings::default)).
pub fn query(
address: &SocketAddr,
engine: Engine,
gather_settings: Option<GatheringSettings>,
timeout_settings: Option<TimeoutSettings>,
) -> GDResult<Response> {
let response_gather_settings = gather_settings.unwrap_or_default();
get_response(address, engine, response_gather_settings, timeout_settings)
}
fn get_response(
address: &SocketAddr,
engine: Engine,
gather_settings: GatheringSettings,
timeout_settings: Option<TimeoutSettings>,
) -> GDResult<Response> {
let mut client = ValveProtocol::new(address, timeout_settings)?;
let info = client.get_server_info(&engine)?;
if let Engine::Source(Some(appids)) = &engine {
let mut is_specified_id = false;
if appids.0 == info.appid {
is_specified_id = true;
} else if let Some(dedicated_appid) = appids.1 {
if dedicated_appid == info.appid {
is_specified_id = true;
}
}
if !is_specified_id && gather_settings.check_app_id {
return Err(BadGame.context(format!("AppId: {}", info.appid)));
}
}
let protocol = info.protocol_version;
Ok(Response {
info,
players: match gather_settings.players {
false => None,
true => Some(client.get_server_players(&engine, protocol)?),
},
rules: match gather_settings.rules {
false => None,
true => Some(client.get_server_rules(&engine, protocol)?),
},
})
}

View file

@ -0,0 +1,556 @@
use std::collections::HashMap;
use crate::protocols::types::{CommonPlayer, CommonResponse, ExtraRequestSettings, GenericPlayer};
use crate::GDErrorKind::UnknownEnumCast;
use crate::GDResult;
use crate::{buffer::Buffer, protocols::GenericResponse};
use byteorder::LittleEndian;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// The type of the server.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Server {
Dedicated,
NonDedicated,
TV,
}
impl Server {
pub(crate) fn from_gldsrc(value: u8) -> GDResult<Self> {
Ok(match value {
100 => Self::Dedicated, //'d'
108 => Self::NonDedicated, //'l'
112 => Self::TV, //'p'
_ => Err(UnknownEnumCast)?,
})
}
}
/// The Operating System that the server is on.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Environment {
Linux,
Windows,
Mac,
}
impl Environment {
pub(crate) fn from_gldsrc(value: u8) -> GDResult<Self> {
Ok(match value {
108 => Self::Linux, //'l'
119 => Self::Windows, //'w'
109 | 111 => Self::Mac, //'m' or 'o'
_ => Err(UnknownEnumCast)?,
})
}
}
/// A query response.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct Response {
pub info: ServerInfo,
pub players: Option<Vec<ServerPlayer>>,
pub rules: Option<HashMap<String, String>>,
}
impl CommonResponse for Response {
fn as_original(&self) -> GenericResponse { GenericResponse::Valve(self) }
fn name(&self) -> Option<&str> { Some(&self.info.name) }
fn game_mode(&self) -> Option<&str> { Some(&self.info.game_mode) }
fn game_version(&self) -> Option<&str> { Some(&self.info.game_version) }
fn map(&self) -> Option<&str> { Some(&self.info.map) }
fn players_maximum(&self) -> u32 { self.info.players_maximum.into() }
fn players_online(&self) -> u32 { self.info.players_online.into() }
fn players_bots(&self) -> Option<u32> { Some(self.info.players_bots.into()) }
fn has_password(&self) -> Option<bool> { Some(self.info.has_password) }
fn players(&self) -> Option<Vec<&dyn CommonPlayer>> {
self.players
.as_ref()
.map(|p| p.iter().map(|p| p as &dyn CommonPlayer).collect())
}
}
/// General server information's.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ServerInfo {
/// Protocol used by the server.
pub protocol_version: u8,
/// Name of the server.
pub name: String,
/// Map name.
pub map: String,
/// Name of the folder containing the game files.
pub folder: String,
/// The server-declared name of the game/game mode.
pub game_mode: String,
/// [Steam Application ID](https://developer.valvesoftware.com/wiki/Steam_Application_ID) of game.
pub appid: u32,
/// Number of players on the server.
pub players_online: u8,
/// Maximum number of players the server reports it can hold.
pub players_maximum: u8,
/// Number of bots on the server.
pub players_bots: u8,
/// Dedicated, NonDedicated or SourceTV
pub server_type: Server,
/// The Operating System that the server is on.
pub environment_type: Environment,
/// Indicates whether the server requires a password.
pub has_password: bool,
/// Indicates whether the server uses VAC.
pub vac_secured: bool,
/// [The ship](https://developer.valvesoftware.com/wiki/The_Ship) extra data
pub the_ship: Option<TheShip>,
/// Version of the game installed on the server.
pub game_version: String,
/// Some extra data that the server might provide or not.
pub extra_data: Option<ExtraData>,
/// GoldSrc only: Indicates whether the hosted game is a mod.
pub is_mod: bool,
/// GoldSrc only: If the game is a mod, provide additional data.
pub mod_data: Option<ModData>,
}
/// A server player.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct ServerPlayer {
/// Player's name.
pub name: String,
/// General score.
pub score: i32,
/// How long a player has been in the server (seconds).
pub duration: f32,
/// Only for [the ship](https://developer.valvesoftware.com/wiki/The_Ship): deaths count
pub deaths: Option<u32>, // the_ship
/// Only for [the ship](https://developer.valvesoftware.com/wiki/The_Ship): money amount
pub money: Option<u32>, // the_ship
}
impl CommonPlayer for ServerPlayer {
fn as_original(&self) -> GenericPlayer { GenericPlayer::Valve(self) }
fn name(&self) -> &str { &self.name }
fn score(&self) -> Option<i32> { Some(self.score) }
}
/// Only present for [the ship](https://developer.valvesoftware.com/wiki/The_Ship).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TheShip {
pub mode: u8,
pub witnesses: u8,
pub duration: u8,
}
/// Some extra data that the server might provide or not.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ExtraData {
/// The server's game port number.
pub port: Option<u16>,
/// Server's SteamID.
pub steam_id: Option<u64>,
/// SourceTV's port.
pub tv_port: Option<u16>,
/// SourceTV's name.
pub tv_name: Option<String>,
/// Keywords that describe the server according to it.
pub keywords: Option<String>,
/// The server's 64-bit GameID.
pub game_id: Option<u64>,
}
/// Data related to GoldSrc Mod response.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ModData {
pub link: String,
pub download_link: String,
pub version: u32,
pub size: u32,
pub multiplayer_only: bool,
pub has_own_dll: bool,
}
pub(crate) type ExtractedData = (
Option<u16>,
Option<u64>,
Option<u16>,
Option<String>,
Option<String>,
);
pub(crate) fn get_optional_extracted_data(data: Option<ExtraData>) -> ExtractedData {
match data {
None => (None, None, None, None, None),
Some(ed) => (ed.port, ed.steam_id, ed.tv_port, ed.tv_name, ed.keywords),
}
}
#[derive(Debug, Clone)]
pub(crate) struct Packet {
pub header: u32,
pub kind: u8,
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(kind: u8, payload: Vec<u8>) -> Self {
Self {
header: u32::MAX, // FF FF FF FF
kind,
payload,
}
}
pub fn new_from_bufferer(buffer: &mut Buffer<LittleEndian>) -> GDResult<Self> {
Ok(Self {
header: buffer.read::<u32>()?,
kind: buffer.read::<u8>()?,
payload: buffer.remaining_bytes().to_vec(),
})
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::from(self.header.to_be_bytes());
buf.push(self.kind);
buf.extend(&self.payload);
buf
}
}
/// The type of the request, see the [protocol](https://developer.valvesoftware.com/wiki/Server_queries).
#[derive(Eq, PartialEq, Copy, Clone)]
#[repr(u8)]
pub(crate) enum Request {
/// Known as `A2S_INFO`
Info = 0x54,
/// Known as `A2S_PLAYERS`
Players = 0x55,
/// Known as `A2S_RULES`
Rules = 0x56,
}
impl Request {
pub fn get_default_payload(self) -> Vec<u8> {
match self {
Self::Info => String::from("Source Engine Query\0").into_bytes(),
_ => vec![0xFF, 0xFF, 0xFF, 0xFF],
}
}
}
/// Supported steam apps
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SteamApp {
/// Counter-Strike
COUNTERSTRIKE,
/// Creativerse
CREATIVERSE,
/// Team Fortress Classic
TFC,
/// Day of Defeat
DOD,
/// Counter-Strike: Condition Zero
CSCZ,
/// Counter-Strike: Source
CSS,
/// Day of Defeat: Source
DODS,
/// Half-Life 2 Deathmatch
HL2D,
/// Half-Life Deathmatch: Source
HLDS,
/// Team Fortress 2
TEAMFORTRESS2,
/// Left 4 Dead
LEFT4DEAD,
/// Left 4 Dead
LEFT4DEAD2,
/// Alien Swarm
ALIENSWARM,
/// Counter-Strike: Global Offensive
CSGO,
/// The Ship
THESHIP,
/// Garry's Mod
GARRYSMOD,
/// Age of Chivalry
AOC,
/// Insurgency: Modern Infantry Combat
IMIC,
/// ARMA 2: Operation Arrowhead
A2OA,
/// Project Zomboid
PROJECTZOMBOID,
/// Insurgency
INSURGENCY,
/// Sven Co-op
SCO,
/// 7 Days To Die
SD2D,
/// Rust
RUST,
/// Ballistic Overkill
BALLISTICOVERKILL,
/// Don't Starve Together
DST,
/// BrainBread 2
BRAINBREAD2,
/// Codename CURE
CODENAMECURE,
/// Black Mesa
BLACKMESA,
/// Colony Survival
COLONYSURVIVAL,
/// Avorion
AVORION,
/// Day of Infamy
DOI,
/// The Forest
THEFOREST,
/// Unturned
UNTURNED,
/// ARK: Survival Evolved
ASE,
/// Battalion 1944
BATTALION1944,
/// Insurgency: Sandstorm
INSURGENCYSANDSTORM,
/// Alien Swarm: Reactive Drop
ASRD,
/// Risk of Rain 2
ROR2,
/// Operation: Harsh Doorstop
OHD,
/// Onset
ONSET,
/// V Rising
VRISING,
/// Hell Let Loose
HLL,
/// Barotrauma
BAROTRAUMA,
}
impl SteamApp {
/// Get the specified app as engine.
pub const fn as_engine(&self) -> Engine {
match self {
Self::CSS => Engine::new_source(240),
Self::DODS => Engine::new_source(300),
Self::HL2D => Engine::new_source(320),
Self::HLDS => Engine::new_source(360),
Self::TEAMFORTRESS2 => Engine::new_source(440),
Self::LEFT4DEAD => Engine::new_source(500),
Self::LEFT4DEAD2 => Engine::new_source(550),
Self::ALIENSWARM => Engine::new_source(630),
Self::CSGO => Engine::new_source(730),
Self::THESHIP => Engine::new_source(2400),
Self::GARRYSMOD => Engine::new_source(4000),
Self::AOC => Engine::new_source(17510),
Self::IMIC => Engine::new_source(17700),
Self::A2OA => Engine::new_source(33930),
Self::PROJECTZOMBOID => Engine::new_source(108_600),
Self::INSURGENCY => Engine::new_source(222_880),
Self::SD2D => Engine::new_source(251_570),
Self::RUST => Engine::new_source(252_490),
Self::CREATIVERSE => Engine::new_source(280_790),
Self::BALLISTICOVERKILL => Engine::new_source(296_300),
Self::DST => Engine::new_source(322_320),
Self::BRAINBREAD2 => Engine::new_source(346_330),
Self::CODENAMECURE => Engine::new_source(355_180),
Self::BLACKMESA => Engine::new_source(362_890),
Self::COLONYSURVIVAL => Engine::new_source(366_090),
Self::AVORION => Engine::new_source(445_220),
Self::DOI => Engine::new_source(447_820),
Self::THEFOREST => Engine::new_source(556_450),
Self::UNTURNED => Engine::new_source(304_930),
Self::ASE => Engine::new_source(346_110),
Self::BATTALION1944 => Engine::new_source(489_940),
Self::INSURGENCYSANDSTORM => Engine::new_source(581_320),
Self::ASRD => Engine::new_source(563_560),
Self::BAROTRAUMA => Engine::new_source(602960),
Self::ROR2 => Engine::new_source(632_360),
Self::OHD => Engine::new_source_with_dedicated(736_590, 950_900),
Self::ONSET => Engine::new_source(1_105_810),
Self::VRISING => Engine::new_source(1_604_030),
Self::HLL => Engine::new_source(686_810),
_ => Engine::GoldSrc(false), // CS - 10, TFC - 20, DOD - 30, CSCZ - 80, SC - 225840
}
}
}
/// Engine type.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Engine {
/// A Source game, the argument represents the possible steam app ids, if
/// its **None**, let the query find it, if its **Some**, the query
/// fails if the response id is not the first one, which is the game app
/// id, or the other one, which is the dedicated server app id.
Source(Option<(u32, Option<u32>)>),
/// A GoldSrc game, the argument indicates whether to enforce
/// requesting the obsolete A2S_INFO response or not.
GoldSrc(bool),
}
impl Engine {
pub const fn new_source(appid: u32) -> Self { Self::Source(Some((appid, None))) }
pub const fn new_source_with_dedicated(appid: u32, dedicated_appid: u32) -> Self {
Self::Source(Some((appid, Some(dedicated_appid))))
}
}
/// What data to gather, purely used only with the query function.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GatheringSettings {
pub players: bool,
pub rules: bool,
pub check_app_id: bool,
}
impl Default for GatheringSettings {
/// Default values are true for both the players and the rules.
fn default() -> Self {
Self {
players: true,
rules: true,
check_app_id: true,
}
}
}
impl From<ExtraRequestSettings> for GatheringSettings {
fn from(value: ExtraRequestSettings) -> Self {
let default = Self::default();
Self {
players: value.gather_players.unwrap_or(default.players),
rules: value.gather_rules.unwrap_or(default.rules),
check_app_id: value.check_app_id.unwrap_or(default.check_app_id),
}
}
}
/// Generic response types that are used by many games, they are the protocol
/// ones, but without the unnecessary bits (example: the **The Ship**-only
/// fields).
pub mod game {
use super::{Server, ServerPlayer};
use crate::protocols::valve::types::get_optional_extracted_data;
use std::collections::HashMap;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// A player's details.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct Player {
/// Player's name.
pub name: String,
/// Player's score.
pub score: i32,
/// How long a player has been in the server (seconds).
pub duration: f32,
}
impl Player {
pub fn from_valve_response(player: &ServerPlayer) -> Self {
Self {
name: player.name.clone(),
score: player.score,
duration: player.duration,
}
}
}
/// The query response.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct Response {
/// Protocol used by the server.
pub protocol: u8,
/// Name of the server.
pub name: String,
/// Map name.
pub map: String,
/// The name of the game.
pub game: String,
/// Server's app id.
pub appid: u32,
/// Number of players on the server.
pub players_online: u8,
/// Details about the server's players (not all players necessarily).
pub players_details: Vec<Player>,
/// Maximum number of players the server reports it can hold.
pub players_maximum: u8,
/// Number of bots on the server.
pub players_bots: u8,
/// Dedicated, NonDedicated or SourceTV
pub server_type: Server,
/// Indicates whether the server requires a password.
pub has_password: bool,
/// Indicated whether the server uses VAC.
pub vac_secured: bool,
/// Version of the game installed on the server.
pub version: String,
/// The server's reported connection port.
pub port: Option<u16>,
/// Server's SteamID.
pub steam_id: Option<u64>,
/// SourceTV's connection port.
pub tv_port: Option<u16>,
/// SourceTV's name.
pub tv_name: Option<String>,
/// Keywords that describe the server according to it.
pub keywords: Option<String>,
/// Server's rules.
pub rules: HashMap<String, String>,
}
impl Response {
pub fn new_from_valve_response(response: super::Response) -> Self {
let (port, steam_id, tv_port, tv_name, keywords) = get_optional_extracted_data(response.info.extra_data);
Self {
protocol: response.info.protocol_version,
name: response.info.name,
map: response.info.map,
game: response.info.game_mode,
appid: response.info.appid,
players_online: response.info.players_online,
players_details: response
.players
.unwrap_or_default()
.iter()
.map(Player::from_valve_response)
.collect(),
players_maximum: response.info.players_maximum,
players_bots: response.info.players_bots,
server_type: response.info.server_type,
has_password: response.info.has_password,
vac_secured: response.info.vac_secured,
version: response.info.game_version,
port,
steam_id,
tv_port,
tv_name,
keywords,
rules: response.rules.unwrap_or_default(),
}
}
}
}