1use std::{
4 fmt::{self, Debug, Display},
5 io::{self, Cursor},
6 marker::PhantomData,
7 net::SocketAddr,
8};
9
10#[cfg(feature = "online-mode")]
11use azalea_auth::{
12 game_profile::GameProfile,
13 sessionserver::{ClientSessionServerError, ServerSessionServerError},
14};
15use azalea_crypto::{Aes128CfbDec, Aes128CfbEnc};
16use thiserror::Error;
17use tokio::{
18 io::{AsyncWriteExt, BufStream},
19 net::{
20 TcpStream,
21 tcp::{OwnedReadHalf, OwnedWriteHalf, ReuniteError},
22 },
23};
24use tracing::{error, info};
25#[cfg(feature = "online-mode")]
26use uuid::Uuid;
27
28#[cfg(feature = "online-mode")]
29use crate::packets::login::ClientboundHello;
30use crate::{
31 packets::{
32 ProtocolPacket,
33 config::{ClientboundConfigPacket, ServerboundConfigPacket},
34 game::{ClientboundGamePacket, ServerboundGamePacket},
35 handshake::{ClientboundHandshakePacket, ServerboundHandshakePacket},
36 login::{ClientboundLoginPacket, ServerboundLoginPacket},
37 status::{ClientboundStatusPacket, ServerboundStatusPacket},
38 },
39 read::{ReadPacketError, deserialize_packet, read_raw_packet, try_read_raw_packet},
40 write::{serialize_packet, write_raw_packet, write_raw_packets},
41};
42
43pub struct RawReadConnection {
44 pub read_stream: OwnedReadHalf,
45 pub buffer: Cursor<Vec<u8>>,
46 pub compression_threshold: Option<u32>,
47 pub dec_cipher: Option<Aes128CfbDec>,
48}
49
50pub struct RawWriteConnection {
51 pub write_stream: OwnedWriteHalf,
52 pub compression_threshold: Option<u32>,
53 pub enc_cipher: Option<Aes128CfbEnc>,
54}
55
56pub struct ReadConnection<R: ProtocolPacket> {
58 pub raw: RawReadConnection,
59 _reading: PhantomData<R>,
60}
61
62pub struct WriteConnection<W: ProtocolPacket> {
64 pub raw: RawWriteConnection,
65 _writing: PhantomData<W>,
66}
67
68pub struct Connection<R: ProtocolPacket, W: ProtocolPacket> {
157 pub reader: ReadConnection<R>,
158 pub writer: WriteConnection<W>,
159}
160
161impl RawReadConnection {
162 pub async fn read(&mut self) -> Result<Box<[u8]>, Box<ReadPacketError>> {
163 read_raw_packet::<_>(
164 &mut self.read_stream,
165 &mut self.buffer,
166 self.compression_threshold,
167 &mut self.dec_cipher,
168 )
169 .await
170 }
171
172 pub fn try_read(&mut self) -> Result<Option<Box<[u8]>>, Box<ReadPacketError>> {
173 try_read_raw_packet::<_>(
174 &mut self.read_stream,
175 &mut self.buffer,
176 self.compression_threshold,
177 &mut self.dec_cipher,
178 )
179 }
180}
181
182impl RawWriteConnection {
183 pub async fn write(&mut self, ctx: azalea_buf::Ctx<'_>, packet: &[u8]) -> io::Result<()> {
184 if let Err(e) = write_raw_packet(
185 ctx,
186 packet,
187 &mut self.write_stream,
188 self.compression_threshold,
189 &mut self.enc_cipher,
190 )
191 .await
192 {
193 if e.kind() == io::ErrorKind::BrokenPipe {
195 info!("Broken pipe, shutting down connection.");
196 if let Err(e) = self.shutdown().await {
197 error!("Couldn't shut down: {}", e);
198 }
199 }
200 return Err(e);
201 }
202 Ok(())
203 }
204
205 pub async fn write_batch(
206 &mut self,
207 ctx: azalea_buf::Ctx<'_>,
208 packets: impl Iterator<Item = &[u8]>,
209 ) -> io::Result<()> {
210 if let Err(e) = write_raw_packets(
211 ctx,
212 packets,
213 &mut self.write_stream,
214 self.compression_threshold,
215 &mut self.enc_cipher,
216 )
217 .await
218 {
219 if e.kind() == io::ErrorKind::BrokenPipe {
221 info!("Broken pipe, shutting down connection.");
222 if let Err(e) = self.shutdown().await {
223 error!("Couldn't shut down: {}", e);
224 }
225 }
226 return Err(e);
227 }
228 Ok(())
229 }
230
231 pub async fn shutdown(&mut self) -> io::Result<()> {
233 self.write_stream.shutdown().await
234 }
235}
236
237impl<R> ReadConnection<R>
238where
239 R: ProtocolPacket + Debug,
240{
241 pub async fn read(&mut self, ctx: azalea_buf::Ctx<'_>) -> Result<R, Box<ReadPacketError>> {
243 let raw_packet = self.raw.read().await?;
244 deserialize_packet(ctx, &mut Cursor::new(&raw_packet))
245 }
246
247 pub fn try_read(
250 &mut self,
251 ctx: azalea_buf::Ctx<'_>,
252 ) -> Result<Option<R>, Box<ReadPacketError>> {
253 let Some(raw_packet) = self.raw.try_read()? else {
254 return Ok(None);
255 };
256 Ok(Some(deserialize_packet(
257 ctx,
258 &mut Cursor::new(&raw_packet),
259 )?))
260 }
261}
262impl<W> WriteConnection<W>
263where
264 W: ProtocolPacket + Debug,
265{
266 pub async fn write(&mut self, ctx: azalea_buf::Ctx<'_>, packet: W) -> io::Result<()> {
268 self.raw
269 .write(ctx, &serialize_packet(ctx, &packet).unwrap())
270 .await
271 }
272
273 pub async fn write_batch(&mut self, ctx: azalea_buf::Ctx<'_>, packets: &[W]) -> io::Result<()> {
275 let serialized_packets: Vec<Box<[u8]>> = packets
276 .iter()
277 .map(|packet| serialize_packet(ctx, packet).unwrap())
278 .collect();
279 self.raw
280 .write_batch(ctx, serialized_packets.iter().map(|data| data.as_ref()))
281 .await
282 }
283
284 pub async fn shutdown(&mut self) -> io::Result<()> {
286 self.raw.shutdown().await
287 }
288}
289
290impl<R, W> Connection<R, W>
291where
292 R: ProtocolPacket + Debug,
293 W: ProtocolPacket + Debug,
294{
295 pub async fn read(&mut self, ctx: azalea_buf::Ctx<'_>) -> Result<R, Box<ReadPacketError>> {
297 self.reader.read(ctx).await
298 }
299
300 pub fn try_read(
303 &mut self,
304 ctx: azalea_buf::Ctx<'_>,
305 ) -> Result<Option<R>, Box<ReadPacketError>> {
306 self.reader.try_read(ctx)
307 }
308
309 pub async fn write(
311 &mut self,
312 ctx: azalea_buf::Ctx<'_>,
313 packet: impl crate::packets::Packet<W>,
314 ) -> io::Result<()> {
315 let packet = packet.into_variant();
316 self.writer.write(ctx, packet).await
317 }
318
319 pub async fn write_batch(&mut self, ctx: azalea_buf::Ctx<'_>, packets: &[W]) -> io::Result<()> {
321 self.writer.write_batch(ctx, packets).await
322 }
323
324 #[must_use]
328 pub fn into_split(self) -> (ReadConnection<R>, WriteConnection<W>) {
329 (self.reader, self.writer)
330 }
331
332 #[must_use]
337 pub fn into_split_raw(self) -> (RawReadConnection, RawWriteConnection) {
338 (self.reader.raw, self.writer.raw)
339 }
340}
341
342#[derive(Debug, Error)]
343pub enum ConnectionError {
344 #[error("{0}")]
345 Io(#[from] io::Error),
346}
347
348use socks5_impl::UserKey;
349
350#[derive(Clone, Debug)]
352pub struct Proxy {
353 pub addr: SocketAddr,
354 pub auth: Option<UserKey>,
355}
356
357impl Proxy {
358 pub fn new(addr: SocketAddr, auth: Option<UserKey>) -> Self {
359 Self { addr, auth }
360 }
361}
362impl Display for Proxy {
363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364 write!(f, "socks5://")?;
365 if let Some(auth) = &self.auth {
366 write!(f, "{auth}@")?;
367 }
368 write!(f, "{}", self.addr)
369 }
370}
371
372#[cfg(feature = "online-mode")]
373impl From<Proxy> for reqwest::Proxy {
374 fn from(proxy: Proxy) -> Self {
375 reqwest::Proxy::all(proxy.to_string())
376 .expect("azalea proxies should not fail to parse as reqwest proxies")
377 }
378}
379
380impl Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> {
381 pub async fn new(address: &SocketAddr) -> Result<Self, ConnectionError> {
383 let stream = TcpStream::connect(address).await?;
384
385 stream.set_nodelay(true)?;
387
388 Self::new_from_stream(stream).await
389 }
390
391 pub async fn new_with_proxy(
395 address: &SocketAddr,
396 proxy: Proxy,
397 ) -> Result<Self, ConnectionError> {
398 let proxy_stream = TcpStream::connect(proxy.addr).await?;
399 let mut stream = BufStream::new(proxy_stream);
400
401 let _ = socks5_impl::client::connect(&mut stream, address, proxy.auth)
402 .await
403 .map_err(io::Error::other)?;
404
405 Self::new_from_stream(stream.into_inner()).await
406 }
407
408 pub async fn new_from_stream(stream: TcpStream) -> Result<Self, ConnectionError> {
413 let (read_stream, write_stream) = stream.into_split();
414
415 Ok(Connection {
416 reader: ReadConnection {
417 raw: RawReadConnection {
418 read_stream,
419 buffer: Cursor::new(Vec::new()),
420 compression_threshold: None,
421 dec_cipher: None,
422 },
423 _reading: PhantomData,
424 },
425 writer: WriteConnection {
426 raw: RawWriteConnection {
427 write_stream,
428 compression_threshold: None,
429 enc_cipher: None,
430 },
431 _writing: PhantomData,
432 },
433 })
434 }
435
436 #[must_use]
440 pub fn login(self) -> Connection<ClientboundLoginPacket, ServerboundLoginPacket> {
441 Connection::from(self)
442 }
443
444 #[must_use]
448 pub fn status(self) -> Connection<ClientboundStatusPacket, ServerboundStatusPacket> {
449 Connection::from(self)
450 }
451}
452
453impl Connection<ClientboundLoginPacket, ServerboundLoginPacket> {
454 pub fn set_compression_threshold(&mut self, threshold: i32) {
460 if threshold >= 0 {
462 self.reader.raw.compression_threshold = Some(threshold as u32);
463 self.writer.raw.compression_threshold = Some(threshold as u32);
464 } else {
465 self.reader.raw.compression_threshold = None;
466 self.writer.raw.compression_threshold = None;
467 }
468 }
469
470 pub fn set_encryption_key(&mut self, key: [u8; 16]) {
474 let (enc_cipher, dec_cipher) = azalea_crypto::create_cipher(&key);
475 self.reader.raw.dec_cipher = Some(dec_cipher);
476 self.writer.raw.enc_cipher = Some(enc_cipher);
477 }
478
479 #[must_use]
484 pub fn config(self) -> Connection<ClientboundConfigPacket, ServerboundConfigPacket> {
485 Connection::from(self)
486 }
487
488 #[cfg(feature = "online-mode")]
542 pub async fn authenticate(
543 &self,
544 access_token: &str,
545 uuid: &Uuid,
546 private_key: [u8; 16],
547 packet: &ClientboundHello,
548 sessionserver_proxy: Option<Proxy>,
549 ) -> Result<(), ClientSessionServerError> {
550 use azalea_auth::sessionserver::{self, SessionServerJoinOpts};
551
552 sessionserver::join(SessionServerJoinOpts {
553 access_token,
554 public_key: &packet.public_key,
555 private_key: &private_key,
556 uuid,
557 server_id: &packet.server_id,
558 proxy: sessionserver_proxy.map(Proxy::into),
559 })
560 .await
561 }
562}
563
564impl Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> {
565 #[must_use]
570 pub fn login(self) -> Connection<ServerboundLoginPacket, ClientboundLoginPacket> {
571 Connection::from(self)
572 }
573
574 #[must_use]
578 pub fn status(self) -> Connection<ServerboundStatusPacket, ClientboundStatusPacket> {
579 Connection::from(self)
580 }
581}
582
583impl Connection<ServerboundLoginPacket, ClientboundLoginPacket> {
584 pub fn set_compression_threshold(&mut self, threshold: i32) {
589 if threshold >= 0 {
591 self.reader.raw.compression_threshold = Some(threshold as u32);
592 self.writer.raw.compression_threshold = Some(threshold as u32);
593 } else {
594 self.reader.raw.compression_threshold = None;
595 self.writer.raw.compression_threshold = None;
596 }
597 }
598
599 pub fn set_encryption_key(&mut self, key: [u8; 16]) {
603 let (enc_cipher, dec_cipher) = azalea_crypto::create_cipher(&key);
604 self.reader.raw.dec_cipher = Some(dec_cipher);
605 self.writer.raw.enc_cipher = Some(enc_cipher);
606 }
607
608 #[must_use]
612 pub fn game(self) -> Connection<ServerboundGamePacket, ClientboundGamePacket> {
613 Connection::from(self)
614 }
615
616 #[cfg(feature = "online-mode")]
620 pub async fn authenticate(
621 &self,
622 username: &str,
623 public_key: &[u8],
624 private_key: &[u8; 16],
625 ip: Option<&str>,
626 ) -> Result<GameProfile, ServerSessionServerError> {
627 azalea_auth::sessionserver::serverside_auth(username, public_key, private_key, ip).await
628 }
629
630 #[must_use]
632 pub fn config(self) -> Connection<ServerboundConfigPacket, ClientboundConfigPacket> {
633 Connection::from(self)
634 }
635}
636
637impl Connection<ServerboundConfigPacket, ClientboundConfigPacket> {
638 #[must_use]
642 pub fn game(self) -> Connection<ServerboundGamePacket, ClientboundGamePacket> {
643 Connection::from(self)
644 }
645}
646
647impl Connection<ClientboundConfigPacket, ServerboundConfigPacket> {
648 #[must_use]
652 pub fn game(self) -> Connection<ClientboundGamePacket, ServerboundGamePacket> {
653 Connection::from(self)
654 }
655}
656
657impl Connection<ClientboundGamePacket, ServerboundGamePacket> {
658 #[must_use]
660 pub fn config(self) -> Connection<ClientboundConfigPacket, ServerboundConfigPacket> {
661 Connection::from(self)
662 }
663}
664impl Connection<ServerboundGamePacket, ClientboundGamePacket> {
665 #[must_use]
667 pub fn config(self) -> Connection<ServerboundConfigPacket, ClientboundConfigPacket> {
668 Connection::from(self)
669 }
670}
671
672impl<R1, W1> Connection<R1, W1>
675where
676 R1: ProtocolPacket + Debug,
677 W1: ProtocolPacket + Debug,
678{
679 #[must_use]
682 pub fn from<R2, W2>(connection: Connection<R1, W1>) -> Connection<R2, W2>
683 where
684 R2: ProtocolPacket + Debug,
685 W2: ProtocolPacket + Debug,
686 {
687 Connection {
688 reader: ReadConnection {
689 raw: connection.reader.raw,
690 _reading: PhantomData,
691 },
692 writer: WriteConnection {
693 raw: connection.writer.raw,
694 _writing: PhantomData,
695 },
696 }
697 }
698
699 pub fn wrap(stream: TcpStream) -> Connection<R1, W1> {
701 let (read_stream, write_stream) = stream.into_split();
702
703 Connection {
704 reader: ReadConnection {
705 raw: RawReadConnection {
706 read_stream,
707 buffer: Cursor::new(Vec::new()),
708 compression_threshold: None,
709 dec_cipher: None,
710 },
711 _reading: PhantomData,
712 },
713 writer: WriteConnection {
714 raw: RawWriteConnection {
715 write_stream,
716 compression_threshold: None,
717 enc_cipher: None,
718 },
719 _writing: PhantomData,
720 },
721 }
722 }
723
724 pub fn unwrap(self) -> Result<TcpStream, ReuniteError> {
726 self.reader
727 .raw
728 .read_stream
729 .reunite(self.writer.raw.write_stream)
730 }
731}