From 56560b467a8fad3ffe02457691bd8486a1a77cb6 Mon Sep 17 00:00:00 2001 From: socksprox Date: Sun, 25 Oct 2026 00:19:47 +0200 Subject: [PATCH 1/2] Multiplayer: answer cookie requests, store cookies, follow transfer packets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ClientboundCookieRequestPacket in play state decoded as Unknown and was dropped; StoreCookie and Transfer likewise, and the configuration-phase CookieRequest was always answered empty. Proxies (BungeeCord, Velocity) store and read cookies around a server switch and send Transfer to move a player to another address — both ended in a kick. Play-state cookie_request/store_cookie/transfer now have packet types, cookie requests answer from the stored cookies in both configuration and play (ClientCommonPacketListenerImpl.handleRequestCookie), stored cookies land in the session's map (handleStoreCookie), and a transfer reconnects the game to the target address carrying them (handleTransfer → ConnectScreen.startConnecting with TransferState). Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game.rs | 10 +- crates/horizon-client/src/game/remote.rs | 51 +++++++++- .../horizon-client/src/game/startup_menu.rs | 4 +- crates/horizon-client/src/net.rs | 94 +++++++++++++++++-- crates/horizon-protocol/src/packets/play.rs | 9 +- 5 files changed, 153 insertions(+), 15 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 699468651..7fcb3be89 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -12098,6 +12098,8 @@ enum PendingWorldEntry { Server { address: String, name: String, + /// A transfer's carried-over server cookies (`TransferState`). + cookies: Option, }, } @@ -12172,8 +12174,12 @@ impl Game<'_> { }) => { self.open_world(&folder, name.as_deref(), seed, creative, create.as_deref())?; } - Some(PendingWorldEntry::Server { address, name }) => { - self.connect_server(&address, &name)?; + Some(PendingWorldEntry::Server { + address, + name, + cookies, + }) => { + self.connect_server_with_cookies(&address, &name, cookies)?; } None => {} } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 044e43835..c10b64c54 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -193,6 +193,9 @@ pub(super) struct Remote { /// the oldest of them first waited (`poll_remote`). backlog: VecDeque, backlog_since: Option, + /// `ClientboundTransferPacket`'s target: when the connection ends the + /// game connects here, the stored cookies carried over (`TransferState`). + transfer: Option, } /// The time a frame spends on chunk packets before it leaves the rest of @@ -257,14 +260,25 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo impl Game<'_> { /// Leave the title for a server (ConnectScreen): an empty world fed by the connection. pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> { + self.connect_server_with_cookies(address, name, None) + } + /// `connect_server` carrying a transfer's stored server cookies + /// (`TransferState`); None on an ordinary join. + pub(super) fn connect_server_with_cookies( + &mut self, + address: &str, + name: &str, + cookies: Option, + ) -> Result<()> { if self.defer_world_entry(super::PendingWorldEntry::Server { address: address.to_owned(), name: name.to_owned(), + cookies: cookies.clone(), })? { return Ok(()); } self.join_world_rest()?; - if let Err(error) = self.join_server(address, name, None) { + if let Err(error) = self.join_server(address, name, None, cookies) { log::warn!("Horizon: could not join server: {error}"); if self.title.is_none() { self.title = Some(horizon_client::title::Title::new( @@ -285,13 +299,14 @@ impl Game<'_> { pipe: horizon_protocol::connection::Pipe, name: &str, ) -> Result<()> { - self.join_server("local", name, Some(pipe)) + self.join_server("local", name, Some(pipe), None) } fn join_server( &mut self, address: &str, name: &str, local: Option, + cookies: Option, ) -> Result<()> { self.perf.world_opening(); let root = self.options.resources.clone(); @@ -323,7 +338,17 @@ impl Game<'_> { Some(pipe) => Session::connect_local(pipe, name, view, lang.clone()), None => { self.extras_connecting(address, name); - Session::connect(address, name, auth.clone(), view, lang.clone()) + match cookies { + Some(cookies) => Session::connect_transferred( + address, + name, + auth.clone(), + view, + lang.clone(), + cookies, + ), + None => Session::connect(address, name, auth.clone(), view, lang.clone()), + } } }; let player_type = super::perspective::player_type(&root); @@ -446,6 +471,7 @@ impl Game<'_> { chunk_center: (0, 0), backlog: VecDeque::new(), backlog_since: None, + transfer: None, }); // The level's TickRateManager follows the server's ticking packets. self.clock = horizon_client::clock::FixedStep::client(); @@ -867,6 +893,11 @@ impl Game<'_> { } } Event::Reconfigured(registries) => self.set_registries(registries), + Event::Transfer { host, port } => { + if let Some(r) = self.remote.as_mut() { + r.transfer = Some(format!("{host}:{port}")); + } + } Event::PackPush(p) => self.handle_pack_push(p), Event::PackPop(id) => self.handle_pack_pop(id), Event::DecodeError(e) => { @@ -882,6 +913,20 @@ impl Game<'_> { from_server, } => { log::info!("Horizon: disconnected: {reason}"); + // ClientboundTransferPacket left a target: connect there + // instead of showing the disconnect, the stored cookies + // carried over (ClientCommonPacketListenerImpl. + // handleTransfer → ConnectScreen.startConnecting). + let transfer = self.remote.as_mut().and_then(|r| { + r.transfer.take().map(|address| { + (address, r.session.name.clone(), r.session.cookies.clone()) + }) + }); + if let Some((address, name, cookies)) = transfer { + self.leave_server(None)?; + self.connect_server_with_cookies(&address, &name, Some(cookies))?; + return Ok(()); + } let retry = self.reconnect_after(&reason, from_server); self.leave_server(Some(reason))?; self.offer_reconnect(retry); diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index 96af99bbc..fe568fe71 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -33,6 +33,7 @@ impl StartupMenu { Some(PendingWorldEntry::Server { address: address.clone(), name: options.player_name(), + cookies: None, }) } else { options @@ -125,6 +126,7 @@ impl StartupMenu { Action::Connect { address } => PendingWorldEntry::Server { address, name: player_name, + cookies: None, }, _ => return, }; @@ -762,7 +764,7 @@ mod tests { "Guest".into(), ); assert!( - matches!(menu.pending.take(), Some(PendingWorldEntry::Server { address, name }) + matches!(menu.pending.take(), Some(PendingWorldEntry::Server { address, name, .. }) if address == "localhost:25565" && name == "Guest") ); assert!(menu.pending.take().is_none(), "an entry is consumed once"); diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 9cce9e1c6..c4e53cef4 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -18,6 +18,7 @@ use horizon_protocol::{ text::{Language, plain, translatable}, }; use std::{ + collections::HashMap, sync::{ Arc, Mutex, atomic::{AtomicBool, Ordering}, @@ -27,6 +28,12 @@ use std::{ time::Duration, }; +/// `CommonListenerCookie.serverCookies`: cookies the server asked the client +/// to store (`ClientboundStoreCookiePacket`), answered to +/// `ClientboundCookieRequestPacket`. A `transfer` carries them to the next +/// connection (`TransferState`), so a proxy's backend switch keeps them. +pub type Cookies = Arc>>>; + /// What the network thread reports to the game. pub enum Event { /// Progress text for the connecting screen. @@ -48,6 +55,13 @@ pub enum Event { PackPush(cfg::ResourcePackPush), /// ClientboundResourcePackPopPacket: one pack, or every pack. PackPop(Option), + /// `ClientboundTransferPacket`: the server sent us to another address. + /// The connection ends right after; the game reconnects there with the + /// stored cookies. + Transfer { + host: String, + port: i32, + }, /// The connection ended. `from_server`: the server gave the reason (or /// the connection was refused for good), rather than the connection /// failing (auto-reconnect retries only failures and shutdowns). @@ -67,6 +81,8 @@ pub struct Session { pub address: String, pub name: String, pub counters: Arc>>>, + /// The cookies this server stored on us (`ClientboundStoreCookiePacket`). + pub cookies: Cookies, /// HORIZON_NET_DEBUG=1 logs every packet sent from the game thread. debug: bool, } @@ -79,7 +95,27 @@ impl Session { view_distance: i8, lang: Arc, ) -> Self { - Self::start(address, name, auth, view_distance, lang, None) + Self::start(address, name, auth, view_distance, lang, None, None) + } + /// `ConnectScreen.startConnecting` for a `transfer`: the cookies the + /// server stored carry to the new connection (`TransferState`). + pub fn connect_transferred( + address: &str, + name: &str, + auth: Option>, + view_distance: i8, + lang: Arc, + cookies: Cookies, + ) -> Self { + Self::start( + address, + name, + auth, + view_distance, + lang, + None, + Some(cookies), + ) } /// Join an integrated server through memory (`Connection.connectToLocalServer`). pub fn connect_local( @@ -88,7 +124,7 @@ impl Session { view_distance: i8, lang: Arc, ) -> Self { - Self::start("local", name, None, view_distance, lang, Some(pipe)) + Self::start("local", name, None, view_distance, lang, Some(pipe), None) } fn start( address: &str, @@ -97,12 +133,15 @@ impl Session { view_distance: i8, lang: Arc, local: Option, + cookies: Option, ) -> Self { let (send, events) = channel(); let writer = Arc::new(Mutex::new(None)); let configuring = Arc::new(AtomicBool::new(true)); let counters = Arc::new(Mutex::new(None)); - let (thread_writer, thread_counters) = (writer.clone(), counters.clone()); + let cookies = cookies.unwrap_or_default(); + let (thread_writer, thread_counters, thread_cookies) = + (writer.clone(), counters.clone(), cookies.clone()); let thread_configuring = configuring.clone(); let (address_owned, name_owned) = (address.to_owned(), name.to_owned()); let thread = std::thread::Builder::new() @@ -119,6 +158,7 @@ impl Session { &thread_writer, &thread_configuring, &thread_counters, + &thread_cookies, ); let from_server = result.is_ok(); let reason = result.unwrap_or_else(|e| e); @@ -140,6 +180,7 @@ impl Session { address: address.to_owned(), name: name.to_owned(), counters, + cookies, debug, } } @@ -291,6 +332,7 @@ fn run( shared_writer: &Mutex>, configuring: &AtomicBool, shared_counters: &Mutex>>, + cookies: &Cookies, ) -> Result { let (host, port, mut c) = if let Some(pipe) = local { (address.to_owned(), 0, Connection::local(pipe)) @@ -419,13 +461,13 @@ fn run( .map_err(e)?; let (mut reader, writer) = c.split(); *shared_writer.lock().unwrap() = Some(writer); - let registries = configure(&mut reader, shared_writer, configuring, lang, send)?; + let registries = configure(&mut reader, shared_writer, configuring, lang, send, cookies)?; let _ = send.send(Event::Joined { registries: Arc::new(registries), uuid: profile.uuid, name: profile.name, }); - receive_play(&mut reader, shared_writer, configuring, lang, send) + receive_play(&mut reader, shared_writer, configuring, lang, send, cookies) } fn receive_play( @@ -434,6 +476,7 @@ fn receive_play( configuring: &AtomicBool, lang: &Language, send: &Sender, + cookies: &Cookies, ) -> Result { loop { let (id, payload) = reader.recv().map_err(|e| e.to_string())?; @@ -469,9 +512,31 @@ fn receive_play( let _ = w.send(&play::Serverbound::ConfigurationAcknowledged(Empty).encode()); configuring.store(true, Ordering::Relaxed); } - let registries = configure(reader, shared_writer, configuring, lang, send)?; + let registries = + configure(reader, shared_writer, configuring, lang, send, cookies)?; let _ = send.send(Event::Reconfigured(Arc::new(registries))); } + // ClientCommonPacketListenerImpl.handleRequestCookie: the stored + // cookie (or none) goes straight back. + play::Clientbound::CookieRequest(q) => { + let payload = cookies.lock().unwrap().get(&q.key).cloned(); + reply(play::Serverbound::CookieResponse(cfg::CookieResponse { + key: q.key, + payload, + })); + } + play::Clientbound::StoreCookie(p) => { + cookies.lock().unwrap().insert(p.key, p.payload); + } + // ClientCommonPacketListenerImpl.handleTransfer: the connection + // ends and the game connects to the other address. + play::Clientbound::Transfer(p) => { + let _ = send.send(Event::Transfer { + host: p.host, + port: p.port, + }); + return Ok(tr(lang, "disconnect.transfer")); + } play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)), play::Clientbound::CustomPayload(p) if p.channel == "minecraft:brand" => { receive_brand(&p, send); @@ -493,6 +558,7 @@ fn configure( configuring: &AtomicBool, lang: &Language, send: &Sender, + cookies: &Cookies, ) -> Result { let mut registries = Dynamic::default(); let reply = |p: cfg::Serverbound| -> Result<(), String> { @@ -525,11 +591,22 @@ fn configure( let _ = send.send(Event::PackPop(p.id)); } cfg::Clientbound::CookieRequest(q) => { + let payload = cookies.lock().unwrap().get(&q.key).cloned(); reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse { key: q.key, - payload: None, + payload, }))? } + cfg::Clientbound::StoreCookie(p) => { + cookies.lock().unwrap().insert(p.key, p.payload); + } + cfg::Clientbound::Transfer(p) => { + let _ = send.send(Event::Transfer { + host: p.host, + port: p.port, + }); + return Err(tr(lang, "disconnect.transfer")); + } cfg::Clientbound::Disconnect(d) => return Err(plain(&d.reason, lang)), cfg::Clientbound::FinishConfiguration(_) => { let mut w = writer.lock().unwrap(); @@ -659,6 +736,7 @@ mod tests { &AtomicBool::new(false), &Language::new(), &send, + &Cookies::default(), ) }); let mut server = Connection::local(server); @@ -708,6 +786,7 @@ mod tests { address: "local".into(), name: "Player".into(), counters: Arc::new(Mutex::new(None)), + cookies: Cookies::default(), debug: false, }; let (thread_writer, thread_configuring) = @@ -719,6 +798,7 @@ mod tests { &thread_configuring, &Language::new(), &send, + &Cookies::default(), ) }); let mut server = Connection::local(server); diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 26bb96316..67373cf4b 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -13,8 +13,9 @@ use crate::{ packets::{ Empty, configuration::{ - ClientInformation, CustomPayload, Disconnect, KeepAlive, Ping, ResourcePackPop, - ResourcePackPush, ResourcePackResponse, UpdateTags, + ClientInformation, CookieRequest, CookieResponse, CustomPayload, Disconnect, KeepAlive, + Ping, ResourcePackPop, ResourcePackPush, ResourcePackResponse, StoreCookie, Transfer, + UpdateTags, }, login::Property, }, @@ -1759,6 +1760,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { ContainerSetContent(ContainerSetContent) = CONTAINER_SET_CONTENT, ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA, ContainerSetSlot(ContainerSetSlot) = CONTAINER_SET_SLOT, + CookieRequest(CookieRequest) = COOKIE_REQUEST, CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, Disconnect(Disconnect) = DISCONNECT, DisguisedChat(DisguisedChat) = DISGUISED_CHAT, @@ -1836,6 +1838,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { SoundEntity(SoundEntity) = SOUND_ENTITY, StopSound(StopSound) = STOP_SOUND, StartConfiguration(Empty) = START_CONFIGURATION, + StoreCookie(StoreCookie) = STORE_COOKIE, SwingAnimation(SwingAnimation) = SWING_ANIMATION, SystemChat(SystemChat) = SYSTEM_CHAT, TabList(TabList) = TAB_LIST, @@ -1843,6 +1846,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { TeleportEntity(TeleportEntity) = TELEPORT_ENTITY, TickingState(TickingState) = TICKING_STATE, TickingStep(TickingStep) = TICKING_STEP, + Transfer(Transfer) = TRANSFER, UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS, UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES, LevelParticles(LevelParticles) = LEVEL_PARTICLES, @@ -2223,6 +2227,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ContainerButtonClick(ContainerButtonClick) = CONTAINER_BUTTON_CLICK, ContainerClick(ContainerClick) = CONTAINER_CLICK, ContainerClose(ContainerClose) = CONTAINER_CLOSE, + CookieResponse(CookieResponse) = COOKIE_RESPONSE, CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, EditBook(EditBook) = EDIT_BOOK, Interact(Interact) = INTERACT, From 6b97107dc7ed8cc1ce6f5d76fcf932febf8b796d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 14:37:02 +0100 Subject: [PATCH 2/2] Transfers: handshake with the TRANSFER intent, answer login cookie requests Vanilla 26.3 reconnects after ClientboundTransferPacket with a TransferState, so Connection.initiateServerboundPlayConnection sends ClientIntent.TRANSFER (3): a target with accepts-transfers=false refuses the player, and the target can ask for the carried cookies during login (ClientHandshakePacketListenerImpl.handleRequestCookie). Both now match. A transfer from single player closes the world instead of connecting elsewhere (handleTransfer: "Cannot transfer to server from singleplayer"). Adds a unit test for the play-state store/request round trip and the Transfer event. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 6 +- crates/horizon-client/src/net.rs | 78 +++++++++++++++++++++++- 2 files changed, 81 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index c10b64c54..d70c0a4ae 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -893,8 +893,12 @@ impl Game<'_> { } } Event::Reconfigured(registries) => self.set_registries(registries), + // handleTransfer: "Cannot transfer to server from + // singleplayer" (no ServerData), so the world just closes. Event::Transfer { host, port } => { - if let Some(r) = self.remote.as_mut() { + if let Some(r) = self.remote.as_mut() + && r.session.address != "local" + { r.transfer = Some(format!("{host}:{port}")); } } diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index c4e53cef4..18aec0bea 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -139,6 +139,9 @@ impl Session { let writer = Arc::new(Mutex::new(None)); let configuring = Arc::new(AtomicBool::new(true)); let counters = Arc::new(Mutex::new(None)); + // Connection.initiateServerboundPlayConnection: a transfer's + // handshake says so (ClientIntent.TRANSFER). + let transferred = cookies.is_some(); let cookies = cookies.unwrap_or_default(); let (thread_writer, thread_counters, thread_cookies) = (writer.clone(), counters.clone(), cookies.clone()); @@ -159,6 +162,7 @@ impl Session { &thread_configuring, &thread_counters, &thread_cookies, + transferred, ); let from_server = result.is_ok(); let reason = result.unwrap_or_else(|e| e); @@ -333,6 +337,7 @@ fn run( configuring: &AtomicBool, shared_counters: &Mutex>>, cookies: &Cookies, + transferred: bool, ) -> Result { let (host, port, mut c) = if let Some(pipe) = local { (address.to_owned(), 0, Connection::local(pipe)) @@ -363,7 +368,11 @@ fn run( protocol: PROTOCOL_VERSION, host: host.clone(), port, - intent: handshake::LOGIN, + intent: if transferred { + handshake::TRANSFER + } else { + handshake::LOGIN + }, }) .encode(), ) @@ -433,11 +442,14 @@ fn run( ) .map_err(e)?; } + // ClientHandshakePacketListenerImpl.handleRequestCookie: the + // cookies a transfer carried over (none on a plain join). login::Clientbound::CookieRequest(q) => { + let payload = cookies.lock().unwrap().get(&q.key).cloned(); c.send( &login::Serverbound::CookieResponse(login::CookieResponse { key: q.key, - payload: None, + payload, }) .encode(), ) @@ -829,6 +841,68 @@ mod tests { assert!(thread.join().unwrap().is_err()); } + #[test] + fn play_answers_cookie_requests_from_stored_cookies_and_follows_transfers() { + let (client, server) = horizon_protocol::connection::Pipe::pair(); + let (mut reader, writer) = Connection::local(client).split(); + let writer = Arc::new(Mutex::new(Some(writer))); + let (send, events) = channel(); + let cookies = Cookies::default(); + let (thread_writer, thread_cookies) = (writer.clone(), cookies.clone()); + let thread = std::thread::spawn(move || { + receive_play( + &mut reader, + &thread_writer, + &AtomicBool::new(false), + &Language::new(), + &send, + &thread_cookies, + ) + }); + let mut server = Connection::local(server); + let ask = |server: &mut Connection, key: &str| { + let request = play::Clientbound::CookieRequest(cfg::CookieRequest { key: key.into() }); + server.send(&request.encode()).unwrap(); + let (id, body) = server.recv().unwrap(); + play::Serverbound::decode(id, &body).unwrap() + }; + // handleRequestCookie answers an unknown key with no payload. + assert_eq!( + ask(&mut server, "proxy:session"), + play::Serverbound::CookieResponse(cfg::CookieResponse { + key: "proxy:session".into(), + payload: None, + }) + ); + let store = play::Clientbound::StoreCookie(cfg::StoreCookie { + key: "proxy:session".into(), + payload: vec![1, 2, 3], + }); + server.send(&store.encode()).unwrap(); + assert_eq!( + ask(&mut server, "proxy:session"), + play::Serverbound::CookieResponse(cfg::CookieResponse { + key: "proxy:session".into(), + payload: Some(vec![1, 2, 3]), + }) + ); + let transfer = play::Clientbound::Transfer(cfg::Transfer { + host: "example.net".into(), + port: 25566, + }); + server.send(&transfer.encode()).unwrap(); + assert!(thread.join().unwrap().is_ok()); + assert!(matches!( + events.try_iter().last(), + Some(Event::Transfer { host, port: 25566 }) if host == "example.net" + )); + // The stored cookie stays for the next connection (TransferState). + assert_eq!( + cookies.lock().unwrap().get("proxy:session"), + Some(&vec![1, 2, 3]) + ); + } + #[test] fn server_brand_payload_is_decoded_and_invalid_or_unrelated_payloads_are_ignored() { let (send, events) = channel();