Skip to main content

PacketProcessor

Struct PacketProcessor 

Source
pub struct PacketProcessor { /* private fields */ }
Expand description

Reassembles fragmented server responses and decompresses compressed packets.

Create one processor for a query session and pass every received UDP datagram to process. The processor keeps incomplete fragments keyed by source address and packet ID. It does not perform network I/O.

Implementations§

Source§

impl PacketProcessor

Source

pub fn new() -> Self

Creates a processor with no pending fragment sequences.

Examples found in repository?
examples/query.rs (line 41)
23fn main() -> Result<(), Box<dyn Error>> {
24    let mut args = std::env::args().skip(1);
25
26    let addr = args.next().unwrap_or_else(|| usage());
27    let kind = args.next().unwrap_or_else(|| "info".into());
28
29    let request = match kind.as_str() {
30        "info" => Request::Info,
31        "players" => Request::Players,
32        "rules" => Request::Rules,
33        _ => usage(),
34    };
35
36    // just some socket setup
37    let socket = UdpSocket::bind("0.0.0.0:0")?;
38    socket.set_read_timeout(Some(Duration::from_secs(2)))?;
39
40    // initial request
41    let mut proc = PacketProcessor::new();
42    socket.send_to(&send_buf(request, None), addr)?;
43
44    loop {
45        let mut buf = [0u8; MAX_PACKET_SIZE];
46        let (len, addr) = socket.recv_from(&mut buf)?;
47        let buf = &buf[..len];
48
49        // does all the work with packet assembling if requires
50        // if it's still not ready, we loop again
51        let Some(resp) = proc.process(addr, buf)? else {
52            continue;
53        };
54
55        match parse_payload(&resp)? {
56            // send challenge if demands
57            Response::Challenge(num) => {
58                socket.send_to(&send_buf(request, Some(num)), addr)?;
59                continue;
60            }
61            // we got any, so print and exit
62            other => {
63                println!("{:#?}", other);
64                break;
65            }
66        }
67    }
68
69    Ok(())
70}
Source

pub fn process<'a>( &mut self, addr: SocketAddr, raw: &'a [u8], ) -> Result<Option<Cow<'a, [u8]>>, Error>

Processes one received UDP datagram.

Returns Ok(None) while more fragments are needed. For a complete single-packet response, the result borrows from raw; assembled or decompressed responses are owned. Pass the returned bytes to crate::parse_payload to decode the A2S response.

addr should be the datagram’s source address. It keeps fragments from different servers in separate sequences.

§Errors

Returns an error for an invalid packet header, malformed fragment sequence, or failed decompression/checksum validation.

Examples found in repository?
examples/query.rs (line 51)
23fn main() -> Result<(), Box<dyn Error>> {
24    let mut args = std::env::args().skip(1);
25
26    let addr = args.next().unwrap_or_else(|| usage());
27    let kind = args.next().unwrap_or_else(|| "info".into());
28
29    let request = match kind.as_str() {
30        "info" => Request::Info,
31        "players" => Request::Players,
32        "rules" => Request::Rules,
33        _ => usage(),
34    };
35
36    // just some socket setup
37    let socket = UdpSocket::bind("0.0.0.0:0")?;
38    socket.set_read_timeout(Some(Duration::from_secs(2)))?;
39
40    // initial request
41    let mut proc = PacketProcessor::new();
42    socket.send_to(&send_buf(request, None), addr)?;
43
44    loop {
45        let mut buf = [0u8; MAX_PACKET_SIZE];
46        let (len, addr) = socket.recv_from(&mut buf)?;
47        let buf = &buf[..len];
48
49        // does all the work with packet assembling if requires
50        // if it's still not ready, we loop again
51        let Some(resp) = proc.process(addr, buf)? else {
52            continue;
53        };
54
55        match parse_payload(&resp)? {
56            // send challenge if demands
57            Response::Challenge(num) => {
58                socket.send_to(&send_buf(request, Some(num)), addr)?;
59                continue;
60            }
61            // we got any, so print and exit
62            other => {
63                println!("{:#?}", other);
64                break;
65            }
66        }
67    }
68
69    Ok(())
70}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.