Merge pull request #1650 from socksprox/fix/proxy-transfers

🤖 Agent: thank you! Merged after the contribution gate (checked against vanilla 26.3, tested in the modes it touches; pr_ready on main + the six gate PRs: fmt, clippy, 1327 tests, 112/112 affected harnesses) and this head's verify.
This commit is contained in:
Ludovic Marie
2026-10-25 17:26:57 +01:00
committed by GitHub
5 changed files with 233 additions and 17 deletions
+8 -2
View File
@@ -12098,6 +12098,8 @@ enum PendingWorldEntry {
Server {
address: String,
name: String,
/// A transfer's carried-over server cookies (`TransferState`).
cookies: Option<horizon_client::net::Cookies>,
},
}
@@ -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 => {}
}
+52 -3
View File
@@ -193,6 +193,9 @@ pub(super) struct Remote {
/// the oldest of them first waited (`poll_remote`).
backlog: VecDeque<Event>,
backlog_since: Option<Instant>,
/// `ClientboundTransferPacket`'s target: when the connection ends the
/// game connects here, the stored cookies carried over (`TransferState`).
transfer: Option<String>,
}
/// 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<horizon_client::net::Cookies>,
) -> 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<horizon_protocol::connection::Pipe>,
cookies: Option<horizon_client::net::Cookies>,
) -> 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,15 @@ 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()
&& r.session.address != "local"
{
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 +917,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);
@@ -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");
+163 -9
View File
@@ -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<Mutex<HashMap<String, Vec<u8>>>>;
/// 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<u128>),
/// `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<Mutex<Option<Arc<Counters>>>>,
/// 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<Language>,
) -> 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<Arc<AuthSession>>,
view_distance: i8,
lang: Arc<Language>,
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<Language>,
) -> 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,18 @@ impl Session {
view_distance: i8,
lang: Arc<Language>,
local: Option<horizon_protocol::connection::Pipe>,
cookies: Option<Cookies>,
) -> 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());
// 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());
let thread_configuring = configuring.clone();
let (address_owned, name_owned) = (address.to_owned(), name.to_owned());
let thread = std::thread::Builder::new()
@@ -119,6 +161,8 @@ impl Session {
&thread_writer,
&thread_configuring,
&thread_counters,
&thread_cookies,
transferred,
);
let from_server = result.is_ok();
let reason = result.unwrap_or_else(|e| e);
@@ -140,6 +184,7 @@ impl Session {
address: address.to_owned(),
name: name.to_owned(),
counters,
cookies,
debug,
}
}
@@ -291,6 +336,8 @@ fn run(
shared_writer: &Mutex<Option<ConnWriter>>,
configuring: &AtomicBool,
shared_counters: &Mutex<Option<Arc<Counters>>>,
cookies: &Cookies,
transferred: bool,
) -> Result<String, String> {
let (host, port, mut c) = if let Some(pipe) = local {
(address.to_owned(), 0, Connection::local(pipe))
@@ -321,7 +368,11 @@ fn run(
protocol: PROTOCOL_VERSION,
host: host.clone(),
port,
intent: handshake::LOGIN,
intent: if transferred {
handshake::TRANSFER
} else {
handshake::LOGIN
},
})
.encode(),
)
@@ -391,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(),
)
@@ -419,13 +473,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 +488,7 @@ fn receive_play(
configuring: &AtomicBool,
lang: &Language,
send: &Sender<Event>,
cookies: &Cookies,
) -> Result<String, String> {
loop {
let (id, payload) = reader.recv().map_err(|e| e.to_string())?;
@@ -469,9 +524,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 +570,7 @@ fn configure(
configuring: &AtomicBool,
lang: &Language,
send: &Sender<Event>,
cookies: &Cookies,
) -> Result<Dynamic, String> {
let mut registries = Dynamic::default();
let reply = |p: cfg::Serverbound| -> Result<(), String> {
@@ -525,11 +603,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 +748,7 @@ mod tests {
&AtomicBool::new(false),
&Language::new(),
&send,
&Cookies::default(),
)
});
let mut server = Connection::local(server);
@@ -708,6 +798,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 +810,7 @@ mod tests {
&thread_configuring,
&Language::new(),
&send,
&Cookies::default(),
)
});
let mut server = Connection::local(server);
@@ -749,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();
+7 -2
View File
@@ -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,