ghast-client 0.4.0

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5 and 26.1)
Documentation
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
//! Connection setup and the session driver: connect → handshake → login → play loop.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use ghast_auth::connect::{Connector, TargetAddr};
use ghast_auth::offline::OfflineProfile;
use ghast_protocol::{FrameDecoder, FrameEncoder, PacketFilter, RawPacket, State};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::time::{Instant, MissedTickBehavior};

use crate::common::{
    ClientSettings, ConfigInbound, ConfigOutbound, Inbound, KnownPack, LoginInbound, chat_to_plain,
};
use crate::engine::{Behavior, CoreOptions, Engine};
use crate::error::{ClientError, SessionEnd};
use crate::interest::Interests;
use crate::sim::{Sim, SimError};
#[cfg(feature = "v1_8")]
use crate::version::V1_8;
#[cfg(feature = "v1_12_2")]
use crate::version::V1_12_2;
#[cfg(feature = "v1_16_5")]
use crate::version::V1_16_5;
#[cfg(feature = "v26_1")]
use crate::version::V26_1;
use crate::version::{ClientVersion, GameVersion, HasSim};

/// Length of one client tick.
pub const TICK: Duration = Duration::from_millis(50);
/// Minimum free space requested from the socket per read.
const READ_CHUNK: usize = 16 * 1024;

/// The account a client logs in with.
#[derive(Clone)]
#[non_exhaustive]
pub enum Account {
    /// Offline mode (the server does not authenticate; the UUID derives from the name).
    Offline(OfflineProfile),
    /// A Microsoft account session (needed for online-mode servers).
    #[cfg(feature = "microsoft")]
    Microsoft {
        /// The logged-in session (access token and profile).
        session: ghast_auth::microsoft::MinecraftSession,
        /// The client that makes the session-server `join` call.
        auth: Arc<ghast_auth::microsoft::MicrosoftAuth>,
    },
}

impl Account {
    /// An offline account (the name is checked like vanilla: 1–16 of `[A-Za-z0-9_]`).
    pub fn offline(name: &str) -> Result<Self, ClientError> {
        Ok(Account::Offline(OfflineProfile::new(name)?))
    }

    /// The player name.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Account::Offline(p) => p.name(),
            #[cfg(feature = "microsoft")]
            Account::Microsoft { session, .. } => &session.profile.name,
        }
    }

    /// The profile id (offline: derived from the name like vanilla's offline mode).
    #[must_use]
    pub fn uuid(&self) -> uuid::Uuid {
        match self {
            Account::Offline(p) => p.uuid(),
            #[cfg(feature = "microsoft")]
            Account::Microsoft { session, .. } => session.profile.id,
        }
    }
}

impl std::fmt::Debug for Account {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Account::Offline(p) => f.debug_tuple("Offline").field(&p.name()).finish(),
            #[cfg(feature = "microsoft")]
            Account::Microsoft { session, .. } => f
                .debug_struct("Microsoft")
                .field("name", &session.profile.name)
                .finish_non_exhaustive(),
        }
    }
}

/// A configured client: where to connect, which version, which account, and how.
///
/// One `Client` can run any number of sessions one after another (reconnects); run several
/// clients concurrently for several bots (one per process, or many tasks in one process —
/// a failing session never affects another).
#[derive(Debug, Clone)]
pub struct Client {
    address: TargetAddr,
    version: GameVersion,
    account: Account,
    connector: Connector,
    settings: ClientSettings,
    brand: Option<String>,
    sensitivity: f32,
    silent_hold: Duration,
    read_timeout: Duration,
    login_timeout: Duration,
    record: Option<std::path::PathBuf>,
    force_step_position: crate::sim::ForceStepPosition,
    hold_turn_on_action: bool,
    world_config: Option<ghast_world::WorldConfig>,
    accept_required_packs: bool,
}

impl Client {
    /// A client with vanilla defaults: direct connection (see [`Client::connector`]),
    /// brand `vanilla`, sensitivity 0.5, 30 s read timeout.
    #[must_use]
    pub fn new(address: TargetAddr, version: GameVersion, account: Account) -> Self {
        Client {
            address,
            version,
            account,
            connector: Connector::new(),
            settings: ClientSettings::default(),
            brand: Some("vanilla".to_owned()),
            sensitivity: 0.5,
            silent_hold: Duration::from_millis(1500),
            read_timeout: Duration::from_secs(30),
            login_timeout: Duration::from_secs(30),
            record: None,
            force_step_position: crate::sim::ForceStepPosition::Off,
            hold_turn_on_action: true,
            world_config: None,
            accept_required_packs: true,
        }
    }

    /// How to open the TCP connection (SOCKS5 proxy, proxy policy, timeouts).
    #[must_use]
    pub fn connector(mut self, connector: Connector) -> Self {
        self.connector = connector;
        self
    }

    /// Client settings sent after joining.
    #[must_use]
    pub fn settings(mut self, settings: ClientSettings) -> Self {
        self.settings = settings;
        self
    }

    /// The client brand sent after joining (`None`: send none).
    #[must_use]
    pub fn brand(mut self, brand: Option<String>) -> Self {
        self.brand = brand;
        self
    }

    /// Mouse sensitivity (options.txt value, 0 … 1) for rotation steps.
    #[must_use]
    pub fn sensitivity(mut self, sensitivity: f32) -> Self {
        self.sensitivity = sensitivity;
        self
    }

    /// The behaviour is frozen after this long without data from the server (default 1.5 s).
    #[must_use]
    pub fn silent_hold(mut self, d: Duration) -> Self {
        self.silent_hold = d;
        self
    }

    /// The session fails after this long without data from the server (default 30 s, like
    /// vanilla's read timeout).
    #[must_use]
    pub fn read_timeout(mut self, d: Duration) -> Self {
        self.read_timeout = d;
        self
    }

    /// Connecting plus login must finish within this time (default 30 s).
    #[must_use]
    pub fn login_timeout(mut self, d: Duration) -> Self {
        self.login_timeout = d;
        self
    }

    /// Records every session's movement in the oracle's replay format (1.8.9; the file is
    /// overwritten by each session). For debugging anticheat flags against vanilla.
    #[must_use]
    pub fn record(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.record = Some(path.into());
        self
    }

    /// What the world keeps besides block states. Default: nothing (no light, no biomes:
    /// the bot does not need them, and they cost memory and decoding time). A viewer that
    /// draws the world can turn them on; [`crate::WorldView::column`] gives the data.
    #[must_use]
    pub fn world_config(mut self, config: ghast_world::WorldConfig) -> Self {
        self.world_config = Some(config);
        self
    }

    /// Keep the look still on a tick that dug or placed when this tick's turn would take the
    /// crosshair off the clicked block (on by default). Grim's
    /// RotationPlace re-checks a dig / place with the look of the movement packet that follows
    /// it; holding the mouse for one tick is what a player does anyway. The held turn
    /// continues on the next tick the behaviour aims.
    #[must_use]
    pub fn hold_turn_on_action(mut self, on: bool) -> Self {
        self.hold_turn_on_action = on;
        self
    }

    /// **Not vanilla** (Grim 2.3 compatibility, off by default): on a tick whose feet height
    /// changed (a step-up or landing) but whose move stayed under the 0.03-block resend
    /// threshold, send the position anyway. Vanilla sends only the look / on-ground there,
    /// which Grim 2.3.73 sets back (soul sand → grass hops).
    #[must_use]
    pub fn force_step_position(mut self, on: bool) -> Self {
        self.force_step_position = if on {
            crate::sim::ForceStepPosition::Always
        } else {
            crate::sim::ForceStepPosition::Off
        };
        self
    }

    /// **Not vanilla**: [`Client::force_step_position`] with a choice of rule, e.g.
    /// [`ForceStepPosition::StepUpOnly`](crate::ForceStepPosition::StepUpOnly), which forces the
    /// position only on step-ups (on ground after the move, feet higher) and leaves sub-0.03
    /// falls and landings vanilla.
    #[must_use]
    pub fn force_step_position_mode(mut self, mode: crate::sim::ForceStepPosition) -> Self {
        self.force_step_position = mode;
        self
    }

    /// Server resource packs (1.20.3+): optional packs are always declined (the client never
    /// shows the prompt); a pack the server requires is reported accepted and loaded when this
    /// is on (default), declined otherwise (the server then usually disconnects). Nothing is
    /// downloaded.
    #[must_use]
    pub fn accept_required_resource_packs(mut self, on: bool) -> Self {
        self.accept_required_packs = on;
        self
    }

    /// The server address.
    #[must_use]
    pub fn address(&self) -> &TargetAddr {
        &self.address
    }

    /// The protocol version.
    #[must_use]
    pub fn version(&self) -> GameVersion {
        self.version
    }

    /// The account.
    #[must_use]
    pub fn account(&self) -> &Account {
        &self.account
    }

    /// Runs one session with `behavior` until the server ends it, the behaviour quits or an
    /// error occurs.
    pub async fn run<B: Behavior>(&self, behavior: &mut B) -> Result<SessionEnd, ClientError> {
        self.run_until(behavior, std::future::pending()).await
    }

    /// Like [`Client::run`], but also ends cleanly (the behaviour is stopped, the socket shut
    /// down) when `shutdown` completes.
    pub async fn run_until<B, S>(
        &self,
        behavior: &mut B,
        shutdown: S,
    ) -> Result<SessionEnd, ClientError>
    where
        B: Behavior,
        S: Future<Output = ()>,
    {
        let shutdown = std::pin::pin!(shutdown);
        // The version is chosen once: everything below is monomorphised per version.
        match self.version {
            #[cfg(feature = "v1_8")]
            GameVersion::V1_8_9 => session::<V1_8, B, S>(self, behavior, shutdown).await,
            #[cfg(feature = "v1_12_2")]
            GameVersion::V1_12_2 => session::<V1_12_2, B, S>(self, behavior, shutdown).await,
            #[cfg(feature = "v1_16_5")]
            GameVersion::V1_16_5 => session::<V1_16_5, B, S>(self, behavior, shutdown).await,
            #[cfg(feature = "v26_1")]
            GameVersion::V26_1 => session::<V26_1, B, S>(self, behavior, shutdown).await,
            #[allow(unreachable_patterns)]
            v => {
                let _ = (behavior, shutdown);
                Err(ClientError::VersionNotEnabled(v))
            }
        }
    }
}

/// Reads more bytes into the decoder. Cancel safe.
async fn read_more<R: AsyncRead + Unpin>(
    rd: &mut R,
    dec: &mut FrameDecoder,
) -> std::io::Result<usize> {
    let want = dec.needed().unwrap_or(0).max(READ_CHUNK);
    let buf = dec.buffer_mut();
    buf.reserve(want);
    let old = buf.len();
    let n = rd.read_buf(buf).await?;
    dec.commit(old);
    Ok(n)
}

/// Writes everything the encoder has queued.
async fn flush<W: AsyncWrite + Unpin>(wr: &mut W, enc: &mut FrameEncoder) -> std::io::Result<()> {
    let out = enc.out_mut();
    if !out.is_empty() {
        wr.write_all_buf(out).await?;
    }
    Ok(())
}

async fn session<V, B, S>(
    client: &Client,
    behavior: &mut B,
    mut shutdown: Pin<&mut S>,
) -> Result<SessionEnd, ClientError>
where
    V: ClientVersion + HasSim,
    B: Behavior,
    S: Future<Output = ()>,
{
    let name: Arc<str> = client.account.name().into();
    let mut dec = FrameDecoder::new();
    let mut enc = FrameEncoder::new();
    let mut wire = V::Wire::default();
    // Configuration-state registries, applied to the world once it exists.
    let mut registries = Vec::new();

    let login = async {
        let stream = client.connector.connect(&client.address).await?;
        let (mut rd, mut wr) = stream.into_split();
        login::<V, _, _>(
            client,
            &mut rd,
            &mut wr,
            &mut dec,
            &mut enc,
            &mut wire,
            &mut registries,
        )
        .await?;
        Ok::<_, ClientError>((rd, wr))
    };
    let (rd, wr) = tokio::select! {
        r = tokio::time::timeout(client.login_timeout, login) => match r {
            Ok(r) => r?,
            Err(_) => return Err(ClientError::Timeout("connect and login")),
        },
        () = shutdown.as_mut() => return Ok(SessionEnd::Shutdown),
    };
    log::info!("[{name}] logged in to {} ({})", client.address, V::GAME);

    let opts = CoreOptions {
        name,
        caps: V::GAME.caps(),
        settings: client.settings.clone(),
        brand: client.brand.clone(),
        sensitivity: client.sensitivity,
        silent_hold: client.silent_hold,
        inventory: V::INVENTORY,
        hold_turn_on_action: client.hold_turn_on_action,
        accept_required_packs: client.accept_required_packs,
    };
    let mut play = Play::<V, _, _> {
        rd,
        wr,
        dec,
        enc,
        engine: Engine::new(
            opts,
            V::new_sim(&crate::sim::SimOptions {
                record: client.record.clone(),
                force_step_position: client.force_step_position,
                entities: entity_config(behavior.interests()),
                world: client.world_config,
            }),
        ),
        read_timeout: client.read_timeout,
        interests: Interests::NONE,
        raw_ids: Vec::new(),
        raw_mask: [0; 4],
        world_errors: 0,
        wire,
        client,
        reconfigure: false,
    };
    for raw in &registries {
        play.engine.sim.registry_data(raw);
    }
    drop(registries);
    V::configure_inventory(play.engine.inventory_mut(), &play.wire);
    let result = play.run(behavior, shutdown).await;
    let reason = match &result {
        Ok(SessionEnd::Kicked { reason, .. }) => format!("kicked: {reason}"),
        Ok(SessionEnd::ServerClosed) => "server closed the connection".to_owned(),
        Ok(SessionEnd::Quit(r)) => format!("quit: {r}"),
        Ok(SessionEnd::Shutdown) => "shutdown".to_owned(),
        Err(e) => format!("error: {e}"),
    };
    play.engine.stop(behavior, &reason);
    let stats = play.dec.stats();
    log::info!(
        "[{}] session ended after {} ticks ({reason}); frames {} skipped {} (compressed {}), inflated {} B",
        play.engine.core_name(),
        play.engine.tick_count(),
        stats.frames,
        stats.skipped,
        stats.skipped_compressed,
        stats.inflated_bytes
    );
    result
}

/// Handshake and login (and on 1.20.2+ the configuration state). Returns once the
/// connection is in the play state.
async fn login<V, R, W>(
    client: &Client,
    rd: &mut R,
    wr: &mut W,
    dec: &mut FrameDecoder,
    enc: &mut FrameEncoder,
    wire: &mut V::Wire,
    registries: &mut Vec<RawPacket>,
) -> Result<(), ClientError>
where
    V: ClientVersion,
    R: AsyncRead + Unpin,
    W: AsyncWrite + Unpin,
{
    V::write_handshake(enc, &client.address.host(), client.address.port())?;
    V::write_login_start(enc, client.account.name(), client.account.uuid())?;
    flush(wr, enc).await?;
    loop {
        while let Some(raw) = dec.next_packet()? {
            let p = V::decode_login(&raw).map_err(|source| ClientError::Decode {
                state: State::Login,
                id: raw.id,
                source,
            })?;
            match p {
                None => {}
                Some(LoginInbound::Disconnect(reason)) => {
                    return Err(ClientError::LoginRefused(chat_to_plain(&reason)));
                }
                Some(LoginInbound::Compress(threshold)) => {
                    dec.set_compression(threshold);
                    enc.set_compression(threshold);
                }
                Some(LoginInbound::PluginRequest {
                    message_id,
                    channel,
                }) => {
                    log::debug!("login plugin request {message_id} on {channel}: not understood");
                    V::write_plugin_response(enc, message_id)?;
                    flush(wr, enc).await?;
                }
                Some(LoginInbound::EncryptionRequest {
                    server_id,
                    public_key,
                    verify_token,
                }) => {
                    let secret =
                        encryption::<V>(client, enc, &server_id, &public_key, &verify_token)
                            .await?;
                    flush(wr, enc).await?;
                    enc.enable_encryption(&secret);
                    dec.enable_encryption(&secret);
                }
                Some(LoginInbound::CookieRequest(key)) => {
                    V::write_login_cookie_response(enc, &key)?;
                    flush(wr, enc).await?;
                }
                Some(LoginInbound::Success { uuid, username }) => {
                    log::debug!("login success: {username} {uuid:?}");
                    if V::GAME.caps().configuration_state {
                        // ClientHandshakePacketListenerImpl.handleLoginFinished: acknowledge,
                        // then the brand and the client information.
                        V::write_login_acknowledged(enc)?;
                        if let Some(brand) = &client.brand {
                            let b = ConfigOutbound::Brand(brand.clone());
                            V::write_configuration(enc, &b, wire)?;
                        }
                        let settings = ConfigOutbound::Settings(client.settings.clone());
                        V::write_configuration(enc, &settings, wire)?;
                        flush(wr, enc).await?;
                        configure::<V, _, _>(client, rd, wr, dec, enc, wire, registries).await?;
                    }
                    return Ok(());
                }
            }
        }
        if read_more(rd, dec).await? == 0 {
            return Err(ClientError::LoginClosed);
        }
    }
}

/// The built-in data packs of the vanilla client (`KnownPacksManager`): core and the feature
/// packs, all in the `minecraft` namespace.
const VANILLA_PACKS: &[&str] = &[
    "core",
    "minecart_improvements",
    "redstone_experiments",
    "trade_rebalance",
];

/// The configuration state (1.20.2+), until the server finishes it. Registry data is collected
/// into `registries` (raw) for the world.
async fn configure<V, R, W>(
    client: &Client,
    rd: &mut R,
    wr: &mut W,
    dec: &mut FrameDecoder,
    enc: &mut FrameEncoder,
    wire: &mut V::Wire,
    registries: &mut Vec<RawPacket>,
) -> Result<(), ClientError>
where
    V: ClientVersion,
    R: AsyncRead + Unpin,
    W: AsyncWrite + Unpin,
{
    let family = V::GAME.protocol_info().game_versions;
    loop {
        while let Some(raw) = dec.next_packet()? {
            let p = V::decode_configuration(&raw, wire).map_err(|source| ClientError::Decode {
                state: State::Configuration,
                id: raw.id,
                source,
            })?;
            let Some(p) = p else { continue };
            let reply = match p {
                ConfigInbound::KeepAlive(id) => vec![ConfigOutbound::KeepAlive(id)],
                ConfigInbound::Ping(id) => vec![ConfigOutbound::Pong(id)],
                ConfigInbound::Finish => {
                    V::write_configuration(enc, &ConfigOutbound::Finish, wire)?;
                    flush(wr, enc).await?;
                    log::debug!("configuration done ({} registries)", registries.len());
                    return Ok(());
                }
                ConfigInbound::Disconnect(reason) => return Err(ClientError::LoginRefused(reason)),
                ConfigInbound::SelectKnownPacks(packs) => {
                    // The vanilla packs of this version family (the server's own patch).
                    let known: Vec<KnownPack> = packs
                        .into_iter()
                        .filter(|k| {
                            &*k.namespace == "minecraft"
                                && VANILLA_PACKS.contains(&&*k.id)
                                && family.contains(&&*k.version)
                        })
                        .collect();
                    vec![ConfigOutbound::SelectKnownPacks(known)]
                }
                ConfigInbound::RegistryData(raw) => {
                    V::note_registry(&raw, wire);
                    registries.push(raw);
                    continue;
                }
                ConfigInbound::ResourcePackPush { id, required } => {
                    if required && client.accept_required_packs {
                        [3, 4, 0]
                            .into_iter()
                            .map(|result| ConfigOutbound::ResourcePackStatus { id, result })
                            .collect()
                    } else {
                        vec![ConfigOutbound::ResourcePackStatus { id, result: 1 }]
                    }
                }
                ConfigInbound::CookieRequest(key) => vec![ConfigOutbound::CookieResponse { key }],
                ConfigInbound::CodeOfConduct(text) => {
                    log::info!("server code of conduct (accepted): {text}");
                    vec![ConfigOutbound::AcceptCodeOfConduct]
                }
                ConfigInbound::Transfer(to) => {
                    log::warn!("server transfer to {to} is not supported; staying");
                    continue;
                }
            };
            for o in &reply {
                V::write_configuration(enc, o, wire)?;
            }
            flush(wr, enc).await?;
        }
        if read_more(rd, dec).await? == 0 {
            return Err(ClientError::LoginClosed);
        }
    }
}

/// Answers an encryption request; returns the shared secret to enable.
// `V` is only used for online mode.
#[cfg_attr(
    not(feature = "microsoft"),
    allow(clippy::extra_unused_type_parameters)
)]
async fn encryption<V: ClientVersion>(
    client: &Client,
    enc: &mut FrameEncoder,
    server_id: &str,
    public_key: &[u8],
    verify_token: &[u8],
) -> Result<[u8; 16], ClientError> {
    match &client.account {
        Account::Offline(_) => {
            let _ = (enc, server_id, public_key, verify_token);
            Err(ClientError::OnlineModeRequired)
        }
        #[cfg(feature = "microsoft")]
        Account::Microsoft { session, auth } => {
            let resp = ghast_auth::crypto::respond_to_encryption_request(
                server_id,
                public_key,
                verify_token,
            )?;
            auth.join_server(&session.access_token, session.profile.id, &resp.server_hash)
                .await?;
            V::write_encryption_response(
                enc,
                &resp.encrypted_shared_secret,
                &resp.encrypted_verify_token,
            )?;
            Ok(*resp.shared_secret.as_bytes())
        }
    }
}

/// The play state of one session.
struct Play<'c, V: ClientVersion + HasSim, R, W> {
    rd: R,
    wr: W,
    dec: FrameDecoder,
    enc: FrameEncoder,
    engine: Engine<V::Sim>,
    read_timeout: Duration,
    interests: Interests,
    /// Packet ids copied for the behaviour (`Behavior::raw_packets`), as a bit set.
    raw_ids: Vec<i32>,
    raw_mask: [u64; 4],
    /// World packets the world rejected (malformed chunk data).
    world_errors: u64,
    /// The version's wire state (sequence numbers, chat acknowledgements).
    wire: V::Wire,
    client: &'c Client,
    /// The server moved the connection to the configuration state (1.20.2+).
    reconfigure: bool,
}

/// The entity tracking the interests ask for: positions and metadata (item stacks, sneak /
/// pose flags); equipment and other entities' effects are not decoded (cheaper).
fn entity_config(interests: Interests) -> Option<ghast_entity::Config> {
    interests.contains(Interests::ENTITIES).then(|| {
        ghast_entity::Config::default()
            .with_metadata(true)
            .with_equipment(false)
            .with_effects(false)
            .with_player_list(interests.contains(Interests::PLAYER_LIST))
            .with_events(false)
            .with_skins(interests.contains(Interests::PLAYER_SKINS))
    })
}

/// What woke the play loop.
enum Wake {
    Read(std::io::Result<usize>),
    Tick,
    Shutdown,
}

impl<V, R, W> Play<'_, V, R, W>
where
    V: ClientVersion + HasSim,
    R: AsyncRead + Unpin,
    W: AsyncWrite + Unpin,
{
    fn set_filter(&mut self, interests: Interests, raw: &[i32]) {
        self.interests = interests;
        raw.clone_into(&mut self.raw_ids);
        self.raw_mask = [0; 4];
        for &id in raw {
            if (0..256).contains(&id) {
                self.raw_mask[id as usize >> 6] |= 1 << (id & 63);
            }
        }
        self.engine
            .sim
            .collect_block_updates(interests.contains(Interests::BLOCK_UPDATES));
        // Entity tracking follows the interests at run time (a tracker started late begins
        // empty: entities spawned before are not known until the server sends them again).
        self.engine.sim.set_entities(entity_config(interests));
        let mut filter: PacketFilter = V::play_filter(interests);
        for id in self.engine.sim.entity_packet_ids() {
            filter.insert(id);
        }
        for id in self.engine.sim.world_packet_ids() {
            filter.insert(id);
        }
        for &id in raw {
            filter.insert(id);
        }
        self.dec.set_filter(filter);
    }

    /// Logs (rate-limited) and optionally dumps a world packet the world rejected.
    fn bad_world_packet(&mut self, raw: &RawPacket, e: &ghast_world::WorldError) {
        self.world_errors += 1;
        let n = self.world_errors;
        if n <= 3 || n.is_power_of_two() {
            log::warn!(
                "[{}] bad world packet 0x{:02x} ({} bytes): {e} ({n} so far)",
                self.engine.name(),
                raw.id,
                raw.body.len()
            );
        }
        // Opt-in capture for bug reports: GHAST_DUMP_BAD_CHUNK=<dir> writes the first few
        // rejected bodies there.
        if n <= 8
            && let Some(dir) = std::env::var_os("GHAST_DUMP_BAD_CHUNK")
        {
            let path = std::path::Path::new(&dir).join(format!(
                "ghast-bad-world-{}-0x{:02x}-{n}.bin",
                std::process::id(),
                raw.id
            ));
            match std::fs::write(&path, &raw.body) {
                Ok(()) => log::warn!("[{}] wrote {}", self.engine.name(), path.display()),
                Err(err) => log::warn!("cannot write {}: {err}", path.display()),
            }
        }
    }

    /// Encodes the engine's outbound packets.
    fn encode_outbound(&mut self) -> Result<(), ClientError> {
        let tick = self.engine.tick_count();
        let out = self.engine.outbound();
        let mut res = Ok(());
        for p in out.drain(..) {
            log::trace!(target: "ghast::packets", "t{tick} -> {p:?}");
            if let Err(e) = V::write_play(&mut self.enc, &p, &mut self.wire) {
                res = Err(e);
                break;
            }
        }
        out.clear();
        res.map_err(ClientError::from)
    }

    /// Decodes and applies everything buffered. Returns a session end on kick.
    fn drain_inbound(&mut self) -> Result<Option<SessionEnd>, ClientError> {
        let mut at = None;
        while let Some(raw) = self.dec.next_packet()? {
            log::trace!(
                target: "ghast::packets",
                "t{} <- 0x{:02x} ({} B)",
                self.engine.tick_count(),
                raw.id,
                raw.body.len()
            );
            if (0..256).contains(&raw.id)
                && self.raw_mask[raw.id as usize >> 6] & (1 << (raw.id & 63)) != 0
            {
                let at = *at.get_or_insert_with(std::time::Instant::now);
                self.engine.push_raw(crate::engine::RawInbound {
                    id: raw.id,
                    body: raw.body.clone(),
                    at,
                });
            }
            match self.engine.sim.world_packet(&raw) {
                Ok(()) => {}
                Err(SimError::Decode(source)) => {
                    return Err(ClientError::Decode {
                        state: State::Play,
                        id: raw.id,
                        source,
                    });
                }
                Err(SimError::World(e)) => {
                    // Malformed chunk data for one column: the world has unloaded that column
                    // (never guessed as air); the session goes on, like vanilla, which logs the
                    // failed task and keeps playing.
                    self.bad_world_packet(&raw, &e);
                    continue;
                }
            }
            // The inventory answers window confirms itself (exactly once).
            let inv = V::inventory_packet(self.engine.inventory_mut(), &raw).map_err(|source| {
                ClientError::Decode {
                    state: State::Play,
                    id: raw.id,
                    source,
                }
            })?;
            if let Some(o) = inv {
                self.engine
                    .outbound()
                    .push(crate::common::Outbound::Inventory(o));
            }
            let p = V::decode_play(&raw, &mut self.wire).map_err(|source| ClientError::Decode {
                state: State::Play,
                id: raw.id,
                source,
            })?;
            V::write_wire_replies(&mut self.enc, &mut self.wire)?;
            match p {
                None => {}
                Some(Inbound::Disconnect(json)) => {
                    let reason = chat_to_plain(&json);
                    log::warn!("[{}] kicked: {reason}", self.engine.core_name());
                    return Ok(Some(SessionEnd::Kicked {
                        reason,
                        json: json.to_string(),
                    }));
                }
                Some(Inbound::StartConfiguration) => {
                    // Everything after this packet is configuration state: stop here.
                    self.engine.handle(Inbound::StartConfiguration);
                    self.reconfigure = true;
                    return Ok(None);
                }
                Some(Inbound::SetCompression(t)) => {
                    // 1.8 play-state Set Compression: applies to the next frame both ways.
                    self.dec.set_compression(t);
                    self.encode_outbound()?;
                    self.enc.set_compression(t);
                }
                Some(p) => self.engine.handle(p),
            }
        }
        Ok(None)
    }

    /// Play → configuration → play (1.20.2+ `start_configuration`): acknowledges, runs the
    /// configuration state (no ticks meanwhile, like vanilla without a level) and resumes play;
    /// the server then sends a new join game.
    async fn reconfigure_if_asked(&mut self) -> Result<(), ClientError> {
        if !self.reconfigure {
            return Ok(());
        }
        self.reconfigure = false;
        log::info!("[{}] server asked for reconfiguration", self.engine.name());
        self.encode_outbound()?;
        V::write_configuration_acknowledged(&mut self.enc)?;
        flush(&mut self.wr, &mut self.enc).await?;
        let play_filter = *self.dec.filter();
        self.dec.set_filter(PacketFilter::all());
        let mut registries = Vec::new();
        configure::<V, _, _>(
            self.client,
            &mut self.rd,
            &mut self.wr,
            &mut self.dec,
            &mut self.enc,
            &mut self.wire,
            &mut registries,
        )
        .await?;
        for raw in &registries {
            self.engine.sim.registry_data(raw);
        }
        V::configure_inventory(self.engine.inventory_mut(), &self.wire);
        self.dec.set_filter(play_filter);
        self.engine.note_inbound(Instant::now().into_std());
        Ok(())
    }

    /// Ends the connection the way a client that keeps reading does: half-close (FIN), then
    /// read and drop whatever the server still sends until it closes too (at most 1 s). Closing
    /// with unread bytes in the receive buffer makes the kernel answer with a reset, which the
    /// server logs as "Connection reset by peer" instead of a normal disconnect.
    async fn close(&mut self) {
        let _ = self.wr.shutdown().await;
        let mut buf = [0u8; 16 * 1024];
        let drain = async {
            loop {
                match self.rd.read(&mut buf).await {
                    Ok(0) | Err(_) => break,
                    Ok(_) => {}
                }
            }
        };
        let _ = tokio::time::timeout(Duration::from_secs(1), drain).await;
    }

    /// Reads if data is available right now; `None` if the read would wait.
    async fn read_ready(&mut self) -> Option<std::io::Result<usize>> {
        let mut fut = std::pin::pin!(read_more(&mut self.rd, &mut self.dec));
        std::future::poll_fn(|cx| {
            std::task::Poll::Ready(match fut.as_mut().poll(cx) {
                std::task::Poll::Ready(r) => Some(r),
                std::task::Poll::Pending => None,
            })
        })
        .await
    }

    async fn run<B: Behavior, S: Future<Output = ()>>(
        &mut self,
        behavior: &mut B,
        mut shutdown: Pin<&mut S>,
    ) -> Result<SessionEnd, ClientError> {
        let interests = self.engine.interests(behavior);
        let raw = self.engine.raw_packets(behavior);
        self.set_filter(interests, &raw);
        self.engine.note_inbound(Instant::now().into_std());
        // Frames that arrived together with login success.
        if let Some(end) = self.drain_inbound()? {
            return Ok(end);
        }
        self.reconfigure_if_asked().await?;
        self.encode_outbound()?;
        flush(&mut self.wr, &mut self.enc).await?;

        let mut ticker = tokio::time::interval_at(Instant::now() + TICK, TICK);
        // After a stall the missed ticks are skipped, never caught up: a burst of movement
        // packets is what anti-cheat timer checks flag.
        ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);

        loop {
            let wake = tokio::select! {
                biased;
                () = shutdown.as_mut() => Wake::Shutdown,
                _ = ticker.tick() => Wake::Tick,
                r = read_more(&mut self.rd, &mut self.dec) => Wake::Read(r),
            };
            match wake {
                Wake::Shutdown => {
                    self.encode_outbound()?;
                    flush(&mut self.wr, &mut self.enc).await?;
                    self.close().await;
                    return Ok(SessionEnd::Shutdown);
                }
                Wake::Read(r) => {
                    if r? == 0 {
                        return Ok(SessionEnd::ServerClosed);
                    }
                    let now = Instant::now().into_std();
                    self.engine.note_inbound(now);
                    if let Some(end) = self.drain_inbound()? {
                        return Ok(end);
                    }
                    self.reconfigure_if_asked().await?;
                    // Replies (keep-alive, teleport, confirms) go out right away, like
                    // vanilla's per-frame packet handling.
                    self.encode_outbound()?;
                    flush(&mut self.wr, &mut self.enc).await?;
                }
                Wake::Tick => {
                    // Apply what arrived since the last read first (inbound before the tick),
                    // without waiting for more.
                    for _ in 0..64 {
                        match self.read_ready().await {
                            None => break,
                            Some(r) => {
                                if r? == 0 {
                                    return Ok(SessionEnd::ServerClosed);
                                }
                                self.engine.note_inbound(Instant::now().into_std());
                                if let Some(end) = self.drain_inbound()? {
                                    return Ok(end);
                                }
                                self.reconfigure_if_asked().await?;
                            }
                        }
                    }
                    let now = Instant::now().into_std();
                    if let Some(last) = self.engine.last_inbound()
                        && now.saturating_duration_since(last) > self.read_timeout
                    {
                        return Err(ClientError::Timeout("no data from the server"));
                    }
                    self.engine.tick(behavior, now);
                    self.encode_outbound()?;
                    flush(&mut self.wr, &mut self.enc).await?;
                    if let Some(reason) = self.engine.quit_requested() {
                        let reason = reason.to_owned();
                        self.close().await;
                        return Ok(SessionEnd::Quit(reason));
                    }
                    let interests = self.engine.interests(behavior);
                    let raw = self.engine.raw_packets(behavior);
                    if interests != self.interests || *raw != *self.raw_ids {
                        self.set_filter(interests, &raw);
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The interests map to the tracker configuration (none without `ENTITIES`).
    #[test]
    fn entity_config_follows_the_interests() {
        assert_eq!(entity_config(Interests::PLAYER_LIST), None);
        let c = entity_config(Interests::ENTITIES).unwrap();
        assert!(c.metadata && !c.player_list && !c.skins);
        let c =
            entity_config(Interests::ENTITIES | Interests::PLAYER_LIST | Interests::PLAYER_SKINS)
                .unwrap();
        assert!(c.player_list && c.skins);
    }
}