chore: format

This commit is contained in:
Cain 2024-01-18 17:56:58 +00:00
parent 1991c9f5eb
commit b49525543d
5 changed files with 101 additions and 93 deletions

View file

@ -51,8 +51,8 @@ enum Action {
#[arg(short, long)] #[arg(short, long)]
ip: String, ip: String,
/// Optional query port number for the server. If not provided the default /// Optional query port number for the server. If not provided the
/// port for the game is used. /// default port for the game is used.
#[arg(short, long)] #[arg(short, long)]
port: Option<u16>, port: Option<u16>,
@ -195,39 +195,51 @@ fn set_hostname_if_missing(host: &str, extra_options: &mut Option<ExtraRequestSe
/// * `result` - A reference to the result of the query. /// * `result` - A reference to the result of the query.
fn output_result<T: CommonResponse + ?Sized>(output_mode: OutputMode, format: OutputFormat, result: &T) { fn output_result<T: CommonResponse + ?Sized>(output_mode: OutputMode, format: OutputFormat, result: &T) {
match format { match format {
OutputFormat::Debug => match output_mode { OutputFormat::Debug => {
OutputMode::Generic => output_result_debug(result.as_json()), match output_mode {
OutputMode::ProtocolSpecific => output_result_debug(result.as_original()), OutputMode::Generic => output_result_debug(result.as_json()),
}, OutputMode::ProtocolSpecific => output_result_debug(result.as_original()),
}
}
#[cfg(feature = "json")] #[cfg(feature = "json")]
OutputFormat::JsonPretty => match output_mode { OutputFormat::JsonPretty => {
OutputMode::Generic => output_result_json_pretty(result.as_json()), match output_mode {
OutputMode::ProtocolSpecific => output_result_json_pretty(result.as_original()), OutputMode::Generic => output_result_json_pretty(result.as_json()),
}, OutputMode::ProtocolSpecific => output_result_json_pretty(result.as_original()),
}
}
#[cfg(feature = "json")] #[cfg(feature = "json")]
OutputFormat::Json => match output_mode { OutputFormat::Json => {
OutputMode::Generic => output_result_json(result.as_json()), match output_mode {
OutputMode::ProtocolSpecific => output_result_json(result.as_original()), OutputMode::Generic => output_result_json(result.as_json()),
}, OutputMode::ProtocolSpecific => output_result_json(result.as_original()),
}
}
#[cfg(feature = "xml")] #[cfg(feature = "xml")]
OutputFormat::Xml => match output_mode { OutputFormat::Xml => {
OutputMode::Generic => output_result_xml(result.as_json()), match output_mode {
//BUG: In this case we get a writer error with all serde write methods some reason with xml 0.6.0 OutputMode::Generic => output_result_xml(result.as_json()),
//BUG: gamedig-cli.exe query -g <GAME> -i <IP> -p <PORT> -f xml --output-mode protocol-specific // BUG: In this case we get a writer error with all serde write methods some reason with xml 0.6.0
//BUG: Writer: emitter error: document start event has already been emitted // BUG: gamedig-cli.exe query -g <GAME> -i <IP> -p <PORT> -f xml --output-mode protocol-specific
//BUG: With xml 0.5.1 we get unsupported operation: 'serialize_unit_variant' // BUG: Writer: emitter error: document start event has already been emitted
OutputMode::ProtocolSpecific => panic!("XML format is not supported for protocol specific output"), // BUG: With xml 0.5.1 we get unsupported operation: 'serialize_unit_variant'
}, OutputMode::ProtocolSpecific => panic!("XML format is not supported for protocol specific output"),
}
}
#[cfg(feature = "bson")] #[cfg(feature = "bson")]
OutputFormat::BsonHex => match output_mode { OutputFormat::BsonHex => {
OutputMode::Generic => output_result_bson_hex(result.as_json()), match output_mode {
OutputMode::ProtocolSpecific => output_result_bson_hex(result.as_original()), OutputMode::Generic => output_result_bson_hex(result.as_json()),
}, OutputMode::ProtocolSpecific => output_result_bson_hex(result.as_original()),
}
}
#[cfg(feature = "bson")] #[cfg(feature = "bson")]
OutputFormat::BsonBase64 => match output_mode { OutputFormat::BsonBase64 => {
OutputMode::Generic => output_result_bson_base64(result.as_json()), match output_mode {
OutputMode::ProtocolSpecific => output_result_bson_base64(result.as_original()), OutputMode::Generic => output_result_bson_base64(result.as_json()),
}, OutputMode::ProtocolSpecific => output_result_bson_base64(result.as_original()),
}
}
} }
} }

View file

@ -38,6 +38,4 @@ pub fn setup_capture(file_path: Option<PathBuf>) {
/// ///
/// # Errors /// # Errors
/// Returns an Error if the writer is already set. /// Returns an Error if the writer is already set.
fn attach(writer: Box<dyn Writer + Send + Sync>) { fn attach(writer: Box<dyn Writer + Send + Sync>) { crate::socket::capture::set_writer(writer); }
crate::socket::capture::set_writer(writer);
}

View file

@ -31,7 +31,8 @@ pub(crate) enum Protocol {
/// Trait for handling different types of IP addresses (IPv4, IPv6). /// Trait for handling different types of IP addresses (IPv4, IPv6).
pub(crate) trait IpAddress: Sized { pub(crate) trait IpAddress: Sized {
/// Creates an instance from a standard `IpAddr`, returning `None` if the types are incompatible. /// Creates an instance from a standard `IpAddr`, returning `None` if the
/// types are incompatible.
fn from_std(ip: IpAddr) -> Option<Self>; fn from_std(ip: IpAddr) -> Option<Self>;
} }
@ -67,12 +68,15 @@ impl CapturePacket<'_> {
(local, remote) (local, remote)
} }
/// Retrieves IP addresses of a specific type (IPv4 or IPv6) based on the packet's direction. /// Retrieves IP addresses of a specific type (IPv4 or IPv6) based on the
/// packet's direction.
/// ///
/// Panics if the IP type of the addresses does not match the requested type. /// Panics if the IP type of the addresses does not match the requested
/// type.
/// ///
/// Returns: /// Returns:
/// - (T, T): Tuple of (source IP, destination IP) of the specified type in order. /// - (T, T): Tuple of (source IP, destination IP) of the specified type in
/// order.
pub(super) fn ipvt_by_direction<T: IpAddress>(&self) -> (T, T) { pub(super) fn ipvt_by_direction<T: IpAddress>(&self) -> (T, T) {
let (local, remote) = ( let (local, remote) = (
T::from_std(self.local_address.ip()).expect("Incorrect IP type for local address"), T::from_std(self.local_address.ip()).expect("Incorrect IP type for local address"),
@ -84,7 +88,8 @@ impl CapturePacket<'_> {
} }
impl Direction { impl Direction {
/// Orders two elements (source and destination) based on the packet's direction. /// Orders two elements (source and destination) based on the packet's
/// direction.
/// ///
/// Returns: /// Returns:
/// - (T, T): Ordered tuple (source, destination). /// - (T, T): Ordered tuple (source, destination).
@ -124,9 +129,7 @@ mod tests {
use std::str::FromStr; use std::str::FromStr;
// Helper function to create a SocketAddr from a string // Helper function to create a SocketAddr from a string
fn socket_addr(addr: &str) -> SocketAddr { fn socket_addr(addr: &str) -> SocketAddr { SocketAddr::from_str(addr).unwrap() }
SocketAddr::from_str(addr).unwrap()
}
#[test] #[test]
fn test_ports_by_direction() { fn test_ports_by_direction() {

View file

@ -11,7 +11,13 @@ use pnet_packet::{
use std::{io::Write, net::IpAddr, time::Instant}; use std::{io::Write, net::IpAddr, time::Instant};
use super::packet::{ use super::packet::{
CapturePacket, Direction, Protocol, HEADER_SIZE_ETHERNET, HEADER_SIZE_IP4, HEADER_SIZE_IP6, HEADER_SIZE_UDP, CapturePacket,
Direction,
Protocol,
HEADER_SIZE_ETHERNET,
HEADER_SIZE_IP4,
HEADER_SIZE_IP6,
HEADER_SIZE_UDP,
PACKET_SIZE, PACKET_SIZE,
}; };
@ -80,7 +86,7 @@ impl<W: Write> Pcap<W> {
self.write_transport_payload( self.write_transport_payload(
info, info,
IpNextHeaderProtocols::Tcp, IpNextHeaderProtocols::Tcp,
&buf[..buf_size + payload.len()], &buf[.. buf_size + payload.len()],
vec![], vec![],
); );
@ -113,7 +119,7 @@ impl<W: Write> Pcap<W> {
self.write_transport_payload( self.write_transport_payload(
&info, &info,
IpNextHeaderProtocols::Tcp, IpNextHeaderProtocols::Tcp,
&buf[..buf_size], &buf[.. buf_size],
vec![EnhancedPacketOption::Comment("Generated TCP ACK".into())], vec![EnhancedPacketOption::Comment("Generated TCP ACK".into())],
); );
} }
@ -131,7 +137,7 @@ impl<W: Write> Pcap<W> {
self.write_transport_payload( self.write_transport_payload(
info, info,
IpNextHeaderProtocols::Udp, IpNextHeaderProtocols::Udp,
&buf[..buf_size + payload.len()], &buf[.. buf_size + payload.len()],
vec![], vec![],
); );
} }
@ -238,7 +244,7 @@ impl<W: Write> Pcap<W> {
self.write_transport_payload( self.write_transport_payload(
&info, &info,
IpNextHeaderProtocols::Tcp, IpNextHeaderProtocols::Tcp,
&buf[..buf_size], &buf[.. buf_size],
options.clone(), options.clone(),
); );
@ -261,7 +267,7 @@ impl<W: Write> Pcap<W> {
self.write_transport_payload( self.write_transport_payload(
&info, &info,
IpNextHeaderProtocols::Tcp, IpNextHeaderProtocols::Tcp,
&buf[..buf_size], &buf[.. buf_size],
options.clone(), options.clone(),
); );
@ -280,7 +286,12 @@ impl<W: Write> Pcap<W> {
tcp.packet_size() tcp.packet_size()
}; };
self.write_transport_payload(&info, IpNextHeaderProtocols::Tcp, &buf[..buf_size], options); self.write_transport_payload(
&info,
IpNextHeaderProtocols::Tcp,
&buf[.. buf_size],
options,
);
self.state.has_sent_handshake = true; self.state.has_sent_handshake = true;
} }
@ -314,7 +325,7 @@ impl<W: Write> Pcap<W> {
self.write_transport_payload( self.write_transport_payload(
info, info,
IpNextHeaderProtocols::Tcp, IpNextHeaderProtocols::Tcp,
&buf[..buf_size], &buf[.. buf_size],
vec![EnhancedPacketOption::Comment("Generated TCP FIN".into())], vec![EnhancedPacketOption::Comment("Generated TCP FIN".into())],
); );

View file

@ -22,8 +22,7 @@ pub trait Socket {
/// # Returns /// # Returns
/// A result containing the socket instance or an error. /// A result containing the socket instance or an error.
fn new(address: &SocketAddr, timeout_settings: &Option<TimeoutSettings>) -> GDResult<Self> fn new(address: &SocketAddr, timeout_settings: &Option<TimeoutSettings>) -> GDResult<Self>
where where Self: Sized;
Self: Sized;
/// Apply read and write timeouts to the socket. /// Apply read and write timeouts to the socket.
/// ///
@ -112,12 +111,8 @@ impl Socket for TcpSocketImpl {
Ok(buf) Ok(buf)
} }
fn port(&self) -> u16 { fn port(&self) -> u16 { self.address.port() }
self.address.port() fn local_addr(&self) -> std::io::Result<SocketAddr> { self.socket.local_addr() }
}
fn local_addr(&self) -> std::io::Result<SocketAddr> {
self.socket.local_addr()
}
} }
/// Implementation of a UDP socket. /// Implementation of a UDP socket.
@ -165,15 +160,11 @@ impl Socket for UdpSocketImpl {
.recv_from(&mut buf) .recv_from(&mut buf)
.map_err(|e| PacketReceive.context(e))?; .map_err(|e| PacketReceive.context(e))?;
Ok(buf[..number_of_bytes_received].to_vec()) Ok(buf[.. number_of_bytes_received].to_vec())
} }
fn port(&self) -> u16 { fn port(&self) -> u16 { self.address.port() }
self.address.port() fn local_addr(&self) -> std::io::Result<SocketAddr> { self.socket.local_addr() }
}
fn local_addr(&self) -> std::io::Result<SocketAddr> {
self.socket.local_addr()
}
} }
/// Things used for capturing packets. /// Things used for capturing packets.
@ -219,17 +210,13 @@ pub mod capture {
/// Represents the TCP protocol provider. /// Represents the TCP protocol provider.
pub(crate) struct ProtocolTCP; pub(crate) struct ProtocolTCP;
impl ProtocolProvider for ProtocolTCP { impl ProtocolProvider for ProtocolTCP {
fn protocol() -> Protocol { fn protocol() -> Protocol { Protocol::TCP }
Protocol::TCP
}
} }
/// Represents the UDP protocol provider. /// Represents the UDP protocol provider.
pub(crate) struct ProtocolUDP; pub(crate) struct ProtocolUDP;
impl ProtocolProvider for ProtocolUDP { impl ProtocolProvider for ProtocolUDP {
fn protocol() -> Protocol { fn protocol() -> Protocol { Protocol::UDP }
Protocol::UDP
}
} }
/// A socket wrapper that allows capturing packets. /// A socket wrapper that allows capturing packets.
@ -247,8 +234,9 @@ pub mod capture {
impl<I: Socket, P: ProtocolProvider> Socket for WrappedCaptureSocket<I, P> { impl<I: Socket, P: ProtocolProvider> Socket for WrappedCaptureSocket<I, P> {
/// Creates a new wrapped socket for capturing packets. /// Creates a new wrapped socket for capturing packets.
/// ///
/// Initializes a new socket of type `I`, wrapping it to enable packet capturing. /// Initializes a new socket of type `I`, wrapping it to enable packet
/// Capturing is protocol-specific, as indicated by the `ProtocolProvider`. /// capturing. Capturing is protocol-specific, as indicated by
/// the `ProtocolProvider`.
/// ///
/// # Arguments /// # Arguments
/// * `address` - The address to connect the socket to. /// * `address` - The address to connect the socket to.
@ -257,9 +245,7 @@ pub mod capture {
/// # Returns /// # Returns
/// A `GDResult` containing either the wrapped socket or an error. /// A `GDResult` containing either the wrapped socket or an error.
fn new(address: &SocketAddr, timeout_settings: &Option<TimeoutSettings>) -> GDResult<Self> fn new(address: &SocketAddr, timeout_settings: &Option<TimeoutSettings>) -> GDResult<Self>
where where Self: Sized {
Self: Sized,
{
let v = Self { let v = Self {
inner: I::new(address, timeout_settings)?, inner: I::new(address, timeout_settings)?,
remote_address: *address, remote_address: *address,
@ -282,8 +268,8 @@ pub mod capture {
/// Sends data over the socket and captures the packet. /// Sends data over the socket and captures the packet.
/// ///
/// The method sends data using the inner socket and captures the sent packet /// The method sends data using the inner socket and captures the sent
/// if a capture writer is set. /// packet if a capture writer is set.
/// ///
/// # Arguments /// # Arguments
/// * `data` - Data to be sent. /// * `data` - Data to be sent.
@ -307,8 +293,8 @@ pub mod capture {
/// Receives data from the socket and captures the packet. /// Receives data from the socket and captures the packet.
/// ///
/// The method receives data using the inner socket and captures the incoming packet /// The method receives data using the inner socket and captures the
/// if a capture writer is set. /// incoming packet if a capture writer is set.
/// ///
/// # Arguments /// # Arguments
/// * `size` - Optional size of data to receive. /// * `size` - Optional size of data to receive.
@ -353,9 +339,7 @@ pub mod capture {
/// ///
/// # Returns /// # Returns
/// The remote port number. /// The remote port number.
fn port(&self) -> u16 { fn port(&self) -> u16 { self.inner.port() }
self.inner.port()
}
/// Returns the local SocketAddr of the wrapped socket. /// Returns the local SocketAddr of the wrapped socket.
/// ///
@ -363,9 +347,7 @@ pub mod capture {
/// ///
/// # Returns /// # Returns
/// The local SocketAddr. /// The local SocketAddr.
fn local_addr(&self) -> std::io::Result<SocketAddr> { fn local_addr(&self) -> std::io::Result<SocketAddr> { self.inner.local_addr() }
self.inner.local_addr()
}
} }
// this seems a bad way to do this, but its safe // this seems a bad way to do this, but its safe
@ -388,18 +370,20 @@ pub mod capture {
} }
} }
/// A specialized `WrappedCaptureSocket` for UDP, using `UdpSocketImpl` as the inner socket /// A specialized `WrappedCaptureSocket` for UDP, using `UdpSocketImpl` as
/// and `ProtocolUDP` as the protocol provider. /// the inner socket and `ProtocolUDP` as the protocol provider.
/// ///
/// This type captures and processes UDP packets, wrapping around standard UDP socket /// This type captures and processes UDP packets, wrapping around standard
/// functionalities with additional packet capture capabilities. /// UDP socket functionalities with additional packet capture
/// capabilities.
pub(crate) type CapturedUdpSocket = WrappedCaptureSocket<UdpSocketImpl, ProtocolUDP>; pub(crate) type CapturedUdpSocket = WrappedCaptureSocket<UdpSocketImpl, ProtocolUDP>;
/// A specialized `WrappedCaptureSocket` for TCP, using `TcpSocketImpl` as the inner socket /// A specialized `WrappedCaptureSocket` for TCP, using `TcpSocketImpl` as
/// and `ProtocolTCP` as the protocol provider. /// the inner socket and `ProtocolTCP` as the protocol provider.
/// ///
/// This type captures and processes TCP packets, wrapping around standard TCP socket /// This type captures and processes TCP packets, wrapping around standard
/// functionalities with additional packet capture capabilities. /// TCP socket functionalities with additional packet capture
/// capabilities.
pub(crate) type CapturedTcpSocket = WrappedCaptureSocket<TcpSocketImpl, ProtocolTCP>; pub(crate) type CapturedTcpSocket = WrappedCaptureSocket<TcpSocketImpl, ProtocolTCP>;
} }