1use 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
35pub const TICK: Duration = Duration::from_millis(50);
37
38#[derive(Clone)]
40#[non_exhaustive]
41pub enum Account {
42 Offline(OfflineProfile),
44 #[cfg(feature = "microsoft")]
46 Microsoft {
47 session: ghast_auth::microsoft::MinecraftSession,
49 auth: Arc<ghast_auth::microsoft::MicrosoftAuth>,
51 },
52}
53
54impl Account {
55 pub fn offline(name: &str) -> Result<Self, ClientError> {
57 Ok(Account::Offline(OfflineProfile::new(name)?))
58 }
59
60 #[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 #[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#[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: Arc<std::sync::Mutex<Option<Arc<ProfileKeys>>>>,
125}
126
127use ghast_auth::chat::ProfileKeys;
128
129impl Client {
130 #[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 #[must_use]
170 pub fn signed_chat(mut self, on: bool) -> Self {
171 self.signed_chat = on;
172 self
173 }
174
175 #[must_use]
182 pub fn follow_transfers(mut self, on: bool) -> Self {
183 self.follow_transfers = on;
184 self
185 }
186
187 #[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 #[must_use]
199 pub fn connector(mut self, connector: Connector) -> Self {
200 self.connector = connector;
201 self
202 }
203
204 #[must_use]
206 pub fn settings(mut self, settings: ClientSettings) -> Self {
207 self.settings = settings;
208 self
209 }
210
211 #[must_use]
213 pub fn brand(mut self, brand: Option<String>) -> Self {
214 self.brand = brand;
215 self
216 }
217
218 #[must_use]
220 pub fn sensitivity(mut self, sensitivity: f32) -> Self {
221 self.sensitivity = sensitivity;
222 self
223 }
224
225 #[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 #[must_use]
252 pub fn gui_releases_keys(mut self, on: bool) -> Self {
253 self.gui_releases_keys = on;
254 self
255 }
256
257 #[must_use]
259 pub fn silent_hold(mut self, d: Duration) -> Self {
260 self.silent_hold = d;
261 self
262 }
263
264 #[must_use]
267 pub fn read_timeout(mut self, d: Duration) -> Self {
268 self.read_timeout = d;
269 self
270 }
271
272 #[must_use]
274 pub fn login_timeout(mut self, d: Duration) -> Self {
275 self.login_timeout = d;
276 self
277 }
278
279 #[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 #[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 #[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 #[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 #[must_use]
350 pub fn entity_push(mut self, on: bool) -> Self {
351 self.entity_push = on;
352 self
353 }
354
355 #[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 #[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 #[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 #[must_use]
396 pub fn address(&self) -> &TargetAddr {
397 &self.address
398 }
399
400 #[must_use]
402 pub fn version(&self) -> GameVersion {
403 self.version
404 }
405
406 #[must_use]
408 pub fn account(&self) -> &Account {
409 &self.account
410 }
411
412 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 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 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
454async 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
466async 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
475struct Hop {
477 address: TargetAddr,
478 cookies: Vec<(ghast_protocol::types::ByteString, bytes::Bytes)>,
479}
480
481const MAX_TRANSFERS: usize = 8;
483
484async 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 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 let mut registries = Vec::new();
560 let mut encrypted = false;
562
563 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 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 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 ®istries {
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
680enum ConfigEnd {
682 Play,
684 Transfer {
686 host: String,
688 port: u16,
690 },
691}
692
693#[allow(clippy::too_many_arguments)] async 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 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 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
811const VANILLA_PACKS: &[&str] = &[
814 "core",
815 "minecart_improvements",
816 "redstone_experiments",
817 "trade_rebalance",
818];
819
820#[allow(clippy::too_many_arguments)] async 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 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 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
914fn 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(¤t)
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(¤t, &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 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#[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
1015struct 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 inventory_ids: &'static [i32],
1026 core_filter: PacketFilter,
1029 raw_ids: Vec<i32>,
1031 raw_mask: [u64; 4],
1032 world_errors: u64,
1034 wire: V::Wire,
1036 client: &'c Client,
1037 reconfigure: bool,
1039 encrypted: bool,
1041 keys_task: Option<KeysTask<'c>>,
1043 keys_checked: Option<Instant>,
1045}
1046
1047type KeysTask<'c> = Pin<Box<dyn Future<Output = Result<ProfileKeys, String>> + Send + 'c>>;
1049
1050pub(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 .with_kept_types(crate::interact::kept_types(caps.protocol))
1067 .with_player_list(list)
1068 .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 .with_client_motion(true)
1078 })
1079}
1080
1081enum 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 fn cached_keys(&self) -> Option<Arc<ProfileKeys>> {
1097 self.client.profile_keys.lock().ok().and_then(|k| k.clone())
1098 }
1099
1100 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 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 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 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 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 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 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 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 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 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 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 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 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 self.bad_world_packet(&raw, &e);
1327 continue;
1328 }
1329 }
1330 self.refilter_if_dirty();
1333 self.engine.sync_snap();
1335 if let Some(o) = self.engine.sim.take_reply() {
1337 self.engine.outbound().push(o);
1338 }
1339 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 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 self.refilter_if_dirty();
1374 if let Some(eid) = mount_eid {
1376 self.engine.mount_screen_opened(eid);
1377 }
1378 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 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 self.engine.handle(Inbound::StartConfiguration);
1411 self.reconfigure = true;
1412 return Ok(None);
1413 }
1414 Some(Inbound::Transfer { host, port }) => {
1415 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 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 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 ®istries {
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 async fn close(&mut self) {
1489 let _ = self.wr.shutdown().await;
1490 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 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 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 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 self.encode_outbound()?;
1576 flush(&mut self.wr, &mut self.enc).await?;
1577 }
1578 Wake::Tick => {
1579 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 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 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 #[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 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 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 #[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#[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 #[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}