Skip to main content

ghast_client/
client.rs

1//! Connection setup and the session driver: connect → handshake → login → play loop.
2
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::Arc;
6use std::time::Duration;
7
8use ghast_auth::connect::{Connector, TargetAddr};
9use ghast_auth::offline::OfflineProfile;
10use ghast_protocol::{FrameDecoder, FrameEncoder, PacketFilter, RawPacket, State};
11use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
12use tokio::time::{Instant, MissedTickBehavior};
13
14use crate::common::{
15    ClientSettings, ConfigInbound, ConfigOutbound, Inbound, KnownPack, LoginInbound, chat_to_plain,
16};
17use crate::engine::{Behavior, CoreOptions, Engine};
18use crate::error::{ClientError, SessionEnd};
19use crate::interest::Interests;
20use crate::sim::{Sim, SimError};
21#[cfg(feature = "v1_8")]
22use crate::version::V1_8;
23#[cfg(feature = "v1_12_2")]
24use crate::version::V1_12_2;
25#[cfg(feature = "v1_16_5")]
26use crate::version::V1_16_5;
27#[cfg(feature = "v26_1")]
28use crate::version::V26_1;
29#[cfg(feature = "v26_2")]
30use crate::version::V26_2;
31#[cfg(feature = "v26_3")]
32use crate::version::V26_3;
33use crate::version::{ClientVersion, GameVersion, HasSim};
34
35/// Length of one client tick.
36pub const TICK: Duration = Duration::from_millis(50);
37
38/// The account a client logs in with.
39#[derive(Clone)]
40#[non_exhaustive]
41pub enum Account {
42    /// Offline mode (the server does not authenticate; the UUID derives from the name).
43    Offline(OfflineProfile),
44    /// A Microsoft account session (needed for online-mode servers).
45    #[cfg(feature = "microsoft")]
46    Microsoft {
47        /// The logged-in session (access token and profile).
48        session: ghast_auth::microsoft::MinecraftSession,
49        /// The client that makes the session-server `join` call.
50        auth: Arc<ghast_auth::microsoft::MicrosoftAuth>,
51    },
52}
53
54impl Account {
55    /// An offline account (the name is checked like vanilla: 1–16 of `[A-Za-z0-9_]`).
56    pub fn offline(name: &str) -> Result<Self, ClientError> {
57        Ok(Account::Offline(OfflineProfile::new(name)?))
58    }
59
60    /// The player name.
61    #[must_use]
62    pub fn name(&self) -> &str {
63        match self {
64            Account::Offline(p) => p.name(),
65            #[cfg(feature = "microsoft")]
66            Account::Microsoft { session, .. } => &session.profile.name,
67        }
68    }
69
70    /// The profile id (offline: derived from the name like vanilla's offline mode).
71    #[must_use]
72    pub fn uuid(&self) -> uuid::Uuid {
73        match self {
74            Account::Offline(p) => p.uuid(),
75            #[cfg(feature = "microsoft")]
76            Account::Microsoft { session, .. } => session.profile.id,
77        }
78    }
79}
80
81impl std::fmt::Debug for Account {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        match self {
84            Account::Offline(p) => f.debug_tuple("Offline").field(&p.name()).finish(),
85            #[cfg(feature = "microsoft")]
86            Account::Microsoft { session, .. } => f
87                .debug_struct("Microsoft")
88                .field("name", &session.profile.name)
89                .finish_non_exhaustive(),
90        }
91    }
92}
93
94/// A configured client: where to connect, which version, which account, and how.
95///
96/// One `Client` can run any number of sessions one after another (reconnects); run several
97/// clients concurrently for several bots (one per process, or many tasks in one process —
98/// a failing session never affects another).
99#[derive(Debug, Clone)]
100pub struct Client {
101    address: TargetAddr,
102    version: GameVersion,
103    account: Account,
104    connector: Connector,
105    settings: ClientSettings,
106    brand: Option<String>,
107    sensitivity: f32,
108    silent_hold: Duration,
109    read_timeout: Duration,
110    login_timeout: Duration,
111    record: Option<std::path::PathBuf>,
112    force_step_position: crate::sim::ForceStepPosition,
113    hold_turn_on_action: bool,
114    entity_push: bool,
115    turn_rate: (f64, f64),
116    gui_releases_keys: bool,
117    world_config: Option<ghast_world::WorldConfig>,
118    shared_chunks: Option<ghast_world::SharedChunks>,
119    accept_required_packs: bool,
120    signed_chat: bool,
121    follow_transfers: bool,
122    /// Profile keys for signed chat, shared by this client's sessions (fetched once, then
123    /// reused until they are due for a refresh).
124    profile_keys: Arc<std::sync::Mutex<Option<Arc<ProfileKeys>>>>,
125}
126
127use ghast_auth::chat::ProfileKeys;
128
129impl Client {
130    /// A client with vanilla defaults: direct connection (see [`Client::connector`]),
131    /// brand `vanilla`, sensitivity 0.5, 30 s read timeout.
132    #[must_use]
133    pub fn new(address: TargetAddr, version: GameVersion, account: Account) -> Self {
134        Client {
135            address,
136            version,
137            account,
138            connector: Connector::new(),
139            settings: ClientSettings::default(),
140            brand: Some("vanilla".to_owned()),
141            sensitivity: 0.5,
142            silent_hold: Duration::from_millis(1500),
143            read_timeout: Duration::from_secs(30),
144            login_timeout: Duration::from_secs(30),
145            record: None,
146            force_step_position: crate::sim::ForceStepPosition::Off,
147            hold_turn_on_action: true,
148            entity_push: true,
149            turn_rate: (
150                crate::rotation::Rotation::MAX_YAW_PER_TICK,
151                crate::rotation::Rotation::MAX_PITCH_PER_TICK,
152            ),
153            gui_releases_keys: true,
154            world_config: None,
155            shared_chunks: None,
156            accept_required_packs: true,
157            signed_chat: true,
158            follow_transfers: false,
159            profile_keys: Arc::default(),
160        }
161    }
162
163    /// Signed chat on encrypted (online-mode) connections, 1.19.3+ (default on, like vanilla):
164    /// the client gets the account's profile key pair (with the `microsoft` feature from the
165    /// Minecraft services, or the one given to [`Client::profile_keys`]), announces a chat
166    /// session after each join and signs chat messages and signable command arguments. Off:
167    /// everything is sent unsigned (servers with `enforce-secure-profile` then refuse chat).
168    /// Offline-mode connections never sign (vanilla has no key pair there).
169    #[must_use]
170    pub fn signed_chat(mut self, on: bool) -> Self {
171        self.signed_chat = on;
172        self
173    }
174
175    /// Follow server transfers (1.20.5+ `transfer`, default off): the client closes the
176    /// connection and logs in to the target with the transfer intent, carrying the cookies the
177    /// server stored, within the same [`Client::run`] (the behaviour stops and starts again, as
178    /// on a reconnect; at most 8 transfers in a row). Off, the session ends with
179    /// [`SessionEnd::Transferred`] and the application decides (vanilla always follows; a
180    /// library should not let a server move a bot to any host, through its proxy, unasked).
181    #[must_use]
182    pub fn follow_transfers(mut self, on: bool) -> Self {
183        self.follow_transfers = on;
184        self
185    }
186
187    /// Uses this profile key pair for signed chat instead of fetching one (for example a pair
188    /// kept from an earlier run; it must belong to the account's profile id).
189    #[must_use]
190    pub fn profile_keys(self, keys: ProfileKeys) -> Self {
191        if let Ok(mut k) = self.profile_keys.lock() {
192            *k = Some(Arc::new(keys));
193        }
194        self
195    }
196
197    /// How to open the TCP connection (SOCKS5 proxy, proxy policy, timeouts).
198    #[must_use]
199    pub fn connector(mut self, connector: Connector) -> Self {
200        self.connector = connector;
201        self
202    }
203
204    /// Client settings sent after joining.
205    #[must_use]
206    pub fn settings(mut self, settings: ClientSettings) -> Self {
207        self.settings = settings;
208        self
209    }
210
211    /// The client brand sent after joining (`None`: send none).
212    #[must_use]
213    pub fn brand(mut self, brand: Option<String>) -> Self {
214        self.brand = brand;
215        self
216    }
217
218    /// Mouse sensitivity (options.txt value, 0 … 1) for rotation steps.
219    #[must_use]
220    pub fn sensitivity(mut self, sensitivity: f32) -> Self {
221        self.sensitivity = sensitivity;
222        self
223    }
224
225    /// The aim's turn rate cap: at most `yaw` / `pitch` degrees per tick (defaults
226    /// [`Rotation::MAX_YAW_PER_TICK`](crate::rotation::Rotation::MAX_YAW_PER_TICK) 14° /
227    /// [`Rotation::MAX_PITCH_PER_TICK`](crate::rotation::Rotation::MAX_PITCH_PER_TICK) 10.5°).
228    /// Every turn stays a whole number of mouse counts of the [`Client::sensitivity`]. The cap
229    /// is a behaviour choice, not vanilla (a mouse has none; players turn 30–60° in a tick in
230    /// fights); values that are not finite and positive keep the default.
231    #[must_use]
232    pub fn turn_rate(mut self, yaw: f64, pitch: f64) -> Self {
233        self.turn_rate = (yaw, pitch);
234        self
235    }
236
237    /// A screen (an open window, the player inventory) releases the movement keys, like
238    /// vanilla (default on): every version's `setScreen` calls `KeyBinding.unpressAll`, and
239    /// the screen takes the keyboard, so while it is open the player walks, jumps, sneaks and
240    /// sprints as if no key were held (a sprint ends on the next movement step, a sneak too).
241    /// The held [`Controls`](crate::Controls) apply again once it closes (1.12+ re-read the
242    /// held keys then; on 1.8 it is the same as pressing them again). Off: the controls apply
243    /// through screens (not vanilla; Grim checks clicking and closing while moving).
244    ///
245    /// 1.16.5's own inventory screen passes key presses through (`passEvents`): a movement key
246    /// pressed while it is open applies (let go of a key held through the opening and press
247    /// it again to walk). The OS key repeat of a key held through the opening is not modelled:
248    /// it stays released, a vanilla-possible input. 1.8.9 and 1.12.2 screens take every key.
249    /// Grim's MultiActionsC / MultiActionsD flag a click or a close while the server sees a
250    /// sprint (also where vanilla allows it): let go of the sprint before clicking.
251    #[must_use]
252    pub fn gui_releases_keys(mut self, on: bool) -> Self {
253        self.gui_releases_keys = on;
254        self
255    }
256
257    /// The behaviour is frozen after this long without data from the server (default 1.5 s).
258    #[must_use]
259    pub fn silent_hold(mut self, d: Duration) -> Self {
260        self.silent_hold = d;
261        self
262    }
263
264    /// The session fails after this long without data from the server (default 30 s, like
265    /// vanilla's read timeout).
266    #[must_use]
267    pub fn read_timeout(mut self, d: Duration) -> Self {
268        self.read_timeout = d;
269        self
270    }
271
272    /// Connecting plus login must finish within this time (default 30 s).
273    #[must_use]
274    pub fn login_timeout(mut self, d: Duration) -> Self {
275        self.login_timeout = d;
276        self
277    }
278
279    /// Records every session's movement in the oracle's replay format (every version; the file
280    /// is overwritten by each session; `MC=<row> oracle/run.sh replay --in <file>` runs it in
281    /// vanilla). For debugging anticheat flags against vanilla. What the format cannot carry is
282    /// written as `ghast_note` lines (explosion pushes, block changes after a column was first
283    /// seen, gliding on 1.12.2, entity pushes and collisions, riding on 26.x).
284    #[must_use]
285    pub fn record(mut self, path: impl Into<std::path::PathBuf>) -> Self {
286        self.record = Some(path.into());
287        self
288    }
289
290    /// What the world keeps besides block states. Default: nothing (no light, no biomes:
291    /// the bot does not need them, and they cost memory and decoding time). A viewer that
292    /// draws the world can turn them on; [`crate::WorldView::column`] gives the data.
293    #[must_use]
294    pub fn world_config(mut self, config: ghast_world::WorldConfig) -> Self {
295        self.world_config = Some(config);
296        self
297    }
298
299    /// Share the block storage of chunk sections with every other client given the same
300    /// store (see [`ghast_world::SharedChunks`]): bots in the same area then hold one copy of
301    /// each identical section instead of one each. Reads stay as fast as without it; a block
302    /// change copies only the section it touches, for this bot only. Opt-in (default: every
303    /// bot owns its sections). Used by the modern versions (26.1 – 26.3); the older versions
304    /// ignore it.
305    ///
306    /// ```no_run
307    /// use ghast_client::{Account, Client, GameVersion, world::SharedChunks};
308    ///
309    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
310    /// let cache = SharedChunks::new(); // one store for all bots of the process
311    /// let mut clients = Vec::new();
312    /// for i in 0..10 {
313    ///     let client = Client::new(
314    ///         "localhost:25565".parse()?,
315    ///         GameVersion::V26_2,
316    ///         Account::offline(&format!("Bot{i}"))?,
317    ///     )
318    ///     .shared_chunks(&cache);
319    ///     clients.push(client);
320    /// }
321    /// # Ok(())
322    /// # }
323    /// ```
324    #[must_use]
325    pub fn shared_chunks(mut self, cache: &ghast_world::SharedChunks) -> Self {
326        self.shared_chunks = Some(cache.clone());
327        self
328    }
329
330    /// Keep the look still on a tick that dug or placed when this tick's turn would take the
331    /// crosshair off the clicked block, or that used an item without a block when the new look
332    /// would pick one (on by default). Grim's RotationPlace re-checks a dig / place / item use
333    /// with the look of the movement packet that follows it; holding the mouse for one tick is
334    /// what a player does anyway. The held turn continues on the next tick the behaviour aims.
335    #[must_use]
336    pub fn hold_turn_on_action(mut self, on: bool) -> Self {
337        self.hold_turn_on_action = on;
338        self
339    }
340
341    /// Whether other entities push the player (default on, like vanilla). **Pushes happen only
342    /// with entity tracking** ([`Interests::ENTITIES`] or [`Interests::ENTITY_TRACKING`]):
343    /// without it the client knows no entities, so nothing pushes the bot and the crosshair
344    /// sees blocks only. With it, on 1.12.2, 1.16.5 and 26.1+ mobs, players and boats around
345    /// the player push it in the client's entity tick; the 1.8.9 client is never pushed by the
346    /// client (the switch is a no-op there). **Off is not vanilla**: a vanilla client always applies
347    /// these pushes itself; off keeps entity tracking (crosshair, attack, interact) without
348    /// them. A behaviour can switch it at run time with [`TickContext::set_entity_push`](crate::TickContext::set_entity_push).
349    #[must_use]
350    pub fn entity_push(mut self, on: bool) -> Self {
351        self.entity_push = on;
352        self
353    }
354
355    /// **Not vanilla** (Grim 2.3 compatibility, off by default): on a tick whose feet height
356    /// changed (a step-up or landing) but whose move stayed under the 0.03-block resend
357    /// threshold, send the position anyway. Vanilla sends only the look / on-ground there,
358    /// which Grim 2.3.73 sets back (soul sand → grass hops).
359    #[must_use]
360    pub fn force_step_position(mut self, on: bool) -> Self {
361        self.force_step_position = if on {
362            crate::sim::ForceStepPosition::Always
363        } else {
364            crate::sim::ForceStepPosition::Off
365        };
366        self
367    }
368
369    /// **Not vanilla**: [`Client::force_step_position`] with a choice of rule, e.g.
370    /// [`ForceStepPosition::StepUpOnly`](crate::ForceStepPosition::StepUpOnly), which forces the
371    /// position only on step-ups (on ground after the move, feet higher) and leaves sub-0.03
372    /// falls and landings vanilla.
373    #[must_use]
374    pub fn force_step_position_mode(mut self, mode: crate::sim::ForceStepPosition) -> Self {
375        self.force_step_position = mode;
376        self
377    }
378
379    /// Server resource packs (1.20.3+): optional packs are always declined (the client never
380    /// shows the prompt); a pack the server requires is reported accepted and loaded when this
381    /// is on (default), declined otherwise (the server then usually disconnects). Nothing is
382    /// downloaded.
383    ///
384    /// 1.8 – 1.16 packs carry no "required" flag, so this decides for every pack: on, it is
385    /// reported accepted then loaded (the vanilla client with the server's packs enabled),
386    /// off, declined. A pack the vanilla client could not load (a `level://` world pack, or on
387    /// 1.12+ a URL its check rejects) is reported "failed download" either way.
388    #[must_use]
389    pub fn accept_required_resource_packs(mut self, on: bool) -> Self {
390        self.accept_required_packs = on;
391        self
392    }
393
394    /// The server address.
395    #[must_use]
396    pub fn address(&self) -> &TargetAddr {
397        &self.address
398    }
399
400    /// The protocol version.
401    #[must_use]
402    pub fn version(&self) -> GameVersion {
403        self.version
404    }
405
406    /// The account.
407    #[must_use]
408    pub fn account(&self) -> &Account {
409        &self.account
410    }
411
412    /// Runs one session with `behavior` until the server ends it, the behaviour quits or an
413    /// error occurs.
414    pub async fn run<B: Behavior>(&self, behavior: &mut B) -> Result<SessionEnd, ClientError> {
415        self.run_until(behavior, std::future::pending()).await
416    }
417
418    /// Like [`Client::run`], but also ends cleanly (the behaviour is stopped, the socket shut
419    /// down) when `shutdown` completes.
420    pub async fn run_until<B, S>(
421        &self,
422        behavior: &mut B,
423        shutdown: S,
424    ) -> Result<SessionEnd, ClientError>
425    where
426        B: Behavior,
427        S: Future<Output = ()>,
428    {
429        let shutdown = std::pin::pin!(shutdown);
430        // The version is chosen once: everything below is monomorphised per version (a
431        // sub-version runs the instance of the version that serves it, with its own row).
432        match self.version.instance() {
433            #[cfg(feature = "v1_8")]
434            GameVersion::V1_8_9 => sessions::<V1_8, B, S>(self, behavior, shutdown).await,
435            #[cfg(feature = "v1_12_2")]
436            GameVersion::V1_12_2 => sessions::<V1_12_2, B, S>(self, behavior, shutdown).await,
437            #[cfg(feature = "v1_16_5")]
438            GameVersion::V1_16_5 => sessions::<V1_16_5, B, S>(self, behavior, shutdown).await,
439            #[cfg(feature = "v26_1")]
440            GameVersion::V26_1 => sessions::<V26_1, B, S>(self, behavior, shutdown).await,
441            #[cfg(feature = "v26_2")]
442            GameVersion::V26_2 => sessions::<V26_2, B, S>(self, behavior, shutdown).await,
443            #[cfg(feature = "v26_3")]
444            GameVersion::V26_3 => sessions::<V26_3, B, S>(self, behavior, shutdown).await,
445            #[allow(unreachable_patterns)]
446            _ => {
447                let _ = (behavior, shutdown);
448                Err(ClientError::VersionNotEnabled(self.version))
449            }
450        }
451    }
452}
453
454/// Reads more bytes into the decoder. Cancel safe.
455async fn read_more<R: AsyncRead + Unpin>(
456    rd: &mut R,
457    dec: &mut FrameDecoder,
458) -> std::io::Result<usize> {
459    let buf = dec.reserve_read();
460    let old = buf.len();
461    let n = rd.read_buf(buf).await?;
462    dec.commit(old);
463    Ok(n)
464}
465
466/// Writes everything the encoder has queued.
467async fn flush<W: AsyncWrite + Unpin>(wr: &mut W, enc: &mut FrameEncoder) -> std::io::Result<()> {
468    let out = enc.out_mut();
469    if !out.is_empty() {
470        wr.write_all_buf(out).await?;
471    }
472    Ok(())
473}
474
475/// A connection that follows a server transfer: the target and the carried cookies.
476struct Hop {
477    address: TargetAddr,
478    cookies: Vec<(ghast_protocol::types::ByteString, bytes::Bytes)>,
479}
480
481/// Most transfers followed in a row.
482const MAX_TRANSFERS: usize = 8;
483
484/// One session, then the sessions of the transfers it follows.
485async fn sessions<V, B, S>(
486    client: &Client,
487    behavior: &mut B,
488    mut shutdown: Pin<&mut S>,
489) -> Result<SessionEnd, ClientError>
490where
491    V: ClientVersion + HasSim,
492    B: Behavior,
493    S: Future<Output = ()>,
494{
495    let mut hop = None;
496    for n in 0.. {
497        let (end, cookies) =
498            session::<V, B, S>(client, behavior, shutdown.as_mut(), hop.take()).await?;
499        match end {
500            SessionEnd::Transferred { host, port }
501                if client.follow_transfers && n < MAX_TRANSFERS =>
502            {
503                match TargetAddr::new(&host, port) {
504                    Ok(address) => {
505                        log::info!(
506                            "[{}] following the transfer to {host}:{port}",
507                            client.account.name()
508                        );
509                        hop = Some(Hop { address, cookies });
510                    }
511                    Err(e) => {
512                        log::warn!(
513                            "[{}] cannot follow the transfer to {host}:{port}: {e}",
514                            client.account.name()
515                        );
516                        return Ok(SessionEnd::Transferred { host, port });
517                    }
518                }
519            }
520            end => return Ok(end),
521        }
522    }
523    unreachable!()
524}
525
526async fn session<V, B, S>(
527    client: &Client,
528    behavior: &mut B,
529    mut shutdown: Pin<&mut S>,
530    hop: Option<Hop>,
531) -> Result<
532    (
533        SessionEnd,
534        Vec<(ghast_protocol::types::ByteString, bytes::Bytes)>,
535    ),
536    ClientError,
537>
538where
539    V: ClientVersion + HasSim,
540    B: Behavior,
541    S: Future<Output = ()>,
542{
543    let name: Arc<str> = client.account.name().into();
544    let mut dec = FrameDecoder::new();
545    // Login and configuration packets (registries, profile) are partly kept for the session:
546    // copied, they do not keep the receive buffers of those states alive.
547    dec.set_detach_frames(true);
548    let mut enc = FrameEncoder::new();
549    let mut wire = V::wire_for(client.version);
550    let transfer = hop.is_some();
551    let address = match hop {
552        Some(h) => {
553            V::put_cookies(&mut wire, h.cookies);
554            h.address
555        }
556        None => client.address.clone(),
557    };
558    // Configuration-state registries, applied to the world once it exists.
559    let mut registries = Vec::new();
560    // The connection is encrypted (vanilla starts a chat session only then).
561    let mut encrypted = false;
562
563    // Boxed while it runs: its state would otherwise keep a slot in the session future for
564    // the whole session.
565    let login = Box::pin(async {
566        let stream = client.connector.connect(&address).await?;
567        let (mut rd, mut wr) = stream.into_split();
568        login::<V, _, _, B>(
569            client,
570            &mut *behavior,
571            &mut rd,
572            &mut wr,
573            &mut dec,
574            &mut enc,
575            &mut wire,
576            &mut registries,
577            &mut encrypted,
578            (&address, transfer),
579        )
580        .await
581        .map(|end| (rd, wr, end))
582    });
583    let (rd, wr, end) = tokio::select! {
584        r = tokio::time::timeout(client.login_timeout, login) => match r {
585            Ok(r) => r?,
586            Err(_) => return Err(ClientError::Timeout("connect and login")),
587        },
588        () = shutdown.as_mut() => return Ok((SessionEnd::Shutdown, Vec::new())),
589    };
590    if let ConfigEnd::Transfer { host, port } = end {
591        // Sent on during the configuration state: the connection closes.
592        drop((rd, wr));
593        return Ok((
594            SessionEnd::Transferred { host, port },
595            V::take_cookies(&mut wire),
596        ));
597    }
598    log::info!("[{name}] logged in to {address} ({})", client.version);
599    // Play packets already received go to a buffer of their own.
600    dec.set_detach_frames(false);
601    dec.rehome();
602
603    let opts = CoreOptions {
604        name,
605        caps: client.version.caps(),
606        settings: client.settings.clone(),
607        brand: client.brand.clone(),
608        sensitivity: client.sensitivity,
609        silent_hold: client.silent_hold,
610        inventory: V::INVENTORY,
611        hold_turn_on_action: client.hold_turn_on_action,
612        accept_required_packs: client.accept_required_packs,
613        entity_push: client.entity_push,
614        turn_rate: client.turn_rate,
615        gui_releases_keys: client.gui_releases_keys,
616    };
617    let mut play = Play::<V, _, _> {
618        rd,
619        wr,
620        dec,
621        enc,
622        engine: Engine::new(
623            opts,
624            V::new_sim(&crate::sim::SimOptions {
625                record: client.record.clone(),
626                force_step_position: client.force_step_position,
627                entities: entity_config(behavior.interests(), V::GAME.caps()),
628                world: client.world_config,
629                shared_chunks: client.shared_chunks.clone(),
630                profile_name: Some(client.account.name().to_string()),
631            }),
632        ),
633        read_timeout: client.read_timeout,
634        interests: Interests::NONE,
635        inventory_ids: &[],
636        core_filter: PacketFilter::none(),
637        raw_ids: Vec::new(),
638        raw_mask: [0; 4],
639        world_errors: 0,
640        wire,
641        client,
642        reconfigure: false,
643        encrypted,
644        keys_task: None,
645        keys_checked: None,
646    };
647    for raw in &registries {
648        play.engine.sim.registry_data(raw);
649    }
650    drop(registries);
651    V::configure_inventory(play.engine.inventory_mut(), &play.wire);
652    V::feed_inventory_config(play.engine.inventory_mut(), &mut play.wire);
653    let result = play.run(behavior, shutdown).await;
654    let reason = match &result {
655        Ok(SessionEnd::Kicked { reason, .. }) => format!("kicked: {reason}"),
656        Ok(SessionEnd::ServerClosed) => "server closed the connection".to_owned(),
657        Ok(SessionEnd::Quit(r)) => format!("quit: {r}"),
658        Ok(SessionEnd::Shutdown) => "shutdown".to_owned(),
659        Ok(SessionEnd::Transferred { host, port }) => format!("transferred to {host}:{port}"),
660        Err(e) => format!("error: {e}"),
661    };
662    play.engine.stop(behavior, &reason);
663    let stats = play.dec.stats();
664    log::info!(
665        "[{}] session ended after {} ticks ({reason}); frames {} skipped {} (compressed {}), inflated {} B",
666        play.engine.core_name(),
667        play.engine.tick_count(),
668        stats.frames,
669        stats.skipped,
670        stats.skipped_compressed,
671        stats.inflated_bytes
672    );
673    if matches!(result, Ok(SessionEnd::Transferred { .. })) {
674        play.close().await;
675    }
676    let cookies = V::take_cookies(&mut play.wire);
677    result.map(|end| (end, cookies))
678}
679
680/// How a configuration phase ended.
681enum ConfigEnd {
682    /// Finished: the connection is in the play state.
683    Play,
684    /// The server sent a transfer.
685    Transfer {
686        /// Target host.
687        host: String,
688        /// Target port.
689        port: u16,
690    },
691}
692
693/// Handshake and login (and on 1.20.2+ the configuration state). Returns once the
694/// connection is in the play state.
695#[allow(clippy::too_many_arguments)] // the session's connection state, borrowed piecewise
696async fn login<V, R, W, B>(
697    client: &Client,
698    behavior: &mut B,
699    rd: &mut R,
700    wr: &mut W,
701    dec: &mut FrameDecoder,
702    enc: &mut FrameEncoder,
703    wire: &mut V::Wire,
704    registries: &mut Vec<RawPacket>,
705    encrypted: &mut bool,
706    (address, transfer): (&TargetAddr, bool),
707) -> Result<ConfigEnd, ClientError>
708where
709    V: ClientVersion,
710    R: AsyncRead + Unpin,
711    W: AsyncWrite + Unpin,
712    B: Behavior,
713{
714    if transfer {
715        V::write_transfer_handshake(enc, &address.host(), address.port())?;
716    } else {
717        V::write_handshake_for(enc, client.version, &address.host(), address.port())?;
718    }
719    V::write_login_start(enc, client.account.name(), client.account.uuid())?;
720    flush(wr, enc).await?;
721    loop {
722        while let Some(raw) = dec.next_packet()? {
723            let p = V::decode_login(&raw).map_err(|source| ClientError::Decode {
724                state: State::Login,
725                id: raw.id,
726                source,
727            })?;
728            match p {
729                None => {}
730                Some(LoginInbound::Disconnect(reason)) => {
731                    return Err(ClientError::LoginRefused(chat_to_plain(&reason)));
732                }
733                Some(LoginInbound::Compress(threshold)) => {
734                    dec.set_compression(threshold);
735                    enc.set_compression(threshold);
736                }
737                Some(LoginInbound::PluginRequest {
738                    message_id,
739                    channel,
740                }) => {
741                    log::debug!("login plugin request {message_id} on {channel}: not understood");
742                    V::write_plugin_response(enc, message_id)?;
743                    flush(wr, enc).await?;
744                }
745                Some(LoginInbound::EncryptionRequest {
746                    server_id,
747                    public_key,
748                    verify_token,
749                }) => {
750                    let secret =
751                        encryption::<V>(client, enc, &server_id, &public_key, &verify_token)
752                            .await?;
753                    flush(wr, enc).await?;
754                    enc.enable_encryption(&secret);
755                    dec.enable_encryption(&secret);
756                    *encrypted = true;
757                }
758                Some(LoginInbound::EncryptionRequestUnauthenticated {
759                    server_id,
760                    public_key,
761                    verify_token,
762                }) => {
763                    // handleHello without shouldAuthenticate: no session-server join.
764                    let resp = ghast_auth::crypto::respond_to_encryption_request(
765                        &server_id,
766                        &public_key,
767                        &verify_token,
768                    )?;
769                    V::write_encryption_response(
770                        enc,
771                        &resp.encrypted_shared_secret,
772                        &resp.encrypted_verify_token,
773                    )?;
774                    flush(wr, enc).await?;
775                    enc.enable_encryption(resp.shared_secret.as_bytes());
776                    dec.enable_encryption(resp.shared_secret.as_bytes());
777                    *encrypted = true;
778                }
779                Some(LoginInbound::CookieRequest(key)) => {
780                    V::write_login_cookie_response_from(enc, &key, wire)?;
781                    flush(wr, enc).await?;
782                }
783                Some(LoginInbound::Success { uuid, username }) => {
784                    log::debug!("login success: {username} {uuid:?}");
785                    if V::GAME.caps().configuration_state {
786                        // ClientHandshakePacketListenerImpl.handleLoginFinished: acknowledge,
787                        // then the brand and the client information.
788                        V::write_login_acknowledged(enc)?;
789                        if let Some(brand) = &client.brand {
790                            let b = ConfigOutbound::Brand(brand.clone());
791                            V::write_configuration(enc, &b, wire)?;
792                        }
793                        let settings = ConfigOutbound::Settings(client.settings.clone());
794                        V::write_configuration(enc, &settings, wire)?;
795                        flush(wr, enc).await?;
796                        return configure::<V, _, _, B>(
797                            client, behavior, rd, wr, dec, enc, wire, registries,
798                        )
799                        .await;
800                    }
801                    return Ok(ConfigEnd::Play);
802                }
803            }
804        }
805        if read_more(rd, dec).await? == 0 {
806            return Err(ClientError::LoginClosed);
807        }
808    }
809}
810
811/// The built-in data packs of the vanilla client (`KnownPacksManager`): core and the feature
812/// packs, all in the `minecraft` namespace.
813const VANILLA_PACKS: &[&str] = &[
814    "core",
815    "minecart_improvements",
816    "redstone_experiments",
817    "trade_rebalance",
818];
819
820/// The configuration state (1.20.2+), until the server finishes it. Registry data is collected
821/// into `registries` (raw) for the world.
822#[allow(clippy::too_many_arguments)] // the session's connection state, borrowed piecewise
823async fn configure<V, R, W, B>(
824    client: &Client,
825    behavior: &mut B,
826    rd: &mut R,
827    wr: &mut W,
828    dec: &mut FrameDecoder,
829    enc: &mut FrameEncoder,
830    wire: &mut V::Wire,
831    registries: &mut Vec<RawPacket>,
832) -> Result<ConfigEnd, ClientError>
833where
834    V: ClientVersion,
835    R: AsyncRead + Unpin,
836    W: AsyncWrite + Unpin,
837    B: Behavior,
838{
839    let family = V::GAME.protocol_info().game_versions;
840    loop {
841        while let Some(raw) = dec.next_packet()? {
842            let p = V::decode_configuration(&raw, wire).map_err(|source| ClientError::Decode {
843                state: State::Configuration,
844                id: raw.id,
845                source,
846            })?;
847            let Some(p) = p else { continue };
848            let reply = match p {
849                ConfigInbound::KeepAlive(id) => vec![ConfigOutbound::KeepAlive(id)],
850                ConfigInbound::Ping(id) => vec![ConfigOutbound::Pong(id)],
851                ConfigInbound::Finish => {
852                    V::write_configuration(enc, &ConfigOutbound::Finish, wire)?;
853                    flush(wr, enc).await?;
854                    log::debug!("configuration done ({} registries)", registries.len());
855                    return Ok(ConfigEnd::Play);
856                }
857                ConfigInbound::Disconnect(reason) => return Err(ClientError::LoginRefused(reason)),
858                ConfigInbound::SelectKnownPacks(packs) => {
859                    // The vanilla packs of this version family (the server's own patch).
860                    let known: Vec<KnownPack> = packs
861                        .into_iter()
862                        .filter(|k| {
863                            &*k.namespace == "minecraft"
864                                && VANILLA_PACKS.contains(&&*k.id)
865                                && family.contains(&&*k.version)
866                        })
867                        .collect();
868                    vec![ConfigOutbound::SelectKnownPacks(known)]
869                }
870                ConfigInbound::RegistryData(raw) => {
871                    V::note_registry(&raw, wire);
872                    registries.push(raw);
873                    continue;
874                }
875                ConfigInbound::ResourcePackPush { id, required } => {
876                    if required && client.accept_required_packs {
877                        [3, 4, 0]
878                            .into_iter()
879                            .map(|result| ConfigOutbound::ResourcePackStatus { id, result })
880                            .collect()
881                    } else {
882                        vec![ConfigOutbound::ResourcePackStatus { id, result: 1 }]
883                    }
884                }
885                ConfigInbound::CookieRequest(key) => vec![ConfigOutbound::CookieResponse { key }],
886                ConfigInbound::CodeOfConduct(text) => {
887                    log::info!("server code of conduct (accepted): {text}");
888                    vec![ConfigOutbound::AcceptCodeOfConduct]
889                }
890                ConfigInbound::Transfer(to) => {
891                    let (host, port) = to.rsplit_once(':').unwrap_or((&to, "25565"));
892                    return Ok(ConfigEnd::Transfer {
893                        host: host.to_owned(),
894                        port: port.parse().unwrap_or(25565),
895                    });
896                }
897                ConfigInbound::ShowDialog(d) => {
898                    configuration_dialog(client.account.name(), behavior, *d)
899                }
900                // A dialog left open closes; nothing is sent.
901                ConfigInbound::ClearDialog => continue,
902            };
903            for o in &reply {
904                V::write_configuration(enc, o, wire)?;
905            }
906            flush(wr, enc).await?;
907        }
908        if read_more(rd, dec).await? == 0 {
909            return Err(ClientError::LoginClosed);
910        }
911    }
912}
913
914/// A dialog shown during the configuration state: the behaviour's answers
915/// ([`Behavior::configuration_dialog`]) as the packets vanilla sends there. Commands do nothing
916/// in this state (vanilla logs them); a dialog an answer opens is offered again (at most 16 in a
917/// row).
918fn configuration_dialog<B: Behavior>(
919    name: &str,
920    behavior: &mut B,
921    dialog: crate::dialog::Dialog,
922) -> Vec<ConfigOutbound> {
923    use crate::dialog::{Effect, Next};
924    let mut out = Vec::new();
925    if !behavior.interests().contains(Interests::DIALOGS) {
926        log::warn!(
927            "[{name}] the server shows a dialog during configuration ({:?}, \"{}\"); no behaviour \
928             answers dialogs (Interests::DIALOGS), so the server may wait for an answer",
929            dialog.kind,
930            dialog.title
931        );
932        return out;
933    }
934    log::info!("[{name}] configuration dialog \"{}\"", dialog.title);
935    let mut current = dialog;
936    for _ in 0..16 {
937        let answer = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
938            behavior.configuration_dialog(&current)
939        }));
940        let answer = match answer {
941            Ok(Some(a)) => a,
942            Ok(None) => break,
943            Err(_) => {
944                log::error!(
945                    "[{name}] behaviour {} panicked in configuration_dialog",
946                    behavior.name()
947                );
948                break;
949            }
950        };
951        let (effect, next) = match crate::dialog::resolve(&current, &answer) {
952            Ok(r) => r,
953            Err(e) => {
954                log::warn!("[{name}] configuration dialog answer refused: {e}");
955                break;
956            }
957        };
958        match effect {
959            Effect::Nothing => {}
960            Effect::Custom { id, payload } => out.push(ConfigOutbound::CustomClickAction {
961                id,
962                payload: crate::dialog::payload_nbt(payload.as_ref()),
963            }),
964            Effect::Command(c) => {
965                // ClientConfigurationPacketListenerImpl: the dialog stays open.
966                log::warn!("[{name}] commands are not supported in configuration phase: {c:?}");
967                break;
968            }
969        }
970        match next {
971            Next::Open(d) => current = (*d).clone(),
972            _ => break,
973        }
974    }
975    out
976}
977
978/// Answers an encryption request; returns the shared secret to enable.
979// `V` is only used for online mode.
980#[cfg_attr(
981    not(feature = "microsoft"),
982    allow(clippy::extra_unused_type_parameters)
983)]
984async fn encryption<V: ClientVersion>(
985    client: &Client,
986    enc: &mut FrameEncoder,
987    server_id: &str,
988    public_key: &[u8],
989    verify_token: &[u8],
990) -> Result<[u8; 16], ClientError> {
991    match &client.account {
992        Account::Offline(_) => {
993            let _ = (enc, server_id, public_key, verify_token);
994            Err(ClientError::OnlineModeRequired)
995        }
996        #[cfg(feature = "microsoft")]
997        Account::Microsoft { session, auth } => {
998            let resp = ghast_auth::crypto::respond_to_encryption_request(
999                server_id,
1000                public_key,
1001                verify_token,
1002            )?;
1003            auth.join_server(&session.access_token, session.profile.id, &resp.server_hash)
1004                .await?;
1005            V::write_encryption_response(
1006                enc,
1007                &resp.encrypted_shared_secret,
1008                &resp.encrypted_verify_token,
1009            )?;
1010            Ok(*resp.shared_secret.as_bytes())
1011        }
1012    }
1013}
1014
1015/// The play state of one session.
1016struct Play<'c, V: ClientVersion + HasSim, R, W> {
1017    rd: R,
1018    wr: W,
1019    dec: FrameDecoder,
1020    enc: FrameEncoder,
1021    engine: Engine<V::Sim>,
1022    read_timeout: Duration,
1023    interests: Interests,
1024    /// The inventory's state-dependent packets in the filter ([`ClientVersion::inventory_packet_ids`]).
1025    inventory_ids: &'static [i32],
1026    /// The filter without the behaviour's raw tap: only these packets reach the inventory (a
1027    /// tapped `declare_recipes` without `Interests::RECIPES` is copied, not decoded and kept).
1028    core_filter: PacketFilter,
1029    /// Packet ids copied for the behaviour (`Behavior::raw_packets`), as a bit set.
1030    raw_ids: Vec<i32>,
1031    raw_mask: [u64; 4],
1032    /// World packets the world rejected (malformed chunk data).
1033    world_errors: u64,
1034    /// The version's wire state (sequence numbers, chat acknowledgements).
1035    wire: V::Wire,
1036    client: &'c Client,
1037    /// The server moved the connection to the configuration state (1.20.2+).
1038    reconfigure: bool,
1039    /// The connection is encrypted (signed chat needs it).
1040    encrypted: bool,
1041    /// A profile key pair request in flight.
1042    keys_task: Option<KeysTask<'c>>,
1043    /// When the key pair was last checked for a refresh (vanilla: at most hourly).
1044    keys_checked: Option<Instant>,
1045}
1046
1047/// A profile key pair request (`ProfileKeyPairManager.prepareKeyPair`).
1048type KeysTask<'c> = Pin<Box<dyn Future<Output = Result<ProfileKeys, String>> + Send + 'c>>;
1049
1050/// The entity tracking the interests ask for: positions and metadata (item stacks, sneak /
1051/// pose flags); equipment and other entities' effects are not decoded (cheaper), except for
1052/// the entity types whose click answers read them.
1053pub(crate) fn entity_config(
1054    interests: Interests,
1055    caps: &crate::version::Capabilities,
1056) -> Option<ghast_entity::Config> {
1057    let metadata = interests.contains(Interests::ENTITIES);
1058    (metadata || interests.contains(Interests::ENTITY_TRACKING)).then(|| {
1059        let list = interests.contains(Interests::PLAYER_LIST);
1060        ghast_entity::Config::default()
1061            .with_metadata(metadata)
1062            .with_equipment(false)
1063            .with_effects(false)
1064            // Except what a right click on an entity reads (26.x: a saddle, horse armor, an
1065            // allay's item, a zombie villager's weakness): those types' equipment and effects.
1066            .with_kept_types(crate::interact::kept_types(caps.protocol))
1067            .with_player_list(list)
1068            // Without the tab list, still each player's name and game mode where the client
1069            // pushes the player itself: pushes are judged by the pusher's team under its
1070            // profile name, spectators do not push, and vanilla skips a player spawn whose
1071            // profile is not in the tab list. Older versions decode no player_info then.
1072            .with_player_names(!list && caps.client_entity_push)
1073            .with_events(interests.contains(Interests::ENTITY_EVENTS))
1074            .with_skins(interests.contains(Interests::PLAYER_SKINS))
1075            // What the vanilla client draws and picks (interpolated positions) and the
1076            // per-entity clocks.
1077            .with_client_motion(true)
1078    })
1079}
1080
1081/// What woke the play loop.
1082enum Wake {
1083    Read(std::io::Result<usize>),
1084    Tick,
1085    Shutdown,
1086    Keys(Box<Result<ProfileKeys, String>>),
1087}
1088
1089impl<'c, V, R, W> Play<'c, V, R, W>
1090where
1091    V: ClientVersion + HasSim,
1092    R: AsyncRead + Unpin,
1093    W: AsyncWrite + Unpin,
1094{
1095    /// The cached key pair, if any.
1096    fn cached_keys(&self) -> Option<Arc<ProfileKeys>> {
1097        self.client.profile_keys.lock().ok().and_then(|k| k.clone())
1098    }
1099
1100    /// handleLogin on an online-mode connection (26.1: encrypted; 26.2+: the login packet's
1101    /// `onlineMode`): `prepareKeyPair` — the cached pair right away unless it is due for a
1102    /// refresh, else a request.
1103    fn on_join(&mut self) {
1104        if !V::online_mode(&self.wire, self.encrypted) || !self.client.signed_chat {
1105            return;
1106        }
1107        match self.cached_keys() {
1108            Some(k) if !k.due_refresh() => self.start_chat_session(&k),
1109            cached => {
1110                if !self.request_keys()
1111                    && let Some(k) = cached
1112                {
1113                    // Nothing to refresh with (no account service): keep using it.
1114                    self.start_chat_session(&k);
1115                }
1116            }
1117        }
1118    }
1119
1120    fn start_chat_session(&mut self, keys: &Arc<ProfileKeys>) {
1121        if V::begin_chat_session(&mut self.wire, keys, self.client.account.uuid()) {
1122            log::debug!("[{}] chat session started", self.engine.name());
1123            self.engine.request_chat_session();
1124        }
1125    }
1126
1127    /// Starts a key pair request if the account can make one; `false` if not.
1128    fn request_keys(&mut self) -> bool {
1129        if self.keys_task.is_some() {
1130            return true;
1131        }
1132        self.keys_checked = Some(Instant::now());
1133        match &self.client.account {
1134            Account::Offline(_) => false,
1135            #[cfg(feature = "microsoft")]
1136            Account::Microsoft { session, auth } => {
1137                let (auth, token) = (auth.clone(), session.access_token.clone());
1138                self.keys_task = Some(Box::pin(async move {
1139                    auth.profile_keys(&token).await.map_err(|e| e.to_string())
1140                }));
1141                true
1142            }
1143        }
1144    }
1145
1146    /// The key pair request finished.
1147    fn keys_done(&mut self, r: Result<ProfileKeys, String>) {
1148        self.keys_task = None;
1149        match r {
1150            Ok(k) => {
1151                let k = Arc::new(k);
1152                if let Ok(mut c) = self.client.profile_keys.lock() {
1153                    *c = Some(k.clone());
1154                }
1155                if self.engine.joined() {
1156                    self.start_chat_session(&k);
1157                }
1158            }
1159            Err(e) => {
1160                // Vanilla logs it and keeps the cached pair (chat stays unsigned without one).
1161                log::warn!(
1162                    "[{}] profile key pair request failed: {e}",
1163                    self.engine.name()
1164                );
1165                if let Some(k) = self.cached_keys()
1166                    && self.engine.joined()
1167                {
1168                    self.start_chat_session(&k);
1169                }
1170            }
1171        }
1172    }
1173
1174    /// ClientPacketListener.tick: `shouldRefreshKeyPair` (at most hourly, once due).
1175    fn maybe_refresh_keys(&mut self) {
1176        if self.keys_task.is_some()
1177            || !V::online_mode(&self.wire, self.encrypted)
1178            || !self.client.signed_chat
1179        {
1180            return;
1181        }
1182        let hour = Duration::from_secs(3600);
1183        if self.keys_checked.is_some_and(|t| t.elapsed() < hour) {
1184            return;
1185        }
1186        if self.cached_keys().is_some_and(|k| k.due_refresh()) {
1187            self.request_keys();
1188        } else {
1189            self.keys_checked = Some(Instant::now());
1190        }
1191    }
1192
1193    fn set_filter(&mut self, interests: Interests, raw: &[i32]) {
1194        // switching the server's recipes and tags off frees them (they come back only on the
1195        // next join or `/reload`)
1196        if self.interests.contains(Interests::RECIPES) && !interests.contains(Interests::RECIPES) {
1197            self.engine.inventory_mut().clear_server_data();
1198        }
1199        self.interests = interests;
1200        raw.clone_into(&mut self.raw_ids);
1201        self.raw_mask = [0; 4];
1202        for &id in raw {
1203            if (0..256).contains(&id) {
1204                self.raw_mask[id as usize >> 6] |= 1 << (id & 63);
1205            }
1206        }
1207        self.engine
1208            .sim
1209            .collect_block_updates(interests.contains(Interests::BLOCK_UPDATES));
1210        self.engine
1211            .track_teams(interests.contains(Interests::TEAMS));
1212        // Entity tracking follows the interests at run time (a tracker started late begins
1213        // empty: entities spawned before are not known until the server sends them again).
1214        self.engine
1215            .sim
1216            .set_entities(entity_config(interests, V::GAME.caps()));
1217        let mut filter: PacketFilter = V::play_filter(interests);
1218        for id in self.engine.sim.entity_packet_ids() {
1219            filter.insert(id);
1220        }
1221        for id in self.engine.sim.world_packet_ids() {
1222            filter.insert(id);
1223        }
1224        self.inventory_ids = V::inventory_packet_ids(self.engine.inventory_mut());
1225        for &id in self.inventory_ids {
1226            filter.insert(id);
1227        }
1228        self.core_filter = filter;
1229        for &id in raw {
1230            filter.insert(id);
1231        }
1232        self.dec.set_filter(filter);
1233    }
1234
1235    /// Applies a packet filter change the sim asked for (it reads more packets from now on).
1236    fn refilter_if_dirty(&mut self) {
1237        let inventory = V::inventory_packet_ids(self.engine.inventory_mut()) != self.inventory_ids;
1238        if self.engine.sim.take_filter_dirty() || inventory {
1239            let raw = self.raw_ids.clone();
1240            self.set_filter(self.interests, &raw);
1241        }
1242    }
1243
1244    /// Logs (rate-limited) and optionally dumps a world packet the world rejected.
1245    fn bad_world_packet(&mut self, raw: &RawPacket, e: &ghast_world::WorldError) {
1246        self.world_errors += 1;
1247        let n = self.world_errors;
1248        if n <= 3 || n.is_power_of_two() {
1249            log::warn!(
1250                "[{}] bad world packet 0x{:02x} ({} bytes): {e} ({n} so far)",
1251                self.engine.name(),
1252                raw.id,
1253                raw.body.len()
1254            );
1255        }
1256        // Opt-in capture for bug reports: GHAST_DUMP_BAD_CHUNK=<dir> writes the first few
1257        // rejected bodies there.
1258        if n <= 8
1259            && let Some(dir) = std::env::var_os("GHAST_DUMP_BAD_CHUNK")
1260        {
1261            let path = std::path::Path::new(&dir).join(format!(
1262                "ghast-bad-world-{}-0x{:02x}-{n}.bin",
1263                std::process::id(),
1264                raw.id
1265            ));
1266            match std::fs::write(&path, &raw.body) {
1267                Ok(()) => log::warn!("[{}] wrote {}", self.engine.name(), path.display()),
1268                Err(err) => log::warn!("cannot write {}: {err}", path.display()),
1269            }
1270        }
1271    }
1272
1273    /// Encodes the engine's outbound packets.
1274    fn encode_outbound(&mut self) -> Result<(), ClientError> {
1275        let tick = self.engine.tick_count();
1276        let out = self.engine.outbound();
1277        V::prepare_play(out, &mut self.wire);
1278        let mut res = Ok(());
1279        for p in out.drain(..) {
1280            log::trace!(target: "ghast::packets", "t{tick} -> {p:?}");
1281            if let Err(e) = V::write_play(&mut self.enc, &p, &mut self.wire) {
1282                res = Err(e);
1283                break;
1284            }
1285        }
1286        out.clear();
1287        self.engine
1288            .note_sequence(V::prediction_sequence(&self.wire));
1289        res.map_err(ClientError::from)
1290    }
1291
1292    /// Decodes and applies everything buffered. Returns a session end on kick.
1293    fn drain_inbound(&mut self) -> Result<Option<SessionEnd>, ClientError> {
1294        let mut at = None;
1295        while let Some(raw) = self.dec.next_packet()? {
1296            log::trace!(
1297                target: "ghast::packets",
1298                "t{} <- 0x{:02x} ({} B)",
1299                self.engine.tick_count(),
1300                raw.id,
1301                raw.body.len()
1302            );
1303            if (0..256).contains(&raw.id)
1304                && self.raw_mask[raw.id as usize >> 6] & (1 << (raw.id & 63)) != 0
1305            {
1306                let at = *at.get_or_insert_with(std::time::Instant::now);
1307                self.engine.push_raw(crate::engine::RawInbound {
1308                    id: raw.id,
1309                    body: raw.body.clone(),
1310                    at,
1311                });
1312            }
1313            match self.engine.sim.world_packet(&raw) {
1314                Ok(()) => {}
1315                Err(SimError::Decode(source)) => {
1316                    return Err(ClientError::Decode {
1317                        state: State::Play,
1318                        id: raw.id,
1319                        source,
1320                    });
1321                }
1322                Err(SimError::World(e)) => {
1323                    // Malformed chunk data for one column: the world has unloaded that column
1324                    // (never guessed as air); the session goes on, like vanilla, which logs the
1325                    // failed task and keeps playing.
1326                    self.bad_world_packet(&raw, &e);
1327                    continue;
1328                }
1329            }
1330            // The sim may read more packets from this one on (26.1: the first boat seen starts
1331            // the vehicle tracker): the rest of this read is decoded with the new filter.
1332            self.refilter_if_dirty();
1333            // A prediction answer may have moved the player back (a restored block held it).
1334            self.engine.sync_snap();
1335            // 26.1 handleMoveVehicle answers at once (sent with this read's replies).
1336            if let Some(o) = self.engine.sim.take_reply() {
1337                self.engine.outbound().push(o);
1338            }
1339            // 1.20.2+ mount screens read the entity (type, saddle / body slots).
1340            let mount_eid = V::mount_screen_entity(&raw);
1341            if let Some(eid) = mount_eid {
1342                let mount = self.engine.sim.mount_info(eid);
1343                V::open_mount_screen(self.engine.inventory_mut(), &raw, mount).map_err(
1344                    |source| ClientError::Decode {
1345                        state: State::Play,
1346                        id: raw.id,
1347                        source,
1348                    },
1349                )?;
1350            }
1351            // The inventory answers window confirms itself (exactly once).
1352            let inv = if self.core_filter.contains(raw.id) {
1353                V::inventory_packet(self.engine.inventory_mut(), &raw).map_err(|source| {
1354                    ClientError::Decode {
1355                        state: State::Play,
1356                        id: raw.id,
1357                        source,
1358                    }
1359                })?
1360            } else {
1361                None
1362            };
1363            if let Some(o) = inv {
1364                self.engine
1365                    .outbound()
1366                    .push(crate::common::Outbound::Inventory(o));
1367            }
1368            if self.core_filter.contains(raw.id) {
1369                self.engine.hands_changed();
1370            }
1371            // A merchant window opened or closed: the rest of this read is decoded with its
1372            // offers passing or dropped again.
1373            self.refilter_if_dirty();
1374            // 1.8 – 1.16.5 mount screens: their slot rules from the tracked entity.
1375            if let Some(eid) = mount_eid {
1376                self.engine.mount_screen_opened(eid);
1377            }
1378            // 1.8 – 1.16 resource packs are answered here (no id; nothing to decode for later).
1379            let accept = self.engine.accept_required_packs();
1380            V::resource_pack(&raw, accept, self.engine.outbound()).map_err(|source| {
1381                ClientError::Decode {
1382                    state: State::Play,
1383                    id: raw.id,
1384                    source,
1385                }
1386            })?;
1387            let p = V::decode_play(&raw, &mut self.wire).map_err(|source| ClientError::Decode {
1388                state: State::Play,
1389                id: raw.id,
1390                source,
1391            })?;
1392            V::write_wire_replies(&mut self.enc, &mut self.wire)?;
1393            // A new level restarts the prediction sequence: the tick's predictions count from it.
1394            if matches!(p, Some(Inbound::JoinGame(_) | Inbound::Respawn { .. })) {
1395                self.engine
1396                    .note_sequence(V::prediction_sequence(&self.wire));
1397            }
1398            match p {
1399                None => {}
1400                Some(Inbound::Disconnect(json)) => {
1401                    let reason = chat_to_plain(&json);
1402                    log::warn!("[{}] kicked: {reason}", self.engine.core_name());
1403                    return Ok(Some(SessionEnd::Kicked {
1404                        reason,
1405                        json: json.to_string(),
1406                    }));
1407                }
1408                Some(Inbound::StartConfiguration) => {
1409                    // Everything after this packet is configuration state: stop here.
1410                    self.engine.handle(Inbound::StartConfiguration);
1411                    self.reconfigure = true;
1412                    return Ok(None);
1413                }
1414                Some(Inbound::Transfer { host, port }) => {
1415                    // ClientCommonPacketListenerImpl.handleTransfer: leave for the target.
1416                    log::info!(
1417                        "[{}] server transfer to {host}:{port}",
1418                        self.engine.core_name()
1419                    );
1420                    return Ok(Some(SessionEnd::Transferred { host, port }));
1421                }
1422                Some(p @ Inbound::JoinGame(_)) => {
1423                    self.engine.handle(p);
1424                    self.on_join();
1425                }
1426                Some(Inbound::SetCompression(t)) => {
1427                    // 1.8 play-state Set Compression: applies to the next frame both ways.
1428                    self.dec.set_compression(t);
1429                    self.encode_outbound()?;
1430                    self.enc.set_compression(t);
1431                }
1432                Some(p) => self.engine.handle(p),
1433            }
1434        }
1435        Ok(None)
1436    }
1437
1438    /// Play → configuration → play (1.20.2+ `start_configuration`): acknowledges, runs the
1439    /// configuration state (no ticks meanwhile, like vanilla without a level) and resumes play;
1440    /// the server then sends a new join game.
1441    async fn reconfigure_if_asked<B: Behavior>(
1442        &mut self,
1443        behavior: &mut B,
1444    ) -> Result<Option<SessionEnd>, ClientError> {
1445        if !self.reconfigure {
1446            return Ok(None);
1447        }
1448        self.reconfigure = false;
1449        log::info!("[{}] server asked for reconfiguration", self.engine.name());
1450        self.encode_outbound()?;
1451        V::write_configuration_start_replies(&mut self.enc, &mut self.wire)?;
1452        V::write_configuration_acknowledged(&mut self.enc)?;
1453        flush(&mut self.wr, &mut self.enc).await?;
1454        let play_filter = *self.dec.filter();
1455        self.dec.set_filter(PacketFilter::all());
1456        self.dec.set_detach_frames(true);
1457        let mut registries = Vec::new();
1458        let end = configure::<V, _, _, B>(
1459            self.client,
1460            behavior,
1461            &mut self.rd,
1462            &mut self.wr,
1463            &mut self.dec,
1464            &mut self.enc,
1465            &mut self.wire,
1466            &mut registries,
1467        )
1468        .await?;
1469        if let ConfigEnd::Transfer { host, port } = end {
1470            return Ok(Some(SessionEnd::Transferred { host, port }));
1471        }
1472        self.dec.set_detach_frames(false);
1473        self.dec.rehome();
1474        for raw in &registries {
1475            self.engine.sim.registry_data(raw);
1476        }
1477        V::configure_inventory(self.engine.inventory_mut(), &self.wire);
1478        V::feed_inventory_config(self.engine.inventory_mut(), &mut self.wire);
1479        self.dec.set_filter(play_filter);
1480        self.engine.note_inbound(Instant::now().into_std());
1481        Ok(None)
1482    }
1483
1484    /// Ends the connection the way a client that keeps reading does: half-close (FIN), then
1485    /// read and drop whatever the server still sends until it closes too (at most 1 s). Closing
1486    /// with unread bytes in the receive buffer makes the kernel answer with a reset, which the
1487    /// server logs as "Connection reset by peer" instead of a normal disconnect.
1488    async fn close(&mut self) {
1489        let _ = self.wr.shutdown().await;
1490        // On the heap: an array here would be part of the session future for its whole life.
1491        let mut buf = vec![0u8; 16 * 1024];
1492        let drain = async {
1493            loop {
1494                match self.rd.read(&mut buf).await {
1495                    Ok(0) | Err(_) => break,
1496                    Ok(_) => {}
1497                }
1498            }
1499        };
1500        let _ = tokio::time::timeout(Duration::from_secs(1), drain).await;
1501    }
1502
1503    /// Reads if data is available right now; `None` if the read would wait.
1504    async fn read_ready(&mut self) -> Option<std::io::Result<usize>> {
1505        let mut fut = std::pin::pin!(read_more(&mut self.rd, &mut self.dec));
1506        std::future::poll_fn(|cx| {
1507            std::task::Poll::Ready(match fut.as_mut().poll(cx) {
1508                std::task::Poll::Ready(r) => Some(r),
1509                std::task::Poll::Pending => None,
1510            })
1511        })
1512        .await
1513    }
1514
1515    async fn run<B: Behavior, S: Future<Output = ()>>(
1516        &mut self,
1517        behavior: &mut B,
1518        mut shutdown: Pin<&mut S>,
1519    ) -> Result<SessionEnd, ClientError> {
1520        let interests = self.engine.interests(behavior);
1521        let raw = self.engine.raw_packets(behavior);
1522        self.set_filter(interests, &raw);
1523        self.engine.note_inbound(Instant::now().into_std());
1524        // Frames that arrived together with login success.
1525        if let Some(end) = self.drain_inbound()? {
1526            return Ok(end);
1527        }
1528        if let Some(end) = self.reconfigure_if_asked(behavior).await? {
1529            return Ok(end);
1530        }
1531        self.encode_outbound()?;
1532        flush(&mut self.wr, &mut self.enc).await?;
1533
1534        let mut ticker = tokio::time::interval_at(Instant::now() + TICK, TICK);
1535        // After a stall the missed ticks are skipped, never caught up: a burst of movement
1536        // packets is what anti-cheat timer checks flag.
1537        ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);
1538
1539        loop {
1540            let keys = async {
1541                match self.keys_task.as_mut() {
1542                    Some(t) => t.await,
1543                    None => std::future::pending().await,
1544                }
1545            };
1546            let wake = tokio::select! {
1547                biased;
1548                () = shutdown.as_mut() => Wake::Shutdown,
1549                _ = ticker.tick() => Wake::Tick,
1550                r = read_more(&mut self.rd, &mut self.dec) => Wake::Read(r),
1551                k = keys => Wake::Keys(Box::new(k)),
1552            };
1553            match wake {
1554                Wake::Keys(k) => self.keys_done(*k),
1555                Wake::Shutdown => {
1556                    self.encode_outbound()?;
1557                    flush(&mut self.wr, &mut self.enc).await?;
1558                    self.close().await;
1559                    return Ok(SessionEnd::Shutdown);
1560                }
1561                Wake::Read(r) => {
1562                    if r? == 0 {
1563                        return Ok(SessionEnd::ServerClosed);
1564                    }
1565                    let now = Instant::now().into_std();
1566                    self.engine.note_inbound(now);
1567                    if let Some(end) = self.drain_inbound()? {
1568                        return Ok(end);
1569                    }
1570                    if let Some(end) = self.reconfigure_if_asked(behavior).await? {
1571                        return Ok(end);
1572                    }
1573                    // Replies (keep-alive, teleport, confirms) go out right away, like
1574                    // vanilla's per-frame packet handling.
1575                    self.encode_outbound()?;
1576                    flush(&mut self.wr, &mut self.enc).await?;
1577                }
1578                Wake::Tick => {
1579                    // Apply what arrived since the last read first (inbound before the tick),
1580                    // without waiting for more.
1581                    for _ in 0..64 {
1582                        match self.read_ready().await {
1583                            None => break,
1584                            Some(r) => {
1585                                if r? == 0 {
1586                                    return Ok(SessionEnd::ServerClosed);
1587                                }
1588                                self.engine.note_inbound(Instant::now().into_std());
1589                                if let Some(end) = self.drain_inbound()? {
1590                                    return Ok(end);
1591                                }
1592                                if let Some(end) = self.reconfigure_if_asked(behavior).await? {
1593                                    return Ok(end);
1594                                }
1595                            }
1596                        }
1597                    }
1598                    let now = Instant::now().into_std();
1599                    if let Some(last) = self.engine.last_inbound()
1600                        && now.saturating_duration_since(last) > self.read_timeout
1601                    {
1602                        return Err(ClientError::Timeout("no data from the server"));
1603                    }
1604                    self.maybe_refresh_keys();
1605                    {
1606                        // Dialog commands are checked against the server's command tree.
1607                        let wire = std::cell::RefCell::new(&mut self.wire);
1608                        let check = |c: &str| V::check_command(&mut wire.borrow_mut(), c);
1609                        self.engine.tick_with(behavior, now, &check);
1610                    }
1611                    // The tick may start reading more packets (1.12.2 / 1.16.5: a jump press
1612                    // with an elytra on asks for our entity data, where a 1.12.2 server answers
1613                    // the glide request with flag 7): the filter changes before the next read,
1614                    // or the answer to this tick's packets is dropped by the old one.
1615                    self.refilter_if_dirty();
1616                    self.encode_outbound()?;
1617                    flush(&mut self.wr, &mut self.enc).await?;
1618                    if let Some(reason) = self.engine.quit_requested() {
1619                        let reason = reason.to_owned();
1620                        self.close().await;
1621                        return Ok(SessionEnd::Quit(reason));
1622                    }
1623                    let interests = self.engine.interests(behavior);
1624                    let raw = self.engine.raw_packets(behavior);
1625                    if interests != self.interests || *raw != *self.raw_ids {
1626                        self.set_filter(interests, &raw);
1627                    }
1628                }
1629            }
1630        }
1631    }
1632}
1633
1634#[cfg(test)]
1635mod tests {
1636    use super::*;
1637
1638    /// The interests map to the tracker configuration (none without `ENTITIES`).
1639    #[test]
1640    fn entity_config_follows_the_interests() {
1641        let caps = GameVersion::V26_2.caps();
1642        assert_eq!(entity_config(Interests::PLAYER_LIST, caps), None);
1643        let c = entity_config(Interests::ENTITIES, caps).unwrap();
1644        assert!(c.metadata && !c.player_list && c.player_names && !c.skins);
1645        let c = entity_config(
1646            Interests::ENTITIES | Interests::PLAYER_LIST | Interests::PLAYER_SKINS,
1647            caps,
1648        )
1649        .unwrap();
1650        assert!(c.player_list && c.skins);
1651        // Lean tracking: the tracker without the generic store; with ENTITIES it is kept.
1652        let c = entity_config(Interests::ENTITY_TRACKING, caps).unwrap();
1653        assert!(!c.metadata && c.reads_tab_list());
1654        assert!(
1655            entity_config(Interests::ENTITIES | Interests::ENTITY_TRACKING, caps)
1656                .unwrap()
1657                .metadata
1658        );
1659        // Versions whose client does not push the player: no tab list without PLAYER_LIST.
1660        let old = GameVersion::V1_8_9.caps();
1661        let c = entity_config(Interests::ENTITIES, old).unwrap();
1662        assert!(!c.reads_tab_list());
1663    }
1664
1665    /// The tab-list packets pass the filter with `Interests::ENTITIES` alone only where the
1666    /// sim uses them (client-side pushes: 1.12.2, 26.1+); with `PLAYER_LIST` everywhere.
1667    #[test]
1668    fn tab_list_packets_follow_the_version() {
1669        use crate::sim::Sim;
1670        fn check(mut sim: impl Sim, v: GameVersion, ids: &[i32]) {
1671            let caps = v.caps();
1672            for (interests, want) in [
1673                (Interests::ENTITIES, caps.client_entity_push),
1674                (Interests::ENTITY_TRACKING, caps.client_entity_push),
1675                (Interests::ENTITIES | Interests::PLAYER_LIST, true),
1676            ] {
1677                sim.set_entities(entity_config(interests, caps));
1678                let passed = sim.entity_packet_ids();
1679                for id in ids {
1680                    assert_eq!(passed.contains(id), want, "{v:?} {interests:?} 0x{id:02x}");
1681                }
1682            }
1683        }
1684        #[cfg(feature = "v1_8")]
1685        check(
1686            crate::sim::Sim18::new(),
1687            GameVersion::V1_8_9,
1688            ghast_entity::v1_8::PLAYER_LIST_IDS,
1689        );
1690        #[cfg(feature = "v1_12_2")]
1691        check(
1692            crate::sim::Sim12::new(),
1693            GameVersion::V1_12_2,
1694            ghast_entity::v1_12::PLAYER_LIST_IDS,
1695        );
1696        #[cfg(feature = "v1_16_5")]
1697        check(
1698            crate::sim::Sim16::new(),
1699            GameVersion::V1_16_5,
1700            ghast_entity::v1_16_5::PLAYER_LIST_IDS,
1701        );
1702        #[cfg(feature = "v26_1")]
1703        check(
1704            crate::sim::Sim26::test_overworld(),
1705            GameVersion::V26_1,
1706            ghast_entity::v26_1::PLAYER_LIST_IDS,
1707        );
1708        #[cfg(feature = "v26_2")]
1709        check(
1710            crate::sim::Sim262::test_overworld(),
1711            GameVersion::V26_2,
1712            ghast_entity::v26_2::PLAYER_LIST_IDS,
1713        );
1714        #[cfg(feature = "v26_3")]
1715        check(
1716            crate::sim::Sim263::test_overworld(),
1717            GameVersion::V26_3,
1718            ghast_entity::v26_3::PLAYER_LIST_IDS,
1719        );
1720    }
1721}
1722
1723/// The session future is allocated per bot for its whole life: beyond the session's state
1724/// (`Play`) it must stay small (a stack array or a long-dead local there costs every bot).
1725#[cfg(all(test, feature = "v26_2"))]
1726mod future_size {
1727    use super::*;
1728
1729    fn size_of_output<Fut>(_: impl FnOnce() -> Fut) -> usize {
1730        std::mem::size_of::<Fut>()
1731    }
1732
1733    #[test]
1734    fn the_session_future_holds_little_beyond_the_session_state() {
1735        type V = ghast_protocol::v26_2::V26_2;
1736        type P<'a> = Play<'a, V, tokio::net::tcp::OwnedReadHalf, tokio::net::tcp::OwnedWriteHalf>;
1737        let client = Client::new(
1738            TargetAddr::new("localhost", 25565).unwrap(),
1739            GameVersion::V26_2,
1740            Account::offline("probe").unwrap(),
1741        );
1742        let mut idle = crate::engine::Idle;
1743        let session = std::mem::size_of_val(&client.run_until(&mut idle, std::future::pending()));
1744        let play = std::mem::size_of::<P<'static>>();
1745        // Only the type is looked at: the closure never runs.
1746        #[allow(unreachable_code, clippy::diverging_sub_expression)]
1747        let run = size_of_output(|| {
1748            let p: &mut P<'_> = unreachable!();
1749            p.run(&mut idle, std::pin::pin!(std::future::pending::<()>()))
1750        });
1751        assert!(
1752            session < play + 6 * 1024,
1753            "session {session} B, play state {play} B"
1754        );
1755        assert!(run < 2 * 1024, "Play::run {run} B");
1756    }
1757}