aboutsummaryrefslogtreecommitdiff
path: root/azalea-protocol/src/write.rs
blob: 9291681c3386c69ae7aa881377349a19604aad14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use crate::{mc_buf::Writable, packets::ProtocolPacket, read::MAXIMUM_UNCOMPRESSED_LENGTH};
use async_compression::tokio::bufread::ZlibEncoder;
use azalea_crypto::Aes128CfbEnc;
use std::fmt::Debug;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};

fn frame_prepender(data: &mut Vec<u8>) -> Result<Vec<u8>, String> {
    let mut buf = Vec::new();
    buf.write_varint(data.len() as i32)
        .map_err(|e| e.to_string())?;
    buf.append(data);
    Ok(buf)
}

fn packet_encoder<P: ProtocolPacket + std::fmt::Debug>(packet: &P) -> Result<Vec<u8>, String> {
    let mut buf = Vec::new();
    buf.write_varint(packet.id() as i32)
        .map_err(|e| e.to_string())?;
    packet.write(&mut buf).map_err(|e| e.to_string())?;
    if buf.len() > MAXIMUM_UNCOMPRESSED_LENGTH as usize {
        return Err(format!(
            "Packet too big (is {} bytes, should be less than {}): {:?}",
            buf.len(),
            MAXIMUM_UNCOMPRESSED_LENGTH,
            packet
        ));
    }
    Ok(buf)
}

async fn compression_encoder(data: &[u8], compression_threshold: u32) -> Result<Vec<u8>, String> {
    let n = data.len();
    // if it's less than the compression threshold, don't compress
    if n < compression_threshold as usize {
        let mut buf = Vec::new();
        buf.write_varint(0).map_err(|e| e.to_string())?;
        buf.write_all(data).await.map_err(|e| e.to_string())?;
        Ok(buf)
    } else {
        // otherwise, compress
        let mut deflater = ZlibEncoder::new(data);
        // write deflated data to buf
        let mut buf = Vec::new();
        deflater
            .read_to_end(&mut buf)
            .await
            .map_err(|e| e.to_string())?;
        Ok(buf)
    }
}

pub async fn write_packet<P, W>(
    packet: P,
    stream: &mut W,
    compression_threshold: Option<u32>,
    cipher: &mut Option<Aes128CfbEnc>,
) where
    P: ProtocolPacket + Debug,
    W: AsyncWrite + Unpin + Send,
{
    let mut buf = packet_encoder(&packet).unwrap();
    if let Some(threshold) = compression_threshold {
        buf = compression_encoder(&buf, threshold).await.unwrap();
    }
    buf = frame_prepender(&mut buf).unwrap();
    // if we were given a cipher, encrypt the packet
    if let Some(cipher) = cipher {
        azalea_crypto::encrypt_packet(cipher, &mut buf);
    }
    stream.write_all(&buf).await.unwrap();
}