Skip to content

Commit

Permalink
Use translatable messages instead of custom ones
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexProgrammerDE committed Jun 16, 2024
1 parent 61e716e commit 9be5568
Show file tree
Hide file tree
Showing 11 changed files with 50 additions and 82 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.geysermc.mcprotocollib.network.example;

import net.kyori.adventure.text.Component;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.network.event.session.ConnectedEvent;
import org.geysermc.mcprotocollib.network.event.session.DisconnectedEvent;
Expand All @@ -22,7 +23,7 @@ public void packetReceived(Session session, Packet packet) {
if (id.equals("hello")) {
session.send(new PingPacket("exit"));
} else if (id.equals("exit")) {
session.disconnect("Finished");
session.disconnect(Component.text("Finished"));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,10 @@ private static void login() {
public void packetReceived(Session session, Packet packet) {
if (packet instanceof ClientboundLoginPacket) {
session.send(new ServerboundChatPacket("Hello, this is a test of MCProtocolLib.", Instant.now().toEpochMilli(), 0L, null, 0, new BitSet()));
} else if (packet instanceof ClientboundSystemChatPacket) {
Component message = ((ClientboundSystemChatPacket) packet).getContent();
} else if (packet instanceof ClientboundSystemChatPacket systemChatPacket) {
Component message = systemChatPacket.getContent();
log.info("Received Message: {}", message);
session.disconnect("Finished");
session.disconnect(Component.text("Finished"));
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.geysermc.mcprotocollib.network;

import net.kyori.adventure.text.Component;
import org.geysermc.mcprotocollib.network.event.server.ServerBoundEvent;
import org.geysermc.mcprotocollib.network.event.server.ServerClosedEvent;
import org.geysermc.mcprotocollib.network.event.server.ServerClosingEvent;
Expand Down Expand Up @@ -119,7 +120,7 @@ public void addSession(Session session) {
public void removeSession(Session session) {
this.sessions.remove(session);
if (session.isConnected()) {
session.disconnect("Connection closed.");
session.disconnect(Component.translatable("disconnect.endOfStream"));
}

this.callEvent(new SessionRemovedEvent(this, session));
Expand Down Expand Up @@ -164,7 +165,7 @@ public void close(boolean wait, Runnable callback) {
this.callEvent(new ServerClosingEvent(this));
for (Session session : this.getSessions()) {
if (session.isConnected()) {
session.disconnect("Server closed.");
session.disconnect(Component.translatable("multiplayer.disconnect.server_shutdown"));
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package org.geysermc.mcprotocollib.network;

import lombok.NonNull;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.geysermc.mcprotocollib.network.codec.PacketCodecHelper;
import org.geysermc.mcprotocollib.network.crypt.PacketEncryption;
import org.geysermc.mcprotocollib.network.event.session.SessionEvent;
Expand Down Expand Up @@ -273,30 +273,15 @@ default void send(Packet packet) {
*
* @param reason Reason for disconnecting.
*/
void disconnect(@Nullable String reason);
void disconnect(@NonNull Component reason);

/**
* Disconnects the session.
*
* @param reason Reason for disconnecting.
* @param cause Throwable responsible for disconnecting.
*/
void disconnect(@Nullable String reason, Throwable cause);

/**
* Disconnects the session.
*
* @param reason Reason for disconnecting.
*/
void disconnect(@Nullable Component reason);

/**
* Disconnects the session.
*
* @param reason Reason for disconnecting.
* @param cause Throwable responsible for disconnecting.
*/
void disconnect(@Nullable Component reason, Throwable cause);
void disconnect(@NonNull Component reason, Throwable cause);

/**
* Auto read in netty means that the server is automatically reading from the channel.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,11 +256,6 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception {
}
}

@Override
public void disconnect(String reason, Throwable cause) {
super.disconnect(reason, cause);
}

private static void createTcpEventLoopGroup() {
if (EVENT_LOOP_GROUP != null) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ConnectTimeoutException;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutException;
import io.netty.handler.timeout.WriteTimeoutHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.NonNull;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.geysermc.mcprotocollib.network.Flag;
Expand All @@ -27,14 +25,14 @@
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.network.packet.PacketProtocol;

import java.net.ConnectException;
import java.net.SocketAddress;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public abstract class TcpSession extends SimpleChannelInboundHandler<Packet> implements Session {
/**
Expand Down Expand Up @@ -283,22 +281,12 @@ public void send(Packet packet, Runnable onSent) {
}

@Override
public void disconnect(String reason) {
this.disconnect(Component.text(reason));
}

@Override
public void disconnect(String reason, Throwable cause) {
this.disconnect(Component.text(reason), cause);
}

@Override
public void disconnect(Component reason) {
public void disconnect(@NonNull Component reason) {
this.disconnect(reason, null);
}

@Override
public void disconnect(final Component reason, final Throwable cause) {
public void disconnect(@NonNull Component reason, Throwable cause) {
if (this.disconnected) {
return;
}
Expand All @@ -308,10 +296,9 @@ public void disconnect(final Component reason, final Throwable cause) {
if (this.channel != null && this.channel.isOpen()) {
this.callEvent(new DisconnectingEvent(this, reason, cause));
this.channel.flush().close().addListener(future ->
callEvent(new DisconnectedEvent(TcpSession.this,
reason != null ? reason : Component.text("Connection closed."), cause)));
callEvent(new DisconnectedEvent(TcpSession.this, reason, cause)));
} else {
this.callEvent(new DisconnectedEvent(this, reason != null ? reason : Component.text("Connection closed."), cause));
this.callEvent(new DisconnectedEvent(this, reason, cause));
}
}

Expand Down Expand Up @@ -339,7 +326,7 @@ public void flushSync() {
// daemon threads and their interaction with the runtime.
PACKET_EVENT_LOOP = new DefaultEventLoopGroup(new DefaultThreadFactory(this.getClass(), true));
Runtime.getRuntime().addShutdownHook(new Thread(
() -> PACKET_EVENT_LOOP.shutdownGracefully(SHUTDOWN_QUIET_PERIOD_MS, SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS)));
() -> PACKET_EVENT_LOOP.shutdownGracefully(SHUTDOWN_QUIET_PERIOD_MS, SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS)));
}
return PACKET_EVENT_LOOP.next();
}
Expand Down Expand Up @@ -403,21 +390,17 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception {
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (ctx.channel() == this.channel) {
this.disconnect("Connection closed.");
this.disconnect(Component.translatable("disconnect.endOfStream"));
}
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
String message;
if (cause instanceof ConnectTimeoutException || (cause instanceof ConnectException && cause.getMessage().contains("connection timed out"))) {
message = "Connection timed out.";
} else if (cause instanceof ReadTimeoutException) {
message = "Read timed out.";
} else if (cause instanceof WriteTimeoutException) {
message = "Write timed out.";
Component message;
if (cause instanceof TimeoutException) {
message = Component.translatable("disconnect.timeout");
} else {
message = cause.toString();
message = Component.translatable("disconnect.genericReason", "Internal Exception: " + cause);
}

this.disconnect(message, cause);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.github.steveice10.mc.auth.service.SessionService;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import net.kyori.adventure.text.Component;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.network.event.session.ConnectedEvent;
import org.geysermc.mcprotocollib.network.event.session.SessionAdapter;
Expand Down Expand Up @@ -77,16 +78,18 @@ public void packetReceived(Session session, Packet packet) {

SessionService sessionService = session.getFlag(MinecraftConstants.SESSION_SERVICE_KEY, new SessionService());
String serverId = sessionService.getServerId(helloPacket.getServerId(), helloPacket.getPublicKey(), key);

// TODO: Add disabled multiplayer and banned from playing online errors
try {
sessionService.joinServer(profile, accessToken, serverId);
} catch (ServiceUnavailableException e) {
session.disconnect("Login failed: Authentication service unavailable.", e);
session.disconnect(Component.translatable("disconnect.loginFailedInfo", Component.translatable("disconnect.loginFailedInfo.serversUnavailable")), e);
return;
} catch (InvalidCredentialsException e) {
session.disconnect("Login failed: Invalid login session.", e);
session.disconnect(Component.translatable("disconnect.loginFailedInfo", Component.translatable("disconnect.loginFailedInfo.invalidSession")), e);
return;
} catch (RequestException e) {
session.disconnect("Login failed: Authentication error: " + e.getMessage(), e);
session.disconnect(Component.translatable("disconnect.loginFailedInfo", e.getMessage()), e);
return;
}

Expand Down Expand Up @@ -120,7 +123,7 @@ public void packetReceived(Session session, Packet packet) {
handler.handle(session, time);
}

session.disconnect("Finished");
session.disconnect(Component.translatable("multiplayer.status.finished"));
}
} else if (protocol.getInboundState() == ProtocolState.GAME) {
if (packet instanceof ClientboundKeepAlivePacket keepAlivePacket && session.getFlag(MinecraftConstants.AUTOMATIC_KEEP_ALIVE_MANAGEMENT, true)) {
Expand All @@ -135,7 +138,7 @@ public void packetReceived(Session session, Packet packet) {
if (session.getFlag(MinecraftConstants.FOLLOW_TRANSFERS, true)) {
TcpClientSession newSession = new TcpClientSession(transferPacket.getHost(), transferPacket.getPort(), session.getPacketProtocol());
newSession.setFlags(session.getFlags());
session.disconnect("Transferring");
session.disconnect(Component.translatable("disconnect.transfer"));
newSession.connect(true, true);
}
}
Expand All @@ -152,7 +155,7 @@ public void packetReceived(Session session, Packet packet) {
if (session.getFlag(MinecraftConstants.FOLLOW_TRANSFERS, true)) {
TcpClientSession newSession = new TcpClientSession(transferPacket.getHost(), transferPacket.getPort(), session.getPacketProtocol());
newSession.setFlags(session.getFlags());
session.disconnect("Transferring");
session.disconnect(Component.translatable("disconnect.transfer"));
newSession.connect(true, true);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public void packetReceived(Session session, Packet packet) {
beginLogin(session, protocol, intentionPacket, true);
} else {
session.switchOutboundProtocol(() -> protocol.setOutboundState(ProtocolState.LOGIN));
session.disconnect("Server does not accept transfers.");
session.disconnect(Component.translatable("multiplayer.disconnect.transfers_disabled"));
}
}
case LOGIN -> {
Expand All @@ -129,9 +129,8 @@ public void packetReceived(Session session, Packet packet) {
} else if (packet instanceof ServerboundKeyPacket keyPacket) {
PrivateKey privateKey = KEY_PAIR.getPrivate();

if (!Arrays.equals(this.challenge, keyPacket.getEncryptedChallenge(privateKey))) {
session.disconnect("Invalid challenge!");
return;
if (!Arrays.equals(this.challenge, keyPacket.getDecryptedChallenge(privateKey))) {
throw new IllegalStateException("Protocol error");
}

SecretKey key = keyPacket.getSecretKey(privateKey);
Expand Down Expand Up @@ -178,6 +177,7 @@ public void packetReceived(Session session, Packet packet) {
session.send(new ClientboundStatusResponsePacket(info));
} else if (packet instanceof ServerboundPingRequestPacket pingRequestPacket) {
session.send(new ClientboundPongResponsePacket(pingRequestPacket.getPingTime()));
session.disconnect(Component.translatable("multiplayer.status.request_handled"));
}
} else if (protocol.getInboundState() == ProtocolState.GAME) {
if (packet instanceof ServerboundKeepAlivePacket keepAlivePacket) {
Expand Down Expand Up @@ -240,12 +240,12 @@ private void authenticate(Session session, SecretKey key) {
try {
profile = sessionService.getProfileByServer(username, sessionService.getServerId(SERVER_ID, KEY_PAIR.getPublic(), key));
} catch (RequestException e) {
session.disconnect("Failed to make session service request.", e);
session.disconnect(Component.translatable("multiplayer.disconnect.authservers_down"), e);
return;
}

if (profile == null) {
session.disconnect("Failed to verify username.");
session.disconnect(Component.translatable("multiplayer.disconnect.unverified_username"));
}
} else {
profile = new GameProfile(UUID.nameUUIDFromBytes(("OfflinePlayer:" + username).getBytes(StandardCharsets.UTF_8)), username);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,17 @@ public class ServerboundKeyPacket implements MinecraftPacket {
private final byte @NonNull [] sharedKey;
private final byte @NonNull [] encryptedChallenge;

public ServerboundKeyPacket(PublicKey publicKey, SecretKey secretKey, byte[] challenge) {
this.sharedKey = runEncryption(Cipher.ENCRYPT_MODE, publicKey, secretKey.getEncoded());
this.encryptedChallenge = runEncryption(Cipher.ENCRYPT_MODE, publicKey, challenge);
public ServerboundKeyPacket(PublicKey publicKey, SecretKey secretKey, byte[] encryptedChallenge) {
this.sharedKey = cipherData(Cipher.ENCRYPT_MODE, publicKey, secretKey.getEncoded());
this.encryptedChallenge = cipherData(Cipher.ENCRYPT_MODE, publicKey, encryptedChallenge);
}

public SecretKey getSecretKey(PrivateKey privateKey) {
return new SecretKeySpec(runEncryption(Cipher.DECRYPT_MODE, privateKey, this.sharedKey), "AES");
return new SecretKeySpec(cipherData(Cipher.DECRYPT_MODE, privateKey, this.sharedKey), "AES");
}

public byte[] getEncryptedChallenge(PrivateKey privateKey) {
return runEncryption(Cipher.DECRYPT_MODE, privateKey, this.encryptedChallenge);
public byte[] getDecryptedChallenge(PrivateKey privateKey) {
return cipherData(Cipher.DECRYPT_MODE, privateKey, this.encryptedChallenge);
}

public ServerboundKeyPacket(ByteBuf in, MinecraftCodecHelper helper) {
Expand All @@ -50,13 +50,13 @@ public boolean isPriority() {
return true;
}

private static byte[] runEncryption(int mode, Key key, byte[] data) {
private static byte[] cipherData(int mode, Key key, byte[] data) {
try {
Cipher cipher = Cipher.getInstance(key.getAlgorithm().equals("RSA") ? "RSA/ECB/PKCS1Padding" : "AES/CFB8/NoPadding");
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(mode, key);
return cipher.doFinal(data);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Failed to " + (mode == Cipher.DECRYPT_MODE ? "decrypt" : "encrypt") + " data.", e);
throw new IllegalStateException("Failed to cipher data.", e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public void testStatus() throws InterruptedException {
assertNotNull(handler.info, "Failed to get server info.");
assertEquals(SERVER_INFO, handler.info, "Received incorrect server info.");
} finally {
session.disconnect("Status test complete.");
session.disconnect(Component.text("Status test complete."));
}
}

Expand All @@ -95,7 +95,7 @@ public void testLogin() throws InterruptedException {
assertNotNull(listener.packet, "Failed to log in.");
assertEquals(JOIN_GAME_PACKET, listener.packet, "Received incorrect join packet.");
} finally {
session.disconnect("Login test complete.");
session.disconnect(Component.text("Login test complete."));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,6 @@ public void setup() {
@Test
public void testEncryptionResponsePacketGetters() {
assertEquals(this.secretKey, this.packet.getSecretKey(this.keyPair.getPrivate()), "Secret key does not match.");
assertArrayEquals(this.verifyToken, this.packet.getEncryptedChallenge(this.keyPair.getPrivate()), "Verify token does not match.");
assertArrayEquals(this.verifyToken, this.packet.getDecryptedChallenge(this.keyPair.getPrivate()), "Verify token does not match.");
}
}

0 comments on commit 9be5568

Please sign in to comment.