1#![allow(clippy::redundant_field_names, reason = "Triggered by `Error` derive")]
2
3use std::{
4 backtrace::{Backtrace, BacktraceStatus},
5 env,
6 fmt::Debug,
7 io::Cursor,
8 mem,
9 sync::{
10 Arc, LazyLock,
11 atomic::{self, AtomicBool},
12 },
13};
14
15use azalea_crypto::Aes128CfbEnc;
16use azalea_protocol::{
17 connect::{RawReadConnection, RawWriteConnection},
18 packets::{
19 ConnectionProtocol, Packet, ProtocolPacket, config::ClientboundConfigPacket,
20 game::ClientboundGamePacket, login::ClientboundLoginPacket,
21 },
22 read::{ReadPacketError, deserialize_packet},
23 write::serialize_packet,
24};
25use bevy_app::prelude::*;
26use bevy_ecs::prelude::*;
27use bevy_tasks::{IoTaskPool, futures_lite::future};
28use thiserror::Error;
29use tokio::{
30 io::AsyncWriteExt,
31 net::tcp::OwnedWriteHalf,
32 sync::mpsc::{self},
33};
34use tracing::{debug, error, info, trace};
35
36use super::packet::{
37 config::ReceiveConfigPacketEvent, game::ReceiveGamePacketEvent, login::ReceiveLoginPacketEvent,
38};
39use crate::{
40 local_player::WorldHolder,
41 packet::{config, game, login},
42};
43
44pub struct ConnectionPlugin;
45impl Plugin for ConnectionPlugin {
46 fn build(&self, app: &mut App) {
47 app.add_systems(PreUpdate, (read_packets, poll_all_writer_tasks).chain());
48 }
49}
50
51pub fn read_packets(ecs: &mut World) {
52 let mut entity_and_conn_query = ecs.query::<(Entity, &mut RawConnection)>();
53 let mut conn_query = ecs.query::<(&mut RawConnection, Option<&WorldHolder>)>();
54
55 let mut entities_handling_packets = Vec::new();
56 let mut entities_with_injected_packets = Vec::new();
57 for (entity, mut raw_conn) in entity_and_conn_query.iter_mut(ecs) {
58 if !raw_conn.injected_clientbound_packets.is_empty() {
59 entities_with_injected_packets.push((
60 entity,
61 mem::take(&mut raw_conn.injected_clientbound_packets),
62 ));
63 }
64
65 if raw_conn.network.is_none() {
66 continue;
69 }
70
71 entities_handling_packets.push(entity);
72 }
73
74 let mut queued_packet_events = QueuedPacketEvents::default();
75
76 for (entity, raw_packets) in entities_with_injected_packets {
79 for raw_packet in raw_packets {
80 let (conn, world) = conn_query.get(ecs, entity).unwrap();
81 let state = conn.state;
82
83 let shared_world = world.map(|w| w.shared.clone());
84
85 trace!("Received injected packet with bytes: {raw_packet:?}");
86 if let Err(e) = handle_raw_packet(
87 ecs,
88 |cb| {
89 if let Some(w) = &shared_world {
90 cb(azalea_buf::Ctx::new(&w.read().registries));
91 } else {
92 cb(azalea_buf::Ctx::default());
93 }
94 },
95 &raw_packet,
96 entity,
97 state,
98 &mut queued_packet_events,
99 ) {
100 error!("Error reading injected packet: {e}");
101 }
102 }
103 }
104
105 for entity in entities_handling_packets {
106 loop {
107 let (mut conn, world) = conn_query.get_mut(ecs, entity).unwrap();
108
109 let shared_world = world.map(|w| w.shared.clone());
110
111 let net_conn = conn.net_conn().unwrap();
112 let read_res = net_conn.reader.try_read();
113 let state = conn.state;
114 match read_res {
115 Ok(Some(raw_packet)) => {
116 let raw_packet = Arc::<[u8]>::from(raw_packet);
117 if let Err(e) = handle_raw_packet(
118 ecs,
119 |cb| {
120 if let Some(shared_world) = &shared_world {
121 let registries = &shared_world.read().registries;
122 cb(azalea_buf::Ctx::new(registries));
123 } else {
124 cb(azalea_buf::Ctx::default());
125 }
126 },
127 &raw_packet,
128 entity,
129 state,
130 &mut queued_packet_events,
131 ) {
132 error!("Error reading packet: {e}");
133
134 let mut backtrace_logged = false;
135
136 let dyn_error = &e as &dyn std::error::Error;
137 let backtrace = std::error::request_ref::<Backtrace>(dyn_error);
138 if let Some(backtrace) = backtrace
139 && backtrace.status() == BacktraceStatus::Captured
141 {
142 backtrace_logged = true;
143 eprintln!("{}", backtrace);
144 }
145
146 static PANIC_ON_PACKET_ERROR: LazyLock<bool> = LazyLock::new(|| {
147 env::var("AZALEA_PANIC_ON_PACKET_ERROR")
151 .map(|s| s == "1" || s == "true")
152 .unwrap_or(false)
153 });
154
155 if *PANIC_ON_PACKET_ERROR {
156 if backtrace_logged {
157 println!("\n---\n");
158 }
159 panic!();
160 }
161 }
162 }
163 Ok(None) => {
164 break;
166 }
167 Err(err) => {
168 log_for_error(&err);
169
170 if matches!(
171 &*err,
172 ReadPacketError::IoError { .. } | ReadPacketError::ConnectionClosed
173 ) {
174 info!("Server closed connection");
175 conn.network = None;
177 conn.is_alive = false;
179 }
180
181 break;
182 }
183 }
184 }
185 }
186
187 queued_packet_events.write_messages(ecs);
188}
189
190fn poll_all_writer_tasks(mut conn_query: Query<&mut RawConnection>) {
191 for mut conn in conn_query.iter_mut() {
192 if let Some(net_conn) = &mut conn.network {
193 if net_conn.poll_writer().is_some() {
197 conn.network = None;
199 conn.is_alive = false;
200 }
201 }
202 }
203}
204
205#[derive(Default)]
206pub struct QueuedPacketEvents {
207 login: Vec<ReceiveLoginPacketEvent>,
208 config: Vec<ReceiveConfigPacketEvent>,
209 game: Vec<ReceiveGamePacketEvent>,
210}
211impl QueuedPacketEvents {
212 fn write_messages(&mut self, ecs: &mut World) {
213 ecs.write_message_batch(self.login.drain(..));
214 ecs.write_message_batch(self.config.drain(..));
215 ecs.write_message_batch(self.game.drain(..));
216 }
217}
218
219fn log_for_error(error: &ReadPacketError) {
220 if !matches!(*error, ReadPacketError::ConnectionClosed) {
221 error!("Error reading packet from Client: {error:?}");
222 }
223}
224
225#[derive(Component)]
227pub struct RawConnection {
228 pub(crate) network: Option<NetworkConnection>,
241 pub state: ConnectionProtocol,
242 pub(crate) is_alive: bool,
243
244 pub injected_clientbound_packets: Vec<Box<[u8]>>,
250}
251impl RawConnection {
252 pub fn new(
253 reader: RawReadConnection,
254 writer: RawWriteConnection,
255 state: ConnectionProtocol,
256 ) -> Self {
257 let task_pool = IoTaskPool::get();
258
259 let (network_packet_writer_tx, network_packet_writer_rx) =
260 mpsc::unbounded_channel::<Box<[u8]>>();
261
262 let writer_task =
263 task_pool.spawn(write_task(network_packet_writer_rx, writer.write_stream));
264
265 let mut conn = Self::new_networkless(state);
266 conn.network = Some(NetworkConnection {
267 reader,
268 enc_cipher: writer.enc_cipher,
269 network_packet_writer_tx,
270 writer_task,
271 });
272
273 conn
274 }
275
276 pub fn new_networkless(state: ConnectionProtocol) -> Self {
277 Self {
278 network: None,
279 state,
280 is_alive: true,
281 injected_clientbound_packets: Vec::new(),
282 }
283 }
284
285 pub fn is_alive(&self) -> bool {
286 self.is_alive
287 }
288
289 pub fn write<P: ProtocolPacket + Debug>(
298 &mut self,
299 ctx: azalea_buf::Ctx,
300 packet: impl Packet<P>,
301 ) -> Result<(), WritePacketError> {
302 if let Some(network) = &mut self.network {
303 network.write(ctx, packet)?;
304 } else {
305 static WARNED: AtomicBool = AtomicBool::new(false);
306 if !WARNED.swap(true, atomic::Ordering::Relaxed) {
307 debug!(
308 "tried to write packet to the network but there is no NetworkConnection. if you're trying to send a packet from the handler function, use self.write instead"
309 );
310 }
311 }
312 Ok(())
313 }
314
315 pub fn net_conn(&mut self) -> Option<&mut NetworkConnection> {
316 self.network.as_mut()
317 }
318}
319
320pub fn handle_raw_packet(
321 ecs: &mut World,
322 with_ctx: impl Fn(&mut dyn FnMut(azalea_buf::Ctx<'_>)),
323 raw_packet: &[u8],
324 entity: Entity,
325 state: ConnectionProtocol,
326 queued_packet_events: &mut QueuedPacketEvents,
327) -> Result<(), Box<ReadPacketError>> {
328 let stream = &mut Cursor::new(raw_packet);
329 match state {
330 ConnectionProtocol::Handshake => {
331 unreachable!()
332 }
333 ConnectionProtocol::Game => {
334 let mut c = Err(ReadPacketError::ConnectionClosed.into());
338 with_ctx(&mut |ctx| c = deserialize_packet::<ClientboundGamePacket>(ctx, stream));
339 let packet = Arc::new(c?);
340
341 trace!("Packet: {packet:?}");
342 game::process_packet(ecs, entity, packet.as_ref());
343 queued_packet_events
344 .game
345 .push(ReceiveGamePacketEvent { entity, packet });
346 }
347 ConnectionProtocol::Status => {
348 unreachable!()
349 }
350 ConnectionProtocol::Login => {
351 let mut c = Err(ReadPacketError::ConnectionClosed.into());
352 with_ctx(&mut |ctx| c = deserialize_packet::<ClientboundLoginPacket>(ctx, stream));
353 let packet = Arc::new(c?);
354
355 trace!("Packet: {packet:?}");
356 login::process_packet(ecs, entity, &packet);
357 queued_packet_events
358 .login
359 .push(ReceiveLoginPacketEvent { entity, packet });
360 }
361 ConnectionProtocol::Configuration => {
362 let mut c = Err(ReadPacketError::ConnectionClosed.into());
363 with_ctx(&mut |ctx| c = deserialize_packet::<ClientboundConfigPacket>(ctx, stream));
364 let packet = Arc::new(c?);
365
366 trace!("Packet: {packet:?}");
367 config::process_packet(ecs, entity, &packet);
368 queued_packet_events
369 .config
370 .push(ReceiveConfigPacketEvent { entity, packet });
371 }
372 };
373
374 Ok(())
375}
376
377pub struct NetworkConnection {
378 reader: RawReadConnection,
379 pub enc_cipher: Option<Aes128CfbEnc>,
381
382 pub writer_task: bevy_tasks::Task<()>,
383 network_packet_writer_tx: mpsc::UnboundedSender<Box<[u8]>>,
388}
389impl NetworkConnection {
390 pub fn write<P: ProtocolPacket + Debug>(
391 &mut self,
392 ctx: azalea_buf::Ctx,
393 packet: impl Packet<P>,
394 ) -> Result<(), WritePacketError> {
395 let packet = packet.into_variant();
396 let raw_packet = serialize_packet(ctx, &packet)?;
397 self.write_raw(ctx, &raw_packet)?;
398
399 Ok(())
400 }
401
402 pub fn write_raw(
403 &mut self,
404 ctx: azalea_buf::Ctx,
405 raw_packet: &[u8],
406 ) -> Result<(), WritePacketError> {
407 let network_packet = azalea_protocol::write::encode_to_network_packet(
408 ctx,
409 raw_packet,
410 self.reader.compression_threshold,
411 &mut self.enc_cipher,
412 );
413 self.network_packet_writer_tx
414 .send(network_packet.into_boxed_slice())?;
415 Ok(())
416 }
417
418 pub fn poll_writer(&mut self) -> Option<()> {
421 let poll_once_res = future::poll_once(&mut self.writer_task);
422 future::block_on(poll_once_res)
423 }
424
425 pub fn set_compression_threshold(&mut self, threshold: Option<u32>) {
426 trace!("Set compression threshold to {threshold:?}");
427 self.reader.compression_threshold = threshold;
428 }
429 pub fn set_encryption_key(&mut self, key: [u8; 16]) {
433 trace!("Enabled protocol encryption");
434 let (enc_cipher, dec_cipher) = azalea_crypto::create_cipher(&key);
435 self.reader.dec_cipher = Some(dec_cipher);
436 self.enc_cipher = Some(enc_cipher);
437 }
438}
439
440async fn write_task(
441 mut network_packet_writer_rx: mpsc::UnboundedReceiver<Box<[u8]>>,
442 mut write_half: OwnedWriteHalf,
443) {
444 while let Some(network_packet) = network_packet_writer_rx.recv().await {
445 if let Err(e) = write_half.write_all(&network_packet).await {
446 debug!("Error writing packet to server: {e}");
447 break;
448 };
449 }
450
451 trace!("write task is done");
452}
453
454#[derive(Debug, Error)]
455pub enum WritePacketError {
456 #[error("Wrong protocol state: expected {expected:?}, got {got:?}")]
457 WrongState {
458 expected: ConnectionProtocol,
459 got: ConnectionProtocol,
460 },
461 #[error(transparent)]
462 Encoding(#[from] azalea_protocol::write::PacketEncodeError),
463 #[error(transparent)]
464 SendError {
465 #[from]
466 #[backtrace]
467 source: mpsc::error::SendError<Box<[u8]>>,
468 },
469}