mirror of
https://github.com/tribufu/rust-gamedig
synced 2026-05-06 15:27:28 +00:00
Reverter errors from taking a &'static str to String
This commit is contained in:
parent
dc0926bab7
commit
7b44c5f7eb
10 changed files with 59 additions and 59 deletions
|
|
@ -11,35 +11,35 @@ pub type GDResult<T> = Result<T, GDError>;
|
|||
#[derive(Debug, Clone)]
|
||||
pub enum GDError {
|
||||
/// The received packet was bigger than the buffer size.
|
||||
PacketOverflow(&'static str),
|
||||
PacketOverflow(String),
|
||||
/// The received packet was shorter than the expected one.
|
||||
PacketUnderflow(&'static str),
|
||||
PacketUnderflow(String),
|
||||
/// The received packet was badly formatted.
|
||||
PacketBad(&'static str),
|
||||
PacketBad(String),
|
||||
/// Couldn't send the packet.
|
||||
PacketSend(&'static str),
|
||||
PacketSend(String),
|
||||
/// Couldn't send the receive.
|
||||
PacketReceive(&'static str),
|
||||
PacketReceive(String),
|
||||
/// Couldn't decompress data.
|
||||
Decompress(&'static str),
|
||||
Decompress(String),
|
||||
/// Unknown cast while translating a value to an enum.
|
||||
UnknownEnumCast,
|
||||
/// The server queried is not from the queried game.
|
||||
BadGame(&'static str),
|
||||
BadGame(String),
|
||||
/// Problems occurred while dns resolving.
|
||||
DnsResolve(&'static str),
|
||||
DnsResolve(String),
|
||||
/// Couldn't bind a socket.
|
||||
SocketBind(&'static str),
|
||||
SocketBind(String),
|
||||
/// Invalid input.
|
||||
InvalidInput(&'static str),
|
||||
InvalidInput(String),
|
||||
/// Couldn't create a socket connection.
|
||||
SocketConnect(&'static str),
|
||||
SocketConnect(String),
|
||||
/// Couldn't parse a json string.
|
||||
JsonParse(&'static str),
|
||||
JsonParse(String),
|
||||
/// Couldn't automatically query.
|
||||
AutoQuery(&'static str),
|
||||
AutoQuery,
|
||||
/// A protocol-defined expected format was not met.
|
||||
ProtocolFormat(&'static str),
|
||||
ProtocolFormat(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for GDError {
|
||||
|
|
@ -58,7 +58,7 @@ impl fmt::Display for GDError {
|
|||
GDError::InvalidInput(details) => write!(f, "Invalid input: {details}"),
|
||||
GDError::SocketConnect(details) => write!(f, "Socket connect: {details}"),
|
||||
GDError::JsonParse(details) => write!(f, "Json parse: {details}"),
|
||||
GDError::AutoQuery(details) => write!(f, "Auto query: {details}"),
|
||||
GDError::AutoQuery => write!(f, "Auto query failed."),
|
||||
GDError::ProtocolFormat(details) => write!(f, "Protocol rule: {details}"),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -73,33 +73,33 @@ impl Java {
|
|||
let mut pos = 0;
|
||||
|
||||
if get_varint(&buf, &mut pos)? != 0 { //first var int is the packet id
|
||||
return Err(GDError::PacketBad("Bad receive packet id."));
|
||||
return Err(GDError::PacketBad("Bad receive packet id.".to_string()));
|
||||
}
|
||||
|
||||
let json_response = get_string(&buf, &mut pos)?;
|
||||
let value_response: Value = serde_json::from_str(&json_response)
|
||||
.map_err(|e| GDError::JsonParse(e.to_string().as_str()))?;
|
||||
.map_err(|e| GDError::JsonParse(e.to_string()))?;
|
||||
|
||||
let version_name = value_response["version"]["name"].as_str()
|
||||
.ok_or(GDError::PacketBad("Couldn't get expected string."))?.to_string();
|
||||
.ok_or(GDError::PacketBad("Couldn't get expected string.".to_string()))?.to_string();
|
||||
let version_protocol = value_response["version"]["protocol"].as_i64()
|
||||
.ok_or(GDError::PacketBad("Couldn't get expected number."))? as i32;
|
||||
.ok_or(GDError::PacketBad("Couldn't get expected number.".to_string()))? as i32;
|
||||
|
||||
let max_players = value_response["players"]["max"].as_u64()
|
||||
.ok_or(GDError::PacketBad("Couldn't get expected number."))? as u32;
|
||||
.ok_or(GDError::PacketBad("Couldn't get expected number.".to_string()))? as u32;
|
||||
let online_players = value_response["players"]["online"].as_u64()
|
||||
.ok_or(GDError::PacketBad("Couldn't get expected number."))? as u32;
|
||||
.ok_or(GDError::PacketBad("Couldn't get expected number.".to_string()))? as u32;
|
||||
let sample_players: Option<Vec<Player>> = match value_response["players"]["sample"].is_null() {
|
||||
true => None,
|
||||
false => Some({
|
||||
let players_values = value_response["players"]["sample"].as_array()
|
||||
.ok_or(GDError::PacketBad("Couldn't get expected array."))?;
|
||||
.ok_or(GDError::PacketBad("Couldn't get expected array.".to_string()))?;
|
||||
|
||||
let mut players = Vec::with_capacity(players_values.len());
|
||||
for player in players_values {
|
||||
players.push(Player {
|
||||
name: player["name"].as_str().ok_or(GDError::PacketBad("Couldn't get expected string."))?.to_string(),
|
||||
id: player["id"].as_str().ok_or(GDError::PacketBad("Couldn't get expected string."))?.to_string()
|
||||
name: player["name"].as_str().ok_or(GDError::PacketBad("Couldn't get expected string.".to_string()))?.to_string(),
|
||||
id: player["id"].as_str().ok_or(GDError::PacketBad("Couldn't get expected string.".to_string()))?.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ impl LegacyBV1_8 {
|
|||
let mut pos = 0;
|
||||
|
||||
if get_u8(&buf, &mut pos)? != 0xFF {
|
||||
return Err(GDError::ProtocolFormat("Expected 0xFF at the begin of the packet."));
|
||||
return Err(GDError::ProtocolFormat("Expected 0xFF at the begin of the packet.".to_string()));
|
||||
}
|
||||
|
||||
let length = get_u16_be(&buf, &mut pos)? * 2;
|
||||
|
|
@ -44,9 +44,9 @@ impl LegacyBV1_8 {
|
|||
|
||||
let description = split[0].to_string();
|
||||
let online_players = split[1].parse()
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int."))?;
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?;
|
||||
let max_players = split[2].parse()
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int."))?;
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?;
|
||||
|
||||
Ok(Response {
|
||||
version_name: "Beta 1.8+".to_string(),
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ impl LegacyV1_4 {
|
|||
let mut pos = 0;
|
||||
|
||||
if get_u8(&buf, &mut pos)? != 0xFF {
|
||||
return Err(GDError::ProtocolFormat("Expected 0xFF at the begin of the packet."));
|
||||
return Err(GDError::ProtocolFormat("Expected 0xFF at the begin of the packet.".to_string()));
|
||||
}
|
||||
|
||||
let length = get_u16_be(&buf, &mut pos)? * 2;
|
||||
|
|
@ -49,9 +49,9 @@ impl LegacyV1_4 {
|
|||
|
||||
let description = split[0].to_string();
|
||||
let online_players = split[1].parse()
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int."))?;
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?;
|
||||
let max_players = split[2].parse()
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int."))?;
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?;
|
||||
|
||||
Ok(Response {
|
||||
version_name: "1.4+".to_string(),
|
||||
|
|
|
|||
|
|
@ -52,13 +52,13 @@ impl LegacyV1_6 {
|
|||
error_by_expected_size(5, split.len())?;
|
||||
|
||||
let version_protocol = split[0].parse()
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int."))?;
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?;
|
||||
let version_name = split[1].to_string();
|
||||
let description = split[2].to_string();
|
||||
let max_players = split[3].parse()
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int."))?;
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?;
|
||||
let online_players = split[4].parse()
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int."))?;
|
||||
.map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?;
|
||||
|
||||
Ok(Response {
|
||||
version_name,
|
||||
|
|
@ -81,14 +81,14 @@ impl LegacyV1_6 {
|
|||
let mut pos = 0;
|
||||
|
||||
if get_u8(&buf, &mut pos)? != 0xFF {
|
||||
return Err(GDError::ProtocolFormat("Expected a certain byte (0xFF) at the begin of the packet."));
|
||||
return Err(GDError::ProtocolFormat("Expected a certain byte (0xFF) at the begin of the packet.".to_string()));
|
||||
}
|
||||
|
||||
let length = get_u16_be(&buf, &mut pos)? * 2;
|
||||
error_by_expected_size((length + 3) as usize, buf.len())?;
|
||||
|
||||
if !LegacyV1_6::is_protocol(&buf, &mut pos)? {
|
||||
return Err(GDError::ProtocolFormat("Expected certain bytes at the beginning of the packet."));
|
||||
return Err(GDError::ProtocolFormat("Expected certain bytes at the beginning of the packet.".to_string()));
|
||||
}
|
||||
|
||||
LegacyV1_6::get_response(&buf, &mut pos)
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>
|
|||
return Ok(response);
|
||||
}
|
||||
|
||||
Err(GDError::AutoQuery("No protocol returned a response.".to_string()))
|
||||
Err(GDError::AutoQuery)
|
||||
}
|
||||
|
||||
/// Queries a specific Minecraft Server type.
|
||||
|
|
|
|||
|
|
@ -96,7 +96,7 @@ pub fn get_varint(buf: &[u8], pos: &mut usize) -> GDResult<i32> {
|
|||
|
||||
// The 5th byte is only allowed to have the 4 smallest bits set
|
||||
if i == 4 && (current_byte & 0xf0 != 0) {
|
||||
return Err(GDError::PacketBad("VarInt Overflow".to_string()))
|
||||
return Err(GDError::PacketBad("Couldn't parse to VarInt: Overflow.".to_string()))
|
||||
}
|
||||
|
||||
if (current_byte & msb) == 0 {
|
||||
|
|
@ -140,7 +140,7 @@ pub fn get_string(buf: &[u8], pos: &mut usize) -> GDResult<String> {
|
|||
}
|
||||
|
||||
Ok(String::from_utf8(text)
|
||||
.map_err(|_| GDError::PacketBad("Minecraft bad String".to_string()))?)
|
||||
.map_err(|_| GDError::PacketBad("Couldn't parse to a Minecraft String.".to_string()))?)
|
||||
}
|
||||
|
||||
pub fn as_string(value: String) -> Vec<u8> {
|
||||
|
|
|
|||
|
|
@ -13,13 +13,13 @@ impl TimeoutSettings {
|
|||
pub fn new(read: Option<Duration>, write: Option<Duration>) -> GDResult<Self> {
|
||||
if let Some(read_duration) = read {
|
||||
if read_duration == Duration::new(0, 0) {
|
||||
return Err(GDError::InvalidInput("Can't pass duration 0 to timeout settings".to_string()))
|
||||
return Err(GDError::InvalidInput("Can't pass duration 0 to timeout settings.".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(write_duration) = write {
|
||||
if write_duration == Duration::new(0, 0) {
|
||||
return Err(GDError::InvalidInput("Can't pass duration 0 to timeout settings".to_string()))
|
||||
return Err(GDError::InvalidInput("Can't pass duration 0 to timeout settings.".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -117,18 +117,18 @@ impl SplitPacket {
|
|||
fn get_payload(&self) -> GDResult<Vec<u8>> {
|
||||
if self.compressed {
|
||||
let mut decoder = Decoder::new();
|
||||
decoder.write(&self.payload).map_err(|e| GDError::Decompress(e.to_string().as_str()))?;
|
||||
decoder.write(&self.payload).map_err(|e| GDError::Decompress(e.to_string()))?;
|
||||
|
||||
let decompressed_size = self.decompressed_size.unwrap() as usize;
|
||||
|
||||
let mut decompressed_payload = Vec::with_capacity(decompressed_size);
|
||||
decoder.read(&mut decompressed_payload).map_err(|e| GDError::Decompress(e.to_string().as_str()))?;
|
||||
decoder.read(&mut decompressed_payload).map_err(|e| GDError::Decompress(e.to_string()))?;
|
||||
|
||||
if decompressed_payload.len() != decompressed_size {
|
||||
Err(GDError::Decompress("The decompressed payload size doesn't match the expected one."))
|
||||
Err(GDError::Decompress("The decompressed payload size doesn't match the expected one.".to_string()))
|
||||
}
|
||||
else if crc32fast::hash(&decompressed_payload) != self.uncompressed_crc32.unwrap() {
|
||||
Err(GDError::Decompress("The decompressed crc32 hash does not match the expected one."))
|
||||
Err(GDError::Decompress("The decompressed crc32 hash does not match the expected one.".to_string()))
|
||||
}
|
||||
else {
|
||||
Ok(decompressed_payload)
|
||||
|
|
@ -420,7 +420,7 @@ fn get_response(address: &str, port: u16, app: App, gather_settings: GatheringSe
|
|||
if let App::Source(x) = &app {
|
||||
if let Some(appid) = x {
|
||||
if *appid != info.appid {
|
||||
return Err(GDError::BadGame(format!("Expected {}, found {} instead!", *appid, info.appid).as_str()));
|
||||
return Err(GDError::BadGame(format!("Expected {}, found {} instead!", *appid, info.appid)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
28
src/utils.rs
28
src/utils.rs
|
|
@ -4,20 +4,20 @@ use crate::{GDResult, GDError};
|
|||
|
||||
fn resolve_dns(address: &str) -> GDResult<String> {
|
||||
let resolver = Resolver::new(ResolverConfig::default(), ResolverOpts::default())
|
||||
.map_err(|e| GDError::DnsResolve(e.to_string().as_str()))?;
|
||||
.map_err(|e| GDError::DnsResolve(e.to_string()))?;
|
||||
|
||||
let response = resolver.lookup_ip(address)
|
||||
.map_err(|e| GDError::DnsResolve(e.to_string().as_str()))?;
|
||||
.map_err(|e| GDError::DnsResolve(e.to_string()))?;
|
||||
|
||||
Ok(response.iter().next().ok_or(GDError::DnsResolve("Couldn't resolve the DNS address."))?.to_string())
|
||||
Ok(response.iter().next().ok_or(GDError::DnsResolve("Couldn't resolve the DNS address.".to_string()))?.to_string())
|
||||
}
|
||||
|
||||
pub fn error_by_expected_size(expected: usize, size: usize) -> GDResult<()> {
|
||||
if size < expected {
|
||||
Err(GDError::PacketUnderflow("Unexpectedly short packet."))
|
||||
Err(GDError::PacketUnderflow("Unexpectedly short packet.".to_string()))
|
||||
}
|
||||
else if size > expected {
|
||||
Err(GDError::PacketOverflow("Unexpectedly long packet."))
|
||||
Err(GDError::PacketOverflow("Unexpectedly long packet.".to_string()))
|
||||
}
|
||||
else {
|
||||
Ok(())
|
||||
|
|
@ -37,7 +37,7 @@ pub mod buffer {
|
|||
|
||||
pub fn get_u8(buf: &[u8], pos: &mut usize) -> GDResult<u8> {
|
||||
if buf.len() <= *pos {
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet."));
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an u8.".to_string()));
|
||||
}
|
||||
|
||||
let value = buf[*pos];
|
||||
|
|
@ -47,7 +47,7 @@ pub mod buffer {
|
|||
|
||||
pub fn get_u16_le(buf: &[u8], pos: &mut usize) -> GDResult<u16> {
|
||||
if buf.len() <= *pos + 1 {
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet."));
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an u16.".to_string()));
|
||||
}
|
||||
|
||||
let value = u16::from_le_bytes([buf[*pos], buf[*pos + 1]]);
|
||||
|
|
@ -57,7 +57,7 @@ pub mod buffer {
|
|||
|
||||
pub fn get_u16_be(buf: &[u8], pos: &mut usize) -> GDResult<u16> {
|
||||
if buf.len() <= *pos + 1 {
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet."));
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an u16.".to_string()));
|
||||
}
|
||||
|
||||
let value = u16::from_be_bytes([buf[*pos], buf[*pos + 1]]);
|
||||
|
|
@ -67,7 +67,7 @@ pub mod buffer {
|
|||
|
||||
pub fn get_u32_le(buf: &[u8], pos: &mut usize) -> GDResult<u32> {
|
||||
if buf.len() <= *pos + 3 {
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet."));
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an u32.".to_string()));
|
||||
}
|
||||
|
||||
let value = u32::from_le_bytes([buf[*pos], buf[*pos + 1], buf[*pos + 2], buf[*pos + 3]]);
|
||||
|
|
@ -77,7 +77,7 @@ pub mod buffer {
|
|||
|
||||
pub fn get_f32_le(buf: &[u8], pos: &mut usize) -> GDResult<f32> {
|
||||
if buf.len() <= *pos + 3 {
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet."));
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an f32.".to_string()));
|
||||
}
|
||||
|
||||
let value = f32::from_le_bytes([buf[*pos], buf[*pos + 1], buf[*pos + 2], buf[*pos + 3]]);
|
||||
|
|
@ -87,7 +87,7 @@ pub mod buffer {
|
|||
|
||||
pub fn get_u64_le(buf: &[u8], pos: &mut usize) -> GDResult<u64> {
|
||||
if buf.len() <= *pos + 7 {
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet."));
|
||||
return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an u64.".to_string()));
|
||||
}
|
||||
|
||||
let value = u64::from_le_bytes([buf[*pos], buf[*pos + 1], buf[*pos + 2], buf[*pos + 3], buf[*pos + 4], buf[*pos + 5], buf[*pos + 6], buf[*pos + 7]]);
|
||||
|
|
@ -98,9 +98,9 @@ pub mod buffer {
|
|||
pub fn get_string_utf8_le(buf: &[u8], pos: &mut usize) -> GDResult<String> {
|
||||
let sub_buf = &buf[*pos..];
|
||||
let first_null_position = sub_buf.iter().position(|&x| x == 0)
|
||||
.ok_or(GDError::PacketBad("Unexpectedly formatted packet."))?;
|
||||
.ok_or(GDError::PacketBad("Unexpectedly formatted packet for getting a string.".to_string()))?;
|
||||
let value = std::str::from_utf8(&sub_buf[..first_null_position])
|
||||
.map_err(|_| GDError::PacketBad("Badly formatted string."))?.to_string();
|
||||
.map_err(|_| GDError::PacketBad("Badly formatted string.".to_string()))?.to_string();
|
||||
|
||||
*pos += value.len() + 1;
|
||||
Ok(value)
|
||||
|
|
@ -112,7 +112,7 @@ pub mod buffer {
|
|||
.into_iter().map(|a| u16::from_be_bytes([a[0], a[1]])).collect();
|
||||
|
||||
let value = String::from_utf16(&paired_buf)
|
||||
.map_err(|_| GDError::PacketBad("Badly formatted string."))?.to_string();
|
||||
.map_err(|_| GDError::PacketBad("Badly formatted string.".to_string()))?.to_string();
|
||||
|
||||
*pos += value.len() + 1;
|
||||
Ok(value)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue