Skip to main content

azalea_client/plugins/
join.rs

1use std::sync::Arc;
2
3use azalea_entity::{LocalEntity, indexing::EntityUuidIndex};
4use azalea_protocol::{
5    address::ResolvedAddr,
6    common::client_information::ClientInformation,
7    connect::{Connection, ConnectionError, Proxy},
8    packets::{
9        ClientIntention, ConnectionProtocol, PROTOCOL_VERSION,
10        handshake::ServerboundIntention,
11        login::{ClientboundLoginPacket, ServerboundHello, ServerboundLoginPacket},
12    },
13};
14use azalea_world::World;
15use bevy_app::prelude::*;
16use bevy_ecs::prelude::*;
17use bevy_tasks::{IoTaskPool, Task, futures_lite::future};
18use parking_lot::RwLock;
19use tokio::sync::mpsc;
20use tracing::{debug, warn};
21
22use crate::{
23    LocalPlayerBundle,
24    account::Account,
25    connection::RawConnection,
26    local_player::WorldHolder,
27    packet::login::{InLoginState, SendLoginPacketEvent},
28};
29
30/// A plugin that allows bots to join servers.
31pub struct JoinPlugin;
32impl Plugin for JoinPlugin {
33    fn build(&self, app: &mut App) {
34        app.add_message::<StartJoinServerEvent>()
35            .add_message::<ConnectionFailedEvent>()
36            .add_systems(
37                Update,
38                (
39                    handle_start_join_server_event.before(super::login::poll_auth_task),
40                    poll_create_connection_task,
41                )
42                    .chain(),
43            );
44    }
45}
46
47/// An event to make a client join the server and be added to our swarm.
48///
49/// This won't do anything if a client with the Account UUID is already
50/// connected to the server.
51#[derive(Debug, Message)]
52pub struct StartJoinServerEvent {
53    pub account: Account,
54    pub connect_opts: ConnectOpts,
55
56    // this is mpsc instead of oneshot so it can be cloned (since it's sent in
57    // an event)
58    pub start_join_callback_tx: Option<mpsc::UnboundedSender<Entity>>,
59}
60
61/// Options for how the connection to the server will be made.
62///
63/// These are persisted on reconnects. This is inserted as a component on
64/// clients to make auto-reconnecting work.
65#[derive(Clone, Component, Debug)]
66pub struct ConnectOpts {
67    pub address: ResolvedAddr,
68    /// The SOCKS5 proxy used for connecting to the Minecraft server.
69    pub server_proxy: Option<Proxy>,
70    /// The SOCKS5 proxy that will be used when authenticating our server join
71    /// with Mojang.
72    ///
73    /// This should typically be either the same as [`Self::server_proxy`], or
74    /// `None`.
75    ///
76    /// This is useful to set if a server has `prevent-proxy-connections`
77    /// enabled.
78    pub sessionserver_proxy: Option<Proxy>,
79}
80
81/// An event that's sent when creating the TCP connection and sending the first
82/// packet fails.
83///
84/// This isn't sent if we're kicked later, see [`DisconnectEvent`].
85///
86/// [`DisconnectEvent`]: crate::disconnect::DisconnectEvent
87#[derive(Message)]
88pub struct ConnectionFailedEvent {
89    pub entity: Entity,
90    // wrap it in Arc so it can be cloned
91    pub error: Arc<ConnectionError>,
92}
93
94pub fn handle_start_join_server_event(
95    mut commands: Commands,
96    mut events: MessageReader<StartJoinServerEvent>,
97    mut entity_uuid_index: ResMut<EntityUuidIndex>,
98    connection_query: Query<&RawConnection>,
99) {
100    for event in events.read() {
101        let uuid = event.account.uuid();
102        let entity = if let Some(entity) = entity_uuid_index.get(&uuid) {
103            debug!("Reusing entity {entity:?} for client");
104
105            // check if it's already connected
106            if let Ok(conn) = connection_query.get(entity)
107                && conn.is_alive()
108            {
109                if let Some(start_join_callback_tx) = &event.start_join_callback_tx {
110                    warn!(
111                        "Received StartJoinServerEvent for {entity:?} but it's already connected. Ignoring the event but replying with Ok."
112                    );
113                    let _ = start_join_callback_tx.send(entity);
114                } else {
115                    warn!(
116                        "Received StartJoinServerEvent for {entity:?} but it's already connected. Ignoring the event."
117                    );
118                }
119                return;
120            }
121
122            entity
123        } else {
124            let entity = commands.spawn_empty().id();
125            debug!("Created new entity {entity:?} for client");
126            // add to the uuid index
127            entity_uuid_index.insert(uuid, entity);
128            entity
129        };
130
131        if let Some(start_join_callback) = &event.start_join_callback_tx {
132            let _ = start_join_callback.send(entity);
133        }
134
135        let mut entity_mut = commands.entity(entity);
136
137        entity_mut.insert((
138            // add the Account to the entity now so plugins can access it
139            // earlier
140            event.account.to_owned(),
141            // localentity is always present for our clients, even if we're not
142            // actually logged in
143            LocalEntity,
144            // this is inserted early so the user can always access and modify
145            // it
146            ClientInformation::default(),
147            // ConnectOpts is inserted as a component here
148            event.connect_opts.clone(),
149            // we don't insert InLoginState until we actually create the connection. note that
150            // there's no InHandshakeState component since we switch off of the handshake state
151            // immediately when the connection is created
152        ));
153
154        let task_pool = IoTaskPool::get();
155        let connect_opts = event.connect_opts.clone();
156        let task = task_pool.spawn(async_compat::Compat::new(
157            create_conn_and_send_intention_packet(connect_opts),
158        ));
159
160        entity_mut.insert(CreateConnectionTask(task));
161    }
162}
163
164async fn create_conn_and_send_intention_packet(
165    opts: ConnectOpts,
166) -> Result<LoginConn, ConnectionError> {
167    let mut conn = if let Some(proxy) = opts.server_proxy {
168        Connection::new_with_proxy(&opts.address.socket, proxy).await?
169    } else {
170        Connection::new(&opts.address.socket).await?
171    };
172
173    conn.write(
174        Default::default(),
175        ServerboundIntention {
176            protocol_version: PROTOCOL_VERSION,
177            hostname: opts.address.server.host.clone(),
178            port: opts.address.server.port,
179            intention: ClientIntention::Login,
180        },
181    )
182    .await?;
183
184    let conn = conn.login();
185
186    Ok(conn)
187}
188
189type LoginConn = Connection<ClientboundLoginPacket, ServerboundLoginPacket>;
190
191#[derive(Component)]
192pub struct CreateConnectionTask(pub Task<Result<LoginConn, ConnectionError>>);
193
194pub fn poll_create_connection_task(
195    mut commands: Commands,
196    mut query: Query<(Entity, &mut CreateConnectionTask, &Account)>,
197    mut connection_failed_events: MessageWriter<ConnectionFailedEvent>,
198) {
199    for (entity, mut task, account) in query.iter_mut() {
200        if let Some(poll_res) = future::block_on(future::poll_once(&mut task.0)) {
201            let mut entity_mut = commands.entity(entity);
202            entity_mut.remove::<CreateConnectionTask>();
203            let conn = match poll_res {
204                Ok(conn) => conn,
205                Err(error) => {
206                    warn!("failed to create connection: {error}");
207                    connection_failed_events.write(ConnectionFailedEvent {
208                        entity,
209                        error: Arc::new(error),
210                    });
211                    return;
212                }
213            };
214
215            let (read_conn, write_conn) = conn.into_split();
216            let (read_conn, write_conn) = (read_conn.raw, write_conn.raw);
217
218            let world = World::default();
219            let world_holder = WorldHolder::new(
220                entity,
221                // default to an empty world, it'll be set correctly later when
222                // we get the login packet
223                Arc::new(RwLock::new(world)),
224            );
225
226            entity_mut.insert((
227                // these stay when we switch to the game state
228                LocalPlayerBundle {
229                    raw_connection: RawConnection::new(
230                        read_conn,
231                        write_conn,
232                        ConnectionProtocol::Login,
233                    ),
234                    world_holder,
235                    metadata: azalea_entity::metadata::PlayerMetadataBundle::default(),
236                },
237                InLoginState,
238            ));
239
240            commands.trigger(SendLoginPacketEvent::new(
241                entity,
242                ServerboundHello {
243                    name: account.username().to_owned(),
244                    profile_id: account.uuid(),
245                },
246            ));
247        }
248    }
249}