a2s-protocol 0.1.1

A protocol core for building A2S server query clients
Documentation
use std::marker::PhantomData;
use crate::{CONNECTIONLESS_HEADER, cursor::Cursor};
use super::Error;

const COMPRESSION_BIT: i32 = 1 << 31;
const SINGLE_PACKET: i32 = CONNECTIONLESS_HEADER;
const MULTI_PACKET: i32 = -2;

#[derive(Debug, Clone, PartialEq)]
pub struct MultiPacketId {
    pub id: i32,
    pub remaining: Vec<u8>
}

#[derive(Debug)]
pub enum PacketKind {
    Single,
    Multi(MultiPacketId)
}

#[derive(Debug)]
pub enum MultiPacketKind<'a> {
    Source(SourceMultiPacket<'a>),
    GoldSrc(GoldSrcMultiPacket<'a>)
}

impl MultiPacketKind<'_> {
    pub fn total(&self) -> u8 {
        match self {
            Self::Source(elem) => elem.total,
            Self::GoldSrc(elem) => elem.total
        }
    }
}

#[derive(Debug)]
pub struct Compression {
    pub size: i32,
    pub crc32_sum: i32,
}

#[derive(Debug, PartialEq)]
pub struct Source;
#[derive(Debug)]
pub struct GoldSrc;

pub type SourceMultiPacket<'a> = MultiPacket<'a, Source>;
pub type GoldSrcMultiPacket<'a> = MultiPacket<'a, GoldSrc>;

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MultiPacket<'a, Engine> {
    pub id: i32,
    pub total: u8,
    pub number: u8,
    payload: &'a [u8],
    _engine: PhantomData<Engine>
}

pub struct FirstSourceMultiPacket {
    pub size: Option<u16>,
    pub compression: Option<Compression>,
}

// use this when the packet is known to belong to a sequence with the same ID
pub trait FromUnchecked<'a>: Sized {
    fn from_unchecked(packet: &'a MultiPacketId) -> Result<Self, Error>;
}

impl<'a> FromUnchecked<'a> for SourceMultiPacket<'a> {
    fn from_unchecked(packet: &'a MultiPacketId) -> Result<Self, Error> {
        let mut cur = Cursor::new(&packet.remaining);
        Ok(Self {
            id: packet.id,
            total: cur.read_byte()?,
            number: cur.read_byte()?,
            payload: cur.as_slice(),
            _engine: PhantomData
        })
    }
}

impl<'a> SourceMultiPacket<'a> {
    pub fn is_compressed(&self) -> bool {
        self.id & COMPRESSION_BIT != 0
    }

    pub fn payload_unchecked(&self, orangebox: bool) -> Result<&[u8], Error> {
        let mut cur = Cursor::new(self.payload);

        if self.is_compressed() {
            // decompressed size and CRC32
            cur.read_longlong()?;
        }

        if orangebox {
            // `Size`
            cur.read_short()?;
        }

        Ok(cur.as_slice())
    }

    // A GoldSrc multipacket must contain at least two fragments, so its fragment count
    // cannot be 1. However, I have seen pre-Orange Box Source engines send single-fragment
    // multipackets, possibly for compression.
    pub fn as_single_multipacket(packet: &'a MultiPacketId) -> Result<Option<Self>, Error> {
        let mut cur = Cursor::new(&packet.remaining);
        let packet_number = cur.read_byte()?;

        Ok(if packet_number == 1 {
            Some(Self::from_unchecked(packet)?)
        } else {
            None
        })
    }

    pub fn as_first(&self) -> Result<Option<FirstSourceMultiPacket>, Error> {
        if self.number != 0 {
            return Ok(None);
        }

        let mut cur = Cursor::new(self.payload);

        let size = if self.is_orangebox()? {
            Some(cur.read_short()?)
        } else {
            None
        };

        let compression = if self.is_compressed() {
            Some(Compression {
                size: cur.read_long()?,
                crc32_sum: cur.read_long()?,
            })
        } else {
            None
        };

        Ok(Some(FirstSourceMultiPacket{size, compression}))
    }

    fn is_orangebox(&self) -> Result<bool, Error> {
        debug_assert!(self.number == 0);

        let mut cur = Cursor::new(self.payload);

        if self.is_compressed() {
            // decompressed size and CRC32
            cur.read_longlong()?;
            // potential `Size`
            cur.read_short()?;
            // Orange Box: first byte of the bzip2 stream ('B').
            // Legacy: third byte of it ('h').
            Ok(cur.read_byte()? == b'B')
        } else {
            cur.read_long()?;
            // Orange Box: third 0xFF of the connection-less prefix.
            // Legacy: response header byte, never 0xFF.
            Ok(cur.read_byte()? == 0xFF)
        }
    }
}

impl<'a> GoldSrcMultiPacket<'a> {
    pub fn payload(&self) -> &[u8] {
        self.payload
    }
}

impl<'a> FromUnchecked<'a> for GoldSrcMultiPacket<'a> {
    fn from_unchecked(packet: &'a MultiPacketId) -> Result<Self, Error> {
        let mut cur = Cursor::new(&packet.remaining);
        let packet_number = cur.read_byte()?;

        Ok(Self {
            id: packet.id,
            total: packet_number & 0x0F,
            number: packet_number >> 4,
            payload: cur.as_slice(),
            _engine: PhantomData
        })
    }
}

impl MultiPacketId {
    // Distinguish Source and GoldSrc multipackets by comparing the first byte of two
    // fragments: Source fragments share the same total-count byte, while GoldSrc headers
    // also encode the fragment number.
    pub fn kind(&self, other: &Self) -> Result<MultiPacketKind<'_>, Error> {
        debug_assert!(self.id == other.id);

        let mut cur = (Cursor::new(&self.remaining), Cursor::new(&other.remaining));

        let first = cur.0.read_byte()?;
        let second = cur.1.read_byte()?;

        let packet = if first == second {
            MultiPacketKind::Source(SourceMultiPacket::from_unchecked(self)?)
        } else {
            MultiPacketKind::GoldSrc(GoldSrcMultiPacket::from_unchecked(self)?)
        };

        Ok(packet)
    }
}

impl FirstSourceMultiPacket {
    pub fn is_orangebox(&self) -> bool {
        self.size.is_some()
    }
}

impl TryFrom<&[u8]> for PacketKind {
    type Error = Error;

    fn try_from(raw: &[u8]) -> Result<Self, Self::Error> {
        parse_packet(raw)
    }
}

fn parse_packet(raw: &[u8]) -> Result<PacketKind, Error> {
    let mut cur = Cursor::new(raw);

    match cur.read_long()? {
        SINGLE_PACKET => Ok(PacketKind::Single),
        MULTI_PACKET => Ok(PacketKind::Multi(
            MultiPacketId { id: cur.read_long()?, remaining: cur.as_slice().into() }
        )),
        other => Err(Error::InvalidPacketHeader(other)),
    }
}