[Crate] Add formatting (#22)

* chore: add standard for formatting

* chore: manually tidy up imports and format

* chore: remove vscode and add to gitignore

* chore: alphabetically order and fix

* chore: format

* chore: fix format issue with payload

* chore: format as merge had unformatted code

* [format] Fix comments, change max width and binop operator

---------

Co-authored-by: CosminPerRam <cosmin.p@live.com>
This commit is contained in:
Cain 2023-03-14 09:31:37 +01:00 committed by GitHub
parent e023e13236
commit 1b13d39856
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
71 changed files with 3165 additions and 2593 deletions

1
.gitignore vendored
View file

@ -12,5 +12,6 @@ Cargo.lock
# Others # Others
.idea/ .idea/
.venv/ .venv/
.vscode/
test_everything.py test_everything.py

72
.rustfmt.toml Normal file
View file

@ -0,0 +1,72 @@
attr_fn_like_width = 70
array_width = 60
binop_separator = "Front"
blank_lines_lower_bound = 0
blank_lines_upper_bound = 1
brace_style = "PreferSameLine"
chain_width = 60
color = "Auto"
combine_control_expr = false
comment_width = 80
condense_wildcard_suffixes = true
control_brace_style = "AlwaysSameLine"
disable_all_formatting = false
doc_comment_code_block_width = 100
edition = "2021"
emit_mode = "Files"
empty_item_single_line = true
error_on_line_overflow = false
error_on_unformatted = false
fn_call_width = 60
fn_params_layout = "Tall"
fn_single_line = true
force_explicit_abi = true
force_multiline_blocks = true
format_generated_files = true
format_macro_bodies = true
format_strings = true
group_imports = "Preserve"
hard_tabs = false
hide_parse_errors = false
hex_literal_case = "Preserve"
ignore = []
indent_style = "Block"
imports_granularity = "Preserve"
imports_indent = "Block"
imports_layout = "HorizontalVertical"
inline_attribute_width = 0
make_backup = false
match_arm_blocks = true
match_arm_leading_pipes = "Never"
match_block_trailing_comma = false
max_width = 120
merge_derives = true
newline_style = "Auto"
normalize_comments = true
normalize_doc_attributes = false
overflow_delimited_expr = false
reorder_impl_items = false
reorder_imports = true
reorder_modules = true
required_version = "1.5.2"
short_array_element_width_threshold = 10
single_line_if_else_max_width = 50
skip_children = false
space_after_colon = true
space_before_colon = false
spaces_around_ranges = true
struct_field_align_threshold = 0
struct_lit_single_line = true
struct_lit_width = 18
struct_variant_width = 35
tab_spaces = 4
trailing_comma = "Vertical"
trailing_semicolon = true
type_punctuation_density = "Wide"
unstable_features = false
use_field_init_shorthand = false
use_small_heuristics = "Default"
use_try_shorthand = true
version = "Two"
where_single_line = true
wrap_comments = true

View file

@ -1,96 +1,172 @@
use gamedig::protocols::gamespy;
use std::env; use gamedig::protocols::minecraft::LegacyGroup;
use gamedig::{aliens, aoc, arma2oa, ase, asrd, avorion, bat1944, bb2, bf1942, bm, bo, ccure, cosu, cs, cscz, csgo, css, dod, dods, doi, dst, GDResult, gm, hl2dm, hldms, ins, insmic, inss, l4d, l4d2, mc, ohd, onset, pz, ror2, rust, sc, sdtd, ss, tf, tf2, tfc, ts, unturned, ut, vr}; use gamedig::protocols::valve;
use gamedig::protocols::minecraft::LegacyGroup; use gamedig::protocols::valve::Engine;
use gamedig::protocols::valve; use gamedig::{
use gamedig::protocols::valve::Engine; aliens,
use gamedig::protocols::gamespy; aoc,
arma2oa,
fn main() -> GDResult<()> { ase,
let args: Vec<String> = env::args().collect(); asrd,
avorion,
if args.len() == 1 || args[1] == "help".to_string() { bat1944,
println!("Usage: <game> <ip> <port>"); bb2,
println!(" <game> - any game, example: tf2"); bf1942,
println!(" <ip> - an ip, example: 192.168.0.0"); bm,
println!(" <port> - an port, optional, example: 27015"); bo,
return Ok(()); ccure,
} else if args.len() < 3 { cosu,
println!("Minimum number of arguments: 3, try 'help' to see the details."); cs,
return Ok(()); cscz,
} csgo,
css,
let ip = args[2].as_str(); dod,
let port = match args.len() == 4 { dods,
false => { doi,
if args[1].starts_with("_") { dst,
panic!("The port must be specified with an anonymous query.") gm,
} hl2dm,
hldms,
None ins,
}, insmic,
true => Some(args[3].parse::<u16>().expect("Invalid port!")) inss,
}; l4d,
l4d2,
match args[1].as_str() { mc,
"aliens" => println!("{:#?}", aliens::query(ip, port)?), ohd,
"asrd" => println!("{:#?}", asrd::query(ip, port)?), onset,
"csgo" => println!("{:#?}", csgo::query(ip, port)?), pz,
"css" => println!("{:#?}", css::query(ip, port)?), ror2,
"dods" => println!("{:#?}", dods::query(ip, port)?), rust,
"gm" => println!("{:#?}", gm::query(ip, port)?), sc,
"hl2dm" => println!("{:#?}", hl2dm::query(ip, port)?), sdtd,
"tf2" => println!("{:#?}", tf2::query(ip, port)?), ss,
"insmic" => println!("{:#?}", insmic::query(ip, port)?), tf,
"ins" => println!("{:#?}", ins::query(ip, port)?), tf2,
"inss" => println!("{:#?}", inss::query(ip, port)?), tfc,
"l4d" => println!("{:#?}", l4d::query(ip, port)?), ts,
"l4d2" => println!("{:#?}", l4d2::query(ip, port)?), unturned,
"ts" => println!("{:#?}", ts::query(ip, port)?), ut,
"cscz" => println!("{:#?}", cscz::query(ip, port)?), vr,
"dod" => println!("{:#?}", dod::query(ip, port)?), GDResult,
"_src" => println!("{:#?}", valve::query(ip, port.unwrap(), Engine::Source(None), None, None)?), };
"_gld" => println!("{:#?}", valve::query(ip, port.unwrap(), Engine::GoldSrc(false), None, None)?), use std::env;
"_gld_f" => println!("{:#?}", valve::query(ip, port.unwrap(), Engine::GoldSrc(true), None, None)?),
"mc" => println!("{:#?}", mc::query(ip, port)?), fn main() -> GDResult<()> {
"mc_java" => println!("{:#?}", mc::query_java(ip, port)?), let args: Vec<String> = env::args().collect();
"mc_bedrock" => println!("{:#?}", mc::query_bedrock(ip, port)?),
"mc_legacy" => println!("{:#?}", mc::query_legacy(ip, port)?), if args.len() == 1 || args[1] == "help".to_string() {
"mc_legacy_vb1_8" => println!("{:#?}", mc::query_legacy_specific(LegacyGroup::VB1_8, ip, port)?), println!("Usage: <game> <ip> <port>");
"mc_legacy_v1_4" => println!("{:#?}", mc::query_legacy_specific(LegacyGroup::V1_4, ip, port)?), println!(" <game> - any game, example: tf2");
"mc_legacy_v1_6" => println!("{:#?}", mc::query_legacy_specific(LegacyGroup::V1_6, ip, port)?), println!(" <ip> - an ip, example: 192.168.0.0");
"7dtd" => println!("{:#?}", sdtd::query(ip, port)?), println!(" <port> - an port, optional, example: 27015");
"ase" => println!("{:#?}", ase::query(ip, port)?), return Ok(());
"unturned" => println!("{:#?}", unturned::query(ip, port)?), } else if args.len() < 3 {
"tf" => println!("{:#?}", tf::query(ip, port)?), println!("Minimum number of arguments: 3, try 'help' to see the details.");
"tfc" => println!("{:#?}", tfc::query(ip, port)?), return Ok(());
"sc" => println!("{:#?}", sc::query(ip, port)?), }
"rust" => println!("{:#?}", rust::query(ip, port)?),
"cs" => println!("{:#?}", cs::query(ip, port)?), let ip = args[2].as_str();
"arma2oa" => println!("{:#?}", arma2oa::query(ip, port)?), let port = match args.len() == 4 {
"doi" => println!("{:#?}", doi::query(ip, port)?), false => {
"hldms" => println!("{:#?}", hldms::query(ip, port)?), if args[1].starts_with("_") {
"ror2" => println!("{:#?}", ror2::query(ip, port)?), panic!("The port must be specified with an anonymous query.")
"bat1944" => println!("{:#?}", bat1944::query(ip, port)?), }
"bm" => println!("{:#?}", bm::query(ip, port)?),
"pz" => println!("{:#?}", pz::query(ip, port)?), None
"aoc" => println!("{:#?}", aoc::query(ip, port)?), }
"dst" => println!("{:#?}", dst::query(ip, port)?), true => Some(args[3].parse::<u16>().expect("Invalid port!")),
"cosu" => println!("{:#?}", cosu::query(ip, port)?), };
"onset" => println!("{:#?}", onset::query(ip, port)?),
"ccure" => println!("{:#?}", ccure::query(ip, port)?), match args[1].as_str() {
"bo" => println!("{:#?}", bo::query(ip, port)?), "aliens" => println!("{:#?}", aliens::query(ip, port)?),
"bb2" => println!("{:#?}", bb2::query(ip, port)?), "asrd" => println!("{:#?}", asrd::query(ip, port)?),
"avorion" => println!("{:#?}", avorion::query(ip, port)?), "csgo" => println!("{:#?}", csgo::query(ip, port)?),
"ohd" => println!("{:#?}", ohd::query(ip, port)?), "css" => println!("{:#?}", css::query(ip, port)?),
"vr" => println!("{:#?}", vr::query(ip, port)?), "dods" => println!("{:#?}", dods::query(ip, port)?),
"_gamespy1" => println!("{:#?}", gamespy::one::query(ip, port.unwrap(), None)), "gm" => println!("{:#?}", gm::query(ip, port)?),
"_gamespy1_vars" => println!("{:#?}", gamespy::one::query_vars(ip, port.unwrap(), None)), "hl2dm" => println!("{:#?}", hl2dm::query(ip, port)?),
"ut" => println!("{:#?}", ut::query(ip, port)), "tf2" => println!("{:#?}", tf2::query(ip, port)?),
"bf1942" => println!("{:#?}", bf1942::query(ip, port)), "insmic" => println!("{:#?}", insmic::query(ip, port)?),
"ss" => println!("{:#?}", ss::query(ip, port)), "ins" => println!("{:#?}", ins::query(ip, port)?),
_ => panic!("Undefined game: {}", args[1]) "inss" => println!("{:#?}", inss::query(ip, port)?),
}; "l4d" => println!("{:#?}", l4d::query(ip, port)?),
"l4d2" => println!("{:#?}", l4d2::query(ip, port)?),
Ok(()) "ts" => println!("{:#?}", ts::query(ip, port)?),
} "cscz" => println!("{:#?}", cscz::query(ip, port)?),
"dod" => println!("{:#?}", dod::query(ip, port)?),
"_src" => {
println!(
"{:#?}",
valve::query(ip, port.unwrap(), Engine::Source(None), None, None)?
)
}
"_gld" => {
println!(
"{:#?}",
valve::query(ip, port.unwrap(), Engine::GoldSrc(false), None, None)?
)
}
"_gld_f" => {
println!(
"{:#?}",
valve::query(ip, port.unwrap(), Engine::GoldSrc(true), None, None)?
)
}
"mc" => println!("{:#?}", mc::query(ip, port)?),
"mc_java" => println!("{:#?}", mc::query_java(ip, port)?),
"mc_bedrock" => println!("{:#?}", mc::query_bedrock(ip, port)?),
"mc_legacy" => println!("{:#?}", mc::query_legacy(ip, port)?),
"mc_legacy_vb1_8" => {
println!(
"{:#?}",
mc::query_legacy_specific(LegacyGroup::VB1_8, ip, port)?
)
}
"mc_legacy_v1_4" => {
println!(
"{:#?}",
mc::query_legacy_specific(LegacyGroup::V1_4, ip, port)?
)
}
"mc_legacy_v1_6" => {
println!(
"{:#?}",
mc::query_legacy_specific(LegacyGroup::V1_6, ip, port)?
)
}
"7dtd" => println!("{:#?}", sdtd::query(ip, port)?),
"ase" => println!("{:#?}", ase::query(ip, port)?),
"unturned" => println!("{:#?}", unturned::query(ip, port)?),
"tf" => println!("{:#?}", tf::query(ip, port)?),
"tfc" => println!("{:#?}", tfc::query(ip, port)?),
"sc" => println!("{:#?}", sc::query(ip, port)?),
"rust" => println!("{:#?}", rust::query(ip, port)?),
"cs" => println!("{:#?}", cs::query(ip, port)?),
"arma2oa" => println!("{:#?}", arma2oa::query(ip, port)?),
"doi" => println!("{:#?}", doi::query(ip, port)?),
"hldms" => println!("{:#?}", hldms::query(ip, port)?),
"ror2" => println!("{:#?}", ror2::query(ip, port)?),
"bat1944" => println!("{:#?}", bat1944::query(ip, port)?),
"bm" => println!("{:#?}", bm::query(ip, port)?),
"pz" => println!("{:#?}", pz::query(ip, port)?),
"aoc" => println!("{:#?}", aoc::query(ip, port)?),
"dst" => println!("{:#?}", dst::query(ip, port)?),
"cosu" => println!("{:#?}", cosu::query(ip, port)?),
"onset" => println!("{:#?}", onset::query(ip, port)?),
"ccure" => println!("{:#?}", ccure::query(ip, port)?),
"bo" => println!("{:#?}", bo::query(ip, port)?),
"bb2" => println!("{:#?}", bb2::query(ip, port)?),
"avorion" => println!("{:#?}", avorion::query(ip, port)?),
"ohd" => println!("{:#?}", ohd::query(ip, port)?),
"vr" => println!("{:#?}", vr::query(ip, port)?),
"_gamespy1" => println!("{:#?}", gamespy::one::query(ip, port.unwrap(), None)),
"_gamespy1_vars" => println!("{:#?}", gamespy::one::query_vars(ip, port.unwrap(), None)),
"ut" => println!("{:#?}", ut::query(ip, port)),
"bf1942" => println!("{:#?}", bf1942::query(ip, port)),
"ss" => println!("{:#?}", ss::query(ip, port)),
_ => panic!("Undefined game: {}", args[1]),
};
Ok(())
}

View file

@ -1,12 +1,12 @@
use gamedig::games::mc;
use gamedig::games::mc;
fn main() {
fn main() { // or Some(<port>), None is the default protocol port (which is 25565 for java
//or Some(<port>), None is the default protocol port (which is 25565 for java and 19132 for bedrock) // and 19132 for bedrock)
let response = mc::query("127.0.0.1", None); let response = mc::query("127.0.0.1", None);
match response { match response {
Err(error) => println!("Couldn't query, error: {}", error), Err(error) => println!("Couldn't query, error: {}", error),
Ok(r) => println!("{:#?}", r) Ok(r) => println!("{:#?}", r),
} }
} }

View file

@ -1,10 +1,10 @@
use gamedig::games::tf2;
use gamedig::games::tf2;
fn main() {
fn main() { let response = tf2::query("127.0.0.1", None); // or Some(27015), None is the default protocol port (which is 27015)
let response = tf2::query("127.0.0.1", None); //or Some(27015), None is the default protocol port (which is 27015) match response {
match response { // Result type, must check what it is... // Result type, must check what it is...
Err(error) => println!("Couldn't query, error: {}", error), Err(error) => println!("Couldn't query, error: {}", error),
Ok(r) => println!("{:#?}", r) Ok(r) => println!("{:#?}", r),
} }
} }

View file

@ -1,15 +1,19 @@
use crate::GDResult; use crate::{
use crate::GDError::{PacketBad, PacketUnderflow}; GDError::{PacketBad, PacketUnderflow},
use byteorder::{ByteOrder, LittleEndian, BigEndian}; GDResult,
};
use byteorder::{BigEndian, ByteOrder, LittleEndian};
pub enum Endianess { pub enum Endianess {
Little, Big Little,
Big,
} }
pub struct Bufferer { pub struct Bufferer {
data: Vec<u8>, data: Vec<u8>,
endianess: Endianess, endianess: Endianess,
position: usize position: usize,
} }
impl Bufferer { impl Bufferer {
@ -17,13 +21,11 @@ impl Bufferer {
Bufferer { Bufferer {
data: data.to_vec(), data: data.to_vec(),
endianess, endianess,
position: 0 position: 0,
} }
} }
fn check_size(&self, by: usize) -> bool { fn check_size(&self, by: usize) -> bool { by > self.remaining_length() }
by > self.remaining_length()
}
pub fn get_u8(&mut self) -> GDResult<u8> { pub fn get_u8(&mut self) -> GDResult<u8> {
if self.check_size(1) { if self.check_size(1) {
@ -70,7 +72,7 @@ impl Bufferer {
let value = match self.endianess { let value = match self.endianess {
Endianess::Little => LittleEndian::read_f32(self.remaining_data()), Endianess::Little => LittleEndian::read_f32(self.remaining_data()),
Endianess::Big => BigEndian::read_f32(self.remaining_data()) Endianess::Big => BigEndian::read_f32(self.remaining_data()),
}; };
self.move_position_ahead(4); self.move_position_ahead(4);
@ -84,7 +86,7 @@ impl Bufferer {
let value = match self.endianess { let value = match self.endianess {
Endianess::Little => LittleEndian::read_u64(self.remaining_data()), Endianess::Little => LittleEndian::read_u64(self.remaining_data()),
Endianess::Big => BigEndian::read_u64(self.remaining_data()) Endianess::Big => BigEndian::read_u64(self.remaining_data()),
}; };
self.move_position_ahead(8); self.move_position_ahead(8);
@ -97,10 +99,10 @@ impl Bufferer {
return Err(PacketUnderflow); return Err(PacketUnderflow);
} }
let first_null_position = sub_buf.iter().position(|&x| x == 0) let first_null_position = sub_buf.iter().position(|&x| x == 0).ok_or(PacketBad)?;
.ok_or(PacketBad)?; let value = std::str::from_utf8(&sub_buf[.. first_null_position])
let value = std::str::from_utf8(&sub_buf[..first_null_position]) .map_err(|_| PacketBad)?
.map_err(|_| PacketBad)?.to_string(); .to_string();
self.move_position_ahead(value.len() + 1); self.move_position_ahead(value.len() + 1);
Ok(value) Ok(value)
@ -113,7 +115,8 @@ impl Bufferer {
} }
let value = std::str::from_utf8(sub_buf) let value = std::str::from_utf8(sub_buf)
.map_err(|_| PacketBad)?.to_string(); .map_err(|_| PacketBad)?
.to_string();
self.move_position_ahead(value.len()); self.move_position_ahead(value.len());
Ok(value) Ok(value)
@ -127,9 +130,11 @@ impl Bufferer {
let paired_buf: Vec<u16> = sub_buf let paired_buf: Vec<u16> = sub_buf
.chunks_exact(2) .chunks_exact(2)
.map(|pair| match self.endianess { .map(|pair| {
Endianess::Little => LittleEndian::read_u16(pair), match self.endianess {
Endianess::Big => BigEndian::read_u16(pair), Endianess::Little => LittleEndian::read_u16(pair),
Endianess::Big => BigEndian::read_u16(pair),
}
}) })
.collect(); .collect();
@ -139,29 +144,17 @@ impl Bufferer {
Ok(value) Ok(value)
} }
pub fn move_position_ahead(&mut self, by: usize) { pub fn move_position_ahead(&mut self, by: usize) { self.position += by; }
self.position += by;
}
pub fn move_position_backward(&mut self, by: usize) { pub fn move_position_backward(&mut self, by: usize) { self.position -= by; }
self.position -= by;
}
pub fn data_length(&self) -> usize { pub fn data_length(&self) -> usize { self.data.len() }
self.data.len()
}
pub fn remaining_data(&self) -> &[u8] { pub fn remaining_data(&self) -> &[u8] { &self.data[self.position ..] }
&self.data[self.position..]
}
pub fn remaining_data_vec(&self) -> Vec<u8> { pub fn remaining_data_vec(&self) -> Vec<u8> { self.remaining_data().to_vec() }
self.remaining_data().to_vec()
}
pub fn remaining_length(&self) -> usize { pub fn remaining_length(&self) -> usize { self.data_length() - self.position }
self.data_length() - self.position
}
pub fn as_endianess(&self, endianess: Endianess) -> Self { pub fn as_endianess(&self, endianess: Endianess) -> Self {
Bufferer { Bufferer {
@ -277,7 +270,10 @@ mod tests {
#[test] #[test]
fn get_string_utf16_le() { fn get_string_utf16_le() {
let mut buffer = Bufferer::new_with_data(Endianess::Little, &[0x48, 0x00, 0x65, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6f, 0x00]); let mut buffer = Bufferer::new_with_data(
Endianess::Little,
&[0x48, 0x00, 0x65, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6f, 0x00],
);
assert_eq!(buffer.get_string_utf16().unwrap(), "Hello"); assert_eq!(buffer.get_string_utf16().unwrap(), "Hello");
assert_eq!(buffer.remaining_length(), 0); assert_eq!(buffer.remaining_length(), 0);
@ -286,7 +282,10 @@ mod tests {
#[test] #[test]
fn get_string_utf16_be() { fn get_string_utf16_be() {
let mut buffer = Bufferer::new_with_data(Endianess::Big, &[0x00, 0x48, 0x00, 0x65, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6f]); let mut buffer = Bufferer::new_with_data(
Endianess::Big,
&[0x00, 0x48, 0x00, 0x65, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6f],
);
assert_eq!(buffer.get_string_utf16().unwrap(), "Hello"); assert_eq!(buffer.get_string_utf16().unwrap(), "Hello");
assert_eq!(buffer.remaining_length(), 0); assert_eq!(buffer.remaining_length(), 0);

View file

@ -1,6 +1,7 @@
//! The library's possible errors. use std::{
use std::fmt; error::Error,
use std::{error::Error, fmt::Formatter}; fmt::{self, Formatter},
};
/// Result of Type and GDError. /// Result of Type and GDError.
pub type GDResult<T> = Result<T, GDError>; pub type GDResult<T> = Result<T, GDError>;
@ -43,9 +44,7 @@ pub enum GDError {
impl Error for GDError {} impl Error for GDError {}
impl fmt::Display for GDError { impl fmt::Display for GDError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) }
write!(f, "{:?}", self)
}
} }
#[cfg(test)] #[cfg(test)]

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::ALIENS.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::ALIENS.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::AOC.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::AOC.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(2304), SteamApp::ARMA2OA.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(2304),
SteamApp::ARMA2OA.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::ASE.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::ASE.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::ASRD.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::ASRD.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27020), SteamApp::AVORION.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27020),
SteamApp::AVORION.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,10 +1,17 @@
use crate::GDError::TypeParse; use crate::{
use crate::GDResult; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve; GDError::TypeParse,
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let mut valve_response = valve::query(address, port.unwrap_or(7780), SteamApp::BAT1944.as_engine(), None, None)?; let mut valve_response = valve::query(
address,
port.unwrap_or(7780),
SteamApp::BAT1944.as_engine(),
None,
None,
)?;
if let Some(rules) = &mut valve_response.rules { if let Some(rules) = &mut valve_response.rules {
if let Some(bat_max_players) = rules.get("bat_max_players_i") { if let Some(bat_max_players) = rules.get("bat_max_players_i") {

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::BB2.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::BB2.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,6 +1,7 @@
use crate::GDResult; use crate::{
use crate::protocols::gamespy; protocols::gamespy::{self, Response},
use crate::protocols::gamespy::Response; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<Response> {
gamespy::one::query(address, port.unwrap_or(23000), None) gamespy::one::query(address, port.unwrap_or(23000), None)

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::BM.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::BM.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27016), SteamApp::BO.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27016),
SteamApp::BO.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::CCURE.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::CCURE.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27004), SteamApp::COSU.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27004),
SteamApp::COSU.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::CS.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::CS.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::CSCZ.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::CSCZ.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::CSGO.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::CSGO.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::CSS.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::CSS.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::DOD.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::DOD.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::DODS.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::DODS.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::DOI.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::DOI.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27016), SteamApp::DST.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27016),
SteamApp::DST.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27016), SteamApp::GM.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27016),
SteamApp::GM.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::HL2DM.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::HL2DM.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::HLDMS.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::HLDMS.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::INS.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::INS.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::INSMIC.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::INSMIC.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27131), SteamApp::INSS.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27131),
SteamApp::INSS.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::L4D.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::L4D.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::L4D2.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::L4D2.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,48 +1,47 @@
use crate::{GDError, GDResult}; use crate::{
use crate::protocols::minecraft; protocols::minecraft::{self, BedrockResponse, JavaResponse, LegacyGroup},
use crate::protocols::minecraft::{JavaResponse, LegacyGroup, BedrockResponse}; GDError,
GDResult,
/// Query with all the protocol variants one by one (Java -> Bedrock -> Legacy (1.6 -> 1.4 -> Beta 1.8)). };
pub fn query(address: &str, port: Option<u16>) -> GDResult<JavaResponse> {
if let Ok(response) = query_java(address, port) { /// Query with all the protocol variants one by one (Java -> Bedrock -> Legacy
return Ok(response); /// (1.6 -> 1.4 -> Beta 1.8)).
} pub fn query(address: &str, port: Option<u16>) -> GDResult<JavaResponse> {
if let Ok(response) = query_java(address, port) {
if let Ok(response) = query_bedrock(address, port) { return Ok(response);
return Ok(JavaResponse::from_bedrock_response(response)); }
}
if let Ok(response) = query_bedrock(address, port) {
if let Ok(response) = query_legacy(address, port) { return Ok(JavaResponse::from_bedrock_response(response));
return Ok(response); }
}
if let Ok(response) = query_legacy(address, port) {
Err(GDError::AutoQuery) return Ok(response);
} }
/// Query a Java Server. Err(GDError::AutoQuery)
pub fn query_java(address: &str, port: Option<u16>) -> GDResult<JavaResponse> { }
minecraft::query_java(address, port_or_java_default(port), None)
} /// Query a Java Server.
pub fn query_java(address: &str, port: Option<u16>) -> GDResult<JavaResponse> {
/// Query a (Java) Legacy Server (1.6 -> 1.4 -> Beta 1.8). minecraft::query_java(address, port_or_java_default(port), None)
pub fn query_legacy(address: &str, port: Option<u16>) -> GDResult<JavaResponse> { }
minecraft::query_legacy(address, port_or_java_default(port), None)
} /// Query a (Java) Legacy Server (1.6 -> 1.4 -> Beta 1.8).
pub fn query_legacy(address: &str, port: Option<u16>) -> GDResult<JavaResponse> {
/// Query a specific (Java) Legacy Server. minecraft::query_legacy(address, port_or_java_default(port), None)
pub fn query_legacy_specific(group: LegacyGroup, address: &str, port: Option<u16>) -> GDResult<JavaResponse> { }
minecraft::query_legacy_specific(group, address, port_or_java_default(port), None)
} /// Query a specific (Java) Legacy Server.
pub fn query_legacy_specific(group: LegacyGroup, address: &str, port: Option<u16>) -> GDResult<JavaResponse> {
/// Query a Bedrock Server. minecraft::query_legacy_specific(group, address, port_or_java_default(port), None)
pub fn query_bedrock(address: &str, port: Option<u16>) -> GDResult<BedrockResponse> { }
minecraft::query_bedrock(address, port_or_bedrock_default(port), None)
} /// Query a Bedrock Server.
pub fn query_bedrock(address: &str, port: Option<u16>) -> GDResult<BedrockResponse> {
fn port_or_java_default(port: Option<u16>) -> u16 { minecraft::query_bedrock(address, port_or_bedrock_default(port), None)
port.unwrap_or(25565) }
}
fn port_or_java_default(port: Option<u16>) -> u16 { port.unwrap_or(25565) }
fn port_or_bedrock_default(port: Option<u16>) -> u16 {
port.unwrap_or(19132) fn port_or_bedrock_default(port: Option<u16>) -> u16 { port.unwrap_or(19132) }
}

View file

@ -1,93 +1,92 @@
//! Currently supported games.
//! Currently supported games.
/// Alien Swarm
/// Team Fortress 2 pub mod aliens;
pub mod tf2; /// Age of Chivalry
/// The Ship pub mod aoc;
pub mod ts; /// ARMA 2: Operation Arrowhead
/// Counter-Strike: Global Offensive pub mod arma2oa;
pub mod csgo; /// ARK: Survival Evolved
/// Counter-Strike: Source pub mod ase;
pub mod css; /// Alien Swarm: Reactive Drop
/// Day of Defeat: Source pub mod asrd;
pub mod dods; /// Avorion
/// Garry's Mod pub mod avorion;
pub mod gm; /// Battalion 1944
/// Left 4 Dead pub mod bat1944;
pub mod l4d; /// BrainBread 2
/// Left 4 Dead 2 pub mod bb2;
pub mod l4d2; /// Battlefield 1942
/// Half-Life 2 Deathmatch pub mod bf1942;
pub mod hl2dm; /// Black Mesa
/// Alien Swarm pub mod bm;
pub mod aliens; /// Ballistic Overkill
/// Alien Swarm: Reactive Drop pub mod bo;
pub mod asrd; /// Codename CURE
/// Insurgency pub mod ccure;
pub mod ins; /// Colony Survival
/// Insurgency: Sandstorm pub mod cosu;
pub mod inss; /// Counter-Strike
/// Insurgency: Modern Infantry Combat pub mod cs;
pub mod insmic; /// Counter Strike: Condition Zero
/// Counter Strike: Condition Zero pub mod cscz;
pub mod cscz; /// Counter-Strike: Global Offensive
/// Day of Defeat pub mod csgo;
pub mod dod; /// Counter-Strike: Source
/// Minecraft pub mod css;
pub mod mc; /// Day of Defeat
/// 7 Days To Die pub mod dod;
pub mod sdtd; /// Day of Defeat: Source
/// ARK: Survival Evolved pub mod dods;
pub mod ase; /// Day of Infamy
/// Unturned pub mod doi;
pub mod unturned; /// Don't Starve Together
/// The Forest pub mod dst;
pub mod tf; /// Garry's Mod
/// Team Fortress Classic pub mod gm;
pub mod tfc; /// Half-Life 2 Deathmatch
/// Sven Co-op pub mod hl2dm;
pub mod sc; /// Half-Life Deathmatch: Source
/// Rust pub mod hldms;
pub mod rust; /// Insurgency
/// Counter-Strike pub mod ins;
pub mod cs; /// Insurgency: Modern Infantry Combat
/// ARMA 2: Operation Arrowhead pub mod insmic;
pub mod arma2oa; /// Insurgency: Sandstorm
/// Day of Infamy pub mod inss;
pub mod doi; /// Left 4 Dead
/// Half-Life Deathmatch: Source pub mod l4d;
pub mod hldms; /// Left 4 Dead 2
/// Risk of Rain 2 pub mod l4d2;
pub mod ror2; /// Minecraft
/// Battalion 1944 pub mod mc;
pub mod bat1944; /// Operation: Harsh Doorstop
/// Black Mesa pub mod ohd;
pub mod bm; /// Onset
/// Project Zomboid pub mod onset;
pub mod pz; /// Project Zomboid
/// Age of Chivalry pub mod pz;
pub mod aoc; /// Risk of Rain 2
/// Don't Starve Together pub mod ror2;
pub mod dst; /// Rust
/// Colony Survival pub mod rust;
pub mod cosu; /// Sven Co-op
/// Onset pub mod sc;
pub mod onset; /// 7 Days To Die
/// Codename CURE pub mod sdtd;
pub mod ccure; /// Serious Sam
/// Ballistic Overkill pub mod ss;
pub mod bo; /// The Forest
/// BrainBread 2 pub mod tf;
pub mod bb2; /// Team Fortress 2
/// Avorion pub mod tf2;
pub mod avorion; /// Team Fortress Classic
/// Operation: Harsh Doorstop pub mod tfc;
pub mod ohd; /// The Ship
/// V Rising pub mod ts;
pub mod vr; /// Unturned
/// Unreal Tournament pub mod unturned;
pub mod ut; /// Unreal Tournament
/// Battlefield 1942 pub mod ut;
pub mod bf1942; /// V Rising
/// Serious Sam pub mod vr;
pub mod ss;

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27005), SteamApp::OHD.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27005),
SteamApp::OHD.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(7776), SteamApp::ONSET.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(7776),
SteamApp::ONSET.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(16261), SteamApp::PZ.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(16261),
SteamApp::PZ.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27016), SteamApp::ROR2.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27016),
SteamApp::ROR2.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::RUST.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::RUST.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::SC.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::SC.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(26900), SteamApp::SDTD.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(26900),
SteamApp::SDTD.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,6 +1,7 @@
use crate::GDResult; use crate::{
use crate::protocols::gamespy; protocols::gamespy::{self, Response},
use crate::protocols::gamespy::Response; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<Response> {
gamespy::one::query(address, port.unwrap_or(25601), None) gamespy::one::query(address, port.unwrap_or(25601), None)

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27016), SteamApp::TF.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27016),
SteamApp::TF.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::TF2.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::TF2.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::TFC.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::TFC.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,93 +1,106 @@
use std::collections::HashMap; use crate::{
use crate::GDResult; protocols::valve::{self, get_optional_extracted_data, Server, ServerPlayer, SteamApp},
use crate::protocols::valve; GDResult,
use crate::protocols::valve::{Server, ServerPlayer, get_optional_extracted_data, SteamApp}; };
#[cfg (feature = "serde")] use std::collections::HashMap;
use serde::{Serialize, Deserialize};
#[cfg(feature = "serde")]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct TheShipPlayer { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub name: String, #[derive(Debug, Clone, PartialEq, PartialOrd)]
pub score: u32, pub struct TheShipPlayer {
pub duration: f32, pub name: String,
pub deaths: u32, pub score: u32,
pub money: u32 pub duration: f32,
} pub deaths: u32,
pub money: u32,
impl TheShipPlayer { }
pub fn new_from_valve_player(player: &ServerPlayer) -> Self {
Self { impl TheShipPlayer {
name: player.name.clone(), pub fn new_from_valve_player(player: &ServerPlayer) -> Self {
score: player.score, Self {
duration: player.duration, name: player.name.clone(),
deaths: player.deaths.unwrap(), score: player.score,
money: player.money.unwrap() duration: player.duration,
} deaths: player.deaths.unwrap(),
} money: player.money.unwrap(),
} }
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] }
#[derive(Debug, Clone, PartialEq)]
pub struct Response { #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub protocol: u8, #[derive(Debug, Clone, PartialEq)]
pub name: String, pub struct Response {
pub map: String, pub protocol: u8,
pub game: String, pub name: String,
pub players: u8, pub map: String,
pub players_details: Vec<TheShipPlayer>, pub game: String,
pub max_players: u8, pub players: u8,
pub bots: u8, pub players_details: Vec<TheShipPlayer>,
pub server_type: Server, pub max_players: u8,
pub has_password: bool, pub bots: u8,
pub vac_secured: bool, pub server_type: Server,
pub version: String, pub has_password: bool,
pub port: Option<u16>, pub vac_secured: bool,
pub steam_id: Option<u64>, pub version: String,
pub tv_port: Option<u16>, pub port: Option<u16>,
pub tv_name: Option<String>, pub steam_id: Option<u64>,
pub keywords: Option<String>, pub tv_port: Option<u16>,
pub rules: HashMap<String, String>, pub tv_name: Option<String>,
pub mode: u8, pub keywords: Option<String>,
pub witnesses: u8, pub rules: HashMap<String, String>,
pub duration: u8 pub mode: u8,
} pub witnesses: u8,
pub duration: u8,
impl Response { }
pub fn new_from_valve_response(response: valve::Response) -> Self {
let (port, steam_id, tv_port, tv_name, keywords) = get_optional_extracted_data(response.info.extra_data); impl Response {
pub fn new_from_valve_response(response: valve::Response) -> Self {
let the_unwrapped_ship = response.info.the_ship.unwrap(); let (port, steam_id, tv_port, tv_name, keywords) = get_optional_extracted_data(response.info.extra_data);
Self { let the_unwrapped_ship = response.info.the_ship.unwrap();
protocol: response.info.protocol,
name: response.info.name, Self {
map: response.info.map, protocol: response.info.protocol,
game: response.info.game, name: response.info.name,
players: response.info.players_online, map: response.info.map,
players_details: response.players.unwrap().iter().map(TheShipPlayer::new_from_valve_player).collect(), game: response.info.game,
max_players: response.info.players_maximum, players: response.info.players_online,
bots: response.info.players_bots, players_details: response
server_type: response.info.server_type, .players
has_password: response.info.has_password, .unwrap()
vac_secured: response.info.vac_secured, .iter()
version: response.info.version, .map(TheShipPlayer::new_from_valve_player)
port, .collect(),
steam_id, max_players: response.info.players_maximum,
tv_port, bots: response.info.players_bots,
tv_name, server_type: response.info.server_type,
keywords, has_password: response.info.has_password,
rules: response.rules.unwrap(), vac_secured: response.info.vac_secured,
mode: the_unwrapped_ship.mode, version: response.info.version,
witnesses: the_unwrapped_ship.witnesses, port,
duration: the_unwrapped_ship.duration steam_id,
} tv_port,
} tv_name,
} keywords,
rules: response.rules.unwrap(),
pub fn query(address: &str, port: Option<u16>) -> GDResult<Response> { mode: the_unwrapped_ship.mode,
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::TS.as_engine(), None, None)?; witnesses: the_unwrapped_ship.witnesses,
duration: the_unwrapped_ship.duration,
Ok(Response::new_from_valve_response(valve_response)) }
} }
}
pub fn query(address: &str, port: Option<u16>) -> GDResult<Response> {
let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::TS.as_engine(),
None,
None,
)?;
Ok(Response::new_from_valve_response(valve_response))
}

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27015), SteamApp::UNTURNED.as_engine(), None, None)?; pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(
Ok(game::Response::new_from_valve_response(valve_response)) address,
} port.unwrap_or(27015),
SteamApp::UNTURNED.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response))
}

View file

@ -1,6 +1,7 @@
use crate::GDResult; use crate::{
use crate::protocols::gamespy; protocols::gamespy::{self, Response},
use crate::protocols::gamespy::Response; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<Response> {
gamespy::one::query(address, port.unwrap_or(7778), None) gamespy::one::query(address, port.unwrap_or(7778), None)

View file

@ -1,9 +1,16 @@
use crate::GDResult; use crate::{
use crate::protocols::valve; protocols::valve::{self, game, SteamApp},
use crate::protocols::valve::{game, SteamApp}; GDResult,
};
pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> { pub fn query(address: &str, port: Option<u16>) -> GDResult<game::Response> {
let valve_response = valve::query(address, port.unwrap_or(27016), SteamApp::VR.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27016),
SteamApp::VR.as_engine(),
None,
None,
)?;
Ok(game::Response::new_from_valve_response(valve_response)) Ok(game::Response::new_from_valve_response(valve_response))
} }

View file

@ -1,8 +1,7 @@
/// The implementation. /// The implementation.
pub mod protocol; pub mod protocol;
/// All types used by the implementation. /// All types used by the implementation.
pub mod types; pub mod types;
pub use types::*;
pub use protocol::*; pub use protocol::*;
pub use types::*;

View file

@ -1,3 +1,2 @@
/// GameSpy 1 /// GameSpy 1
pub mod one; pub mod one;

View file

@ -1,11 +1,21 @@
use std::collections::HashMap; use crate::{
use crate::bufferer::{Bufferer, Endianess}; bufferer::{Bufferer, Endianess},
use crate::{GDError, GDResult}; protocols::{
use crate::protocols::gamespy::{Player, Response}; gamespy::{Player, Response},
use crate::protocols::types::TimeoutSettings; types::TimeoutSettings,
use crate::socket::{Socket, UdpSocket}; },
socket::{Socket, UdpSocket},
GDError,
GDResult,
};
fn get_server_values(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<HashMap<String, String>> { use std::collections::HashMap;
fn get_server_values(
address: &str,
port: u16,
timeout_settings: Option<TimeoutSettings>,
) -> GDResult<HashMap<String, String>> {
let mut socket = UdpSocket::new(address, port)?; let mut socket = UdpSocket::new(address, port)?;
socket.apply_timeout(timeout_settings)?; socket.apply_timeout(timeout_settings)?;
@ -26,12 +36,12 @@ fn get_server_values(address: &str, port: u16, timeout_settings: Option<TimeoutS
let splited: Vec<String> = as_string.split('\\').map(str::to_string).collect(); let splited: Vec<String> = as_string.split('\\').map(str::to_string).collect();
for i in 0..splited.len() / 2 { for i in 0 .. splited.len() / 2 {
let position = i * 2; let position = i * 2;
let key = splited[position].clone(); let key = splited[position].clone();
let value = match splited.get(position + 1) { let value = match splited.get(position + 1) {
None => "".to_string(), None => "".to_string(),
Some(v) => v.clone() Some(v) => v.clone(),
}; };
server_values.insert(key, value); server_values.insert(key, value);
@ -42,7 +52,7 @@ fn get_server_values(address: &str, port: u16, timeout_settings: Option<TimeoutS
let query_data = server_values.get("queryid"); let query_data = server_values.get("queryid");
let mut part = parts.len(); //if the part number isn't provided, it's value is the parts length let mut part = parts.len(); // if the part number isn't provided, it's value is the parts length
let mut query_id = None; let mut query_id = None;
if let Some(qid) = query_data { if let Some(qid) = query_data {
let split: Vec<&str> = qid.split('.').collect(); let split: Vec<&str> = qid.split('.').collect();
@ -51,22 +61,22 @@ fn get_server_values(address: &str, port: u16, timeout_settings: Option<TimeoutS
match split.len() { match split.len() {
1 => (), 1 => (),
2 => part = split[1].parse().map_err(|_| GDError::TypeParse)?, 2 => part = split[1].parse().map_err(|_| GDError::TypeParse)?,
_ => Err(GDError::PacketBad)? //the queryid can't be splitted in more than 2 elements _ => Err(GDError::PacketBad)?, /* the queryid can't be splitted in more than 2
* elements */
}; };
} }
server_values.remove("queryid"); server_values.remove("queryid");
if received_query_id.is_some() && received_query_id != query_id { if received_query_id.is_some() && received_query_id != query_id {
return Err(GDError::PacketBad); //wrong query id! return Err(GDError::PacketBad); // wrong query id!
} } else {
else {
received_query_id = query_id; received_query_id = query_id;
} }
match parts.contains(&part) { match parts.contains(&part) {
true => Err(GDError::PacketBad)?, true => Err(GDError::PacketBad)?,
false => parts.push(part) false => parts.push(part),
} }
} }
@ -86,15 +96,12 @@ fn extract_players(server_vars: &mut HashMap<String, String>, players_maximum: u
let kind = split[0]; let kind = split[0];
let id: usize = match split[1].parse() { let id: usize = match split[1].parse() {
Ok(v) => v, Ok(v) => v,
Err(_) => return true Err(_) => return true,
}; };
let early_return = match kind { let early_return = match kind {
"team" | "player" | "ping" | "face" | "skin" | "mesh" | "frags" | "ngsecret" | "deaths" | "health" => false, "team" | "player" | "ping" | "face" | "skin" | "mesh" | "frags" | "ngsecret" | "deaths" | "health" => false,
_x => { _x => true, // println!("UNKNOWN {id} {x} {value}");
//println!("UNKNOWN {id} {x} {value}");
true
}
}; };
if early_return { if early_return {
@ -116,23 +123,48 @@ fn extract_players(server_vars: &mut HashMap<String, String>, players_maximum: u
let new_player = Player { let new_player = Player {
name: match player_data.get("player") { name: match player_data.get("player") {
Some(v) => v.clone(), Some(v) => v.clone(),
None => player_data.get("playername").ok_or(GDError::PacketBad)?.clone() None => {
player_data
.get("playername")
.ok_or(GDError::PacketBad)?
.clone()
}
}, },
team: player_data.get("team").ok_or(GDError::PacketBad)?.trim().parse().map_err(|_| GDError::TypeParse)?, team: player_data
ping: player_data.get("ping").ok_or(GDError::PacketBad)?.trim().parse().map_err(|_| GDError::TypeParse)?, .get("team")
.ok_or(GDError::PacketBad)?
.trim()
.parse()
.map_err(|_| GDError::TypeParse)?,
ping: player_data
.get("ping")
.ok_or(GDError::PacketBad)?
.trim()
.parse()
.map_err(|_| GDError::TypeParse)?,
face: player_data.get("face").ok_or(GDError::PacketBad)?.clone(), face: player_data.get("face").ok_or(GDError::PacketBad)?.clone(),
skin: player_data.get("skin").ok_or(GDError::PacketBad)?.clone(), skin: player_data.get("skin").ok_or(GDError::PacketBad)?.clone(),
mesh: player_data.get("mesh").ok_or(GDError::PacketBad)?.clone(), mesh: player_data.get("mesh").ok_or(GDError::PacketBad)?.clone(),
frags: player_data.get("frags").ok_or(GDError::PacketBad)?.trim().parse().map_err(|_| GDError::TypeParse)?, frags: player_data
.get("frags")
.ok_or(GDError::PacketBad)?
.trim()
.parse()
.map_err(|_| GDError::TypeParse)?,
deaths: match player_data.get("deaths") { deaths: match player_data.get("deaths") {
Some(v) => Some(v.trim().parse().map_err(|_| GDError::TypeParse)?), Some(v) => Some(v.trim().parse().map_err(|_| GDError::TypeParse)?),
None => None None => None,
}, },
health: match player_data.get("health") { health: match player_data.get("health") {
Some(v) => Some(v.trim().parse().map_err(|_| GDError::TypeParse)?), Some(v) => Some(v.trim().parse().map_err(|_| GDError::TypeParse)?),
None => None None => None,
}, },
secret: player_data.get("ngsecret").ok_or(GDError::PacketBad)?.to_lowercase().parse().map_err(|_| GDError::TypeParse)?, secret: player_data
.get("ngsecret")
.ok_or(GDError::PacketBad)?
.to_lowercase()
.parse()
.map_err(|_| GDError::TypeParse)?,
}; };
players.push(new_player); players.push(new_player);
@ -142,7 +174,10 @@ fn extract_players(server_vars: &mut HashMap<String, String>, players_maximum: u
} }
fn has_password(server_vars: &mut HashMap<String, String>) -> GDResult<bool> { fn has_password(server_vars: &mut HashMap<String, String>) -> GDResult<bool> {
let password_value = server_vars.remove("password").ok_or(GDError::PacketBad)?.to_lowercase(); let password_value = server_vars
.remove("password")
.ok_or(GDError::PacketBad)?
.to_lowercase();
if let Ok(has) = password_value.parse::<bool>() { if let Ok(has) = password_value.parse::<bool>() {
return Ok(has); return Ok(has);
@ -153,17 +188,27 @@ fn has_password(server_vars: &mut HashMap<String, String>) -> GDResult<bool> {
Ok(as_numeral != 0) Ok(as_numeral != 0)
} }
/// If there are parsing problems using the `query` function, you can directly get the server's values using this function. /// If there are parsing problems using the `query` function, you can directly
pub fn query_vars(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<HashMap<String, String>> { /// get the server's values using this function.
pub fn query_vars(
address: &str,
port: u16,
timeout_settings: Option<TimeoutSettings>,
) -> GDResult<HashMap<String, String>> {
get_server_values(address, port, timeout_settings) get_server_values(address, port, timeout_settings)
} }
/// Query a server by providing the address, the port and timeout settings. /// Query a server by providing the address, the port and timeout settings.
/// Providing None to the timeout settings results in using the default values. (TimeoutSettings::[default](TimeoutSettings::default)). /// Providing None to the timeout settings results in using the default values.
/// (TimeoutSettings::[default](TimeoutSettings::default)).
pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Response> { pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Response> {
let mut server_vars = query_vars(address, port, timeout_settings)?; let mut server_vars = query_vars(address, port, timeout_settings)?;
let players_maximum = server_vars.remove("maxplayers").ok_or(GDError::PacketBad)?.parse().map_err(|_| GDError::TypeParse)?; let players_maximum = server_vars
.remove("maxplayers")
.ok_or(GDError::PacketBad)?
.parse()
.map_err(|_| GDError::TypeParse)?;
let players = extract_players(&mut server_vars, players_maximum)?; let players = extract_players(&mut server_vars, players_maximum)?;
@ -172,15 +217,26 @@ pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>
map: server_vars.remove("mapname").ok_or(GDError::PacketBad)?, map: server_vars.remove("mapname").ok_or(GDError::PacketBad)?,
map_title: server_vars.remove("maptitle"), map_title: server_vars.remove("maptitle"),
admin_contact: server_vars.remove("AdminEMail"), admin_contact: server_vars.remove("AdminEMail"),
admin_name: server_vars.remove("AdminName").or_else(|| server_vars.remove("admin")), admin_name: server_vars
.remove("AdminName")
.or_else(|| server_vars.remove("admin")),
has_password: has_password(&mut server_vars)?, has_password: has_password(&mut server_vars)?,
game_type: server_vars.remove("gametype").ok_or(GDError::PacketBad)?, game_type: server_vars.remove("gametype").ok_or(GDError::PacketBad)?,
game_version: server_vars.remove("gamever").ok_or(GDError::PacketBad)?, game_version: server_vars.remove("gamever").ok_or(GDError::PacketBad)?,
players_maximum, players_maximum,
players_online: players.len(), players_online: players.len(),
players_minimum: server_vars.remove("minplayers").unwrap_or_else(|| "0".to_string()).parse().map_err(|_| GDError::TypeParse)?, players_minimum: server_vars
.remove("minplayers")
.unwrap_or_else(|| "0".to_string())
.parse()
.map_err(|_| GDError::TypeParse)?,
players, players,
tournament: server_vars.remove("tournament").unwrap_or_else(|| "true".to_string()).to_lowercase().parse().map_err(|_| GDError::TypeParse)?, tournament: server_vars
unused_entries: server_vars .remove("tournament")
.unwrap_or_else(|| "true".to_string())
.to_lowercase()
.parse()
.map_err(|_| GDError::TypeParse)?,
unused_entries: server_vars,
}) })
} }

View file

@ -1,9 +1,8 @@
/// The implementation.
/// The implementation. pub mod protocol;
pub mod protocol; /// All types used by the implementation.
/// All types used by the implementation. pub mod types;
pub mod types;
pub use protocol::*;
pub use protocol::*; pub use protocol::*;
pub use types::*; pub use types::*;
pub use protocol::*;

View file

@ -1,101 +1,98 @@
// This file has code that has been documented by the NodeJS GameDig library
/* // (MIT) from https://github.com/gamedig/node-gamedig/blob/master/protocols/minecraftbedrock.js
This file has code that has been documented by the NodeJS GameDig library (MIT) from
https://github.com/gamedig/node-gamedig/blob/master/protocols/minecraftbedrock.js use crate::{
*/ bufferer::{Bufferer, Endianess},
protocols::{
use crate::GDResult; minecraft::{BedrockResponse, GameMode, Server},
use crate::bufferer::{Bufferer, Endianess}; types::TimeoutSettings,
use crate::GDError::{PacketBad, TypeParse}; },
use crate::protocols::minecraft::{BedrockResponse, GameMode, Server}; socket::{Socket, UdpSocket},
use crate::protocols::types::TimeoutSettings; utils::error_by_expected_size,
use crate::socket::{Socket, UdpSocket}; GDError::{PacketBad, TypeParse},
use crate::utils::error_by_expected_size; GDResult,
};
pub struct Bedrock {
socket: UdpSocket pub struct Bedrock {
} socket: UdpSocket,
}
impl Bedrock {
fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> { impl Bedrock {
let socket = UdpSocket::new(address, port)?; fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> {
socket.apply_timeout(timeout_settings)?; let socket = UdpSocket::new(address, port)?;
socket.apply_timeout(timeout_settings)?;
Ok(Self {
socket Ok(Self { socket })
}) }
}
fn send_status_request(&mut self) -> GDResult<()> {
fn send_status_request(&mut self) -> GDResult<()> { self.socket.send(&[
self.socket.send(&[ 0x01, // Message ID: ID_UNCONNECTED_PING
// Message ID, ID_UNCONNECTED_PING 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, // Nonce / timestamp
0x01, 0x00, 0xff, 0xff, 0x00, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfd, 0x12, 0x34, // Magic
// Nonce / timestamp 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Client GUID
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, ])?;
// Magic
0x00, 0xff, 0xff, 0x00, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfd, 0x12, 0x34, 0x56, 0x78, Ok(())
// Client GUID }
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])?;
fn get_info(&mut self) -> GDResult<BedrockResponse> {
Ok(()) self.send_status_request()?;
}
let mut buffer = Bufferer::new_with_data(Endianess::Little, &self.socket.receive(None)?);
fn get_info(&mut self) -> GDResult<BedrockResponse> {
self.send_status_request()?; if buffer.get_u8()? != 0x1c {
return Err(PacketBad);
let mut buffer = Bufferer::new_with_data(Endianess::Little, &self.socket.receive(None)?); }
if buffer.get_u8()? != 0x1c { // Checking for our nonce directly from a u64 (as the nonce is 8 bytes).
return Err(PacketBad); if buffer.get_u64()? != 9833440827789222417 {
} return Err(PacketBad);
}
// Checking for our nonce directly from a u64 (as the nonce is 8 bytes).
if buffer.get_u64()? != 9833440827789222417 { // These 8 bytes are identical to the serverId string we receive in decimal
return Err(PacketBad); // below
} buffer.move_position_ahead(8);
// These 8 bytes are identical to the serverId string we receive in decimal below // Verifying the magic value (as we need 16 bytes, cast to two u64 values)
buffer.move_position_ahead(8); if buffer.get_u64()? != 18374403896610127616 {
return Err(PacketBad);
// Verifying the magic value (as we need 16 bytes, cast to two u64 values) }
if buffer.get_u64()? != 18374403896610127616 {
return Err(PacketBad); if buffer.get_u64()? != 8671175388723805693 {
} return Err(PacketBad);
}
if buffer.get_u64()? != 8671175388723805693 {
return Err(PacketBad); let remaining_length = buffer.as_endianess(Endianess::Big).get_u16()? as usize;
} buffer.move_position_ahead(2);
error_by_expected_size(remaining_length, buffer.remaining_length())?;
let remaining_length = buffer.as_endianess(Endianess::Big).get_u16()? as usize;
buffer.move_position_ahead(2); let binding = buffer.get_string_utf8_unended()?;
error_by_expected_size(remaining_length, buffer.remaining_length())?; let status: Vec<&str> = binding.split(';').collect();
let binding = buffer.get_string_utf8_unended()?; // We must have at least 6 values
let status: Vec<&str> = binding.split(';').collect(); if status.len() < 6 {
return Err(PacketBad);
// We must have at least 6 values }
if status.len() < 6 {
return Err(PacketBad); Ok(BedrockResponse {
} edition: status[0].to_string(),
name: status[1].to_string(),
Ok(BedrockResponse { version_name: status[3].to_string(),
edition: status[0].to_string(), version_protocol: status[2].to_string(),
name: status[1].to_string(), players_maximum: status[5].parse().map_err(|_| TypeParse)?,
version_name: status[3].to_string(), players_online: status[4].parse().map_err(|_| TypeParse)?,
version_protocol: status[2].to_string(), id: status.get(6).map(|v| v.to_string()),
players_maximum: status[5].parse().map_err(|_| TypeParse)?, map: status.get(7).map(|v| v.to_string()),
players_online: status[4].parse().map_err(|_| TypeParse)?, game_mode: match status.get(8) {
id: status.get(6).map(|v| v.to_string()), None => None,
map: status.get(7).map(|v| v.to_string()), Some(v) => Some(GameMode::from_bedrock(v)?),
game_mode: match status.get(8) { },
None => None, server_type: Server::Bedrock,
Some(v) => Some(GameMode::from_bedrock(v)?) })
}, }
server_type: Server::Bedrock
}) pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<BedrockResponse> {
} Bedrock::new(address, port, timeout_settings)?.get_info()
}
pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<BedrockResponse> { }
Bedrock::new(address, port, timeout_settings)?.get_info()
}
}

View file

@ -1,127 +1,144 @@
use serde_json::Value; use crate::{
use crate::GDResult; bufferer::{Bufferer, Endianess},
use crate::GDError::{JsonParse, PacketBad}; protocols::{
use crate::bufferer::{Bufferer, Endianess}; minecraft::{as_varint, get_string, get_varint, JavaResponse, Player, Server},
use crate::protocols::minecraft::{as_varint, get_string, get_varint, Player, JavaResponse, Server}; types::TimeoutSettings,
use crate::protocols::types::TimeoutSettings; },
use crate::socket::{Socket, TcpSocket}; socket::{Socket, TcpSocket},
GDError::{JsonParse, PacketBad},
pub struct Java { GDResult,
socket: TcpSocket };
}
use serde_json::Value;
impl Java {
fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> { #[rustfmt::skip]
let socket = TcpSocket::new(address, port)?; const PAYLOAD: [u8; 17] = [
socket.apply_timeout(timeout_settings)?; //Packet ID (0)
0x00,
Ok(Self { //Protocol Version (-1 to determine version)
socket 0xFF, 0xFF, 0xFF, 0xFF, 0x0F,
}) //Server address (can be anything)
} 0x07, 0x47, 0x61, 0x6D, 0x65, 0x44, 0x69, 0x67,
//Server port (can be anything)
fn send(&mut self, data: Vec<u8>) -> GDResult<()> { 0x00, 0x00,
self.socket.send(&[as_varint(data.len() as i32), data].concat()) //Next state (1 for status)
} 0x01
];
fn receive(&mut self) -> GDResult<Bufferer> {
let mut buffer = Bufferer::new_with_data(Endianess::Little, &self.socket.receive(None)?); pub struct Java {
socket: TcpSocket,
let _packet_length = get_varint(&mut buffer)? as usize; }
//this declared 'packet length' from within the packet might be wrong (?), not checking with it...
impl Java {
Ok(buffer) fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> {
} let socket = TcpSocket::new(address, port)?;
socket.apply_timeout(timeout_settings)?;
fn send_handshake(&mut self) -> GDResult<()> {
self.send([ Ok(Self { socket })
//Packet ID (0) }
0x00,
//Protocol Version (-1 to determine version) fn send(&mut self, data: Vec<u8>) -> GDResult<()> {
0xFF, 0xFF, 0xFF, 0xFF, 0x0F, self.socket
//Server address (can be anything) .send(&[as_varint(data.len() as i32), data].concat())
0x07, 0x47, 0x61, 0x6D, 0x65, 0x44, 0x69, 0x67, }
//Server port (can be anything)
0x00, 0x00, fn receive(&mut self) -> GDResult<Bufferer> {
//Next state (1 for status) let mut buffer = Bufferer::new_with_data(Endianess::Little, &self.socket.receive(None)?);
0x01].to_vec())?;
let _packet_length = get_varint(&mut buffer)? as usize;
Ok(()) // this declared 'packet length' from within the packet might be wrong (?), not
} // checking with it...
fn send_status_request(&mut self) -> GDResult<()> { Ok(buffer)
self.send([ }
//Packet ID (0)
0x00].to_vec())?; fn send_handshake(&mut self) -> GDResult<()> {
self.send(PAYLOAD.to_vec())?;
Ok(())
} Ok(())
}
fn send_ping_request(&mut self) -> GDResult<()> {
self.send([ fn send_status_request(&mut self) -> GDResult<()> {
//Packet ID (1) self.send(
0x01].to_vec())?; [0x00] // Packet ID (0)
.to_vec(),
Ok(()) )?;
}
Ok(())
fn get_info(&mut self) -> GDResult<JavaResponse> { }
self.send_handshake()?;
self.send_status_request()?; fn send_ping_request(&mut self) -> GDResult<()> {
self.send_ping_request()?; self.send(
[0x01] // Packet ID (1)
let mut buffer = self.receive()?; .to_vec(),
)?;
if get_varint(&mut buffer)? != 0 { //first var int is the packet id
return Err(PacketBad); Ok(())
} }
let json_response = get_string(&mut buffer)?; fn get_info(&mut self) -> GDResult<JavaResponse> {
let value_response: Value = serde_json::from_str(&json_response) self.send_handshake()?;
.map_err(|_|JsonParse)?; self.send_status_request()?;
self.send_ping_request()?;
let version_name = value_response["version"]["name"].as_str()
.ok_or(PacketBad)?.to_string(); let mut buffer = self.receive()?;
let version_protocol = value_response["version"]["protocol"].as_i64()
.ok_or(PacketBad)? as i32; if get_varint(&mut buffer)? != 0 {
// first var int is the packet id
let max_players = value_response["players"]["max"].as_u64() return Err(PacketBad);
.ok_or(PacketBad)? as u32; }
let online_players = value_response["players"]["online"].as_u64()
.ok_or(PacketBad)? as u32; let json_response = get_string(&mut buffer)?;
let sample_players: Option<Vec<Player>> = match value_response["players"]["sample"].is_null() { let value_response: Value = serde_json::from_str(&json_response).map_err(|_| JsonParse)?;
true => None,
false => Some({ let version_name = value_response["version"]["name"]
let players_values = value_response["players"]["sample"].as_array() .as_str()
.ok_or(PacketBad)?; .ok_or(PacketBad)?
.to_string();
let mut players = Vec::with_capacity(players_values.len()); let version_protocol = value_response["version"]["protocol"]
for player in players_values { .as_i64()
players.push(Player { .ok_or(PacketBad)? as i32;
name: player["name"].as_str().ok_or(PacketBad)?.to_string(),
id: player["id"].as_str().ok_or(PacketBad)?.to_string() let max_players = value_response["players"]["max"].as_u64().ok_or(PacketBad)? as u32;
}) let online_players = value_response["players"]["online"]
} .as_u64()
.ok_or(PacketBad)? as u32;
players let sample_players: Option<Vec<Player>> = match value_response["players"]["sample"].is_null() {
}) true => None,
}; false => {
Some({
Ok(JavaResponse { let players_values = value_response["players"]["sample"]
version_name, .as_array()
version_protocol, .ok_or(PacketBad)?;
players_maximum: max_players,
players_online: online_players, let mut players = Vec::with_capacity(players_values.len());
players_sample: sample_players, for player in players_values {
description: value_response["description"].to_string(), players.push(Player {
favicon: value_response["favicon"].as_str().map(str::to_string), name: player["name"].as_str().ok_or(PacketBad)?.to_string(),
previews_chat: value_response["previewsChat"].as_bool(), id: player["id"].as_str().ok_or(PacketBad)?.to_string(),
enforces_secure_chat: value_response["enforcesSecureChat"].as_bool(), })
server_type: Server::Java }
})
} players
})
pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> { }
Java::new(address, port, timeout_settings)?.get_info() };
}
} Ok(JavaResponse {
version_name,
version_protocol,
players_maximum: max_players,
players_online: online_players,
players_sample: sample_players,
description: value_response["description"].to_string(),
favicon: value_response["favicon"].as_str().map(str::to_string),
previews_chat: value_response["previewsChat"].as_bool(),
enforces_secure_chat: value_response["enforcesSecureChat"].as_bool(),
server_type: Server::Java,
})
}
pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
Java::new(address, port, timeout_settings)?.get_info()
}
}

View file

@ -1,68 +1,65 @@
use crate::{
use crate::GDResult; bufferer::{Bufferer, Endianess},
use crate::bufferer::{Bufferer, Endianess}; protocols::{
use crate::GDError::{PacketBad, ProtocolFormat}; minecraft::{JavaResponse, LegacyGroup, Server},
use crate::protocols::minecraft::{LegacyGroup, JavaResponse, Server}; types::TimeoutSettings,
use crate::protocols::types::TimeoutSettings; },
use crate::socket::{Socket, TcpSocket}; socket::{Socket, TcpSocket},
use crate::utils::error_by_expected_size; utils::error_by_expected_size,
GDError::{PacketBad, ProtocolFormat},
pub struct LegacyBV1_8 { GDResult,
socket: TcpSocket };
}
pub struct LegacyBV1_8 {
impl LegacyBV1_8 { socket: TcpSocket,
fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> { }
let socket = TcpSocket::new(address, port)?;
socket.apply_timeout(timeout_settings)?; impl LegacyBV1_8 {
fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> {
Ok(Self { let socket = TcpSocket::new(address, port)?;
socket socket.apply_timeout(timeout_settings)?;
})
} Ok(Self { socket })
}
fn send_initial_request(&mut self) -> GDResult<()> {
self.socket.send(&[0xFE]) fn send_initial_request(&mut self) -> GDResult<()> { self.socket.send(&[0xFE]) }
}
fn get_info(&mut self) -> GDResult<JavaResponse> {
fn get_info(&mut self) -> GDResult<JavaResponse> { self.send_initial_request()?;
self.send_initial_request()?;
let mut buffer = Bufferer::new_with_data(Endianess::Big, &self.socket.receive(None)?);
let mut buffer = Bufferer::new_with_data(Endianess::Big, &self.socket.receive(None)?);
if buffer.get_u8()? != 0xFF {
if buffer.get_u8()? != 0xFF { return Err(ProtocolFormat);
return Err(ProtocolFormat); }
}
let length = buffer.get_u16()? * 2;
let length = buffer.get_u16()? * 2; error_by_expected_size((length + 3) as usize, buffer.data_length())?;
error_by_expected_size((length + 3) as usize, buffer.data_length())?;
let packet_string = buffer.get_string_utf16()?;
let packet_string = buffer.get_string_utf16()?;
let split: Vec<&str> = packet_string.split('§').collect();
let split: Vec<&str> = packet_string.split('§').collect(); error_by_expected_size(3, split.len())?;
error_by_expected_size(3, split.len())?;
let description = split[0].to_string();
let description = split[0].to_string(); let online_players = split[1].parse().map_err(|_| PacketBad)?;
let online_players = split[1].parse() let max_players = split[2].parse().map_err(|_| PacketBad)?;
.map_err(|_| PacketBad)?;
let max_players = split[2].parse() Ok(JavaResponse {
.map_err(|_| PacketBad)?; version_name: "Beta 1.8+".to_string(),
version_protocol: -1,
Ok(JavaResponse { players_maximum: max_players,
version_name: "Beta 1.8+".to_string(), players_online: online_players,
version_protocol: -1, players_sample: None,
players_maximum: max_players, description,
players_online: online_players, favicon: None,
players_sample: None, previews_chat: None,
description, enforces_secure_chat: None,
favicon: None, server_type: Server::Legacy(LegacyGroup::VB1_8),
previews_chat: None, })
enforces_secure_chat: None, }
server_type: Server::Legacy(LegacyGroup::VB1_8)
}) pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
} LegacyBV1_8::new(address, port, timeout_settings)?.get_info()
}
pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> { }
LegacyBV1_8::new(address, port, timeout_settings)?.get_info()
}
}

View file

@ -1,73 +1,69 @@
use crate::{
use crate::GDResult; bufferer::{Bufferer, Endianess},
use crate::bufferer::{Bufferer, Endianess}; protocols::{
use crate::GDError::{PacketBad, ProtocolFormat}; minecraft::{protocol::legacy_v1_6::LegacyV1_6, JavaResponse, LegacyGroup, Server},
use crate::protocols::minecraft::{LegacyGroup, JavaResponse, Server}; types::TimeoutSettings,
use crate::protocols::minecraft::protocol::legacy_v1_6::LegacyV1_6; },
use crate::protocols::types::TimeoutSettings; socket::{Socket, TcpSocket},
use crate::socket::{Socket, TcpSocket}; utils::error_by_expected_size,
use crate::utils::error_by_expected_size; GDError::{PacketBad, ProtocolFormat},
GDResult,
pub struct LegacyV1_4 { };
socket: TcpSocket
} pub struct LegacyV1_4 {
socket: TcpSocket,
impl LegacyV1_4 { }
fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> {
let socket = TcpSocket::new(address, port)?; impl LegacyV1_4 {
socket.apply_timeout(timeout_settings)?; fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> {
let socket = TcpSocket::new(address, port)?;
Ok(Self { socket.apply_timeout(timeout_settings)?;
socket
}) Ok(Self { socket })
} }
fn send_initial_request(&mut self) -> GDResult<()> { fn send_initial_request(&mut self) -> GDResult<()> { self.socket.send(&[0xFE, 0x01]) }
self.socket.send(&[0xFE, 0x01])
} fn get_info(&mut self) -> GDResult<JavaResponse> {
self.send_initial_request()?;
fn get_info(&mut self) -> GDResult<JavaResponse> {
self.send_initial_request()?; let mut buffer = Bufferer::new_with_data(Endianess::Big, &self.socket.receive(None)?);
let mut buffer = Bufferer::new_with_data(Endianess::Big, &self.socket.receive(None)?); if buffer.get_u8()? != 0xFF {
return Err(ProtocolFormat);
if buffer.get_u8()? != 0xFF { }
return Err(ProtocolFormat);
} let length = buffer.get_u16()? * 2;
error_by_expected_size((length + 3) as usize, buffer.data_length())?;
let length = buffer.get_u16()? * 2;
error_by_expected_size((length + 3) as usize, buffer.data_length())?; if LegacyV1_6::is_protocol(&mut buffer)? {
return LegacyV1_6::get_response(&mut buffer);
if LegacyV1_6::is_protocol(&mut buffer)? { }
return LegacyV1_6::get_response(&mut buffer);
} let packet_string = buffer.get_string_utf16()?;
let packet_string = buffer.get_string_utf16()?; let split: Vec<&str> = packet_string.split('§').collect();
error_by_expected_size(3, split.len())?;
let split: Vec<&str> = packet_string.split('§').collect();
error_by_expected_size(3, split.len())?; let description = split[0].to_string();
let online_players = split[1].parse().map_err(|_| PacketBad)?;
let description = split[0].to_string(); let max_players = split[2].parse().map_err(|_| PacketBad)?;
let online_players = split[1].parse()
.map_err(|_| PacketBad)?; Ok(JavaResponse {
let max_players = split[2].parse() version_name: "1.4+".to_string(),
.map_err(|_| PacketBad)?; version_protocol: -1,
players_maximum: max_players,
Ok(JavaResponse { players_online: online_players,
version_name: "1.4+".to_string(), players_sample: None,
version_protocol: -1, description,
players_maximum: max_players, favicon: None,
players_online: online_players, previews_chat: None,
players_sample: None, enforces_secure_chat: None,
description, server_type: Server::Legacy(LegacyGroup::V1_4),
favicon: None, })
previews_chat: None, }
enforces_secure_chat: None,
server_type: Server::Legacy(LegacyGroup::V1_4) pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
}) LegacyV1_4::new(address, port, timeout_settings)?.get_info()
} }
}
pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
LegacyV1_4::new(address, port, timeout_settings)?.get_info()
}
}

View file

@ -1,100 +1,98 @@
use crate::GDResult; use crate::{
use crate::GDError::{PacketBad, ProtocolFormat}; bufferer::{Bufferer, Endianess},
use crate::bufferer::{Bufferer, Endianess}; protocols::{
use crate::protocols::minecraft::{LegacyGroup, JavaResponse, Server}; minecraft::{JavaResponse, LegacyGroup, Server},
use crate::protocols::types::TimeoutSettings; types::TimeoutSettings,
use crate::socket::{Socket, TcpSocket}; },
use crate::utils::error_by_expected_size; socket::{Socket, TcpSocket},
utils::error_by_expected_size,
pub struct LegacyV1_6 { GDError::{PacketBad, ProtocolFormat},
socket: TcpSocket GDResult,
} };
impl LegacyV1_6 { pub struct LegacyV1_6 {
fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> { socket: TcpSocket,
let socket = TcpSocket::new(address, port)?; }
socket.apply_timeout(timeout_settings)?;
impl LegacyV1_6 {
Ok(Self { fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> {
socket let socket = TcpSocket::new(address, port)?;
}) socket.apply_timeout(timeout_settings)?;
}
Ok(Self { socket })
fn send_initial_request(&mut self) -> GDResult<()> { }
self.socket.send(&[
// Packet ID (FE) fn send_initial_request(&mut self) -> GDResult<()> {
0xfe, self.socket.send(&[
// Ping payload (01) 0xfe, // Packet ID (FE)
0x01, 0x01, // Ping payload (01)
// Packet identifier for plugin message 0xfa, // Packet identifier for plugin message
0xfa, 0x00, 0x07, // Length of 'GameDig' string (7) as unsigned short
// Length of 'GameDig' string (7) as unsigned short 0x00, 0x47, 0x00, 0x61, 0x00, 0x6D, 0x00, 0x65, 0x00, 0x44, 0x00, 0x69, 0x00,
0x00, 0x07, 0x67, // 'GameDig' string as UTF-16BE
// 'GameDig' string as UTF-16BE ])?;
0x00, 0x47, 0x00, 0x61, 0x00, 0x6D, 0x00, 0x65, 0x00, 0x44, 0x00, 0x69, 0x00, 0x67])?;
Ok(())
Ok(()) }
}
pub fn is_protocol(buffer: &mut Bufferer) -> GDResult<bool> {
pub fn is_protocol(buffer: &mut Bufferer) -> GDResult<bool> { let state = buffer
let state = buffer.remaining_data().starts_with(&[0x00, 0xA7, 0x00, 0x31, 0x00, 0x00]); .remaining_data()
.starts_with(&[0x00, 0xA7, 0x00, 0x31, 0x00, 0x00]);
if state {
buffer.move_position_ahead(6); if state {
} buffer.move_position_ahead(6);
}
Ok(state)
} Ok(state)
}
pub fn get_response(buffer: &mut Bufferer) -> GDResult<JavaResponse> {
let packet_string = buffer.get_string_utf16()?; pub fn get_response(buffer: &mut Bufferer) -> GDResult<JavaResponse> {
let packet_string = buffer.get_string_utf16()?;
let split: Vec<&str> = packet_string.split('\x00').collect();
error_by_expected_size(5, split.len())?; let split: Vec<&str> = packet_string.split('\x00').collect();
error_by_expected_size(5, split.len())?;
let version_protocol = split[0].parse()
.map_err(|_| PacketBad)?; let version_protocol = split[0].parse().map_err(|_| PacketBad)?;
let version_name = split[1].to_string(); let version_name = split[1].to_string();
let description = split[2].to_string(); let description = split[2].to_string();
let online_players = split[3].parse() let online_players = split[3].parse().map_err(|_| PacketBad)?;
.map_err(|_| PacketBad)?; let max_players = split[4].parse().map_err(|_| PacketBad)?;
let max_players = split[4].parse()
.map_err(|_| PacketBad)?; Ok(JavaResponse {
version_name,
Ok(JavaResponse { version_protocol,
version_name, players_maximum: max_players,
version_protocol, players_online: online_players,
players_maximum: max_players, players_sample: None,
players_online: online_players, description,
players_sample: None, favicon: None,
description, previews_chat: None,
favicon: None, enforces_secure_chat: None,
previews_chat: None, server_type: Server::Legacy(LegacyGroup::V1_6),
enforces_secure_chat: None, })
server_type: Server::Legacy(LegacyGroup::V1_6) }
})
} fn get_info(&mut self) -> GDResult<JavaResponse> {
self.send_initial_request()?;
fn get_info(&mut self) -> GDResult<JavaResponse> {
self.send_initial_request()?; let mut buffer = Bufferer::new_with_data(Endianess::Big, &self.socket.receive(None)?);
let mut buffer = Bufferer::new_with_data(Endianess::Big, &self.socket.receive(None)?); if buffer.get_u8()? != 0xFF {
return Err(ProtocolFormat);
if buffer.get_u8()? != 0xFF { }
return Err(ProtocolFormat);
} let length = buffer.get_u16()? * 2;
error_by_expected_size((length + 3) as usize, buffer.data_length())?;
let length = buffer.get_u16()? * 2;
error_by_expected_size((length + 3) as usize, buffer.data_length())?; if !LegacyV1_6::is_protocol(&mut buffer)? {
return Err(ProtocolFormat);
if !LegacyV1_6::is_protocol(&mut buffer)? { }
return Err(ProtocolFormat);
} LegacyV1_6::get_response(&mut buffer)
}
LegacyV1_6::get_response(&mut buffer)
} pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
LegacyV1_6::new(address, port, timeout_settings)?.get_info()
pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> { }
LegacyV1_6::new(address, port, timeout_settings)?.get_info() }
}
}

View file

@ -1,68 +1,82 @@
use crate::GDError::AutoQuery; use crate::{
use crate::GDResult; protocols::minecraft::{
use crate::protocols::minecraft::{BedrockResponse, LegacyGroup, JavaResponse}; protocol::{
use crate::protocols::minecraft::protocol::bedrock::Bedrock; bedrock::Bedrock,
use crate::protocols::minecraft::protocol::java::Java; java::Java,
use crate::protocols::minecraft::protocol::legacy_v1_4::LegacyV1_4; legacy_bv1_8::LegacyBV1_8,
use crate::protocols::minecraft::protocol::legacy_v1_6::LegacyV1_6; legacy_v1_4::LegacyV1_4,
use crate::protocols::minecraft::protocol::legacy_bv1_8::LegacyBV1_8; legacy_v1_6::LegacyV1_6,
use crate::protocols::types::TimeoutSettings; },
BedrockResponse,
mod java; JavaResponse,
mod legacy_v1_4; LegacyGroup,
mod legacy_v1_6; },
mod legacy_bv1_8; protocols::types::TimeoutSettings,
mod bedrock; GDError::AutoQuery,
GDResult,
/// Queries a Minecraft server with all the protocol variants one by one (Java -> Bedrock -> Legacy (1.6 -> 1.4 -> Beta 1.8)). };
pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
if let Ok(response) = query_java(address, port, timeout_settings.clone()) { mod bedrock;
return Ok(response); mod java;
} mod legacy_bv1_8;
mod legacy_v1_4;
if let Ok(response) = query_bedrock(address, port, timeout_settings.clone()) { mod legacy_v1_6;
return Ok(JavaResponse::from_bedrock_response(response));
} /// Queries a Minecraft server with all the protocol variants one by one (Java
/// -> Bedrock -> Legacy (1.6 -> 1.4 -> Beta 1.8)).
if let Ok(response) = query_legacy(address, port, timeout_settings) { pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
return Ok(response); if let Ok(response) = query_java(address, port, timeout_settings.clone()) {
} return Ok(response);
}
Err(AutoQuery)
} if let Ok(response) = query_bedrock(address, port, timeout_settings.clone()) {
return Ok(JavaResponse::from_bedrock_response(response));
/// Query a Java Server. }
pub fn query_java(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
Java::query(address, port, timeout_settings) if let Ok(response) = query_legacy(address, port, timeout_settings) {
} return Ok(response);
}
/// Query a (Java) Legacy Server (1.6 -> 1.4 -> Beta 1.8).
pub fn query_legacy(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> { Err(AutoQuery)
if let Ok(response) = query_legacy_specific(LegacyGroup::V1_6, address, port, timeout_settings.clone()) { }
return Ok(response);
} /// Query a Java Server.
pub fn query_java(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
if let Ok(response) = query_legacy_specific(LegacyGroup::V1_4, address, port, timeout_settings.clone()) { Java::query(address, port, timeout_settings)
return Ok(response); }
}
/// Query a (Java) Legacy Server (1.6 -> 1.4 -> Beta 1.8).
if let Ok(response) = query_legacy_specific(LegacyGroup::VB1_8, address, port, timeout_settings) { pub fn query_legacy(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
return Ok(response); if let Ok(response) = query_legacy_specific(LegacyGroup::V1_6, address, port, timeout_settings.clone()) {
} return Ok(response);
}
Err(AutoQuery)
} if let Ok(response) = query_legacy_specific(LegacyGroup::V1_4, address, port, timeout_settings.clone()) {
return Ok(response);
/// Query a specific (Java) Legacy Server. }
pub fn query_legacy_specific(group: LegacyGroup, address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
match group { if let Ok(response) = query_legacy_specific(LegacyGroup::VB1_8, address, port, timeout_settings) {
LegacyGroup::V1_6 => LegacyV1_6::query(address, port, timeout_settings), return Ok(response);
LegacyGroup::V1_4 => LegacyV1_4::query(address, port, timeout_settings), }
LegacyGroup::VB1_8 => LegacyBV1_8::query(address, port, timeout_settings)
} Err(AutoQuery)
} }
/// Query a Bedrock Server. /// Query a specific (Java) Legacy Server.
pub fn query_bedrock(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<BedrockResponse> { pub fn query_legacy_specific(
Bedrock::query(address, port, timeout_settings) group: LegacyGroup,
} address: &str,
port: u16,
timeout_settings: Option<TimeoutSettings>,
) -> GDResult<JavaResponse> {
match group {
LegacyGroup::V1_6 => LegacyV1_6::query(address, port, timeout_settings),
LegacyGroup::V1_4 => LegacyV1_4::query(address, port, timeout_settings),
LegacyGroup::VB1_8 => LegacyBV1_8::query(address, port, timeout_settings),
}
}
/// Query a Bedrock Server.
pub fn query_bedrock(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<BedrockResponse> {
Bedrock::query(address, port, timeout_settings)
}

View file

@ -1,204 +1,205 @@
/* // Although its a lightly modified version, this file contains code
Although its a lightly modified version, this file contains code // by Jaiden Bernard (2021-2022 - MIT) from
by Jaiden Bernard (2021-2022 - MIT) from // https://github.com/thisjaiden/golden_apple/blob/master/src/lib.rs
https://github.com/thisjaiden/golden_apple/blob/master/src/lib.rs
*/ use crate::{
bufferer::Bufferer,
use crate::bufferer::Bufferer; GDError::{PacketBad, UnknownEnumCast},
use crate::GDError::{PacketBad, UnknownEnumCast}; GDResult,
use crate::GDResult; };
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// The type of Minecraft Server you want to query. /// The type of Minecraft Server you want to query.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Server { pub enum Server {
/// Java Edition. /// Java Edition.
Java, Java,
/// Legacy Java. /// Legacy Java.
Legacy(LegacyGroup), Legacy(LegacyGroup),
/// Bedrock Edition. /// Bedrock Edition.
Bedrock, Bedrock,
} }
/// Legacy Java (Versions) Groups. /// Legacy Java (Versions) Groups.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum LegacyGroup { pub enum LegacyGroup {
/// 1.6 /// 1.6
V1_6, V1_6,
/// 1.4 - 1.5 /// 1.4 - 1.5
V1_4, V1_4,
/// Beta 1.8 - 1.3 /// Beta 1.8 - 1.3
VB1_8, VB1_8,
} }
/// Information about a player. /// Information about a player.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Player { pub struct Player {
pub name: String, pub name: String,
pub id: String, pub id: String,
} }
/// A Java query response. /// A Java query response.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct JavaResponse { pub struct JavaResponse {
/// Version name, example: "1.19.2". /// Version name, example: "1.19.2".
pub version_name: String, pub version_name: String,
/// Version protocol, example: 760 (for 1.19.2). Note that for versions below 1.6 this field is always -1. /// Version protocol, example: 760 (for 1.19.2). Note that for versions
pub version_protocol: i32, /// below 1.6 this field is always -1.
/// Number of server capacity. pub version_protocol: i32,
pub players_maximum: u32, /// Number of server capacity.
/// Number of online players. pub players_maximum: u32,
pub players_online: u32, /// Number of online players.
/// Some online players (can be missing). pub players_online: u32,
pub players_sample: Option<Vec<Player>>, /// Some online players (can be missing).
/// Server's description or MOTD. pub players_sample: Option<Vec<Player>>,
pub description: String, /// Server's description or MOTD.
/// The favicon (can be missing). pub description: String,
pub favicon: Option<String>, /// The favicon (can be missing).
/// Tells if the chat preview is enabled (can be missing). pub favicon: Option<String>,
pub previews_chat: Option<bool>, /// Tells if the chat preview is enabled (can be missing).
/// Tells if secure chat is enforced (can be missing). pub previews_chat: Option<bool>,
pub enforces_secure_chat: Option<bool>, /// Tells if secure chat is enforced (can be missing).
/// Tell's the server type. pub enforces_secure_chat: Option<bool>,
pub server_type: Server, /// Tell's the server type.
} pub server_type: Server,
}
/// A Bedrock Edition query response.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] /// A Bedrock Edition query response.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BedrockResponse { #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
/// Server's edition. pub struct BedrockResponse {
pub edition: String, /// Server's edition.
/// Server's name. pub edition: String,
pub name: String, /// Server's name.
/// Version name, example: "1.19.40". pub name: String,
pub version_name: String, /// Version name, example: "1.19.40".
/// Version protocol, example: 760 (for 1.19.2). pub version_name: String,
pub version_protocol: String, /// Version protocol, example: 760 (for 1.19.2).
/// Maximum number of players the server reports it can hold. pub version_protocol: String,
pub players_maximum: u32, /// Maximum number of players the server reports it can hold.
/// Number of players on the server. pub players_maximum: u32,
pub players_online: u32, /// Number of players on the server.
/// Server id. pub players_online: u32,
pub id: Option<String>, /// Server id.
/// Currently running map's name. pub id: Option<String>,
pub map: Option<String>, /// Currently running map's name.
/// Current game mode. pub map: Option<String>,
pub game_mode: Option<GameMode>, /// Current game mode.
/// Tells the server type. pub game_mode: Option<GameMode>,
pub server_type: Server, /// Tells the server type.
} pub server_type: Server,
}
impl JavaResponse {
pub fn from_bedrock_response(response: BedrockResponse) -> Self { impl JavaResponse {
Self { pub fn from_bedrock_response(response: BedrockResponse) -> Self {
version_name: response.version_name, Self {
version_protocol: 0, version_name: response.version_name,
players_maximum: response.players_maximum, version_protocol: 0,
players_online: response.players_online, players_maximum: response.players_maximum,
players_sample: None, players_online: response.players_online,
description: response.name, players_sample: None,
favicon: None, description: response.name,
previews_chat: None, favicon: None,
enforces_secure_chat: None, previews_chat: None,
server_type: Server::Bedrock, enforces_secure_chat: None,
} server_type: Server::Bedrock,
} }
} }
}
/// A server's game mode (used only by Bedrock servers.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] /// A server's game mode (used only by Bedrock servers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum GameMode { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
Survival, pub enum GameMode {
Creative, Survival,
Hardcore, Creative,
Spectator, Hardcore,
Adventure, Spectator,
} Adventure,
}
impl GameMode {
pub fn from_bedrock(value: &&str) -> GDResult<Self> { impl GameMode {
match *value { pub fn from_bedrock(value: &&str) -> GDResult<Self> {
"Survival" => Ok(GameMode::Survival), match *value {
"Creative" => Ok(GameMode::Creative), "Survival" => Ok(GameMode::Survival),
"Hardcore" => Ok(GameMode::Hardcore), "Creative" => Ok(GameMode::Creative),
"Spectator" => Ok(GameMode::Spectator), "Hardcore" => Ok(GameMode::Hardcore),
"Adventure" => Ok(GameMode::Adventure), "Spectator" => Ok(GameMode::Spectator),
_ => Err(UnknownEnumCast), "Adventure" => Ok(GameMode::Adventure),
} _ => Err(UnknownEnumCast),
} }
} }
}
pub(crate) fn get_varint(buffer: &mut Bufferer) -> GDResult<i32> {
let mut result = 0; pub(crate) fn get_varint(buffer: &mut Bufferer) -> GDResult<i32> {
let mut result = 0;
let msb: u8 = 0b10000000;
let mask: u8 = !msb; let msb: u8 = 0b10000000;
let mask: u8 = !msb;
for i in 0..5 {
let current_byte = buffer.get_u8()?; for i in 0 .. 5 {
let current_byte = buffer.get_u8()?;
result |= ((current_byte & mask) as i32) << (7 * i);
result |= ((current_byte & mask) as i32) << (7 * i);
// The 5th byte is only allowed to have the 4 smallest bits set
if i == 4 && (current_byte & 0xf0 != 0) { // The 5th byte is only allowed to have the 4 smallest bits set
return Err(PacketBad); if i == 4 && (current_byte & 0xf0 != 0) {
} return Err(PacketBad);
}
if (current_byte & msb) == 0 {
break; if (current_byte & msb) == 0 {
} break;
} }
}
Ok(result)
} Ok(result)
}
pub(crate) fn as_varint(value: i32) -> Vec<u8> {
let mut bytes = vec![]; pub(crate) fn as_varint(value: i32) -> Vec<u8> {
let mut reading_value = value; let mut bytes = vec![];
let mut reading_value = value;
let msb: u8 = 0b10000000;
let mask: i32 = 0b01111111; let msb: u8 = 0b10000000;
let mask: i32 = 0b01111111;
for _ in 0..5 {
let tmp = (reading_value & mask) as u8; for _ in 0 .. 5 {
let tmp = (reading_value & mask) as u8;
reading_value &= !mask;
reading_value = reading_value.rotate_right(7); reading_value &= !mask;
reading_value = reading_value.rotate_right(7);
if reading_value != 0 {
bytes.push(tmp | msb); if reading_value != 0 {
} else { bytes.push(tmp | msb);
bytes.push(tmp); } else {
break; bytes.push(tmp);
} break;
} }
}
bytes
} bytes
}
pub(crate) fn get_string(buffer: &mut Bufferer) -> GDResult<String> {
let length = get_varint(buffer)? as usize; pub(crate) fn get_string(buffer: &mut Bufferer) -> GDResult<String> {
let mut text = Vec::with_capacity(length); let length = get_varint(buffer)? as usize;
let mut text = Vec::with_capacity(length);
for _ in 0..length {
text.push(buffer.get_u8()?) for _ in 0 .. length {
} text.push(buffer.get_u8()?)
}
String::from_utf8(text).map_err(|_| PacketBad)
} String::from_utf8(text).map_err(|_| PacketBad)
}
#[allow(dead_code)]
pub(crate) fn as_string(value: String) -> Vec<u8> { #[allow(dead_code)]
let mut buf = as_varint(value.len() as i32); pub(crate) fn as_string(value: String) -> Vec<u8> {
buf.extend(value.as_bytes().to_vec()); let mut buf = as_varint(value.len() as i32);
buf.extend(value.as_bytes().to_vec());
buf
} buf
}

View file

@ -1,14 +1,14 @@
//! Protocols that are currently implemented.
//! Protocols that are currently implemented. //!
//! //! A protocol will be here if it supports multiple entries, if not, its
//! A protocol will be here if it supports multiple entries, if not, its implementation will be //! implementation will be in that specific needed place, a protocol can be
//! in that specific needed place, a protocol can be independently queried. //! independently queried.
/// General types that are used by all protocols. /// Reference: [node-GameDig](https://github.com/gamedig/node-gamedig/blob/master/protocols/gamespy1.js)
pub mod types; pub mod gamespy;
/// Reference: [Server Query](https://developer.valvesoftware.com/wiki/Server_queries) /// Reference: [Server List Ping](https://wiki.vg/Server_List_Ping)
pub mod valve; pub mod minecraft;
/// Reference: [Server List Ping](https://wiki.vg/Server_List_Ping) /// General types that are used by all protocols.
pub mod minecraft; pub mod types;
/// Reference: [node-GameDig](https://github.com/gamedig/node-gamedig/blob/master/protocols/gamespy1.js) /// Reference: [Server Query](https://developer.valvesoftware.com/wiki/Server_queries)
pub mod gamespy; pub mod valve;

View file

@ -1,5 +1,5 @@
use crate::GDError::InvalidInput; use crate::{GDError::InvalidInput, GDResult};
use crate::GDResult;
use std::time::Duration; use std::time::Duration;
/// Timeout settings for socket operations /// Timeout settings for socket operations
@ -10,7 +10,8 @@ pub struct TimeoutSettings {
} }
impl TimeoutSettings { impl TimeoutSettings {
/// Construct new settings, passing None will block indefinitely. Passing zero Duration throws GDError::[InvalidInput](InvalidInput). /// Construct new settings, passing None will block indefinitely. Passing
/// zero Duration throws GDError::[InvalidInput](InvalidInput).
pub fn new(read: Option<Duration>, write: Option<Duration>) -> GDResult<Self> { pub fn new(read: Option<Duration>, write: Option<Duration>) -> GDResult<Self> {
if let Some(read_duration) = read { if let Some(read_duration) = read {
if read_duration == Duration::new(0, 0) { if read_duration == Duration::new(0, 0) {
@ -28,14 +29,10 @@ impl TimeoutSettings {
} }
/// Get the read timeout. /// Get the read timeout.
pub fn get_read(&self) -> Option<Duration> { pub fn get_read(&self) -> Option<Duration> { self.read }
self.read
}
/// Get the write timeout. /// Get the write timeout.
pub fn get_write(&self) -> Option<Duration> { pub fn get_write(&self) -> Option<Duration> { self.write }
self.write
}
} }
impl Default for TimeoutSettings { impl Default for TimeoutSettings {
@ -77,10 +74,12 @@ mod tests {
let read_duration = Duration::new(0, 0); let read_duration = Duration::new(0, 0);
let write_duration = Duration::from_secs(2); let write_duration = Duration::from_secs(2);
// Try to create new TimeoutSettings with the zero read duration (this should fail) // Try to create new TimeoutSettings with the zero read duration (this should
// fail)
let result = TimeoutSettings::new(Some(read_duration), Some(write_duration)); let result = TimeoutSettings::new(Some(read_duration), Some(write_duration));
// Verify that the function returned an error and that the error type is InvalidInput // Verify that the function returned an error and that the error type is
// InvalidInput
assert!(result.is_err()); assert!(result.is_err());
assert_eq!(result.unwrap_err(), InvalidInput); assert_eq!(result.unwrap_err(), InvalidInput);
} }
@ -91,7 +90,8 @@ mod tests {
// Get the default TimeoutSettings values // Get the default TimeoutSettings values
let default_settings = TimeoutSettings::default(); let default_settings = TimeoutSettings::default();
// Verify that the get_read and get_write methods return the expected default values // Verify that the get_read and get_write methods return the expected default
// values
assert_eq!(default_settings.get_read(), Some(Duration::from_secs(4))); assert_eq!(default_settings.get_read(), Some(Duration::from_secs(4)));
assert_eq!(default_settings.get_write(), Some(Duration::from_secs(4))); assert_eq!(default_settings.get_write(), Some(Duration::from_secs(4)));
} }

View file

@ -1,8 +1,7 @@
/// The implementation.
/// The implementation. pub mod protocol;
pub mod protocol; /// All types used by the implementation.
/// All types used by the implementation. pub mod types;
pub mod types;
pub use protocol::*;
pub use protocol::*; pub use types::*;
pub use types::*;

View file

@ -1,455 +1,512 @@
use std::collections::HashMap; use crate::{
use bzip2_rs::decoder::Decoder; bufferer::{Bufferer, Endianess},
use crate::GDResult; protocols::{
use crate::bufferer::{Bufferer, Endianess}; types::TimeoutSettings,
use crate::GDError::{BadGame, Decompress, UnknownEnumCast}; valve::{
use crate::protocols::types::TimeoutSettings; types::{
use crate::protocols::valve::{Engine, ModData, SteamApp}; Environment,
use crate::protocols::valve::types::{Environment, ExtraData, GatheringSettings, Request, Response, Server, ServerInfo, ServerPlayer, TheShip}; ExtraData,
use crate::socket::{Socket, UdpSocket}; GatheringSettings,
use crate::utils::u8_lower_upper; Request,
Response,
#[derive(Debug, Clone)] Server,
struct Packet { ServerInfo,
pub header: u32, ServerPlayer,
pub kind: u8, TheShip,
pub payload: Vec<u8> },
} Engine,
ModData,
impl Packet { SteamApp,
fn new(buffer: &mut Bufferer) -> GDResult<Self> { },
Ok(Self { },
header: buffer.get_u32()?,
kind: buffer.get_u8()?, socket::{Socket, UdpSocket},
payload: buffer.remaining_data_vec() utils::u8_lower_upper,
}) GDError::{BadGame, Decompress, UnknownEnumCast},
} GDResult,
};
fn challenge(kind: Request, challenge: Vec<u8>) -> Self {
let mut initial = Packet::initial(kind); use bzip2_rs::decoder::Decoder;
Self { use std::collections::HashMap;
header: initial.header,
kind: initial.kind, #[derive(Debug, Clone)]
payload: match kind { struct Packet {
Request::Info => { pub header: u32,
initial.payload.extend(challenge); pub kind: u8,
initial.payload pub payload: Vec<u8>,
}, }
_ => challenge
} impl Packet {
} fn new(buffer: &mut Bufferer) -> GDResult<Self> {
} Ok(Self {
header: buffer.get_u32()?,
fn initial(kind: Request) -> Self { kind: buffer.get_u8()?,
Self { payload: buffer.remaining_data_vec(),
header: 4294967295, //FF FF FF FF })
kind: kind as u8, }
payload: match kind {
Request::Info => String::from("Source Engine Query\0").into_bytes(), fn challenge(kind: Request, challenge: Vec<u8>) -> Self {
_ => vec![0xFF, 0xFF, 0xFF, 0xFF] let mut initial = Packet::initial(kind);
}
} Self {
} header: initial.header,
kind: initial.kind,
fn to_bytes(&self) -> Vec<u8> { payload: match kind {
let mut buf = Vec::from(self.header.to_be_bytes()); Request::Info => {
initial.payload.extend(challenge);
buf.push(self.kind); initial.payload
buf.extend(&self.payload); }
_ => challenge,
buf },
} }
} }
#[derive(Debug)] fn initial(kind: Request) -> Self {
#[allow(dead_code)] //remove this later on Self {
struct SplitPacket { header: 4294967295, // FF FF FF FF
pub header: u32, kind: kind as u8,
pub id: u32, payload: match kind {
pub total: u8, Request::Info => String::from("Source Engine Query\0").into_bytes(),
pub number: u8, _ => vec![0xFF, 0xFF, 0xFF, 0xFF],
pub size: u16, },
pub compressed: bool, }
pub decompressed_size: Option<u32>, }
pub uncompressed_crc32: Option<u32>,
payload: Vec<u8> fn to_bytes(&self) -> Vec<u8> {
} let mut buf = Vec::from(self.header.to_be_bytes());
impl SplitPacket { buf.push(self.kind);
fn new(engine: &Engine, protocol: u8, buffer: &mut Bufferer) -> GDResult<Self> { buf.extend(&self.payload);
let header = buffer.get_u32()?;
let id = buffer.get_u32()?; buf
let (total, number, size, compressed, decompressed_size, uncompressed_crc32) = match engine { }
Engine::GoldSrc(_) => { }
let (lower, upper) = u8_lower_upper(buffer.get_u8()?);
(lower, upper, 0, false, None, None) #[derive(Debug)]
} #[allow(dead_code)] //remove this later on
Engine::Source(_) => { struct SplitPacket {
let total = buffer.get_u8()?; pub header: u32,
let number = buffer.get_u8()?; pub id: u32,
let size = match protocol == 7 && (*engine == SteamApp::CSS.as_engine()) { //certain apps with protocol = 7 dont have this field pub total: u8,
false => buffer.get_u16()?, pub number: u8,
true => 1248 pub size: u16,
}; pub compressed: bool,
let compressed = ((id >> 31) & 1) == 1; pub decompressed_size: Option<u32>,
let (decompressed_size, uncompressed_crc32) = match compressed { pub uncompressed_crc32: Option<u32>,
false => (None, None), payload: Vec<u8>,
true => (Some(buffer.get_u32()?), Some(buffer.get_u32()?)) }
};
(total, number, size, compressed, decompressed_size, uncompressed_crc32) impl SplitPacket {
} fn new(engine: &Engine, protocol: u8, buffer: &mut Bufferer) -> GDResult<Self> {
}; let header = buffer.get_u32()?;
let id = buffer.get_u32()?;
Ok(Self { let (total, number, size, compressed, decompressed_size, uncompressed_crc32) = match engine {
header, Engine::GoldSrc(_) => {
id, let (lower, upper) = u8_lower_upper(buffer.get_u8()?);
total, (lower, upper, 0, false, None, None)
number, }
size, Engine::Source(_) => {
compressed, let total = buffer.get_u8()?;
decompressed_size, let number = buffer.get_u8()?;
uncompressed_crc32, let size = match protocol == 7 && (*engine == SteamApp::CSS.as_engine()) {
payload: buffer.remaining_data_vec() // certain apps with protocol = 7 dont have this field
}) false => buffer.get_u16()?,
} true => 1248,
};
fn get_payload(&self) -> GDResult<Vec<u8>> { let compressed = ((id >> 31) & 1) == 1;
if self.compressed { let (decompressed_size, uncompressed_crc32) = match compressed {
let mut decoder = Decoder::new(); false => (None, None),
decoder.write(&self.payload).map_err(|_| Decompress)?; true => (Some(buffer.get_u32()?), Some(buffer.get_u32()?)),
};
let decompressed_size = self.decompressed_size.unwrap() as usize; (
total,
let mut decompressed_payload = vec![0; decompressed_size]; number,
size,
decoder.read(&mut decompressed_payload).map_err(|_| Decompress)?; compressed,
decompressed_size,
if decompressed_payload.len() != decompressed_size uncompressed_crc32,
|| crc32fast::hash(&decompressed_payload) != self.uncompressed_crc32.unwrap() { )
Err(Decompress) }
} };
else {
Ok(decompressed_payload) Ok(Self {
} header,
} else { id,
Ok(self.payload.clone()) total,
} number,
} size,
} compressed,
decompressed_size,
struct ValveProtocol { uncompressed_crc32,
socket: UdpSocket payload: buffer.remaining_data_vec(),
} })
}
static PACKET_SIZE: usize = 6144;
fn get_payload(&self) -> GDResult<Vec<u8>> {
impl ValveProtocol { if self.compressed {
fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> { let mut decoder = Decoder::new();
let socket = UdpSocket::new(address, port)?; decoder.write(&self.payload).map_err(|_| Decompress)?;
socket.apply_timeout(timeout_settings)?;
let decompressed_size = self.decompressed_size.unwrap() as usize;
Ok(Self {
socket let mut decompressed_payload = vec![0; decompressed_size];
})
} decoder
.read(&mut decompressed_payload)
fn receive(&mut self, engine: &Engine, protocol: u8, buffer_size: usize) -> GDResult<Packet> { .map_err(|_| Decompress)?;
let data = self.socket.receive(Some(buffer_size))?;
let mut buffer = Bufferer::new_with_data(Endianess::Little, &data); if decompressed_payload.len() != decompressed_size
|| crc32fast::hash(&decompressed_payload) != self.uncompressed_crc32.unwrap()
let header = buffer.get_u8()?; {
buffer.move_position_backward(1); Err(Decompress)
if header == 0xFE { //the packet is split } else {
let mut main_packet = SplitPacket::new(engine, protocol, &mut buffer)?; Ok(decompressed_payload)
let mut chunk_packets = Vec::with_capacity((main_packet.total - 1) as usize); }
} else {
for _ in 1..main_packet.total { Ok(self.payload.clone())
let new_data = self.socket.receive(Some(buffer_size))?; }
buffer = Bufferer::new_with_data(Endianess::Little, &new_data); }
let chunk_packet = SplitPacket::new(engine, protocol, &mut buffer)?; }
chunk_packets.push(chunk_packet);
} struct ValveProtocol {
socket: UdpSocket,
chunk_packets.sort_by(|a, b| a.number.cmp(&b.number)); }
for chunk_packet in chunk_packets { static PACKET_SIZE: usize = 6144;
main_packet.payload.extend(chunk_packet.payload);
} impl ValveProtocol {
fn new(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<Self> {
let mut new_packet_buffer = Bufferer::new_with_data(Endianess::Little, &main_packet.get_payload()?); let socket = UdpSocket::new(address, port)?;
Ok(Packet::new(&mut new_packet_buffer)?) socket.apply_timeout(timeout_settings)?;
}
else { Ok(Self { socket })
Packet::new(&mut buffer) }
}
} fn receive(&mut self, engine: &Engine, protocol: u8, buffer_size: usize) -> GDResult<Packet> {
let data = self.socket.receive(Some(buffer_size))?;
/// Ask for a specific request only. let mut buffer = Bufferer::new_with_data(Endianess::Little, &data);
fn get_request_data(&mut self, engine: &Engine, protocol: u8, kind: Request) -> GDResult<Bufferer> {
let request_initial_packet = Packet::initial(kind).to_bytes(); let header = buffer.get_u8()?;
self.socket.send(&request_initial_packet)?; buffer.move_position_backward(1);
if header == 0xFE {
let mut packet = self.receive(engine, protocol, PACKET_SIZE)?; // the packet is split
while packet.kind == 0x41 {// 'A' let mut main_packet = SplitPacket::new(engine, protocol, &mut buffer)?;
let challenge = packet.payload.clone(); let mut chunk_packets = Vec::with_capacity((main_packet.total - 1) as usize);
let challenge_packet = Packet::challenge(kind, challenge).to_bytes();
for _ in 1 .. main_packet.total {
self.socket.send(&challenge_packet)?; let new_data = self.socket.receive(Some(buffer_size))?;
buffer = Bufferer::new_with_data(Endianess::Little, &new_data);
packet = self.receive(engine, protocol, PACKET_SIZE)?; let chunk_packet = SplitPacket::new(engine, protocol, &mut buffer)?;
} chunk_packets.push(chunk_packet);
}
let data = packet.payload;
Ok(Bufferer::new_with_data(Endianess::Little, &data)) chunk_packets.sort_by(|a, b| a.number.cmp(&b.number));
}
for chunk_packet in chunk_packets {
fn get_goldsrc_server_info(buffer: &mut Bufferer) -> GDResult<ServerInfo> { main_packet.payload.extend(chunk_packet.payload);
buffer.get_u8()?; //get the header (useless info) }
buffer.get_string_utf8()?; //get the server address (useless info)
let name = buffer.get_string_utf8()?; let mut new_packet_buffer = Bufferer::new_with_data(Endianess::Little, &main_packet.get_payload()?);
let map = buffer.get_string_utf8()?; Ok(Packet::new(&mut new_packet_buffer)?)
let folder = buffer.get_string_utf8()?; } else {
let game = buffer.get_string_utf8()?; Packet::new(&mut buffer)
let players = buffer.get_u8()?; }
let max_players = buffer.get_u8()?; }
let protocol = buffer.get_u8()?;
let server_type = match buffer.get_u8()? { /// Ask for a specific request only.
68 => Server::Dedicated, //'D' fn get_request_data(&mut self, engine: &Engine, protocol: u8, kind: Request) -> GDResult<Bufferer> {
76 => Server::NonDedicated, //'L' let request_initial_packet = Packet::initial(kind).to_bytes();
80 => Server::TV, //'P' self.socket.send(&request_initial_packet)?;
_ => Err(UnknownEnumCast)?
}; let mut packet = self.receive(engine, protocol, PACKET_SIZE)?;
let environment_type = match buffer.get_u8()? { while packet.kind == 0x41 {
76 => Environment::Linux, //'L' // 'A'
87 => Environment::Windows, //'W' let challenge = packet.payload.clone();
_ => Err(UnknownEnumCast)? let challenge_packet = Packet::challenge(kind, challenge).to_bytes();
};
let has_password = buffer.get_u8()? == 1; self.socket.send(&challenge_packet)?;
let is_mod = buffer.get_u8()? == 1;
let mod_data = match is_mod { packet = self.receive(engine, protocol, PACKET_SIZE)?;
false => None, }
true => Some(ModData {
link: buffer.get_string_utf8()?, let data = packet.payload;
download_link: buffer.get_string_utf8()?, Ok(Bufferer::new_with_data(Endianess::Little, &data))
version: buffer.get_u32()?, }
size: buffer.get_u32()?,
multiplayer_only: buffer.get_u8()? == 1, fn get_goldsrc_server_info(buffer: &mut Bufferer) -> GDResult<ServerInfo> {
has_own_dll: buffer.get_u8()? == 1 buffer.get_u8()?; //get the header (useless info)
}) buffer.get_string_utf8()?; //get the server address (useless info)
}; let name = buffer.get_string_utf8()?;
let vac_secured = buffer.get_u8()? == 1; let map = buffer.get_string_utf8()?;
let bots = buffer.get_u8()?; let folder = buffer.get_string_utf8()?;
let game = buffer.get_string_utf8()?;
Ok(ServerInfo { let players = buffer.get_u8()?;
protocol, let max_players = buffer.get_u8()?;
name, let protocol = buffer.get_u8()?;
map, let server_type = match buffer.get_u8()? {
folder, 68 => Server::Dedicated, //'D'
game, 76 => Server::NonDedicated, //'L'
appid: 0, //not present in the obsolete response 80 => Server::TV, //'P'
players_online: players, _ => Err(UnknownEnumCast)?,
players_maximum: max_players, };
players_bots: bots, let environment_type = match buffer.get_u8()? {
server_type, 76 => Environment::Linux, //'L'
environment_type, 87 => Environment::Windows, //'W'
has_password, _ => Err(UnknownEnumCast)?,
vac_secured, };
the_ship: None, let has_password = buffer.get_u8()? == 1;
version: "".to_string(), //a version field only for the mod let is_mod = buffer.get_u8()? == 1;
extra_data: None, let mod_data = match is_mod {
is_mod, false => None,
mod_data true => {
}) Some(ModData {
} link: buffer.get_string_utf8()?,
download_link: buffer.get_string_utf8()?,
/// Get the server information's. version: buffer.get_u32()?,
fn get_server_info(&mut self, engine: &Engine) -> GDResult<ServerInfo> { size: buffer.get_u32()?,
let mut buffer = self.get_request_data(engine, 0, Request::Info)?; multiplayer_only: buffer.get_u8()? == 1,
has_own_dll: buffer.get_u8()? == 1,
if let Engine::GoldSrc(force) = engine { })
if *force { }
return ValveProtocol::get_goldsrc_server_info(&mut buffer); };
} let vac_secured = buffer.get_u8()? == 1;
} let bots = buffer.get_u8()?;
let protocol = buffer.get_u8()?; Ok(ServerInfo {
let name = buffer.get_string_utf8()?; protocol,
let map = buffer.get_string_utf8()?; name,
let folder = buffer.get_string_utf8()?; map,
let game = buffer.get_string_utf8()?; folder,
let mut appid = buffer.get_u16()? as u32; game,
let players = buffer.get_u8()?; appid: 0, // not present in the obsolete response
let max_players = buffer.get_u8()?; players_online: players,
let bots = buffer.get_u8()?; players_maximum: max_players,
let server_type = match buffer.get_u8()? { players_bots: bots,
100 => Server::Dedicated, //'d' server_type,
108 => Server::NonDedicated, //'l' environment_type,
112 => Server::TV, //'p' has_password,
_ => Err(UnknownEnumCast)? vac_secured,
}; the_ship: None,
let environment_type = match buffer.get_u8()? { version: "".to_string(), // a version field only for the mod
108 => Environment::Linux, //'l' extra_data: None,
119 => Environment::Windows, //'w' is_mod,
109 | 111 => Environment::Mac, //'m' or 'o' mod_data,
_ => Err(UnknownEnumCast)? })
}; }
let has_password = buffer.get_u8()? == 1;
let vac_secured = buffer.get_u8()? == 1; /// Get the server information's.
let the_ship = match *engine == SteamApp::TS.as_engine() { fn get_server_info(&mut self, engine: &Engine) -> GDResult<ServerInfo> {
false => None, let mut buffer = self.get_request_data(engine, 0, Request::Info)?;
true => Some(TheShip {
mode: buffer.get_u8()?, if let Engine::GoldSrc(force) = engine {
witnesses: buffer.get_u8()?, if *force {
duration: buffer.get_u8()? return ValveProtocol::get_goldsrc_server_info(&mut buffer);
}) }
}; }
let version = buffer.get_string_utf8()?;
let extra_data = match buffer.get_u8() { let protocol = buffer.get_u8()?;
Err(_) => None, let name = buffer.get_string_utf8()?;
Ok(value) => Some(ExtraData { let map = buffer.get_string_utf8()?;
port: match (value & 0x80) > 0 { let folder = buffer.get_string_utf8()?;
false => None, let game = buffer.get_string_utf8()?;
true => Some(buffer.get_u16()?) let mut appid = buffer.get_u16()? as u32;
}, let players = buffer.get_u8()?;
steam_id: match (value & 0x10) > 0 { let max_players = buffer.get_u8()?;
false => None, let bots = buffer.get_u8()?;
true => Some(buffer.get_u64()?) let server_type = match buffer.get_u8()? {
}, 100 => Server::Dedicated, //'d'
tv_port: match (value & 0x40) > 0 { 108 => Server::NonDedicated, //'l'
false => None, 112 => Server::TV, //'p'
true => Some(buffer.get_u16()?) _ => Err(UnknownEnumCast)?,
}, };
tv_name: match (value & 0x40) > 0 { let environment_type = match buffer.get_u8()? {
false => None, 108 => Environment::Linux, //'l'
true => Some(buffer.get_string_utf8()?) 119 => Environment::Windows, //'w'
}, 109 | 111 => Environment::Mac, //'m' or 'o'
keywords: match (value & 0x20) > 0 { _ => Err(UnknownEnumCast)?,
false => None, };
true => Some(buffer.get_string_utf8()?) let has_password = buffer.get_u8()? == 1;
}, let vac_secured = buffer.get_u8()? == 1;
game_id: match (value & 0x01) > 0 { let the_ship = match *engine == SteamApp::TS.as_engine() {
false => None, false => None,
true => { true => {
let gid = buffer.get_u64()?; Some(TheShip {
appid = (gid & ((1 << 24) - 1)) as u32; mode: buffer.get_u8()?,
witnesses: buffer.get_u8()?,
Some(gid) duration: buffer.get_u8()?,
} })
} }
}) };
}; let version = buffer.get_string_utf8()?;
let extra_data = match buffer.get_u8() {
Ok(ServerInfo { Err(_) => None,
protocol, Ok(value) => {
name, Some(ExtraData {
map, port: match (value & 0x80) > 0 {
folder, false => None,
game, true => Some(buffer.get_u16()?),
appid, },
players_online: players, steam_id: match (value & 0x10) > 0 {
players_maximum: max_players, false => None,
players_bots: bots, true => Some(buffer.get_u64()?),
server_type, },
environment_type, tv_port: match (value & 0x40) > 0 {
has_password, false => None,
vac_secured, true => Some(buffer.get_u16()?),
the_ship, },
version, tv_name: match (value & 0x40) > 0 {
extra_data, false => None,
is_mod: false, true => Some(buffer.get_string_utf8()?),
mod_data: None },
}) keywords: match (value & 0x20) > 0 {
} false => None,
true => Some(buffer.get_string_utf8()?),
/// Get the server player's. },
fn get_server_players(&mut self, engine: &Engine, protocol: u8) -> GDResult<Vec<ServerPlayer>> { game_id: match (value & 0x01) > 0 {
let mut buffer = self.get_request_data(engine, protocol, Request::Players)?; false => None,
true => {
let count = buffer.get_u8()? as usize; let gid = buffer.get_u64()?;
let mut players: Vec<ServerPlayer> = Vec::with_capacity(count); appid = (gid & ((1 << 24) - 1)) as u32;
for _ in 0..count { Some(gid)
buffer.move_position_ahead(1); //skip the index byte }
},
players.push(ServerPlayer { })
name: buffer.get_string_utf8()?, }
score: buffer.get_u32()?, };
duration: buffer.get_f32()?,
deaths: match *engine == SteamApp::TS.as_engine() { Ok(ServerInfo {
false => None, protocol,
true => Some(buffer.get_u32()?) name,
}, map,
money: match *engine == SteamApp::TS.as_engine() { folder,
false => None, game,
true => Some(buffer.get_u32()?) appid,
}, players_online: players,
}); players_maximum: max_players,
} players_bots: bots,
server_type,
Ok(players) environment_type,
} has_password,
vac_secured,
/// Get the server's rules. the_ship,
fn get_server_rules(&mut self, engine: &Engine, protocol: u8) -> GDResult<HashMap<String, String>> { version,
let mut buffer = self.get_request_data(engine, protocol, Request::Rules)?; extra_data,
is_mod: false,
let count = buffer.get_u16()? as usize; mod_data: None,
let mut rules: HashMap<String, String> = HashMap::with_capacity(count); })
}
for _ in 0..count {
let name = buffer.get_string_utf8()?; /// Get the server player's.
let value = buffer.get_string_utf8()?; fn get_server_players(&mut self, engine: &Engine, protocol: u8) -> GDResult<Vec<ServerPlayer>> {
let mut buffer = self.get_request_data(engine, protocol, Request::Players)?;
rules.insert(name, value);
} let count = buffer.get_u8()? as usize;
let mut players: Vec<ServerPlayer> = Vec::with_capacity(count);
if *engine == SteamApp::ROR2.as_engine() {
rules.remove("Test"); for _ in 0 .. count {
} buffer.move_position_ahead(1); //skip the index byte
Ok(rules) players.push(ServerPlayer {
} name: buffer.get_string_utf8()?,
} score: buffer.get_u32()?,
duration: buffer.get_f32()?,
/// Query a server by providing the address, the port, the app, gather and timeout settings. deaths: match *engine == SteamApp::TS.as_engine() {
/// Providing None to the settings results in using the default values for them (GatherSettings::[default](GatheringSettings::default), TimeoutSettings::[default](TimeoutSettings::default)). false => None,
pub fn query(address: &str, port: u16, engine: Engine, gather_settings: Option<GatheringSettings>, timeout_settings: Option<TimeoutSettings>) -> GDResult<Response> { true => Some(buffer.get_u32()?),
let response_gather_settings = gather_settings.unwrap_or_default(); },
get_response(address, port, engine, response_gather_settings, timeout_settings) money: match *engine == SteamApp::TS.as_engine() {
} false => None,
true => Some(buffer.get_u32()?),
fn get_response(address: &str, port: u16, engine: Engine, gather_settings: GatheringSettings, timeout_settings: Option<TimeoutSettings>) -> GDResult<Response> { },
let mut client = ValveProtocol::new(address, port, timeout_settings)?; });
}
let info = client.get_server_info(&engine)?;
let protocol = info.protocol; Ok(players)
}
if let Engine::Source(Some(appids)) = &engine {
let mut is_specified_id = false; /// Get the server's rules.
fn get_server_rules(&mut self, engine: &Engine, protocol: u8) -> GDResult<HashMap<String, String>> {
if appids.0 == info.appid { let mut buffer = self.get_request_data(engine, protocol, Request::Rules)?;
is_specified_id = true;
} else if let Some(dedicated_appid) = appids.1 { let count = buffer.get_u16()? as usize;
if dedicated_appid == info.appid { let mut rules: HashMap<String, String> = HashMap::with_capacity(count);
is_specified_id = true;
} for _ in 0 .. count {
} let name = buffer.get_string_utf8()?;
let value = buffer.get_string_utf8()?;
if !is_specified_id {
return Err(BadGame(format!("AppId: {}", info.appid))); rules.insert(name, value);
} }
}
if *engine == SteamApp::ROR2.as_engine() {
Ok(Response { rules.remove("Test");
info, }
players: match gather_settings.players {
false => None, Ok(rules)
true => Some(client.get_server_players(&engine, protocol)?) }
}, }
rules: match gather_settings.rules {
false => None, /// Query a server by providing the address, the port, the app, gather and
true => Some(client.get_server_rules(&engine, protocol)?) /// 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: &str,
port: u16,
engine: Engine,
gather_settings: Option<GatheringSettings>,
timeout_settings: Option<TimeoutSettings>,
) -> GDResult<Response> {
let response_gather_settings = gather_settings.unwrap_or_default();
get_response(
address,
port,
engine,
response_gather_settings,
timeout_settings,
)
}
fn get_response(
address: &str,
port: u16,
engine: Engine,
gather_settings: GatheringSettings,
timeout_settings: Option<TimeoutSettings>,
) -> GDResult<Response> {
let mut client = ValveProtocol::new(address, port, timeout_settings)?;
let info = client.get_server_info(&engine)?;
let protocol = info.protocol;
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 {
return Err(BadGame(format!("AppId: {}", info.appid)));
}
}
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

@ -1,444 +1,441 @@
use std::collections::HashMap; use std::collections::HashMap;
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// The type of the server. /// The type of the server.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Server { pub enum Server {
Dedicated, Dedicated,
NonDedicated, NonDedicated,
TV, TV,
} }
/// The Operating System that the server is on. /// The Operating System that the server is on.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Environment { pub enum Environment {
Linux, Linux,
Windows, Windows,
Mac, Mac,
} }
/// A query response. /// A query response.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct Response { pub struct Response {
pub info: ServerInfo, pub info: ServerInfo,
pub players: Option<Vec<ServerPlayer>>, pub players: Option<Vec<ServerPlayer>>,
pub rules: Option<HashMap<String, String>>, pub rules: Option<HashMap<String, String>>,
} }
/// General server information's. /// General server information's.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ServerInfo { pub struct ServerInfo {
/// Protocol used by the server. /// Protocol used by the server.
pub protocol: u8, pub protocol: u8,
/// Name of the server. /// Name of the server.
pub name: String, pub name: String,
/// Map name. /// Map name.
pub map: String, pub map: String,
/// Name of the folder containing the game files. /// Name of the folder containing the game files.
pub folder: String, pub folder: String,
/// The name of the game. /// The name of the game.
pub game: String, pub game: String,
/// [Steam Application ID](https://developer.valvesoftware.com/wiki/Steam_Application_ID) of game. /// [Steam Application ID](https://developer.valvesoftware.com/wiki/Steam_Application_ID) of game.
pub appid: u32, pub appid: u32,
/// Number of players on the server. /// Number of players on the server.
pub players_online: u8, pub players_online: u8,
/// Maximum number of players the server reports it can hold. /// Maximum number of players the server reports it can hold.
pub players_maximum: u8, pub players_maximum: u8,
/// Number of bots on the server. /// Number of bots on the server.
pub players_bots: u8, pub players_bots: u8,
/// Dedicated, NonDedicated or SourceTV /// Dedicated, NonDedicated or SourceTV
pub server_type: Server, pub server_type: Server,
/// The Operating System that the server is on. /// The Operating System that the server is on.
pub environment_type: Environment, pub environment_type: Environment,
/// Indicates whether the server requires a password. /// Indicates whether the server requires a password.
pub has_password: bool, pub has_password: bool,
/// Indicates whether the server uses VAC. /// Indicates whether the server uses VAC.
pub vac_secured: bool, pub vac_secured: bool,
/// [The ship](https://developer.valvesoftware.com/wiki/The_Ship) extra data /// [The ship](https://developer.valvesoftware.com/wiki/The_Ship) extra data
pub the_ship: Option<TheShip>, pub the_ship: Option<TheShip>,
/// Version of the game installed on the server. /// Version of the game installed on the server.
pub version: String, pub version: String,
/// Some extra data that the server might provide or not. /// Some extra data that the server might provide or not.
pub extra_data: Option<ExtraData>, pub extra_data: Option<ExtraData>,
/// GoldSrc only: Indicates whether the hosted game is a mod. /// GoldSrc only: Indicates whether the hosted game is a mod.
pub is_mod: bool, pub is_mod: bool,
/// GoldSrc only: If the game is a mod, provide additional data. /// GoldSrc only: If the game is a mod, provide additional data.
pub mod_data: Option<ModData>, pub mod_data: Option<ModData>,
} }
/// A server player. /// A server player.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct ServerPlayer { pub struct ServerPlayer {
/// Player's name. /// Player's name.
pub name: String, pub name: String,
/// General score. /// General score.
pub score: u32, pub score: u32,
/// How long a player has been in the server (seconds). /// How long a player has been in the server (seconds).
pub duration: f32, pub duration: f32,
/// Only for [the ship](https://developer.valvesoftware.com/wiki/The_Ship): deaths count /// Only for [the ship](https://developer.valvesoftware.com/wiki/The_Ship): deaths count
pub deaths: Option<u32>, //the_ship pub deaths: Option<u32>, // the_ship
/// Only for [the ship](https://developer.valvesoftware.com/wiki/The_Ship): money amount /// Only for [the ship](https://developer.valvesoftware.com/wiki/The_Ship): money amount
pub money: Option<u32>, //the_ship pub money: Option<u32>, // the_ship
} }
/// Only present for [the ship](https://developer.valvesoftware.com/wiki/The_Ship). /// Only present for [the ship](https://developer.valvesoftware.com/wiki/The_Ship).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TheShip { pub struct TheShip {
pub mode: u8, pub mode: u8,
pub witnesses: u8, pub witnesses: u8,
pub duration: u8, pub duration: u8,
} }
/// Some extra data that the server might provide or not. /// Some extra data that the server might provide or not.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ExtraData { pub struct ExtraData {
/// The server's game port number. /// The server's game port number.
pub port: Option<u16>, pub port: Option<u16>,
/// Server's SteamID. /// Server's SteamID.
pub steam_id: Option<u64>, pub steam_id: Option<u64>,
/// SourceTV's port. /// SourceTV's port.
pub tv_port: Option<u16>, pub tv_port: Option<u16>,
/// SourceTV's name. /// SourceTV's name.
pub tv_name: Option<String>, pub tv_name: Option<String>,
/// Keywords that describe the server according to it. /// Keywords that describe the server according to it.
pub keywords: Option<String>, pub keywords: Option<String>,
/// The server's 64-bit GameID. /// The server's 64-bit GameID.
pub game_id: Option<u64>, pub game_id: Option<u64>,
} }
/// Data related to GoldSrc Mod response. /// Data related to GoldSrc Mod response.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ModData { pub struct ModData {
pub link: String, pub link: String,
pub download_link: String, pub download_link: String,
pub version: u32, pub version: u32,
pub size: u32, pub size: u32,
pub multiplayer_only: bool, pub multiplayer_only: bool,
pub has_own_dll: bool, pub has_own_dll: bool,
} }
pub(crate) type ExtractedData = ( pub(crate) type ExtractedData = (
Option<u16>, Option<u16>,
Option<u64>, Option<u64>,
Option<u16>, Option<u16>,
Option<String>, Option<String>,
Option<String>, Option<String>,
); );
pub(crate) fn get_optional_extracted_data( pub(crate) fn get_optional_extracted_data(data: Option<ExtraData>) -> ExtractedData {
data: Option<ExtraData>, match data {
) -> ExtractedData { None => (None, None, None, None, None),
match data { Some(ed) => (ed.port, ed.steam_id, ed.tv_port, ed.tv_name, ed.keywords),
None => (None, None, None, None, None), }
Some(ed) => (ed.port, ed.steam_id, ed.tv_port, ed.tv_name, ed.keywords), }
}
} /// The type of the request, see the [protocol](https://developer.valvesoftware.com/wiki/Server_queries).
#[derive(Eq, PartialEq, Copy, Clone)]
/// The type of the request, see the [protocol](https://developer.valvesoftware.com/wiki/Server_queries). #[repr(u8)]
#[derive(Eq, PartialEq, Copy, Clone)] pub(crate) enum Request {
#[repr(u8)] /// Known as `A2S_INFO`
pub(crate) enum Request { Info = 0x54,
/// Known as `A2S_INFO` /// Known as `A2S_PLAYERS`
Info = 0x54, Players = 0x55,
/// Known as `A2S_PLAYERS` /// Known as `A2S_RULES`
Players = 0x55, Rules = 0x56,
/// Known as `A2S_RULES` }
Rules = 0x56,
} /// Supported steam apps
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
/// Supported steam apps #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum SteamApp {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] /// Counter-Strike
pub enum SteamApp { CS,
/// Counter-Strike /// Team Fortress Classic
CS, TFC,
/// Team Fortress Classic /// Day of Defeat
TFC, DOD,
/// Day of Defeat /// Counter-Strike: Condition Zero
DOD, CSCZ,
/// Counter-Strike: Condition Zero /// Counter-Strike: Source
CSCZ, CSS,
/// Counter-Strike: Source /// Day of Defeat: Source
CSS, DODS,
/// Day of Defeat: Source /// Half-Life 2 Deathmatch
DODS, HL2DM,
/// Half-Life 2 Deathmatch /// Half-Life Deathmatch: Source
HL2DM, HLDMS,
/// Half-Life Deathmatch: Source /// Team Fortress 2
HLDMS, TF2,
/// Team Fortress 2 /// Left 4 Dead
TF2, L4D,
/// Left 4 Dead /// Left 4 Dead
L4D, L4D2,
/// Left 4 Dead /// Alien Swarm
L4D2, ALIENS,
/// Alien Swarm /// Counter-Strike: Global Offensive
ALIENS, CSGO,
/// Counter-Strike: Global Offensive /// The Ship
CSGO, TS,
/// The Ship /// Garry's Mod
TS, GM,
/// Garry's Mod /// Age of Chivalry
GM, AOC,
/// Age of Chivalry /// Insurgency: Modern Infantry Combat
AOC, INSMIC,
/// Insurgency: Modern Infantry Combat /// ARMA 2: Operation Arrowhead
INSMIC, ARMA2OA,
/// ARMA 2: Operation Arrowhead /// Project Zomboid
ARMA2OA, PZ,
/// Project Zomboid /// Insurgency
PZ, INS,
/// Insurgency /// Sven Co-op
INS, SC,
/// Sven Co-op /// 7 Days To Die
SC, SDTD,
/// 7 Days To Die /// Rust
SDTD, RUST,
/// Rust /// Vallistic Overkill
RUST, BO,
/// Vallistic Overkill /// Don't Starve Together
BO, DST,
/// Don't Starve Together /// BrainBread 2
DST, BB2,
/// BrainBread 2 /// Codename CURE
BB2, CCURE,
/// Codename CURE /// Black Mesa
CCURE, BM,
/// Black Mesa /// Colony Survival
BM, COSU,
/// Colony Survival /// Avorion
COSU, AVORION,
/// Avorion /// Day of Infamy
AVORION, DOI,
/// Day of Infamy /// The Forest
DOI, TF,
/// The Forest /// Unturned
TF, UNTURNED,
/// Unturned /// ARK: Survival Evolved
UNTURNED, ASE,
/// ARK: Survival Evolved /// Battalion 1944
ASE, BAT1944,
/// Battalion 1944 /// Insurgency: Sandstorm
BAT1944, INSS,
/// Insurgency: Sandstorm /// Alien Swarm: Reactive Drop
INSS, ASRD,
/// Alien Swarm: Reactive Drop /// Risk of Rain 2
ASRD, ROR2,
/// Risk of Rain 2 /// Operation: Harsh Doorstop
ROR2, OHD,
/// Operation: Harsh Doorstop /// Onset
OHD, ONSET,
/// Onset /// V Rising
ONSET, VR,
/// V Rising }
VR,
} impl SteamApp {
/// Get the specified app as engine.
impl SteamApp { pub fn as_engine(&self) -> Engine {
/// Get the specified app as engine. match self {
pub fn as_engine(&self) -> Engine { SteamApp::CS => Engine::GoldSrc(false), // 10
match self { SteamApp::TFC => Engine::GoldSrc(false), // 20
SteamApp::CS => Engine::GoldSrc(false), //10 SteamApp::DOD => Engine::GoldSrc(false), // 30
SteamApp::TFC => Engine::GoldSrc(false), //20 SteamApp::CSCZ => Engine::GoldSrc(false), // 80
SteamApp::DOD => Engine::GoldSrc(false), //30 SteamApp::CSS => Engine::new_source(240),
SteamApp::CSCZ => Engine::GoldSrc(false), //80 SteamApp::DODS => Engine::new_source(300),
SteamApp::CSS => Engine::new_source(240), SteamApp::HL2DM => Engine::new_source(320),
SteamApp::DODS => Engine::new_source(300), SteamApp::HLDMS => Engine::new_source(360),
SteamApp::HL2DM => Engine::new_source(320), SteamApp::TF2 => Engine::new_source(440),
SteamApp::HLDMS => Engine::new_source(360), SteamApp::L4D => Engine::new_source(500),
SteamApp::TF2 => Engine::new_source(440), SteamApp::L4D2 => Engine::new_source(550),
SteamApp::L4D => Engine::new_source(500), SteamApp::ALIENS => Engine::new_source(630),
SteamApp::L4D2 => Engine::new_source(550), SteamApp::CSGO => Engine::new_source(730),
SteamApp::ALIENS => Engine::new_source(630), SteamApp::TS => Engine::new_source(2400),
SteamApp::CSGO => Engine::new_source(730), SteamApp::GM => Engine::new_source(4000),
SteamApp::TS => Engine::new_source(2400), SteamApp::AOC => Engine::new_source(17510),
SteamApp::GM => Engine::new_source(4000), SteamApp::INSMIC => Engine::new_source(17700),
SteamApp::AOC => Engine::new_source(17510), SteamApp::ARMA2OA => Engine::new_source(33930),
SteamApp::INSMIC => Engine::new_source(17700), SteamApp::PZ => Engine::new_source(108600),
SteamApp::ARMA2OA => Engine::new_source(33930), SteamApp::INS => Engine::new_source(222880),
SteamApp::PZ => Engine::new_source(108600), SteamApp::SC => Engine::GoldSrc(false), // 225840
SteamApp::INS => Engine::new_source(222880), SteamApp::SDTD => Engine::new_source(251570),
SteamApp::SC => Engine::GoldSrc(false), //225840 SteamApp::RUST => Engine::new_source(252490),
SteamApp::SDTD => Engine::new_source(251570), SteamApp::BO => Engine::new_source(296300),
SteamApp::RUST => Engine::new_source(252490), SteamApp::DST => Engine::new_source(322320),
SteamApp::BO => Engine::new_source(296300), SteamApp::BB2 => Engine::new_source(346330),
SteamApp::DST => Engine::new_source(322320), SteamApp::CCURE => Engine::new_source(355180),
SteamApp::BB2 => Engine::new_source(346330), SteamApp::BM => Engine::new_source(362890),
SteamApp::CCURE => Engine::new_source(355180), SteamApp::COSU => Engine::new_source(366090),
SteamApp::BM => Engine::new_source(362890), SteamApp::AVORION => Engine::new_source(445220),
SteamApp::COSU => Engine::new_source(366090), SteamApp::DOI => Engine::new_source(447820),
SteamApp::AVORION => Engine::new_source(445220), SteamApp::TF => Engine::new_source(556450),
SteamApp::DOI => Engine::new_source(447820), SteamApp::UNTURNED => Engine::new_source(304930),
SteamApp::TF => Engine::new_source(556450), SteamApp::ASE => Engine::new_source(346110),
SteamApp::UNTURNED => Engine::new_source(304930), SteamApp::BAT1944 => Engine::new_source(489940),
SteamApp::ASE => Engine::new_source(346110), SteamApp::INSS => Engine::new_source(581320),
SteamApp::BAT1944 => Engine::new_source(489940), SteamApp::ASRD => Engine::new_source(563560),
SteamApp::INSS => Engine::new_source(581320), SteamApp::ROR2 => Engine::new_source(632360),
SteamApp::ASRD => Engine::new_source(563560), SteamApp::OHD => Engine::new_source_with_dedicated(736590, 950900),
SteamApp::ROR2 => Engine::new_source(632360), SteamApp::ONSET => Engine::new_source(1105810),
SteamApp::OHD => Engine::new_source_with_dedicated(736590, 950900), SteamApp::VR => Engine::new_source(1604030),
SteamApp::ONSET => Engine::new_source(1105810), }
SteamApp::VR => Engine::new_source(1604030), }
} }
}
} /// Engine type.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
/// Engine type. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum Engine {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] /// A Source game, the argument represents the possible steam app ids, if
pub enum Engine { /// its **None**, let the query find it, if its **Some**, the query
/// A Source game, the argument represents the possible steam app ids, if its **None**, let /// fails if the response id is not the first one, which is the game app
/// the query find it, if its **Some**, the query fails if the response id is not the first /// id, or the other one, which is the dedicated server app id.
/// one, which is the game app id, or the other one, which is the dedicated server app id. Source(Option<(u32, Option<u32>)>),
Source(Option<(u32, Option<u32>)>), /// A GoldSrc game, the argument indicates whether to enforce
/// A GoldSrc game, the argument indicates whether to enforce /// requesting the obsolete A2S_INFO response or not.
/// requesting the obsolete A2S_INFO response or not. GoldSrc(bool),
GoldSrc(bool), }
}
impl Engine {
impl Engine { pub fn new_source(appid: u32) -> Self { Engine::Source(Some((appid, None))) }
pub fn new_source(appid: u32) -> Self {
Engine::Source(Some((appid, None))) pub fn new_source_with_dedicated(appid: u32, dedicated_appid: u32) -> Self {
} Engine::Source(Some((appid, Some(dedicated_appid))))
}
pub fn new_source_with_dedicated(appid: u32, dedicated_appid: u32) -> Self { }
Engine::Source(Some((appid, Some(dedicated_appid))))
} /// What data to gather, purely used only with the query function.
} pub struct GatheringSettings {
pub players: bool,
/// What data to gather, purely used only with the query function. pub rules: bool,
pub struct GatheringSettings { }
pub players: bool,
pub rules: bool, impl Default for GatheringSettings {
} /// Default values are true for both the players and the rules.
fn default() -> Self {
impl Default for GatheringSettings { Self {
/// Default values are true for both the players and the rules. players: true,
fn default() -> Self { rules: true,
Self { }
players: true, }
rules: true, }
}
} /// 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).
/// Generic response types that are used by many games, they are the protocol ones, but without the pub mod game {
/// unnecessary bits (example: the **The Ship**-only fields). use super::{Server, ServerPlayer};
pub mod game { use crate::protocols::valve::types::get_optional_extracted_data;
use super::{Server, ServerPlayer}; use std::collections::HashMap;
use crate::protocols::valve::types::get_optional_extracted_data;
use std::collections::HashMap; #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; /// A player's details.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
/// A player's details. #[derive(Debug, Clone, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Player {
#[derive(Debug, Clone, PartialEq, PartialOrd)] /// Player's name.
pub struct Player { pub name: String,
/// Player's name. /// Player's score.
pub name: String, pub score: u32,
/// Player's score. /// How long a player has been in the server (seconds).
pub score: u32, pub duration: f32,
/// How long a player has been in the server (seconds). }
pub duration: f32,
} impl Player {
pub fn from_valve_response(player: &ServerPlayer) -> Self {
impl Player { Self {
pub fn from_valve_response(player: &ServerPlayer) -> Self { name: player.name.clone(),
Self { score: player.score,
name: player.name.clone(), duration: player.duration,
score: player.score, }
duration: player.duration, }
} }
}
} /// The query response.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
/// The query response. #[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Response {
#[derive(Debug, Clone, PartialEq)] /// Protocol used by the server.
pub struct Response { pub protocol: u8,
/// Protocol used by the server. /// Name of the server.
pub protocol: u8, pub name: String,
/// Name of the server. /// Map name.
pub name: String, pub map: String,
/// Map name. /// The name of the game.
pub map: String, pub game: String,
/// The name of the game. /// Server's app id.
pub game: String, pub appid: u32,
/// Server's app id. /// Number of players on the server.
pub appid: u32, pub players_online: u8,
/// Number of players on the server. /// Details about the server's players (not all players necessarily).
pub players_online: u8, pub players_details: Vec<Player>,
/// Details about the server's players (not all players necessarily). /// Maximum number of players the server reports it can hold.
pub players_details: Vec<Player>, pub players_maximum: u8,
/// Maximum number of players the server reports it can hold. /// Number of bots on the server.
pub players_maximum: u8, pub players_bots: u8,
/// Number of bots on the server. /// Dedicated, NonDedicated or SourceTV
pub players_bots: u8, pub server_type: Server,
/// Dedicated, NonDedicated or SourceTV /// Indicates whether the server requires a password.
pub server_type: Server, pub has_password: bool,
/// Indicates whether the server requires a password. /// Indicated whether the server uses VAC.
pub has_password: bool, pub vac_secured: bool,
/// Indicated whether the server uses VAC. /// Version of the game installed on the server.
pub vac_secured: bool, pub version: String,
/// Version of the game installed on the server. /// The server's reported connection port.
pub version: String, pub port: Option<u16>,
/// The server's reported connection port. /// Server's SteamID.
pub port: Option<u16>, pub steam_id: Option<u64>,
/// Server's SteamID. /// SourceTV's connection port.
pub steam_id: Option<u64>, pub tv_port: Option<u16>,
/// SourceTV's connection port. /// SourceTV's name.
pub tv_port: Option<u16>, pub tv_name: Option<String>,
/// SourceTV's name. /// Keywords that describe the server according to it.
pub tv_name: Option<String>, pub keywords: Option<String>,
/// Keywords that describe the server according to it. /// Server's rules.
pub keywords: Option<String>, pub rules: HashMap<String, String>,
/// Server's rules. }
pub rules: HashMap<String, String>,
} impl Response {
pub fn new_from_valve_response(response: super::Response) -> Self {
impl Response { let (port, steam_id, tv_port, tv_name, keywords) = get_optional_extracted_data(response.info.extra_data);
pub fn new_from_valve_response(response: super::Response) -> Self {
let (port, steam_id, tv_port, tv_name, keywords) = Self {
get_optional_extracted_data(response.info.extra_data); protocol: response.info.protocol,
name: response.info.name,
Self { map: response.info.map,
protocol: response.info.protocol, game: response.info.game,
name: response.info.name, appid: response.info.appid,
map: response.info.map, players_online: response.info.players_online,
game: response.info.game, players_details: response
appid: response.info.appid, .players
players_online: response.info.players_online, .unwrap_or_default()
players_details: response .iter()
.players .map(Player::from_valve_response)
.unwrap_or_default() .collect(),
.iter() players_maximum: response.info.players_maximum,
.map(Player::from_valve_response) players_bots: response.info.players_bots,
.collect(), server_type: response.info.server_type,
players_maximum: response.info.players_maximum, has_password: response.info.has_password,
players_bots: response.info.players_bots, vac_secured: response.info.vac_secured,
server_type: response.info.server_type, version: response.info.version,
has_password: response.info.has_password, port,
vac_secured: response.info.vac_secured, steam_id,
version: response.info.version, tv_port,
port, tv_name,
steam_id, keywords,
tv_port, rules: response.rules.unwrap_or_default(),
tv_name, }
keywords, }
rules: response.rules.unwrap_or_default(), }
} }
}
}
}

View file

@ -1,165 +1,168 @@
use crate::protocols::types::TimeoutSettings; use crate::{
use crate::utils::address_and_port_as_string; protocols::types::TimeoutSettings,
use crate::GDError::{PacketReceive, PacketSend, SocketBind, SocketConnect}; utils::address_and_port_as_string,
use crate::GDResult; GDError::{PacketReceive, PacketSend, SocketBind, SocketConnect},
use std::io::{Read, Write}; GDResult,
use std::net; };
const DEFAULT_PACKET_SIZE: usize = 1024; use std::{
io::{Read, Write},
pub trait Socket { net,
fn new(address: &str, port: u16) -> GDResult<Self> };
where
Self: Sized; const DEFAULT_PACKET_SIZE: usize = 1024;
fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()>; pub trait Socket {
fn new(address: &str, port: u16) -> GDResult<Self>
fn send(&mut self, data: &[u8]) -> GDResult<()>; where Self: Sized;
fn receive(&mut self, size: Option<usize>) -> GDResult<Vec<u8>>;
} fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()>;
pub struct TcpSocket { fn send(&mut self, data: &[u8]) -> GDResult<()>;
socket: net::TcpStream, fn receive(&mut self, size: Option<usize>) -> GDResult<Vec<u8>>;
} }
impl Socket for TcpSocket { pub struct TcpSocket {
fn new(address: &str, port: u16) -> GDResult<Self> { socket: net::TcpStream,
let complete_address = address_and_port_as_string(address, port); }
Ok(Self { impl Socket for TcpSocket {
socket: net::TcpStream::connect(complete_address).map_err(|_| SocketConnect)?, fn new(address: &str, port: u16) -> GDResult<Self> {
}) let complete_address = address_and_port_as_string(address, port);
}
Ok(Self {
fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()> { socket: net::TcpStream::connect(complete_address).map_err(|_| SocketConnect)?,
let settings = timeout_settings.unwrap_or_default(); })
self.socket.set_read_timeout(settings.get_read()).unwrap(); //unwrapping because TimeoutSettings::new }
self.socket.set_write_timeout(settings.get_write()).unwrap(); //checks if these are 0 and throws an error
fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()> {
Ok(()) let settings = timeout_settings.unwrap_or_default();
} self.socket.set_read_timeout(settings.get_read()).unwrap(); // unwrapping because TimeoutSettings::new
self.socket.set_write_timeout(settings.get_write()).unwrap(); // checks if these are 0 and throws an error
fn send(&mut self, data: &[u8]) -> GDResult<()> {
self.socket.write(data).map_err(|_| PacketSend)?; Ok(())
Ok(()) }
}
fn send(&mut self, data: &[u8]) -> GDResult<()> {
fn receive(&mut self, size: Option<usize>) -> GDResult<Vec<u8>> { self.socket.write(data).map_err(|_| PacketSend)?;
let mut buf = Vec::with_capacity(size.unwrap_or(DEFAULT_PACKET_SIZE)); Ok(())
self.socket }
.read_to_end(&mut buf)
.map_err(|_| PacketReceive)?; fn receive(&mut self, size: Option<usize>) -> GDResult<Vec<u8>> {
let mut buf = Vec::with_capacity(size.unwrap_or(DEFAULT_PACKET_SIZE));
Ok(buf) self.socket
} .read_to_end(&mut buf)
} .map_err(|_| PacketReceive)?;
pub struct UdpSocket { Ok(buf)
socket: net::UdpSocket, }
complete_address: String, }
}
pub struct UdpSocket {
impl Socket for UdpSocket { socket: net::UdpSocket,
fn new(address: &str, port: u16) -> GDResult<Self> { complete_address: String,
let complete_address = address_and_port_as_string(address, port); }
let socket = net::UdpSocket::bind("0.0.0.0:0").map_err(|_| SocketBind)?;
impl Socket for UdpSocket {
Ok(Self { fn new(address: &str, port: u16) -> GDResult<Self> {
socket, let complete_address = address_and_port_as_string(address, port);
complete_address, let socket = net::UdpSocket::bind("0.0.0.0:0").map_err(|_| SocketBind)?;
})
} Ok(Self {
socket,
fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()> { complete_address,
let settings = timeout_settings.unwrap_or_default(); })
self.socket.set_read_timeout(settings.get_read()).unwrap(); //unwrapping because TimeoutSettings::new }
self.socket.set_write_timeout(settings.get_write()).unwrap(); //checks if these are 0 and throws an error
fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()> {
Ok(()) let settings = timeout_settings.unwrap_or_default();
} self.socket.set_read_timeout(settings.get_read()).unwrap(); // unwrapping because TimeoutSettings::new
self.socket.set_write_timeout(settings.get_write()).unwrap(); // checks if these are 0 and throws an error
fn send(&mut self, data: &[u8]) -> GDResult<()> {
self.socket Ok(())
.send_to(data, &self.complete_address) }
.map_err(|_| PacketSend)?;
Ok(()) fn send(&mut self, data: &[u8]) -> GDResult<()> {
} self.socket
.send_to(data, &self.complete_address)
fn receive(&mut self, size: Option<usize>) -> GDResult<Vec<u8>> { .map_err(|_| PacketSend)?;
let mut buf: Vec<u8> = vec![0; size.unwrap_or(DEFAULT_PACKET_SIZE)]; Ok(())
let (number_of_bytes_received, _) = }
self.socket.recv_from(&mut buf).map_err(|_| PacketReceive)?;
fn receive(&mut self, size: Option<usize>) -> GDResult<Vec<u8>> {
Ok(buf[..number_of_bytes_received].to_vec()) let mut buf: Vec<u8> = vec![0; size.unwrap_or(DEFAULT_PACKET_SIZE)];
} let (number_of_bytes_received, _) = self.socket.recv_from(&mut buf).map_err(|_| PacketReceive)?;
}
Ok(buf[.. number_of_bytes_received].to_vec())
#[cfg(test)] }
mod tests { }
use std::thread;
#[cfg(test)]
use super::*; mod tests {
use std::thread;
#[test]
fn test_tcp_socket_send_and_receive() { use super::*;
// Spawn a thread to run the server
let listener = net::TcpListener::bind("127.0.0.1:0").unwrap(); #[test]
let bound_address = listener.local_addr().unwrap(); fn test_tcp_socket_send_and_receive() {
let server_thread = thread::spawn(move || { // Spawn a thread to run the server
let (mut stream, _) = listener.accept().unwrap(); let listener = net::TcpListener::bind("127.0.0.1:0").unwrap();
let mut buf = [0; 1024]; let bound_address = listener.local_addr().unwrap();
stream.read(&mut buf).unwrap(); let server_thread = thread::spawn(move || {
stream.write(&buf).unwrap(); let (mut stream, _) = listener.accept().unwrap();
}); let mut buf = [0; 1024];
stream.read(&mut buf).unwrap();
// Create a TCP socket and send a message to the server stream.write(&buf).unwrap();
let mut socket = TcpSocket::new(&*bound_address.ip().to_string(), bound_address.port()).unwrap(); });
let message = b"hello, world!";
socket.send(message).unwrap(); // Create a TCP socket and send a message to the server
let mut socket = TcpSocket::new(&*bound_address.ip().to_string(), bound_address.port()).unwrap();
// Receive the response from the server let message = b"hello, world!";
let received_message: Vec<u8> = socket socket.send(message).unwrap();
.receive(None)
.unwrap() // Receive the response from the server
// Iterate over the buffer and remove 0s that are alone in the buffer let received_message: Vec<u8> = socket
// just added to pass default size .receive(None)
.into_iter() .unwrap()
.filter(|&x| x != 0) // Iterate over the buffer and remove 0s that are alone in the buffer
.collect(); // just added to pass default size
.into_iter()
server_thread.join().expect("server thread panicked"); .filter(|&x| x != 0)
.collect();
assert_eq!(message, &received_message[..]);
} server_thread.join().expect("server thread panicked");
#[test] assert_eq!(message, &received_message[..]);
fn test_udp_socket_send_and_receive() { }
// Spawn a thread to run the server
let socket = net::UdpSocket::bind("127.0.0.1:0").unwrap(); #[test]
let bound_address = socket.local_addr().unwrap(); fn test_udp_socket_send_and_receive() {
let server_thread = thread::spawn(move || { // Spawn a thread to run the server
let mut buf = [0; 1024]; let socket = net::UdpSocket::bind("127.0.0.1:0").unwrap();
let (_, src_addr) = socket.recv_from(&mut buf).unwrap(); let bound_address = socket.local_addr().unwrap();
socket.send_to(&buf, src_addr).unwrap(); let server_thread = thread::spawn(move || {
}); let mut buf = [0; 1024];
let (_, src_addr) = socket.recv_from(&mut buf).unwrap();
// Create a UDP socket and send a message to the server socket.send_to(&buf, src_addr).unwrap();
let mut socket = UdpSocket::new(&*bound_address.ip().to_string(), bound_address.port()).unwrap(); });
let message = b"hello, world!";
socket.send(message).unwrap(); // Create a UDP socket and send a message to the server
let mut socket = UdpSocket::new(&*bound_address.ip().to_string(), bound_address.port()).unwrap();
// Receive the response from the server let message = b"hello, world!";
let received_message: Vec<u8> = socket socket.send(message).unwrap();
.receive(None)
.unwrap() // Receive the response from the server
// Iterate over the buffer and remove 0s that are alone in the buffer let received_message: Vec<u8> = socket
// just added to pass default size .receive(None)
.into_iter() .unwrap()
.filter(|&x| x != 0) // Iterate over the buffer and remove 0s that are alone in the buffer
.collect(); // just added to pass default size
.into_iter()
server_thread.join().expect("server thread panicked"); .filter(|&x| x != 0)
.collect();
assert_eq!(message, &received_message[..]);
} server_thread.join().expect("server thread panicked");
}
assert_eq!(message, &received_message[..]);
}
}

View file

@ -1,39 +1,41 @@
use std::cmp::Ordering; use crate::{
use crate::GDResult; GDError::{PacketOverflow, PacketUnderflow},
use crate::GDError::{PacketOverflow, PacketUnderflow}; GDResult,
};
pub fn error_by_expected_size(expected: usize, size: usize) -> GDResult<()> {
match size.cmp(&expected) { use std::cmp::Ordering;
Ordering::Greater => Err(PacketOverflow),
Ordering::Less => Err(PacketUnderflow), pub fn error_by_expected_size(expected: usize, size: usize) -> GDResult<()> {
Ordering::Equal => Ok(()) match size.cmp(&expected) {
} Ordering::Greater => Err(PacketOverflow),
} Ordering::Less => Err(PacketUnderflow),
Ordering::Equal => Ok(()),
pub fn address_and_port_as_string(address: &str, port: u16) -> String { }
format!("{}:{}", address, port) }
}
pub fn address_and_port_as_string(address: &str, port: u16) -> String { format!("{}:{}", address, port) }
pub fn u8_lower_upper(n: u8) -> (u8, u8) {
(n & 15, n >> 4) pub fn u8_lower_upper(n: u8) -> (u8, u8) { (n & 15, n >> 4) }
}
#[cfg(test)]
#[cfg(test)] mod tests {
mod tests { #[test]
#[test] fn address_and_port_as_string() {
fn address_and_port_as_string() { assert_eq!(
assert_eq!(super::address_and_port_as_string("192.168.0.1", 27015), "192.168.0.1:27015"); super::address_and_port_as_string("192.168.0.1", 27015),
} "192.168.0.1:27015"
);
#[test] }
fn u8_lower_upper() {
assert_eq!(super::u8_lower_upper(171), (11, 10)); #[test]
} fn u8_lower_upper() {
assert_eq!(super::u8_lower_upper(171), (11, 10));
#[test] }
fn error_by_expected_size() {
assert!(super::error_by_expected_size(69, 69).is_ok()); #[test]
assert!(super::error_by_expected_size(69, 68).is_err()); fn error_by_expected_size() {
assert!(super::error_by_expected_size(69, 70).is_err()); assert!(super::error_by_expected_size(69, 69).is_ok());
} assert!(super::error_by_expected_size(69, 68).is_err());
} assert!(super::error_by_expected_size(69, 70).is_err());
}
}