azalea_protocol/connect.rs
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
//! Connect to remote servers/clients.
use std::fmt::Debug;
use std::io::Cursor;
use std::marker::PhantomData;
use std::net::SocketAddr;
use azalea_auth::game_profile::GameProfile;
use azalea_auth::sessionserver::{ClientSessionServerError, ServerSessionServerError};
use azalea_crypto::{Aes128CfbDec, Aes128CfbEnc};
use bytes::BytesMut;
use thiserror::Error;
use tokio::io::{AsyncWriteExt, BufStream};
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf, ReuniteError};
use tokio::net::TcpStream;
use tracing::{error, info};
use uuid::Uuid;
use crate::packets::configuration::{
ClientboundConfigurationPacket, ServerboundConfigurationPacket,
};
use crate::packets::game::{ClientboundGamePacket, ServerboundGamePacket};
use crate::packets::handshaking::{ClientboundHandshakePacket, ServerboundHandshakePacket};
use crate::packets::login::clientbound_hello_packet::ClientboundHelloPacket;
use crate::packets::login::{ClientboundLoginPacket, ServerboundLoginPacket};
use crate::packets::status::{ClientboundStatusPacket, ServerboundStatusPacket};
use crate::packets::ProtocolPacket;
use crate::read::{deserialize_packet, read_raw_packet, try_read_raw_packet, ReadPacketError};
use crate::write::{serialize_packet, write_raw_packet};
pub struct RawReadConnection {
pub read_stream: OwnedReadHalf,
pub buffer: BytesMut,
pub compression_threshold: Option<u32>,
pub dec_cipher: Option<Aes128CfbDec>,
}
pub struct RawWriteConnection {
pub write_stream: OwnedWriteHalf,
pub compression_threshold: Option<u32>,
pub enc_cipher: Option<Aes128CfbEnc>,
}
/// The read half of a connection.
pub struct ReadConnection<R: ProtocolPacket> {
pub raw: RawReadConnection,
_reading: PhantomData<R>,
}
/// The write half of a connection.
pub struct WriteConnection<W: ProtocolPacket> {
pub raw: RawWriteConnection,
_writing: PhantomData<W>,
}
/// A connection that can read and write packets.
///
/// # Examples
///
/// Join an offline-mode server and go through the handshake.
/// ```rust,no_run
/// use azalea_protocol::{
/// resolver,
/// connect::Connection,
/// packets::{
/// ClientIntention, PROTOCOL_VERSION,
/// login::{
/// ClientboundLoginPacket,
/// serverbound_hello_packet::ServerboundHelloPacket,
/// serverbound_key_packet::ServerboundKeyPacket
/// },
/// handshaking::client_intention_packet::ClientIntentionPacket
/// }
/// };
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let resolved_address = resolver::resolve_address(&"localhost".try_into().unwrap()).await?;
/// let mut conn = Connection::new(&resolved_address).await?;
///
/// // handshake
/// conn.write(
/// ClientIntentionPacket {
/// protocol_version: PROTOCOL_VERSION,
/// hostname: resolved_address.ip().to_string(),
/// port: resolved_address.port(),
/// intention: ClientIntention::Login,
/// }
/// .get(),
/// )
/// .await?;
///
/// let mut conn = conn.login();
///
/// // login
/// conn.write(
/// ServerboundHelloPacket {
/// name: "bot".to_string(),
/// profile_id: uuid::Uuid::nil(),
/// }
/// .get(),
/// )
/// .await?;
///
/// let (conn, game_profile) = loop {
/// let packet = conn.read().await?;
/// match packet {
/// ClientboundLoginPacket::Hello(p) => {
/// let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
///
/// conn.write(
/// ServerboundKeyPacket {
/// key_bytes: e.encrypted_public_key,
/// encrypted_challenge: e.encrypted_challenge,
/// }
/// .get(),
/// )
/// .await?;
/// conn.set_encryption_key(e.secret_key);
/// }
/// ClientboundLoginPacket::LoginCompression(p) => {
/// conn.set_compression_threshold(p.compression_threshold);
/// }
/// ClientboundLoginPacket::LoginFinished(p) => {
/// break (conn.configuration(), p.game_profile);
/// }
/// ClientboundLoginPacket::LoginDisconnect(p) => {
/// eprintln!("login disconnect: {}", p.reason);
/// return Err("login disconnect".into());
/// }
/// ClientboundLoginPacket::CustomQuery(p) => {}
/// ClientboundLoginPacket::CookieRequest(_) => {}
/// }
/// };
///
/// Ok(())
/// }
/// ```
pub struct Connection<R: ProtocolPacket, W: ProtocolPacket> {
pub reader: ReadConnection<R>,
pub writer: WriteConnection<W>,
}
impl RawReadConnection {
pub async fn read(&mut self) -> Result<Vec<u8>, Box<ReadPacketError>> {
read_raw_packet::<_>(
&mut self.read_stream,
&mut self.buffer,
self.compression_threshold,
&mut self.dec_cipher,
)
.await
}
pub fn try_read(&mut self) -> Result<Option<Vec<u8>>, Box<ReadPacketError>> {
try_read_raw_packet::<_>(
&mut self.read_stream,
&mut self.buffer,
self.compression_threshold,
&mut self.dec_cipher,
)
}
}
impl RawWriteConnection {
pub async fn write(&mut self, packet: &[u8]) -> std::io::Result<()> {
if let Err(e) = write_raw_packet(
packet,
&mut self.write_stream,
self.compression_threshold,
&mut self.enc_cipher,
)
.await
{
// detect broken pipe
if e.kind() == std::io::ErrorKind::BrokenPipe {
info!("Broken pipe, shutting down connection.");
if let Err(e) = self.shutdown().await {
error!("Couldn't shut down: {}", e);
}
}
return Err(e);
}
Ok(())
}
/// End the connection.
pub async fn shutdown(&mut self) -> std::io::Result<()> {
self.write_stream.shutdown().await
}
}
impl<R> ReadConnection<R>
where
R: ProtocolPacket + Debug,
{
/// Read a packet from the stream.
pub async fn read(&mut self) -> Result<R, Box<ReadPacketError>> {
let raw_packet = self.raw.read().await?;
deserialize_packet(&mut Cursor::new(raw_packet.as_slice()))
}
/// Try to read a packet from the stream, or return Ok(None) if there's no
/// packet.
pub fn try_read(&mut self) -> Result<Option<R>, Box<ReadPacketError>> {
let Some(raw_packet) = self.raw.try_read()? else {
return Ok(None);
};
Ok(Some(deserialize_packet(&mut Cursor::new(
raw_packet.as_slice(),
))?))
}
}
impl<W> WriteConnection<W>
where
W: ProtocolPacket + Debug,
{
/// Write a packet to the server.
pub async fn write(&mut self, packet: W) -> std::io::Result<()> {
self.raw.write(&serialize_packet(&packet).unwrap()).await
}
/// End the connection.
pub async fn shutdown(&mut self) -> std::io::Result<()> {
self.raw.shutdown().await
}
}
impl<R, W> Connection<R, W>
where
R: ProtocolPacket + Debug,
W: ProtocolPacket + Debug,
{
/// Read a packet from the other side of the connection.
pub async fn read(&mut self) -> Result<R, Box<ReadPacketError>> {
self.reader.read().await
}
/// Try to read a packet from the other side of the connection, or return
/// Ok(None) if there's no packet to read.
pub fn try_read(&mut self) -> Result<Option<R>, Box<ReadPacketError>> {
self.reader.try_read()
}
/// Write a packet to the other side of the connection.
pub async fn write(&mut self, packet: W) -> std::io::Result<()> {
self.writer.write(packet).await
}
/// Split the reader and writer into two objects. This doesn't allocate.
#[must_use]
pub fn into_split(self) -> (ReadConnection<R>, WriteConnection<W>) {
(self.reader, self.writer)
}
}
#[derive(Error, Debug)]
pub enum ConnectionError {
#[error("{0}")]
Io(#[from] std::io::Error),
}
use socks5_impl::protocol::UserKey;
#[derive(Debug, Clone)]
pub struct Proxy {
pub addr: SocketAddr,
pub auth: Option<UserKey>,
}
impl Proxy {
pub fn new(addr: SocketAddr, auth: Option<UserKey>) -> Self {
Self { addr, auth }
}
}
impl Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> {
/// Create a new connection to the given address.
pub async fn new(address: &SocketAddr) -> Result<Self, ConnectionError> {
let stream = TcpStream::connect(address).await?;
// enable tcp_nodelay
stream.set_nodelay(true)?;
Self::new_from_stream(stream).await
}
/// Create a new connection to the given address and Socks5 proxy. If you're
/// not using a proxy, use [`Self::new`] instead.
pub async fn new_with_proxy(
address: &SocketAddr,
proxy: Proxy,
) -> Result<Self, ConnectionError> {
let proxy_stream = TcpStream::connect(proxy.addr).await?;
let mut stream = BufStream::new(proxy_stream);
let _ = socks5_impl::client::connect(&mut stream, address, proxy.auth)
.await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
Self::new_from_stream(stream.into_inner()).await
}
/// Create a new connection from an existing stream. Useful if you want to
/// set custom options on the stream. Otherwise, just use [`Self::new`].
pub async fn new_from_stream(stream: TcpStream) -> Result<Self, ConnectionError> {
let (read_stream, write_stream) = stream.into_split();
Ok(Connection {
reader: ReadConnection {
raw: RawReadConnection {
read_stream,
buffer: BytesMut::new(),
compression_threshold: None,
dec_cipher: None,
},
_reading: PhantomData,
},
writer: WriteConnection {
raw: RawWriteConnection {
write_stream,
compression_threshold: None,
enc_cipher: None,
},
_writing: PhantomData,
},
})
}
/// Change our state from handshake to login. This is the state that is used
/// for logging in.
#[must_use]
pub fn login(self) -> Connection<ClientboundLoginPacket, ServerboundLoginPacket> {
Connection::from(self)
}
/// Change our state from handshake to status. This is the state that is
/// used for pinging the server.
#[must_use]
pub fn status(self) -> Connection<ClientboundStatusPacket, ServerboundStatusPacket> {
Connection::from(self)
}
}
impl Connection<ClientboundLoginPacket, ServerboundLoginPacket> {
/// Set our compression threshold, i.e. the maximum size that a packet is
/// allowed to be without getting compressed. If you set it to less than 0
/// then compression gets disabled.
pub fn set_compression_threshold(&mut self, threshold: i32) {
// if you pass a threshold of less than 0, compression is disabled
if threshold >= 0 {
self.reader.raw.compression_threshold = Some(threshold as u32);
self.writer.raw.compression_threshold = Some(threshold as u32);
} else {
self.reader.raw.compression_threshold = None;
self.writer.raw.compression_threshold = None;
}
}
/// Set the encryption key that is used to encrypt and decrypt packets. It's
/// the same for both reading and writing.
pub fn set_encryption_key(&mut self, key: [u8; 16]) {
let (enc_cipher, dec_cipher) = azalea_crypto::create_cipher(&key);
self.reader.raw.dec_cipher = Some(dec_cipher);
self.writer.raw.enc_cipher = Some(enc_cipher);
}
/// Change our state from login to configuration. This is the state where
/// the server sends us the registries and resource pack and stuff.
#[must_use]
pub fn configuration(
self,
) -> Connection<ClientboundConfigurationPacket, ServerboundConfigurationPacket> {
Connection::from(self)
}
/// Authenticate with Minecraft's servers, which is required to join
/// online-mode servers. This must happen when you get a
/// `ClientboundLoginPacket::Hello` packet.
///
/// # Examples
///
/// ```rust,no_run
/// use azalea_auth::AuthResult;
/// use azalea_protocol::connect::Connection;
/// use azalea_protocol::packets::login::{
/// ClientboundLoginPacket,
/// serverbound_key_packet::ServerboundKeyPacket
/// };
/// use uuid::Uuid;
/// # use azalea_protocol::ServerAddress;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let AuthResult { access_token, profile } = azalea_auth::auth(
/// "[email protected]",
/// azalea_auth::AuthOpts::default()
/// ).await.expect("Couldn't authenticate");
/// #
/// # let address = ServerAddress::try_from("[email protected]").unwrap();
/// # let resolved_address = azalea_protocol::resolver::resolve_address(&address).await?;
///
/// let mut conn = Connection::new(&resolved_address).await?;
///
/// // transition to the login state, in a real program we would have done a handshake first
/// let mut conn = conn.login();
///
/// match conn.read().await? {
/// ClientboundLoginPacket::Hello(p) => {
/// // tell Mojang we're joining the server & enable encryption
/// let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
/// conn.authenticate(
/// &access_token,
/// &profile.id,
/// e.secret_key,
/// &p
/// ).await?;
/// conn.write(
/// ServerboundKeyPacket {
/// key_bytes: e.encrypted_public_key,
/// encrypted_challenge: e.encrypted_challenge,
/// }.get()
/// ).await?;
/// conn.set_encryption_key(e.secret_key);
/// }
/// _ => {}
/// }
/// # Ok(())
/// # }
/// ```
pub async fn authenticate(
&self,
access_token: &str,
uuid: &Uuid,
private_key: [u8; 16],
packet: &ClientboundHelloPacket,
) -> Result<(), ClientSessionServerError> {
azalea_auth::sessionserver::join(
access_token,
&packet.public_key,
&private_key,
uuid,
&packet.server_id,
)
.await
}
}
impl Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> {
/// Change our state from handshake to login. This is the state that is used
/// for logging in.
#[must_use]
pub fn login(self) -> Connection<ServerboundLoginPacket, ClientboundLoginPacket> {
Connection::from(self)
}
/// Change our state from handshake to status. This is the state that is
/// used for pinging the server.
#[must_use]
pub fn status(self) -> Connection<ServerboundStatusPacket, ClientboundStatusPacket> {
Connection::from(self)
}
}
impl Connection<ServerboundLoginPacket, ClientboundLoginPacket> {
/// Set our compression threshold, i.e. the maximum size that a packet is
/// allowed to be without getting compressed. If you set it to less than 0
/// then compression gets disabled.
pub fn set_compression_threshold(&mut self, threshold: i32) {
// if you pass a threshold of less than 0, compression is disabled
if threshold >= 0 {
self.reader.raw.compression_threshold = Some(threshold as u32);
self.writer.raw.compression_threshold = Some(threshold as u32);
} else {
self.reader.raw.compression_threshold = None;
self.writer.raw.compression_threshold = None;
}
}
/// Set the encryption key that is used to encrypt and decrypt packets. It's
/// the same for both reading and writing.
pub fn set_encryption_key(&mut self, key: [u8; 16]) {
let (enc_cipher, dec_cipher) = azalea_crypto::create_cipher(&key);
self.reader.raw.dec_cipher = Some(dec_cipher);
self.writer.raw.enc_cipher = Some(enc_cipher);
}
/// Change our state from login to game. This is the state that's used when
/// the client is actually in the game.
#[must_use]
pub fn game(self) -> Connection<ServerboundGamePacket, ClientboundGamePacket> {
Connection::from(self)
}
/// Verify connecting clients have authenticated with Minecraft's servers.
/// This must happen after the client sends a `ServerboundLoginPacket::Key`
/// packet.
pub async fn authenticate(
&self,
username: &str,
public_key: &[u8],
private_key: &[u8; 16],
ip: Option<&str>,
) -> Result<GameProfile, ServerSessionServerError> {
azalea_auth::sessionserver::serverside_auth(username, public_key, private_key, ip).await
}
/// Change our state back to configuration.
#[must_use]
pub fn configuration(
self,
) -> Connection<ServerboundConfigurationPacket, ClientboundConfigurationPacket> {
Connection::from(self)
}
}
impl Connection<ServerboundConfigurationPacket, ClientboundConfigurationPacket> {
/// Change our state from configuration to game. This is the state that's
/// used when the client is actually in the world.
#[must_use]
pub fn game(self) -> Connection<ServerboundGamePacket, ClientboundGamePacket> {
Connection::from(self)
}
}
impl Connection<ClientboundConfigurationPacket, ServerboundConfigurationPacket> {
/// Change our state from configuration to game. This is the state that's
/// used when the client is actually in the world.
#[must_use]
pub fn game(self) -> Connection<ClientboundGamePacket, ServerboundGamePacket> {
Connection::from(self)
}
}
impl Connection<ClientboundGamePacket, ServerboundGamePacket> {
/// Change our state back to configuration.
#[must_use]
pub fn configuration(
self,
) -> Connection<ClientboundConfigurationPacket, ServerboundConfigurationPacket> {
Connection::from(self)
}
}
// rust doesn't let us implement From because allegedly it conflicts with
// `core`'s "impl<T> From<T> for T" so we do this instead
impl<R1, W1> Connection<R1, W1>
where
R1: ProtocolPacket + Debug,
W1: ProtocolPacket + Debug,
{
/// Creates a `Connection` of a type from a `Connection` of another type.
/// Useful for servers or custom packets.
#[must_use]
pub fn from<R2, W2>(connection: Connection<R1, W1>) -> Connection<R2, W2>
where
R2: ProtocolPacket + Debug,
W2: ProtocolPacket + Debug,
{
Connection {
reader: ReadConnection {
raw: connection.reader.raw,
_reading: PhantomData,
},
writer: WriteConnection {
raw: connection.writer.raw,
_writing: PhantomData,
},
}
}
/// Convert an existing `TcpStream` into a `Connection`. Useful for servers.
pub fn wrap(stream: TcpStream) -> Connection<R1, W1> {
let (read_stream, write_stream) = stream.into_split();
Connection {
reader: ReadConnection {
raw: RawReadConnection {
read_stream,
buffer: BytesMut::new(),
compression_threshold: None,
dec_cipher: None,
},
_reading: PhantomData,
},
writer: WriteConnection {
raw: RawWriteConnection {
write_stream,
compression_threshold: None,
enc_cipher: None,
},
_writing: PhantomData,
},
}
}
/// Convert from a `Connection` into a `TcpStream`. Useful for servers.
pub fn unwrap(self) -> Result<TcpStream, ReuniteError> {
self.reader
.raw
.read_stream
.reunite(self.writer.raw.write_stream)
}
}