[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,10 +1,56 @@
use gamedig::protocols::gamespy;
use std::env;
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::minecraft::LegacyGroup; use gamedig::protocols::minecraft::LegacyGroup;
use gamedig::protocols::valve; use gamedig::protocols::valve;
use gamedig::protocols::valve::Engine; use gamedig::protocols::valve::Engine;
use gamedig::protocols::gamespy; use gamedig::{
aliens,
aoc,
arma2oa,
ase,
asrd,
avorion,
bat1944,
bb2,
bf1942,
bm,
bo,
ccure,
cosu,
cs,
cscz,
csgo,
css,
dod,
dods,
doi,
dst,
gm,
hl2dm,
hldms,
ins,
insmic,
inss,
l4d,
l4d2,
mc,
ohd,
onset,
pz,
ror2,
rust,
sc,
sdtd,
ss,
tf,
tf2,
tfc,
ts,
unturned,
ut,
vr,
GDResult,
};
use std::env;
fn main() -> GDResult<()> { fn main() -> GDResult<()> {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
@ -28,8 +74,8 @@ fn main() -> GDResult<()> {
} }
None None
}, }
true => Some(args[3].parse::<u16>().expect("Invalid port!")) true => Some(args[3].parse::<u16>().expect("Invalid port!")),
}; };
match args[1].as_str() { match args[1].as_str() {
@ -49,16 +95,46 @@ fn main() -> GDResult<()> {
"ts" => println!("{:#?}", ts::query(ip, port)?), "ts" => println!("{:#?}", ts::query(ip, port)?),
"cscz" => println!("{:#?}", cscz::query(ip, port)?), "cscz" => println!("{:#?}", cscz::query(ip, port)?),
"dod" => println!("{:#?}", dod::query(ip, port)?), "dod" => println!("{:#?}", dod::query(ip, port)?),
"_src" => println!("{:#?}", valve::query(ip, port.unwrap(), Engine::Source(None), None, None)?), "_src" => {
"_gld" => println!("{:#?}", valve::query(ip, port.unwrap(), Engine::GoldSrc(false), None, None)?), println!(
"_gld_f" => println!("{:#?}", valve::query(ip, port.unwrap(), Engine::GoldSrc(true), None, None)?), "{:#?}",
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" => println!("{:#?}", mc::query(ip, port)?),
"mc_java" => println!("{:#?}", mc::query_java(ip, port)?), "mc_java" => println!("{:#?}", mc::query_java(ip, port)?),
"mc_bedrock" => println!("{:#?}", mc::query_bedrock(ip, port)?), "mc_bedrock" => println!("{:#?}", mc::query_bedrock(ip, port)?),
"mc_legacy" => println!("{:#?}", mc::query_legacy(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_vb1_8" => {
"mc_legacy_v1_4" => println!("{:#?}", mc::query_legacy_specific(LegacyGroup::V1_4, ip, port)?), println!(
"mc_legacy_v1_6" => println!("{:#?}", mc::query_legacy_specific(LegacyGroup::V1_6, ip, port)?), "{:#?}",
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)?), "7dtd" => println!("{:#?}", sdtd::query(ip, port)?),
"ase" => println!("{:#?}", ase::query(ip, port)?), "ase" => println!("{:#?}", ase::query(ip, port)?),
"unturned" => println!("{:#?}", unturned::query(ip, port)?), "unturned" => println!("{:#?}", unturned::query(ip, port)?),
@ -89,7 +165,7 @@ fn main() -> GDResult<()> {
"ut" => println!("{:#?}", ut::query(ip, port)), "ut" => println!("{:#?}", ut::query(ip, port)),
"bf1942" => println!("{:#?}", bf1942::query(ip, port)), "bf1942" => println!("{:#?}", bf1942::query(ip, port)),
"ss" => println!("{:#?}", ss::query(ip, port)), "ss" => println!("{:#?}", ss::query(ip, port)),
_ => panic!("Undefined game: {}", args[1]) _ => panic!("Undefined game: {}", args[1]),
}; };
Ok(()) 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 and 19132 for bedrock) // or Some(<port>), None is the default protocol port (which is 25565 for java
// 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 { // Result type, must check what it is... match response {
// 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> { 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)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::ALIENS.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::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> { 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)?; let valve_response = valve::query(
address,
port.unwrap_or(2304),
SteamApp::ARMA2OA.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::ASE.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::ASE.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::ASRD.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::ASRD.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(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> { 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)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::CS.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::CSCZ.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::CSCZ.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::CSGO.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::CSGO.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::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> { 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)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::DOD.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::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> { 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)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::DOI.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::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> { 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)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::HLDMS.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::INS.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::INS.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::INSMIC.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::INSMIC.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(27131), SteamApp::INSS.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27131),
SteamApp::INSS.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::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,8 +1,11 @@
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)). /// 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> { pub fn query(address: &str, port: Option<u16>) -> GDResult<JavaResponse> {
if let Ok(response) = query_java(address, port) { if let Ok(response) = query_java(address, port) {
return Ok(response); return Ok(response);
@ -39,10 +42,6 @@ pub fn query_bedrock(address: &str, port: Option<u16>) -> GDResult<BedrockRespon
minecraft::query_bedrock(address, port_or_bedrock_default(port), None) minecraft::query_bedrock(address, port_or_bedrock_default(port), None)
} }
fn port_or_java_default(port: Option<u16>) -> u16 { fn port_or_java_default(port: Option<u16>) -> u16 { port.unwrap_or(25565) }
port.unwrap_or(25565)
}
fn port_or_bedrock_default(port: Option<u16>) -> u16 { fn port_or_bedrock_default(port: Option<u16>) -> u16 { port.unwrap_or(19132) }
port.unwrap_or(19132)
}

View file

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

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> { 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)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::RUST.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::SC.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::SC.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(26900), SteamApp::SDTD.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(26900),
SteamApp::SDTD.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(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> { 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)?; let valve_response = valve::query(
address,
port.unwrap_or(27016),
SteamApp::TF.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::TF2.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::TF2.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::TFC.as_engine(), None, None)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::TFC.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,12 @@
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")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, PartialOrd)] #[derive(Debug, Clone, PartialEq, PartialOrd)]
@ -13,7 +15,7 @@ pub struct TheShipPlayer {
pub score: u32, pub score: u32,
pub duration: f32, pub duration: f32,
pub deaths: u32, pub deaths: u32,
pub money: u32 pub money: u32,
} }
impl TheShipPlayer { impl TheShipPlayer {
@ -23,7 +25,7 @@ impl TheShipPlayer {
score: player.score, score: player.score,
duration: player.duration, duration: player.duration,
deaths: player.deaths.unwrap(), deaths: player.deaths.unwrap(),
money: player.money.unwrap() money: player.money.unwrap(),
} }
} }
} }
@ -51,7 +53,7 @@ pub struct Response {
pub rules: HashMap<String, String>, pub rules: HashMap<String, String>,
pub mode: u8, pub mode: u8,
pub witnesses: u8, pub witnesses: u8,
pub duration: u8 pub duration: u8,
} }
impl Response { impl Response {
@ -66,7 +68,12 @@ impl Response {
map: response.info.map, map: response.info.map,
game: response.info.game, game: response.info.game,
players: response.info.players_online, players: response.info.players_online,
players_details: response.players.unwrap().iter().map(TheShipPlayer::new_from_valve_player).collect(), players_details: response
.players
.unwrap()
.iter()
.map(TheShipPlayer::new_from_valve_player)
.collect(),
max_players: response.info.players_maximum, max_players: response.info.players_maximum,
bots: response.info.players_bots, bots: response.info.players_bots,
server_type: response.info.server_type, server_type: response.info.server_type,
@ -81,13 +88,19 @@ impl Response {
rules: response.rules.unwrap(), rules: response.rules.unwrap(),
mode: the_unwrapped_ship.mode, mode: the_unwrapped_ship.mode,
witnesses: the_unwrapped_ship.witnesses, witnesses: the_unwrapped_ship.witnesses,
duration: the_unwrapped_ship.duration duration: the_unwrapped_ship.duration,
} }
} }
} }
pub fn query(address: &str, port: Option<u16>) -> GDResult<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)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::TS.as_engine(),
None,
None,
)?;
Ok(Response::new_from_valve_response(valve_response)) 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> { 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)?; let valve_response = valve::query(
address,
port.unwrap_or(27015),
SteamApp::UNTURNED.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(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 types::*;
pub use protocol::*; pub use protocol::*;
pub use types::*;

View file

@ -1,19 +1,20 @@
// 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::{
This file has code that has been documented by the NodeJS GameDig library (MIT) from bufferer::{Bufferer, Endianess},
https://github.com/gamedig/node-gamedig/blob/master/protocols/minecraftbedrock.js protocols::{
*/ minecraft::{BedrockResponse, GameMode, Server},
types::TimeoutSettings,
use crate::GDResult; },
use crate::bufferer::{Bufferer, Endianess}; socket::{Socket, UdpSocket},
use crate::GDError::{PacketBad, TypeParse}; utils::error_by_expected_size,
use crate::protocols::minecraft::{BedrockResponse, GameMode, Server}; GDError::{PacketBad, TypeParse},
use crate::protocols::types::TimeoutSettings; GDResult,
use crate::socket::{Socket, UdpSocket}; };
use crate::utils::error_by_expected_size;
pub struct Bedrock { pub struct Bedrock {
socket: UdpSocket socket: UdpSocket,
} }
impl Bedrock { impl Bedrock {
@ -21,21 +22,16 @@ impl Bedrock {
let socket = UdpSocket::new(address, port)?; let socket = UdpSocket::new(address, port)?;
socket.apply_timeout(timeout_settings)?; socket.apply_timeout(timeout_settings)?;
Ok(Self { Ok(Self { socket })
socket
})
} }
fn send_status_request(&mut self) -> GDResult<()> { fn send_status_request(&mut self) -> GDResult<()> {
self.socket.send(&[ self.socket.send(&[
// Message ID, ID_UNCONNECTED_PING 0x01, // Message ID: ID_UNCONNECTED_PING
0x01, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, // Nonce / timestamp
// Nonce / timestamp 0x00, 0xff, 0xff, 0x00, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfd, 0x12, 0x34, // Magic
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Client GUID
// Magic ])?;
0x00, 0xff, 0xff, 0x00, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 0xfd, 0xfd, 0xfd, 0x12, 0x34, 0x56, 0x78,
// Client GUID
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])?;
Ok(()) Ok(())
} }
@ -54,7 +50,8 @@ impl Bedrock {
return Err(PacketBad); return Err(PacketBad);
} }
// These 8 bytes are identical to the serverId string we receive in decimal below // These 8 bytes are identical to the serverId string we receive in decimal
// below
buffer.move_position_ahead(8); buffer.move_position_ahead(8);
// Verifying the magic value (as we need 16 bytes, cast to two u64 values) // Verifying the magic value (as we need 16 bytes, cast to two u64 values)
@ -82,16 +79,16 @@ impl Bedrock {
edition: status[0].to_string(), edition: status[0].to_string(),
name: status[1].to_string(), name: status[1].to_string(),
version_name: status[3].to_string(), version_name: status[3].to_string(),
version_protocol: status[2].to_string(), version_protocol: status[2].to_string(),
players_maximum: status[5].parse().map_err(|_| TypeParse)?, players_maximum: status[5].parse().map_err(|_| TypeParse)?,
players_online: status[4].parse().map_err(|_| TypeParse)?, players_online: status[4].parse().map_err(|_| TypeParse)?,
id: status.get(6).map(|v| v.to_string()), id: status.get(6).map(|v| v.to_string()),
map: status.get(7).map(|v| v.to_string()), map: status.get(7).map(|v| v.to_string()),
game_mode: match status.get(8) { game_mode: match status.get(8) {
None => None, None => None,
Some(v) => Some(GameMode::from_bedrock(v)?) Some(v) => Some(GameMode::from_bedrock(v)?),
}, },
server_type: Server::Bedrock server_type: Server::Bedrock,
}) })
} }

View file

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

View file

@ -1,14 +1,17 @@
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},
GDResult,
};
pub struct LegacyBV1_8 { pub struct LegacyBV1_8 {
socket: TcpSocket socket: TcpSocket,
} }
impl LegacyBV1_8 { impl LegacyBV1_8 {
@ -16,14 +19,10 @@ impl LegacyBV1_8 {
let socket = TcpSocket::new(address, port)?; let socket = TcpSocket::new(address, port)?;
socket.apply_timeout(timeout_settings)?; socket.apply_timeout(timeout_settings)?;
Ok(Self { Ok(Self { socket })
socket
})
} }
fn send_initial_request(&mut self) -> GDResult<()> { fn send_initial_request(&mut self) -> GDResult<()> { self.socket.send(&[0xFE]) }
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()?;
@ -43,10 +42,8 @@ impl LegacyBV1_8 {
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() let online_players = split[1].parse().map_err(|_| PacketBad)?;
.map_err(|_| PacketBad)?; let max_players = split[2].parse().map_err(|_| PacketBad)?;
let max_players = split[2].parse()
.map_err(|_| PacketBad)?;
Ok(JavaResponse { Ok(JavaResponse {
version_name: "Beta 1.8+".to_string(), version_name: "Beta 1.8+".to_string(),
@ -58,7 +55,7 @@ impl LegacyBV1_8 {
favicon: None, favicon: None,
previews_chat: None, previews_chat: None,
enforces_secure_chat: None, enforces_secure_chat: None,
server_type: Server::Legacy(LegacyGroup::VB1_8) server_type: Server::Legacy(LegacyGroup::VB1_8),
}) })
} }

View file

@ -1,15 +1,17 @@
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 { pub struct LegacyV1_4 {
socket: TcpSocket socket: TcpSocket,
} }
impl LegacyV1_4 { impl LegacyV1_4 {
@ -17,14 +19,10 @@ impl LegacyV1_4 {
let socket = TcpSocket::new(address, port)?; let socket = TcpSocket::new(address, port)?;
socket.apply_timeout(timeout_settings)?; socket.apply_timeout(timeout_settings)?;
Ok(Self { Ok(Self { socket })
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> { fn get_info(&mut self) -> GDResult<JavaResponse> {
self.send_initial_request()?; self.send_initial_request()?;
@ -48,10 +46,8 @@ impl LegacyV1_4 {
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() let online_players = split[1].parse().map_err(|_| PacketBad)?;
.map_err(|_| PacketBad)?; let max_players = split[2].parse().map_err(|_| PacketBad)?;
let max_players = split[2].parse()
.map_err(|_| PacketBad)?;
Ok(JavaResponse { Ok(JavaResponse {
version_name: "1.4+".to_string(), version_name: "1.4+".to_string(),
@ -63,7 +59,7 @@ impl LegacyV1_4 {
favicon: None, favicon: None,
previews_chat: None, previews_chat: None,
enforces_secure_chat: None, enforces_secure_chat: None,
server_type: Server::Legacy(LegacyGroup::V1_4) server_type: Server::Legacy(LegacyGroup::V1_4),
}) })
} }

View file

@ -1,13 +1,17 @@
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,
GDError::{PacketBad, ProtocolFormat},
GDResult,
};
pub struct LegacyV1_6 { pub struct LegacyV1_6 {
socket: TcpSocket socket: TcpSocket,
} }
impl LegacyV1_6 { impl LegacyV1_6 {
@ -15,29 +19,26 @@ impl LegacyV1_6 {
let socket = TcpSocket::new(address, port)?; let socket = TcpSocket::new(address, port)?;
socket.apply_timeout(timeout_settings)?; socket.apply_timeout(timeout_settings)?;
Ok(Self { Ok(Self { socket })
socket
})
} }
fn send_initial_request(&mut self) -> GDResult<()> { fn send_initial_request(&mut self) -> GDResult<()> {
self.socket.send(&[ self.socket.send(&[
// Packet ID (FE) 0xfe, // Packet ID (FE)
0xfe, 0x01, // Ping payload (01)
// Ping payload (01) 0xfa, // Packet identifier for plugin message
0x01, 0x00, 0x07, // Length of 'GameDig' string (7) as unsigned short
// Packet identifier for plugin message 0x00, 0x47, 0x00, 0x61, 0x00, 0x6D, 0x00, 0x65, 0x00, 0x44, 0x00, 0x69, 0x00,
0xfa, 0x67, // 'GameDig' string as UTF-16BE
// Length of 'GameDig' string (7) as unsigned short ])?;
0x00, 0x07,
// '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.remaining_data().starts_with(&[0x00, 0xA7, 0x00, 0x31, 0x00, 0x00]); let state = buffer
.remaining_data()
.starts_with(&[0x00, 0xA7, 0x00, 0x31, 0x00, 0x00]);
if state { if state {
buffer.move_position_ahead(6); buffer.move_position_ahead(6);
@ -52,14 +53,11 @@ impl LegacyV1_6 {
let split: Vec<&str> = packet_string.split('\x00').collect(); let split: Vec<&str> = packet_string.split('\x00').collect();
error_by_expected_size(5, split.len())?; error_by_expected_size(5, split.len())?;
let version_protocol = split[0].parse() let version_protocol = split[0].parse().map_err(|_| PacketBad)?;
.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 { Ok(JavaResponse {
version_name, version_name,
@ -71,7 +69,7 @@ impl LegacyV1_6 {
favicon: None, favicon: None,
previews_chat: None, previews_chat: None,
enforces_secure_chat: None, enforces_secure_chat: None,
server_type: Server::Legacy(LegacyGroup::V1_6) server_type: Server::Legacy(LegacyGroup::V1_6),
}) })
} }

View file

@ -1,20 +1,29 @@
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,
JavaResponse,
LegacyGroup,
},
protocols::types::TimeoutSettings,
GDError::AutoQuery,
GDResult,
};
mod bedrock;
mod java; mod java;
mod legacy_bv1_8;
mod legacy_v1_4; mod legacy_v1_4;
mod legacy_v1_6; mod legacy_v1_6;
mod legacy_bv1_8;
mod bedrock;
/// Queries a Minecraft server with all the protocol variants one by one (Java -> Bedrock -> Legacy (1.6 -> 1.4 -> Beta 1.8)). /// 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> { pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> {
if let Ok(response) = query_java(address, port, timeout_settings.clone()) { if let Ok(response) = query_java(address, port, timeout_settings.clone()) {
return Ok(response); return Ok(response);
@ -54,11 +63,16 @@ pub fn query_legacy(address: &str, port: u16, timeout_settings: Option<TimeoutSe
} }
/// Query a specific (Java) Legacy Server. /// Query a specific (Java) Legacy Server.
pub fn query_legacy_specific(group: LegacyGroup, address: &str, port: u16, timeout_settings: Option<TimeoutSettings>) -> GDResult<JavaResponse> { pub fn query_legacy_specific(
group: LegacyGroup,
address: &str,
port: u16,
timeout_settings: Option<TimeoutSettings>,
) -> GDResult<JavaResponse> {
match group { match group {
LegacyGroup::V1_6 => LegacyV1_6::query(address, port, timeout_settings), LegacyGroup::V1_6 => LegacyV1_6::query(address, port, timeout_settings),
LegacyGroup::V1_4 => LegacyV1_4::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) LegacyGroup::VB1_8 => LegacyBV1_8::query(address, port, timeout_settings),
} }
} }

View file

@ -1,12 +1,12 @@
/* // 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::{
use crate::GDError::{PacketBad, UnknownEnumCast}; bufferer::Bufferer,
use crate::GDResult; GDError::{PacketBad, UnknownEnumCast},
GDResult,
};
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -49,7 +49,8 @@ pub struct Player {
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
/// below 1.6 this field is always -1.
pub version_protocol: i32, pub version_protocol: i32,
/// Number of server capacity. /// Number of server capacity.
pub players_maximum: u32, pub players_maximum: u32,
@ -142,7 +143,7 @@ pub(crate) fn get_varint(buffer: &mut Bufferer) -> GDResult<i32> {
let msb: u8 = 0b10000000; let msb: u8 = 0b10000000;
let mask: u8 = !msb; let mask: u8 = !msb;
for i in 0..5 { for i in 0 .. 5 {
let current_byte = buffer.get_u8()?; let current_byte = buffer.get_u8()?;
result |= ((current_byte & mask) as i32) << (7 * i); result |= ((current_byte & mask) as i32) << (7 * i);
@ -167,7 +168,7 @@ pub(crate) fn as_varint(value: i32) -> Vec<u8> {
let msb: u8 = 0b10000000; let msb: u8 = 0b10000000;
let mask: i32 = 0b01111111; let mask: i32 = 0b01111111;
for _ in 0..5 { for _ in 0 .. 5 {
let tmp = (reading_value & mask) as u8; let tmp = (reading_value & mask) as u8;
reading_value &= !mask; reading_value &= !mask;
@ -188,7 +189,7 @@ pub(crate) fn get_string(buffer: &mut Bufferer) -> GDResult<String> {
let length = get_varint(buffer)? as usize; let length = get_varint(buffer)? as usize;
let mut text = Vec::with_capacity(length); let mut text = Vec::with_capacity(length);
for _ in 0..length { for _ in 0 .. length {
text.push(buffer.get_u8()?) text.push(buffer.get_u8()?)
} }

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

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,4 +1,3 @@
/// The implementation. /// The implementation.
pub mod protocol; pub mod protocol;
/// All types used by the implementation. /// All types used by the implementation.

View file

@ -1,19 +1,40 @@
use std::collections::HashMap; use crate::{
bufferer::{Bufferer, Endianess},
protocols::{
types::TimeoutSettings,
valve::{
types::{
Environment,
ExtraData,
GatheringSettings,
Request,
Response,
Server,
ServerInfo,
ServerPlayer,
TheShip,
},
Engine,
ModData,
SteamApp,
},
},
socket::{Socket, UdpSocket},
utils::u8_lower_upper,
GDError::{BadGame, Decompress, UnknownEnumCast},
GDResult,
};
use bzip2_rs::decoder::Decoder; use bzip2_rs::decoder::Decoder;
use crate::GDResult;
use crate::bufferer::{Bufferer, Endianess}; use std::collections::HashMap;
use crate::GDError::{BadGame, Decompress, UnknownEnumCast};
use crate::protocols::types::TimeoutSettings;
use crate::protocols::valve::{Engine, ModData, SteamApp};
use crate::protocols::valve::types::{Environment, ExtraData, GatheringSettings, Request, Response, Server, ServerInfo, ServerPlayer, TheShip};
use crate::socket::{Socket, UdpSocket};
use crate::utils::u8_lower_upper;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct Packet { struct Packet {
pub header: u32, pub header: u32,
pub kind: u8, pub kind: u8,
pub payload: Vec<u8> pub payload: Vec<u8>,
} }
impl Packet { impl Packet {
@ -21,7 +42,7 @@ impl Packet {
Ok(Self { Ok(Self {
header: buffer.get_u32()?, header: buffer.get_u32()?,
kind: buffer.get_u8()?, kind: buffer.get_u8()?,
payload: buffer.remaining_data_vec() payload: buffer.remaining_data_vec(),
}) })
} }
@ -35,20 +56,20 @@ impl Packet {
Request::Info => { Request::Info => {
initial.payload.extend(challenge); initial.payload.extend(challenge);
initial.payload initial.payload
}, }
_ => challenge _ => challenge,
} },
} }
} }
fn initial(kind: Request) -> Self { fn initial(kind: Request) -> Self {
Self { Self {
header: 4294967295, //FF FF FF FF header: 4294967295, // FF FF FF FF
kind: kind as u8, kind: kind as u8,
payload: match kind { payload: match kind {
Request::Info => String::from("Source Engine Query\0").into_bytes(), Request::Info => String::from("Source Engine Query\0").into_bytes(),
_ => vec![0xFF, 0xFF, 0xFF, 0xFF] _ => vec![0xFF, 0xFF, 0xFF, 0xFF],
} },
} }
} }
@ -73,7 +94,7 @@ struct SplitPacket {
pub compressed: bool, pub compressed: bool,
pub decompressed_size: Option<u32>, pub decompressed_size: Option<u32>,
pub uncompressed_crc32: Option<u32>, pub uncompressed_crc32: Option<u32>,
payload: Vec<u8> payload: Vec<u8>,
} }
impl SplitPacket { impl SplitPacket {
@ -88,16 +109,24 @@ impl SplitPacket {
Engine::Source(_) => { Engine::Source(_) => {
let total = buffer.get_u8()?; let total = buffer.get_u8()?;
let number = buffer.get_u8()?; let number = buffer.get_u8()?;
let size = match protocol == 7 && (*engine == SteamApp::CSS.as_engine()) { //certain apps with protocol = 7 dont have this field let size = match protocol == 7 && (*engine == SteamApp::CSS.as_engine()) {
// certain apps with protocol = 7 dont have this field
false => buffer.get_u16()?, false => buffer.get_u16()?,
true => 1248 true => 1248,
}; };
let compressed = ((id >> 31) & 1) == 1; let compressed = ((id >> 31) & 1) == 1;
let (decompressed_size, uncompressed_crc32) = match compressed { let (decompressed_size, uncompressed_crc32) = match compressed {
false => (None, None), false => (None, None),
true => (Some(buffer.get_u32()?), Some(buffer.get_u32()?)) true => (Some(buffer.get_u32()?), Some(buffer.get_u32()?)),
}; };
(total, number, size, compressed, decompressed_size, uncompressed_crc32) (
total,
number,
size,
compressed,
decompressed_size,
uncompressed_crc32,
)
} }
}; };
@ -110,7 +139,7 @@ impl SplitPacket {
compressed, compressed,
decompressed_size, decompressed_size,
uncompressed_crc32, uncompressed_crc32,
payload: buffer.remaining_data_vec() payload: buffer.remaining_data_vec(),
}) })
} }
@ -123,13 +152,15 @@ impl SplitPacket {
let mut decompressed_payload = vec![0; decompressed_size]; let mut decompressed_payload = vec![0; decompressed_size];
decoder.read(&mut decompressed_payload).map_err(|_| Decompress)?; decoder
.read(&mut decompressed_payload)
.map_err(|_| Decompress)?;
if decompressed_payload.len() != decompressed_size if decompressed_payload.len() != decompressed_size
|| crc32fast::hash(&decompressed_payload) != self.uncompressed_crc32.unwrap() { || crc32fast::hash(&decompressed_payload) != self.uncompressed_crc32.unwrap()
{
Err(Decompress) Err(Decompress)
} } else {
else {
Ok(decompressed_payload) Ok(decompressed_payload)
} }
} else { } else {
@ -139,7 +170,7 @@ impl SplitPacket {
} }
struct ValveProtocol { struct ValveProtocol {
socket: UdpSocket socket: UdpSocket,
} }
static PACKET_SIZE: usize = 6144; static PACKET_SIZE: usize = 6144;
@ -149,9 +180,7 @@ impl ValveProtocol {
let socket = UdpSocket::new(address, port)?; let socket = UdpSocket::new(address, port)?;
socket.apply_timeout(timeout_settings)?; socket.apply_timeout(timeout_settings)?;
Ok(Self { Ok(Self { socket })
socket
})
} }
fn receive(&mut self, engine: &Engine, protocol: u8, buffer_size: usize) -> GDResult<Packet> { fn receive(&mut self, engine: &Engine, protocol: u8, buffer_size: usize) -> GDResult<Packet> {
@ -160,11 +189,12 @@ impl ValveProtocol {
let header = buffer.get_u8()?; let header = buffer.get_u8()?;
buffer.move_position_backward(1); buffer.move_position_backward(1);
if header == 0xFE { //the packet is split if header == 0xFE {
// the packet is split
let mut main_packet = SplitPacket::new(engine, protocol, &mut buffer)?; let mut main_packet = SplitPacket::new(engine, protocol, &mut buffer)?;
let mut chunk_packets = Vec::with_capacity((main_packet.total - 1) as usize); let mut chunk_packets = Vec::with_capacity((main_packet.total - 1) as usize);
for _ in 1..main_packet.total { for _ in 1 .. main_packet.total {
let new_data = self.socket.receive(Some(buffer_size))?; let new_data = self.socket.receive(Some(buffer_size))?;
buffer = Bufferer::new_with_data(Endianess::Little, &new_data); buffer = Bufferer::new_with_data(Endianess::Little, &new_data);
let chunk_packet = SplitPacket::new(engine, protocol, &mut buffer)?; let chunk_packet = SplitPacket::new(engine, protocol, &mut buffer)?;
@ -179,8 +209,7 @@ impl ValveProtocol {
let mut new_packet_buffer = Bufferer::new_with_data(Endianess::Little, &main_packet.get_payload()?); let mut new_packet_buffer = Bufferer::new_with_data(Endianess::Little, &main_packet.get_payload()?);
Ok(Packet::new(&mut new_packet_buffer)?) Ok(Packet::new(&mut new_packet_buffer)?)
} } else {
else {
Packet::new(&mut buffer) Packet::new(&mut buffer)
} }
} }
@ -191,7 +220,8 @@ impl ValveProtocol {
self.socket.send(&request_initial_packet)?; self.socket.send(&request_initial_packet)?;
let mut packet = self.receive(engine, protocol, PACKET_SIZE)?; let mut packet = self.receive(engine, protocol, PACKET_SIZE)?;
while packet.kind == 0x41 {// 'A' while packet.kind == 0x41 {
// 'A'
let challenge = packet.payload.clone(); let challenge = packet.payload.clone();
let challenge_packet = Packet::challenge(kind, challenge).to_bytes(); let challenge_packet = Packet::challenge(kind, challenge).to_bytes();
@ -215,28 +245,30 @@ impl ValveProtocol {
let max_players = buffer.get_u8()?; let max_players = buffer.get_u8()?;
let protocol = buffer.get_u8()?; let protocol = buffer.get_u8()?;
let server_type = match buffer.get_u8()? { let server_type = match buffer.get_u8()? {
68 => Server::Dedicated, //'D' 68 => Server::Dedicated, //'D'
76 => Server::NonDedicated, //'L' 76 => Server::NonDedicated, //'L'
80 => Server::TV, //'P' 80 => Server::TV, //'P'
_ => Err(UnknownEnumCast)? _ => Err(UnknownEnumCast)?,
}; };
let environment_type = match buffer.get_u8()? { let environment_type = match buffer.get_u8()? {
76 => Environment::Linux, //'L' 76 => Environment::Linux, //'L'
87 => Environment::Windows, //'W' 87 => Environment::Windows, //'W'
_ => Err(UnknownEnumCast)? _ => Err(UnknownEnumCast)?,
}; };
let has_password = buffer.get_u8()? == 1; let has_password = buffer.get_u8()? == 1;
let is_mod = buffer.get_u8()? == 1; let is_mod = buffer.get_u8()? == 1;
let mod_data = match is_mod { let mod_data = match is_mod {
false => None, false => None,
true => Some(ModData { true => {
link: buffer.get_string_utf8()?, Some(ModData {
download_link: buffer.get_string_utf8()?, link: buffer.get_string_utf8()?,
version: buffer.get_u32()?, download_link: buffer.get_string_utf8()?,
size: buffer.get_u32()?, version: buffer.get_u32()?,
multiplayer_only: buffer.get_u8()? == 1, size: buffer.get_u32()?,
has_own_dll: buffer.get_u8()? == 1 multiplayer_only: buffer.get_u8()? == 1,
}) has_own_dll: buffer.get_u8()? == 1,
})
}
}; };
let vac_secured = buffer.get_u8()? == 1; let vac_secured = buffer.get_u8()? == 1;
let bots = buffer.get_u8()?; let bots = buffer.get_u8()?;
@ -247,7 +279,7 @@ impl ValveProtocol {
map, map,
folder, folder,
game, game,
appid: 0, //not present in the obsolete response appid: 0, // not present in the obsolete response
players_online: players, players_online: players,
players_maximum: max_players, players_maximum: max_players,
players_bots: bots, players_bots: bots,
@ -256,10 +288,10 @@ impl ValveProtocol {
has_password, has_password,
vac_secured, vac_secured,
the_ship: None, the_ship: None,
version: "".to_string(), //a version field only for the mod version: "".to_string(), // a version field only for the mod
extra_data: None, extra_data: None,
is_mod, is_mod,
mod_data mod_data,
}) })
} }
@ -283,61 +315,65 @@ impl ValveProtocol {
let max_players = buffer.get_u8()?; let max_players = buffer.get_u8()?;
let bots = buffer.get_u8()?; let bots = buffer.get_u8()?;
let server_type = match buffer.get_u8()? { let server_type = match buffer.get_u8()? {
100 => Server::Dedicated, //'d' 100 => Server::Dedicated, //'d'
108 => Server::NonDedicated, //'l' 108 => Server::NonDedicated, //'l'
112 => Server::TV, //'p' 112 => Server::TV, //'p'
_ => Err(UnknownEnumCast)? _ => Err(UnknownEnumCast)?,
}; };
let environment_type = match buffer.get_u8()? { let environment_type = match buffer.get_u8()? {
108 => Environment::Linux, //'l' 108 => Environment::Linux, //'l'
119 => Environment::Windows, //'w' 119 => Environment::Windows, //'w'
109 | 111 => Environment::Mac, //'m' or 'o' 109 | 111 => Environment::Mac, //'m' or 'o'
_ => Err(UnknownEnumCast)? _ => Err(UnknownEnumCast)?,
}; };
let has_password = buffer.get_u8()? == 1; let has_password = buffer.get_u8()? == 1;
let vac_secured = buffer.get_u8()? == 1; let vac_secured = buffer.get_u8()? == 1;
let the_ship = match *engine == SteamApp::TS.as_engine() { let the_ship = match *engine == SteamApp::TS.as_engine() {
false => None, false => None,
true => Some(TheShip { true => {
mode: buffer.get_u8()?, Some(TheShip {
witnesses: buffer.get_u8()?, mode: buffer.get_u8()?,
duration: buffer.get_u8()? witnesses: buffer.get_u8()?,
}) duration: buffer.get_u8()?,
})
}
}; };
let version = buffer.get_string_utf8()?; let version = buffer.get_string_utf8()?;
let extra_data = match buffer.get_u8() { let extra_data = match buffer.get_u8() {
Err(_) => None, Err(_) => None,
Ok(value) => Some(ExtraData { Ok(value) => {
port: match (value & 0x80) > 0 { Some(ExtraData {
false => None, port: match (value & 0x80) > 0 {
true => Some(buffer.get_u16()?) false => None,
}, true => Some(buffer.get_u16()?),
steam_id: match (value & 0x10) > 0 { },
false => None, steam_id: match (value & 0x10) > 0 {
true => Some(buffer.get_u64()?) false => None,
}, true => Some(buffer.get_u64()?),
tv_port: match (value & 0x40) > 0 { },
false => None, tv_port: match (value & 0x40) > 0 {
true => Some(buffer.get_u16()?) false => None,
}, true => Some(buffer.get_u16()?),
tv_name: match (value & 0x40) > 0 { },
false => None, tv_name: match (value & 0x40) > 0 {
true => Some(buffer.get_string_utf8()?) false => None,
}, true => Some(buffer.get_string_utf8()?),
keywords: match (value & 0x20) > 0 { },
false => None, keywords: match (value & 0x20) > 0 {
true => Some(buffer.get_string_utf8()?) false => None,
}, true => Some(buffer.get_string_utf8()?),
game_id: match (value & 0x01) > 0 { },
false => None, game_id: match (value & 0x01) > 0 {
true => { false => None,
let gid = buffer.get_u64()?; true => {
appid = (gid & ((1 << 24) - 1)) as u32; let gid = buffer.get_u64()?;
appid = (gid & ((1 << 24) - 1)) as u32;
Some(gid) Some(gid)
} }
} },
}) })
}
}; };
Ok(ServerInfo { Ok(ServerInfo {
@ -358,7 +394,7 @@ impl ValveProtocol {
version, version,
extra_data, extra_data,
is_mod: false, is_mod: false,
mod_data: None mod_data: None,
}) })
} }
@ -369,7 +405,7 @@ impl ValveProtocol {
let count = buffer.get_u8()? as usize; let count = buffer.get_u8()? as usize;
let mut players: Vec<ServerPlayer> = Vec::with_capacity(count); let mut players: Vec<ServerPlayer> = Vec::with_capacity(count);
for _ in 0..count { for _ in 0 .. count {
buffer.move_position_ahead(1); //skip the index byte buffer.move_position_ahead(1); //skip the index byte
players.push(ServerPlayer { players.push(ServerPlayer {
@ -378,11 +414,11 @@ impl ValveProtocol {
duration: buffer.get_f32()?, duration: buffer.get_f32()?,
deaths: match *engine == SteamApp::TS.as_engine() { deaths: match *engine == SteamApp::TS.as_engine() {
false => None, false => None,
true => Some(buffer.get_u32()?) true => Some(buffer.get_u32()?),
}, },
money: match *engine == SteamApp::TS.as_engine() { money: match *engine == SteamApp::TS.as_engine() {
false => None, false => None,
true => Some(buffer.get_u32()?) true => Some(buffer.get_u32()?),
}, },
}); });
} }
@ -397,7 +433,7 @@ impl ValveProtocol {
let count = buffer.get_u16()? as usize; let count = buffer.get_u16()? as usize;
let mut rules: HashMap<String, String> = HashMap::with_capacity(count); let mut rules: HashMap<String, String> = HashMap::with_capacity(count);
for _ in 0..count { for _ in 0 .. count {
let name = buffer.get_string_utf8()?; let name = buffer.get_string_utf8()?;
let value = buffer.get_string_utf8()?; let value = buffer.get_string_utf8()?;
@ -412,14 +448,35 @@ impl ValveProtocol {
} }
} }
/// Query a server by providing the address, the port, the app, gather and timeout settings. /// Query a server by providing the address, the port, the app, gather and
/// Providing None to the settings results in using the default values for them (GatherSettings::[default](GatheringSettings::default), TimeoutSettings::[default](TimeoutSettings::default)). /// timeout settings. Providing None to the settings results in using the
pub fn query(address: &str, port: u16, engine: Engine, gather_settings: Option<GatheringSettings>, timeout_settings: Option<TimeoutSettings>) -> GDResult<Response> { /// 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(); let response_gather_settings = gather_settings.unwrap_or_default();
get_response(address, port, engine, response_gather_settings, timeout_settings) 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> { 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 mut client = ValveProtocol::new(address, port, timeout_settings)?;
let info = client.get_server_info(&engine)?; let info = client.get_server_info(&engine)?;
@ -445,11 +502,11 @@ fn get_response(address: &str, port: u16, engine: Engine, gather_settings: Gathe
info, info,
players: match gather_settings.players { players: match gather_settings.players {
false => None, false => None,
true => Some(client.get_server_players(&engine, protocol)?) true => Some(client.get_server_players(&engine, protocol)?),
}, },
rules: match gather_settings.rules { rules: match gather_settings.rules {
false => None, false => None,
true => Some(client.get_server_rules(&engine, protocol)?) true => Some(client.get_server_rules(&engine, protocol)?),
} },
}) })
} }

View file

@ -83,9 +83,9 @@ pub struct ServerPlayer {
/// 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).
@ -135,9 +135,7 @@ pub(crate) type ExtractedData = (
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>,
) -> ExtractedData {
match data { match data {
None => (None, None, None, None, None), None => (None, None, None, None, None),
Some(ed) => (ed.port, ed.steam_id, ed.tv_port, ed.tv_name, ed.keywords), Some(ed) => (ed.port, ed.steam_id, ed.tv_port, ed.tv_name, ed.keywords),
@ -248,10 +246,10 @@ impl SteamApp {
/// Get the specified app as engine. /// Get the specified app as engine.
pub fn as_engine(&self) -> Engine { pub fn as_engine(&self) -> Engine {
match self { match self {
SteamApp::CS => Engine::GoldSrc(false), //10 SteamApp::CS => Engine::GoldSrc(false), // 10
SteamApp::TFC => Engine::GoldSrc(false), //20 SteamApp::TFC => Engine::GoldSrc(false), // 20
SteamApp::DOD => Engine::GoldSrc(false), //30 SteamApp::DOD => Engine::GoldSrc(false), // 30
SteamApp::CSCZ => Engine::GoldSrc(false), //80 SteamApp::CSCZ => Engine::GoldSrc(false), // 80
SteamApp::CSS => Engine::new_source(240), SteamApp::CSS => Engine::new_source(240),
SteamApp::DODS => Engine::new_source(300), SteamApp::DODS => Engine::new_source(300),
SteamApp::HL2DM => Engine::new_source(320), SteamApp::HL2DM => Engine::new_source(320),
@ -268,7 +266,7 @@ impl SteamApp {
SteamApp::ARMA2OA => Engine::new_source(33930), SteamApp::ARMA2OA => Engine::new_source(33930),
SteamApp::PZ => Engine::new_source(108600), SteamApp::PZ => Engine::new_source(108600),
SteamApp::INS => Engine::new_source(222880), SteamApp::INS => Engine::new_source(222880),
SteamApp::SC => Engine::GoldSrc(false), //225840 SteamApp::SC => Engine::GoldSrc(false), // 225840
SteamApp::SDTD => Engine::new_source(251570), SteamApp::SDTD => Engine::new_source(251570),
SteamApp::RUST => Engine::new_source(252490), SteamApp::RUST => Engine::new_source(252490),
SteamApp::BO => Engine::new_source(296300), SteamApp::BO => Engine::new_source(296300),
@ -297,9 +295,10 @@ impl SteamApp {
#[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 Engine { pub enum Engine {
/// A Source game, the argument represents the possible steam app ids, if its **None**, let /// A Source game, the argument represents the possible steam app ids, if
/// the query find it, if its **Some**, the query fails if the response id is not the first /// its **None**, let the query find it, if its **Some**, the query
/// one, which is the game app id, or the other one, which is the dedicated server app id. /// fails if the response id is not the first one, which is the game app
/// id, or the other one, which is the dedicated server app id.
Source(Option<(u32, Option<u32>)>), 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.
@ -307,9 +306,7 @@ pub enum Engine {
} }
impl Engine { impl Engine {
pub fn new_source(appid: u32) -> Self { pub fn new_source(appid: u32) -> Self { Engine::Source(Some((appid, None))) }
Engine::Source(Some((appid, None)))
}
pub fn new_source_with_dedicated(appid: u32, dedicated_appid: u32) -> Self { pub fn new_source_with_dedicated(appid: u32, dedicated_appid: u32) -> Self {
Engine::Source(Some((appid, Some(dedicated_appid)))) Engine::Source(Some((appid, Some(dedicated_appid))))
@ -332,8 +329,9 @@ impl Default for GatheringSettings {
} }
} }
/// Generic response types that are used by many games, they are the protocol ones, but without the /// Generic response types that are used by many games, they are the protocol
/// unnecessary bits (example: the **The Ship**-only fields). /// ones, but without the unnecessary bits (example: the **The Ship**-only
/// fields).
pub mod game { pub mod game {
use super::{Server, ServerPlayer}; use super::{Server, ServerPlayer};
use crate::protocols::valve::types::get_optional_extracted_data; use crate::protocols::valve::types::get_optional_extracted_data;
@ -410,8 +408,7 @@ pub mod game {
impl Response { impl Response {
pub fn new_from_valve_response(response: super::Response) -> Self { pub fn new_from_valve_response(response: super::Response) -> Self {
let (port, steam_id, tv_port, tv_name, keywords) = let (port, steam_id, tv_port, tv_name, keywords) = get_optional_extracted_data(response.info.extra_data);
get_optional_extracted_data(response.info.extra_data);
Self { Self {
protocol: response.info.protocol, protocol: response.info.protocol,

View file

@ -1,16 +1,20 @@
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; };
use std::{
io::{Read, Write},
net,
};
const DEFAULT_PACKET_SIZE: usize = 1024; const DEFAULT_PACKET_SIZE: usize = 1024;
pub trait Socket { pub trait Socket {
fn new(address: &str, port: u16) -> GDResult<Self> fn new(address: &str, port: u16) -> GDResult<Self>
where where Self: Sized;
Self: Sized;
fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()>; fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()>;
@ -33,8 +37,8 @@ impl Socket for TcpSocket {
fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()> { fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()> {
let settings = timeout_settings.unwrap_or_default(); let settings = timeout_settings.unwrap_or_default();
self.socket.set_read_timeout(settings.get_read()).unwrap(); //unwrapping because TimeoutSettings::new 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 self.socket.set_write_timeout(settings.get_write()).unwrap(); // checks if these are 0 and throws an error
Ok(()) Ok(())
} }
@ -72,8 +76,8 @@ impl Socket for UdpSocket {
fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()> { fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()> {
let settings = timeout_settings.unwrap_or_default(); let settings = timeout_settings.unwrap_or_default();
self.socket.set_read_timeout(settings.get_read()).unwrap(); //unwrapping because TimeoutSettings::new 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 self.socket.set_write_timeout(settings.get_write()).unwrap(); // checks if these are 0 and throws an error
Ok(()) Ok(())
} }
@ -87,10 +91,9 @@ impl Socket for UdpSocket {
fn receive(&mut self, size: Option<usize>) -> GDResult<Vec<u8>> { fn receive(&mut self, size: Option<usize>) -> GDResult<Vec<u8>> {
let mut buf: Vec<u8> = vec![0; size.unwrap_or(DEFAULT_PACKET_SIZE)]; let mut buf: Vec<u8> = vec![0; size.unwrap_or(DEFAULT_PACKET_SIZE)];
let (number_of_bytes_received, _) = let (number_of_bytes_received, _) = self.socket.recv_from(&mut buf).map_err(|_| PacketReceive)?;
self.socket.recv_from(&mut buf).map_err(|_| PacketReceive)?;
Ok(buf[..number_of_bytes_received].to_vec()) Ok(buf[.. number_of_bytes_received].to_vec())
} }
} }

View file

@ -1,28 +1,30 @@
use crate::{
GDError::{PacketOverflow, PacketUnderflow},
GDResult,
};
use std::cmp::Ordering; use std::cmp::Ordering;
use crate::GDResult;
use crate::GDError::{PacketOverflow, PacketUnderflow};
pub fn error_by_expected_size(expected: usize, size: usize) -> GDResult<()> { pub fn error_by_expected_size(expected: usize, size: usize) -> GDResult<()> {
match size.cmp(&expected) { match size.cmp(&expected) {
Ordering::Greater => Err(PacketOverflow), Ordering::Greater => Err(PacketOverflow),
Ordering::Less => Err(PacketUnderflow), Ordering::Less => Err(PacketUnderflow),
Ordering::Equal => Ok(()) Ordering::Equal => Ok(()),
} }
} }
pub fn address_and_port_as_string(address: &str, port: u16) -> String { pub fn address_and_port_as_string(address: &str, port: u16) -> String { format!("{}:{}", address, port) }
format!("{}:{}", address, port)
}
pub fn u8_lower_upper(n: u8) -> (u8, u8) { pub fn u8_lower_upper(n: u8) -> (u8, u8) { (n & 15, n >> 4) }
(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!(super::address_and_port_as_string("192.168.0.1", 27015), "192.168.0.1:27015"); assert_eq!(
super::address_and_port_as_string("192.168.0.1", 27015),
"192.168.0.1:27015"
);
} }
#[test] #[test]