1use std::{
4 fmt::Debug,
5 io::{self, Read},
6};
7
8use azalea_buf::AzBufVar;
9use azalea_crypto::Aes128CfbEnc;
10use flate2::{Compression, bufread::ZlibEncoder};
11use thiserror::Error;
12use tokio::io::{AsyncWrite, AsyncWriteExt};
13use tracing::trace;
14
15use crate::{packets::ProtocolPacket, read::MAXIMUM_UNCOMPRESSED_LENGTH};
16
17pub async fn write_packet<P, W>(
18 ctx: azalea_buf::Ctx<'_>,
19 packet: &P,
20 stream: &mut W,
21 compression_threshold: Option<u32>,
22 cipher: &mut Option<Aes128CfbEnc>,
23) -> io::Result<()>
24where
25 P: ProtocolPacket + Debug,
26 W: AsyncWrite + Unpin + Send,
27{
28 trace!("Sending packet: {packet:?}");
29 let raw_packet = serialize_packet(ctx, packet).unwrap();
30 write_raw_packet(ctx, &raw_packet, stream, compression_threshold, cipher).await
31}
32
33pub fn serialize_packet<P: ProtocolPacket + Debug>(
34 ctx: azalea_buf::Ctx,
35 packet: &P,
36) -> Result<Box<[u8]>, PacketEncodeError> {
37 let mut buf = Vec::new();
38 packet.id().azalea_write_var(ctx, &mut buf)?;
39 packet.write(ctx, &mut buf)?;
40 if buf.len() > MAXIMUM_UNCOMPRESSED_LENGTH as usize {
41 return Err(PacketEncodeError::TooBig {
42 actual: buf.len(),
43 maximum: MAXIMUM_UNCOMPRESSED_LENGTH as usize,
44 packet_string: format!("{packet:?}"),
45 });
46 }
47 Ok(buf.into_boxed_slice())
48}
49
50pub async fn write_raw_packet<W>(
51 ctx: azalea_buf::Ctx<'_>,
52 raw_packet: &[u8],
53 stream: &mut W,
54 compression_threshold: Option<u32>,
55 cipher: &mut Option<Aes128CfbEnc>,
56) -> io::Result<()>
57where
58 W: AsyncWrite + Unpin + Send,
59{
60 let network_packet = encode_to_network_packet(ctx, raw_packet, compression_threshold, cipher);
61 stream.write_all(&network_packet).await
62}
63
64pub async fn write_raw_packets<W>(
65 ctx: azalea_buf::Ctx<'_>,
66 raw_packets: impl Iterator<Item = &[u8]>,
67 stream: &mut W,
68 compression_threshold: Option<u32>,
69 cipher: &mut Option<Aes128CfbEnc>,
70) -> io::Result<()>
71where
72 W: AsyncWrite + Unpin + Send,
73{
74 let mut buffer = Vec::new();
75 for raw_packet in raw_packets {
76 buffer.extend(encode_to_network_packet(
77 ctx,
78 raw_packet,
79 compression_threshold,
80 cipher,
81 ));
82 }
83 stream.write_all(&buffer).await
84}
85
86pub fn encode_to_network_packet(
87 ctx: azalea_buf::Ctx<'_>,
88 raw_packet: &[u8],
89 compression_threshold: Option<u32>,
90 cipher: &mut Option<Aes128CfbEnc>,
91) -> Vec<u8> {
92 trace!("Writing raw packet: {raw_packet:?}");
93 let mut raw_packet = raw_packet.to_vec();
94 if let Some(threshold) = compression_threshold {
95 raw_packet = compression_encoder(ctx, &raw_packet, threshold).unwrap();
96 }
97 raw_packet = frame_prepender(raw_packet).unwrap();
98 if let Some(cipher) = cipher {
100 azalea_crypto::encrypt_packet(cipher, &mut raw_packet);
101 }
102 raw_packet
103}
104
105pub fn compression_encoder(
106 ctx: azalea_buf::Ctx<'_>,
107 data: &[u8],
108 compression_threshold: u32,
109) -> Result<Vec<u8>, PacketCompressError> {
110 let n = data.len();
111 if n < compression_threshold as usize {
113 let mut buf = Vec::new();
114 0_u32.azalea_write_var(ctx, &mut buf)?;
115 io::Write::write_all(&mut buf, data)?;
116 Ok(buf)
117 } else {
118 let mut deflater = ZlibEncoder::new(data, Compression::default());
120
121 let mut compressed_data = Vec::new();
123 deflater.read_to_end(&mut compressed_data)?;
124
125 let mut len_prepended_compressed_data = Vec::new();
127 (data.len() as u32).azalea_write_var(ctx, &mut len_prepended_compressed_data)?;
128 len_prepended_compressed_data.append(&mut compressed_data);
129
130 Ok(len_prepended_compressed_data)
131 }
132}
133
134fn frame_prepender(mut data: Vec<u8>) -> Result<Vec<u8>, io::Error> {
136 let mut buf = Vec::new();
137 azalea_buf::primitives::write_varint(data.len() as u32 as i32, &mut buf)?;
138 buf.append(&mut data);
139 Ok(buf)
140}
141
142#[derive(Debug, Error)]
143pub enum PacketEncodeError {
144 #[error("{0}")]
145 Io(#[from] io::Error),
146 #[error("Packet too big (is {actual} bytes, should be less than {maximum}): {packet_string}")]
147 TooBig {
148 actual: usize,
149 maximum: usize,
150 packet_string: String,
151 },
152}
153
154#[derive(Debug, Error)]
155pub enum PacketCompressError {
156 #[error("{0}")]
157 Io(#[from] io::Error),
158}