Refactored address handling to support unix socket files

This commit is contained in:
RaphiMC 2023-12-17 21:20:48 +01:00
parent 2b27f48c14
commit b24145f217
No known key found for this signature in database
GPG Key ID: 0F6BB0657A03AC94
20 changed files with 236 additions and 293 deletions

View File

@ -77,7 +77,7 @@ dependencies {
6. Have fun!
Here is an example command to allow players to join on yourserverip:25568 and connect to a beta 1.7.3 server running on port 25565:
``java -jar ViaProxy-whateverversion.jar --bind_port 25568 --target_ip 127.0.0.1 --target_port 25565 --version b1.7-b1.7.3``
``java -jar ViaProxy-whateverversion.jar --bind_address 0.0.0.0:25568 --target_ip 127.0.0.1:25565 --version b1.7-b1.7.3``
### Configuring the protocol translation
To change the protocol translation settings/features you can look into the ViaProtocolHack folder.

View File

@ -85,10 +85,10 @@ dependencies {
include "net.lenni0451.classtransform:additionalclassprovider:1.13.0-SNAPSHOT"
include "net.lenni0451:Reflect:1.3.1"
include "net.lenni0451:LambdaEvents:2.4.0"
include("net.lenni0451:MCPing:1.3.0") {
include("net.lenni0451:MCPing:1.4.0-SNAPSHOT") {
exclude group: "com.google.code.gson", module: "gson"
}
include("net.raphimc.netminecraft:all:2.3.8-SNAPSHOT") {
include("net.raphimc.netminecraft:all:2.4.0-SNAPSHOT") {
exclude group: "com.google.code.gson", module: "gson"
}
include("net.raphimc:MinecraftAuth:3.0.1-SNAPSHOT") {

View File

@ -4,4 +4,4 @@ org.gradle.configureondemand=true
maven_group=net.raphimc
maven_name=ViaProxy
maven_version=3.0.24-SNAPSHOT
maven_version=3.1.0-SNAPSHOT

View File

@ -44,7 +44,6 @@ import net.raphimc.viaproxy.plugins.events.Client2ProxyHandlerCreationEvent;
import net.raphimc.viaproxy.plugins.events.ProxyStartEvent;
import net.raphimc.viaproxy.plugins.events.ProxyStopEvent;
import net.raphimc.viaproxy.plugins.events.ViaProxyLoadedEvent;
import net.raphimc.viaproxy.proxy.EventListener;
import net.raphimc.viaproxy.proxy.client2proxy.Client2ProxyChannelInitializer;
import net.raphimc.viaproxy.proxy.client2proxy.Client2ProxyHandler;
import net.raphimc.viaproxy.proxy.session.ProxyConnection;
@ -139,7 +138,6 @@ public class ViaProxy {
SAVE_MANAGER = new SaveManager();
PLUGIN_MANAGER = new PluginManager();
EVENT_MANAGER.register(EventListener.class);
final Thread loaderThread = new Thread(new LoaderTask(), "ViaLoader");
final Thread updateCheckThread = new Thread(new UpdateCheckTask(hasUI), "UpdateCheck");
@ -191,8 +189,8 @@ public class ViaProxy {
Logger.LOGGER.info("Starting proxy server");
currentProxyServer = new NetServer(() -> EVENT_MANAGER.call(new Client2ProxyHandlerCreationEvent(new Client2ProxyHandler(), false)).getHandler(), Client2ProxyChannelInitializer::new);
EVENT_MANAGER.call(new ProxyStartEvent());
Logger.LOGGER.info("Binding proxy server to " + Options.BIND_ADDRESS + ":" + Options.BIND_PORT);
currentProxyServer.bind(Options.BIND_ADDRESS, Options.BIND_PORT, false);
Logger.LOGGER.info("Binding proxy server to " + Options.BIND_ADDRESS);
currentProxyServer.bind(Options.BIND_ADDRESS, false);
} catch (Throwable e) {
currentProxyServer = null;
throw e;

View File

@ -23,13 +23,14 @@ import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import net.raphimc.vialoader.util.VersionEnum;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.plugins.events.GetDefaultPortEvent;
import net.raphimc.viaproxy.plugins.events.PostOptionsParseEvent;
import net.raphimc.viaproxy.plugins.events.PreOptionsParseEvent;
import net.raphimc.viaproxy.saves.impl.accounts.Account;
import net.raphimc.viaproxy.util.AddressUtil;
import net.raphimc.viaproxy.util.logging.Logger;
import java.io.IOException;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
@ -38,10 +39,8 @@ import static java.util.Arrays.asList;
public class Options {
public static String BIND_ADDRESS = "0.0.0.0";
public static int BIND_PORT = 25568;
public static String CONNECT_ADDRESS;
public static int CONNECT_PORT = 25565;
public static SocketAddress BIND_ADDRESS;
public static SocketAddress CONNECT_ADDRESS;
public static VersionEnum PROTOCOL_VERSION;
public static boolean ONLINE_MODE;
public static boolean OPENAUTHMOD_AUTH;
@ -58,7 +57,7 @@ public class Options {
// CLI only config options
public static int COMPRESSION_THRESHOLD = 256;
public static boolean SRV_MODE; // Example: lenni0451.net_25565_1.8.x.viaproxy.127.0.0.1.nip.io
public static boolean INTERNAL_SRV_MODE; // Example: ip\7port\7version\7mppass
public static boolean INTERNAL_SRV_MODE; // Example: ip:port\7version\7mppass
public static String RESOURCE_PACK_URL; // Example: http://example.com/resourcepack.zip
public static boolean SERVER_HAPROXY_PROTOCOL;
public static boolean LEGACY_CLIENT_PASSTHROUGH;
@ -67,15 +66,13 @@ public class Options {
final OptionParser parser = new OptionParser();
final OptionSpec<Void> help = parser.acceptsAll(asList("help", "h", "?"), "Get a list of all arguments").forHelp();
final OptionSpec<String> bindAddress = parser.acceptsAll(asList("bind_address", "bind_ip", "ba"), "The address the proxy should bind to").withRequiredArg().ofType(String.class).defaultsTo(BIND_ADDRESS);
final OptionSpec<Integer> bindPort = parser.acceptsAll(asList("bind_port", "bp"), "The port the proxy should bind to").withRequiredArg().ofType(Integer.class).defaultsTo(BIND_PORT);
final OptionSpec<String> bindAddress = parser.acceptsAll(asList("bind_address", "bind_ip", "ba"), "The address the proxy should bind to").withRequiredArg().ofType(String.class).defaultsTo("0.0.0.0:25568");
final OptionSpec<String> connectAddress = parser.acceptsAll(asList("connect_address", "target_ip", "ca", "a"), "The address of the target server").withRequiredArg().ofType(String.class).required();
final OptionSpec<VersionEnum> version = parser.acceptsAll(asList("version", "v"), "The version of the target server").withRequiredArg().withValuesConvertedBy(new VersionEnumConverter()).required();
final OptionSpec<Void> srvMode = parser.acceptsAll(asList("srv_mode", "srv", "s"), "Enable srv mode");
final OptionSpec<Void> iSrvMode = parser.acceptsAll(asList("internal_srv_mode", "isrv"), "Enable internal srv mode").availableUnless(srvMode);
final OptionSpec<Void> proxyOnlineMode = parser.acceptsAll(asList("online_mode", "om", "o"), "Enable proxy online mode");
final OptionSpec<Integer> compressionThreshold = parser.acceptsAll(asList("compression_threshold", "ct", "c"), "The threshold for packet compression").withRequiredArg().ofType(Integer.class).defaultsTo(COMPRESSION_THRESHOLD);
final OptionSpec<String> connectAddress = parser.acceptsAll(asList("connect_address", "target_ip", "ca", "a"), "The address of the target server").withRequiredArg().ofType(String.class).required();
final OptionSpec<Integer> connectPort = parser.acceptsAll(asList("connect_port", "target_port", "cp", "p"), "The port of the target server").withRequiredArg().ofType(Integer.class);
final OptionSpec<VersionEnum> version = parser.acceptsAll(asList("version", "v"), "The version of the target server").withRequiredArg().withValuesConvertedBy(new VersionEnumConverter()).required();
final OptionSpec<Void> openAuthModAuth = parser.acceptsAll(asList("openauthmod_auth", "oam_auth"), "Use OpenAuthMod for joining online mode servers");
final OptionSpec<Integer> guiAccountIndex = parser.acceptsAll(asList("gui_account_index", "gui_account"), "Use an account from the ViaProxy GUI for joining online mode servers (Specify -1 for instructions)").withRequiredArg().ofType(Integer.class);
final OptionSpec<Void> betaCraftAuth = parser.accepts("betacraft_auth", "Use BetaCraft authentication for classic servers");
@ -96,18 +93,12 @@ public class Options {
System.exit(1);
}
BIND_ADDRESS = options.valueOf(bindAddress);
BIND_PORT = options.valueOf(bindPort);
PROTOCOL_VERSION = options.valueOf(version);
BIND_ADDRESS = AddressUtil.parse(options.valueOf(bindAddress), null);
CONNECT_ADDRESS = AddressUtil.parse(options.valueOf(connectAddress), PROTOCOL_VERSION);
SRV_MODE = options.has(srvMode);
INTERNAL_SRV_MODE = options.has(iSrvMode);
ONLINE_MODE = options.has(proxyOnlineMode);
CONNECT_ADDRESS = options.valueOf(connectAddress);
PROTOCOL_VERSION = options.valueOf(version);
if (options.has(connectPort)) {
CONNECT_PORT = options.valueOf(connectPort);
} else {
CONNECT_PORT = ViaProxy.EVENT_MANAGER.call(new GetDefaultPortEvent(PROTOCOL_VERSION, 25565)).getDefaultPort();
}
COMPRESSION_THRESHOLD = options.valueOf(compressionThreshold);
OPENAUTHMOD_AUTH = options.has(openAuthModAuth);
if (options.has(guiAccountIndex)) {

View File

@ -1,44 +0,0 @@
/*
* This file is part of ViaProxy - https://github.com/RaphiMC/ViaProxy
* Copyright (C) 2023 RK_01/RaphiMC and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.raphimc.viaproxy.plugins.events;
import net.raphimc.vialoader.util.VersionEnum;
public class GetDefaultPortEvent {
private final VersionEnum serverVersion;
private int defaultPort;
public GetDefaultPortEvent(final VersionEnum serverVersion, final int defaultPort) {
this.serverVersion = serverVersion;
this.defaultPort = defaultPort;
}
public VersionEnum getServerVersion() {
return this.serverVersion;
}
public int getDefaultPort() {
return this.defaultPort;
}
public void setDefaultPort(final int defaultPort) {
this.defaultPort = defaultPort;
}
}

View File

@ -18,34 +18,43 @@
package net.raphimc.viaproxy.plugins.events;
import io.netty.channel.Channel;
import net.raphimc.netminecraft.util.ServerAddress;
import net.raphimc.vialoader.util.VersionEnum;
import net.raphimc.viaproxy.plugins.events.types.EventCancellable;
import java.net.SocketAddress;
public class PreConnectEvent extends EventCancellable {
private final ServerAddress serverAddress;
private final VersionEnum serverVersion;
private SocketAddress serverAddress;
private VersionEnum serverVersion;
private final VersionEnum clientVersion;
private final Channel clientChannel;
private String cancelMessage = "§cCould not connect to the backend server! (Server is blacklisted)";
public PreConnectEvent(final ServerAddress serverAddress, final VersionEnum serverVersion, final VersionEnum clientVersion, final Channel clientChannel) {
public PreConnectEvent(final SocketAddress serverAddress, final VersionEnum serverVersion, final VersionEnum clientVersion, final Channel clientChannel) {
this.serverAddress = serverAddress;
this.serverVersion = serverVersion;
this.clientVersion = clientVersion;
this.clientChannel = clientChannel;
}
public ServerAddress getServerAddress() {
public SocketAddress getServerAddress() {
return this.serverAddress;
}
public void setServerAddress(final SocketAddress serverAddress) {
this.serverAddress = serverAddress;
}
public VersionEnum getServerVersion() {
return this.serverVersion;
}
public void setServerVersion(final VersionEnum serverVersion) {
this.serverVersion = serverVersion;
}
public VersionEnum getClientVersion() {
return this.clientVersion;
}

View File

@ -1,55 +0,0 @@
/*
* This file is part of ViaProxy - https://github.com/RaphiMC/ViaProxy
* Copyright (C) 2023 RK_01/RaphiMC and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.raphimc.viaproxy.plugins.events;
import net.raphimc.vialoader.util.VersionEnum;
import net.raphimc.viaproxy.plugins.events.types.EventCancellable;
public class ResolveSrvEvent extends EventCancellable {
private final VersionEnum serverVersion;
private String host;
private int port;
public ResolveSrvEvent(final VersionEnum serverVersion, final String host, final int port) {
this.serverVersion = serverVersion;
this.host = host;
this.port = port;
}
public VersionEnum getServerVersion() {
return this.serverVersion;
}
public String getHost() {
return this.host;
}
public void setHost(final String host) {
this.host = host;
}
public int getPort() {
return this.port;
}
public void setPort(final int port) {
this.port = port;
}
}

View File

@ -1,33 +0,0 @@
/*
* This file is part of ViaProxy - https://github.com/RaphiMC/ViaProxy
* Copyright (C) 2023 RK_01/RaphiMC and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.raphimc.viaproxy.proxy;
import net.lenni0451.lambdaevents.EventHandler;
import net.raphimc.vialoader.util.VersionEnum;
import net.raphimc.viaproxy.plugins.events.GetDefaultPortEvent;
public class EventListener {
@EventHandler
public static void onGetDefaultPort(final GetDefaultPortEvent event) {
if (event.getServerVersion().equals(VersionEnum.bedrockLatest)) {
event.setDefaultPort(19132);
}
}
}

View File

@ -26,12 +26,14 @@ import io.netty.channel.SimpleChannelInboundHandler;
import net.raphimc.netminecraft.constants.ConnectionState;
import net.raphimc.netminecraft.packet.IPacket;
import net.raphimc.netminecraft.packet.impl.handshake.C2SHandshakePacket;
import net.raphimc.netminecraft.util.ServerAddress;
import net.raphimc.vialoader.util.VersionEnum;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.cli.options.Options;
import net.raphimc.viaproxy.injection.VersionEnumExtension;
import net.raphimc.viaproxy.plugins.events.*;
import net.raphimc.viaproxy.plugins.events.ConnectEvent;
import net.raphimc.viaproxy.plugins.events.PreConnectEvent;
import net.raphimc.viaproxy.plugins.events.Proxy2ServerHandlerCreationEvent;
import net.raphimc.viaproxy.plugins.events.ProxySessionCreationEvent;
import net.raphimc.viaproxy.protocolhack.viaproxy.ViaBedrockTransferHolder;
import net.raphimc.viaproxy.proxy.packethandler.*;
import net.raphimc.viaproxy.proxy.proxy2server.Proxy2ServerChannelInitializer;
@ -41,12 +43,14 @@ import net.raphimc.viaproxy.proxy.session.DummyProxyConnection;
import net.raphimc.viaproxy.proxy.session.ProxyConnection;
import net.raphimc.viaproxy.proxy.session.UserOptions;
import net.raphimc.viaproxy.proxy.util.*;
import net.raphimc.viaproxy.util.AddressUtil;
import net.raphimc.viaproxy.util.ArrayHelper;
import net.raphimc.viaproxy.util.ProtocolVersionDetector;
import net.raphimc.viaproxy.util.logging.Logger;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.UnresolvedAddressException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@ -116,21 +120,19 @@ public class Client2ProxyHandler extends SimpleChannelInboundHandler<IPacket> {
final String[] handshakeParts = packet.address.split("\0");
String connectIP = Options.CONNECT_ADDRESS;
int connectPort = Options.CONNECT_PORT;
SocketAddress serverAddress = Options.CONNECT_ADDRESS;
VersionEnum serverVersion = Options.PROTOCOL_VERSION;
String classicMpPass = Options.CLASSIC_MP_PASS;
if (Options.INTERNAL_SRV_MODE) {
final ArrayHelper arrayHelper = ArrayHelper.instanceOf(handshakeParts[0].split("\7"));
connectIP = arrayHelper.get(0);
connectPort = arrayHelper.getInteger(1);
final String versionString = arrayHelper.get(2);
if (arrayHelper.isIndexValid(3)) {
classicMpPass = arrayHelper.getString(3);
}
final String versionString = arrayHelper.get(1);
serverVersion = VersionEnum.fromProtocolName(versionString);
if (serverVersion == VersionEnum.UNKNOWN) throw CloseAndReturn.INSTANCE;
serverAddress = AddressUtil.parse(arrayHelper.get(0), serverVersion);
if (arrayHelper.isIndexValid(2)) {
classicMpPass = arrayHelper.getString(2);
}
} else if (Options.SRV_MODE) {
try {
if (handshakeParts[0].toLowerCase().contains(".viaproxy.")) {
@ -142,48 +144,39 @@ public class Client2ProxyHandler extends SimpleChannelInboundHandler<IPacket> {
if (arrayHelper.getLength() < 3) {
throw CloseAndReturn.INSTANCE;
}
connectIP = arrayHelper.getAsString(0, arrayHelper.getLength() - 3, "_");
connectPort = arrayHelper.getInteger(arrayHelper.getLength() - 2);
final String versionString = arrayHelper.get(arrayHelper.getLength() - 1);
serverVersion = VersionEnum.fromProtocolName(versionString);
if (serverVersion == VersionEnum.UNKNOWN) {
serverVersion = VersionEnum.fromProtocolName(versionString.replace("-", " "));
}
if (serverVersion == VersionEnum.UNKNOWN) throw CloseAndReturn.INSTANCE;
final String connectIP = arrayHelper.getAsString(0, arrayHelper.getLength() - 3, "_");
final int connectPort = arrayHelper.getInteger(arrayHelper.getLength() - 2);
serverAddress = AddressUtil.parse(connectIP + ":" + connectPort, serverVersion);
} catch (CloseAndReturn e) {
this.proxyConnection.kickClient("§cWrong SRV syntax! §6Please use:\n§7ip_port_version.viaproxy.hostname");
}
}
if (serverVersion.equals(VersionEnum.bedrockLatest) && packet.intendedState == ConnectionState.LOGIN && ViaBedrockTransferHolder.hasTempRedirect(this.proxyConnection.getC2P())) {
final InetSocketAddress newAddress = ViaBedrockTransferHolder.removeTempRedirect(this.proxyConnection.getC2P());
connectIP = newAddress.getHostString();
connectPort = newAddress.getPort();
}
final ResolveSrvEvent resolveSrvEvent = ViaProxy.EVENT_MANAGER.call(new ResolveSrvEvent(serverVersion, connectIP, connectPort));
connectIP = resolveSrvEvent.getHost();
connectPort = resolveSrvEvent.getPort();
final ServerAddress serverAddress;
if (resolveSrvEvent.isCancelled() || serverVersion.isOlderThan(VersionEnum.r1_3_1tor1_3_2) || serverVersion.equals(VersionEnum.bedrockLatest)) {
serverAddress = new ServerAddress(connectIP, connectPort);
} else {
serverAddress = ServerAddress.fromSRV(connectIP + ":" + connectPort);
serverAddress = ViaBedrockTransferHolder.removeTempRedirect(this.proxyConnection.getC2P());
}
final PreConnectEvent preConnectEvent = new PreConnectEvent(serverAddress, serverVersion, clientVersion, this.proxyConnection.getC2P());
if (ViaProxy.EVENT_MANAGER.call(preConnectEvent).isCancelled()) {
this.proxyConnection.kickClient(preConnectEvent.getCancelMessage());
}
serverAddress = preConnectEvent.getServerAddress();
serverVersion = preConnectEvent.getServerVersion();
final UserOptions userOptions = new UserOptions(classicMpPass, Options.MC_ACCOUNT);
ChannelUtil.disableAutoRead(this.proxyConnection.getC2P());
if (packet.intendedState == ConnectionState.LOGIN && serverVersion.equals(VersionEnumExtension.AUTO_DETECT)) {
SocketAddress finalServerAddress = serverAddress;
CompletableFuture.runAsync(() -> {
final VersionEnum detectedVersion = ProtocolVersionDetector.get(serverAddress, clientVersion);
this.connect(serverAddress, detectedVersion, clientVersion, packet.intendedState, userOptions, handshakeParts);
final VersionEnum detectedVersion = ProtocolVersionDetector.get(finalServerAddress, clientVersion);
this.connect(finalServerAddress, detectedVersion, clientVersion, packet.intendedState, userOptions, handshakeParts);
}).exceptionally(t -> {
if (t instanceof ConnectException || t instanceof UnresolvedAddressException) {
this.proxyConnection.kickClient("§cCould not connect to the backend server!");
@ -197,7 +190,7 @@ public class Client2ProxyHandler extends SimpleChannelInboundHandler<IPacket> {
}
}
private void connect(final ServerAddress serverAddress, final VersionEnum serverVersion, final VersionEnum clientVersion, final ConnectionState intendedState, final UserOptions userOptions, final String[] handshakeParts) {
private void connect(final SocketAddress serverAddress, final VersionEnum serverVersion, final VersionEnum clientVersion, final ConnectionState intendedState, final UserOptions userOptions, final String[] handshakeParts) {
final Supplier<ChannelHandler> handlerSupplier = () -> ViaProxy.EVENT_MANAGER.call(new Proxy2ServerHandlerCreationEvent(new Proxy2ServerHandler(), false)).getHandler();
final ProxyConnection proxyConnection;
if (serverVersion.equals(VersionEnum.bedrockLatest)) {
@ -223,7 +216,7 @@ public class Client2ProxyHandler extends SimpleChannelInboundHandler<IPacket> {
this.proxyConnection.getPacketHandlers().add(new ResourcePackPacketHandler(this.proxyConnection));
this.proxyConnection.getPacketHandlers().add(new UnexpectedPacketHandler(this.proxyConnection));
Logger.u_info("connect", this.proxyConnection.getC2P().remoteAddress(), this.proxyConnection.getGameProfile(), "[" + clientVersion.getName() + " <-> " + serverVersion.getName() + "] Connecting to " + serverAddress.getAddress() + ":" + serverAddress.getPort());
Logger.u_info("connect", this.proxyConnection.getC2P().remoteAddress(), this.proxyConnection.getGameProfile(), "[" + clientVersion.getName() + " <-> " + serverVersion.getName() + "] Connecting to " + AddressUtil.toString(serverAddress));
ViaProxy.EVENT_MANAGER.call(new ConnectEvent(this.proxyConnection));
this.proxyConnection.connectToServer(serverAddress, serverVersion).addListeners((ThrowingChannelFutureListener) f -> {
@ -233,8 +226,18 @@ public class Client2ProxyHandler extends SimpleChannelInboundHandler<IPacket> {
this.proxyConnection.getChannel().writeAndFlush(HAProxyUtil.createMessage(this.proxyConnection.getC2P(), this.proxyConnection.getChannel(), clientVersion)).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
handshakeParts[0] = serverAddress.getAddress();
final C2SHandshakePacket newHandshakePacket = new C2SHandshakePacket(clientVersion.getOriginalVersion(), String.join("\0", handshakeParts), serverAddress.getPort(), intendedState);
final String address;
final int port;
if (serverAddress instanceof InetSocketAddress inetSocketAddress) {
address = inetSocketAddress.getHostString();
port = inetSocketAddress.getPort();
} else {
address = AddressUtil.toString(serverAddress);
port = 25565;
}
handshakeParts[0] = address;
final C2SHandshakePacket newHandshakePacket = new C2SHandshakePacket(clientVersion.getOriginalVersion(), String.join("\0", handshakeParts), port, intendedState);
this.proxyConnection.getChannel().writeAndFlush(newHandshakePacket).addListeners(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE, (ChannelFutureListener) f2 -> {
if (f2.isSuccess()) {
this.proxyConnection.setP2sConnectionState(intendedState);

View File

@ -19,13 +19,10 @@ package net.raphimc.viaproxy.proxy.client2proxy.passthrough;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import net.raphimc.netminecraft.util.ServerAddress;
import net.raphimc.vialoader.util.VersionEnum;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.cli.options.Options;
import net.raphimc.viaproxy.plugins.events.Proxy2ServerHandlerCreationEvent;
import net.raphimc.viaproxy.plugins.events.ProxySessionCreationEvent;
import net.raphimc.viaproxy.plugins.events.ResolveSrvEvent;
import net.raphimc.viaproxy.proxy.proxy2server.passthrough.PassthroughProxy2ServerChannelInitializer;
import net.raphimc.viaproxy.proxy.proxy2server.passthrough.PassthroughProxy2ServerHandler;
import net.raphimc.viaproxy.proxy.session.LegacyProxyConnection;
@ -33,8 +30,10 @@ import net.raphimc.viaproxy.proxy.util.ChannelUtil;
import net.raphimc.viaproxy.proxy.util.ExceptionUtil;
import net.raphimc.viaproxy.proxy.util.HAProxyUtil;
import net.raphimc.viaproxy.proxy.util.ThrowingChannelFutureListener;
import net.raphimc.viaproxy.util.AddressUtil;
import net.raphimc.viaproxy.util.logging.Logger;
import java.net.SocketAddress;
import java.util.function.Supplier;
public class PassthroughClient2ProxyHandler extends SimpleChannelInboundHandler<ByteBuf> {
@ -79,22 +78,10 @@ public class PassthroughClient2ProxyHandler extends SimpleChannelInboundHandler<
this.proxyConnection = ViaProxy.EVENT_MANAGER.call(new ProxySessionCreationEvent<>(proxyConnection, true)).getProxySession();
this.proxyConnection.getC2P().attr(LegacyProxyConnection.LEGACY_PROXY_CONNECTION_ATTRIBUTE_KEY).set(this.proxyConnection);
final ServerAddress unresolvedAddress = this.getServerAddress();
final VersionEnum serverVersion = Options.PROTOCOL_VERSION;
final ResolveSrvEvent resolveSrvEvent = ViaProxy.EVENT_MANAGER.call(new ResolveSrvEvent(serverVersion, unresolvedAddress.getAddress(), unresolvedAddress.getPort()));
final String connectIP = resolveSrvEvent.getHost();
final int connectPort = resolveSrvEvent.getPort();
final ServerAddress serverAddress;
if (resolveSrvEvent.isCancelled() || serverVersion.isOlderThan(VersionEnum.r1_3_1tor1_3_2) || serverVersion.equals(VersionEnum.bedrockLatest)) {
serverAddress = new ServerAddress(connectIP, connectPort);
} else {
serverAddress = ServerAddress.fromSRV(connectIP + ":" + connectPort);
}
final SocketAddress serverAddress = this.getServerAddress();
ChannelUtil.disableAutoRead(this.proxyConnection.getC2P());
Logger.u_info("connect", this.proxyConnection.getC2P().remoteAddress(), null, "[Legacy <-> Legacy] Connecting to " + serverAddress.getAddress() + ":" + serverAddress.getPort());
Logger.u_info("connect", this.proxyConnection.getC2P().remoteAddress(), null, "[Legacy <-> Legacy] Connecting to " + AddressUtil.toString(serverAddress));
this.proxyConnection.connect(serverAddress).addListeners((ThrowingChannelFutureListener) f -> {
if (f.isSuccess()) {
@ -115,8 +102,8 @@ public class PassthroughClient2ProxyHandler extends SimpleChannelInboundHandler<
});
}
protected ServerAddress getServerAddress() {
return new ServerAddress(Options.CONNECT_ADDRESS, Options.CONNECT_PORT);
protected SocketAddress getServerAddress() {
return Options.CONNECT_ADDRESS;
}
}

View File

@ -19,14 +19,11 @@ package net.raphimc.viaproxy.proxy.session;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollDatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.DatagramChannel;
import net.lenni0451.reflect.stream.RStream;
import net.raphimc.netminecraft.constants.ConnectionState;
import net.raphimc.netminecraft.constants.MCPipeline;
import net.raphimc.netminecraft.util.LazyLoadBase;
import net.raphimc.netminecraft.util.ServerAddress;
import net.raphimc.netminecraft.util.ChannelType;
import net.raphimc.viabedrock.protocol.data.ProtocolConstants;
import net.raphimc.vialoader.netty.VLPipeline;
import net.raphimc.vialoader.netty.viabedrock.PingEncapsulationCodec;
@ -35,6 +32,7 @@ import org.cloudburstmc.netty.channel.raknet.RakChannelFactory;
import org.cloudburstmc.netty.channel.raknet.config.RakChannelOption;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.function.Supplier;
@ -46,18 +44,15 @@ public class BedrockProxyConnection extends ProxyConnection {
}
@Override
public void initialize(Bootstrap bootstrap) {
if (Epoll.isAvailable()) {
bootstrap
.group(LazyLoadBase.CLIENT_EPOLL_EVENTLOOP.getValue())
.channelFactory(RakChannelFactory.client(EpollDatagramChannel.class));
} else {
bootstrap
.group(LazyLoadBase.CLIENT_NIO_EVENTLOOP.getValue())
.channelFactory(RakChannelFactory.client(NioDatagramChannel.class));
public void initialize(final ChannelType channelType, final Bootstrap bootstrap) {
if (!DatagramChannel.class.isAssignableFrom(channelType.udpClientChannelClass())) {
throw new IllegalArgumentException("Channel type must be a DatagramChannel");
}
final Class<? extends DatagramChannel> channelClass = (Class<? extends DatagramChannel>) channelType.udpClientChannelClass();
bootstrap
.group(channelType.clientEventLoopGroup().get())
.channelFactory(RakChannelFactory.client(channelClass))
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4_000)
.option(ChannelOption.IP_TOS, 0x18)
.option(RakChannelOption.RAK_PROTOCOL_VERSION, ProtocolConstants.BEDROCK_RAKNET_PROTOCOL_VERSION)
@ -71,7 +66,11 @@ public class BedrockProxyConnection extends ProxyConnection {
}
@Override
public ChannelFuture connectToServer(ServerAddress serverAddress, VersionEnum targetVersion) {
public ChannelFuture connectToServer(final SocketAddress serverAddress, final VersionEnum targetVersion) {
if (!(serverAddress instanceof InetSocketAddress)) {
throw new IllegalArgumentException("Server address must be an InetSocketAddress");
}
if (this.getC2pConnectionState() == ConnectionState.STATUS) {
RStream.of(this).withSuper().fields().by("serverAddress").set(serverAddress);
RStream.of(this).withSuper().fields().by("serverVersion").set(targetVersion);
@ -81,11 +80,11 @@ public class BedrockProxyConnection extends ProxyConnection {
}
}
private ChannelFuture ping(final ServerAddress serverAddress) {
if (this.channelFuture == null) this.initialize(new Bootstrap());
private ChannelFuture ping(final SocketAddress address) {
if (this.channelFuture == null) this.initialize(ChannelType.get(address), new Bootstrap());
this.channelFuture.channel().eventLoop().submit(() -> {
this.getChannel().pipeline().replace(VLPipeline.VIABEDROCK_FRAME_ENCAPSULATION_HANDLER_NAME, "ping_encapsulation", new PingEncapsulationCodec(serverAddress.toSocketAddress()));
this.getChannel().pipeline().replace(VLPipeline.VIABEDROCK_FRAME_ENCAPSULATION_HANDLER_NAME, "ping_encapsulation", new PingEncapsulationCodec(((InetSocketAddress) address)));
this.getChannel().pipeline().remove(VLPipeline.VIABEDROCK_PACKET_ENCAPSULATION_HANDLER_NAME);
this.getChannel().pipeline().remove(MCPipeline.SIZER_HANDLER_NAME);
});

View File

@ -25,9 +25,10 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import net.raphimc.netminecraft.constants.ConnectionState;
import net.raphimc.netminecraft.packet.impl.login.C2SLoginHelloPacket1_7;
import net.raphimc.netminecraft.util.ServerAddress;
import net.raphimc.netminecraft.util.ChannelType;
import net.raphimc.vialoader.util.VersionEnum;
import java.net.SocketAddress;
import java.security.Key;
import java.util.concurrent.CompletableFuture;
@ -38,17 +39,17 @@ public class DummyProxyConnection extends ProxyConnection {
}
@Override
public void initialize(Bootstrap bootstrap) {
public void initialize(ChannelType channelType, Bootstrap bootstrap) {
throw new UnsupportedOperationException();
}
@Override
public ChannelFuture connectToServer(ServerAddress serverAddress, VersionEnum targetVersion) {
public ChannelFuture connectToServer(SocketAddress serverAddress, VersionEnum targetVersion) {
throw new UnsupportedOperationException();
}
@Override
public ServerAddress getServerAddress() {
public SocketAddress getServerAddress() {
throw new UnsupportedOperationException();
}

View File

@ -21,8 +21,9 @@ import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.util.AttributeKey;
import net.raphimc.netminecraft.netty.connection.NetClient;
import net.raphimc.netminecraft.util.ServerAddress;
import net.raphimc.netminecraft.util.ChannelType;
import java.net.SocketAddress;
import java.util.function.Function;
import java.util.function.Supplier;
@ -31,7 +32,7 @@ public class LegacyProxyConnection extends NetClient {
public static final AttributeKey<LegacyProxyConnection> LEGACY_PROXY_CONNECTION_ATTRIBUTE_KEY = AttributeKey.valueOf("legacy_proxy_connection");
private final Channel c2p;
private ServerAddress serverAddress;
private SocketAddress serverAddress;
public LegacyProxyConnection(final Supplier<ChannelHandler> handlerSupplier, final Function<Supplier<ChannelHandler>, ChannelInitializer<Channel>> channelInitializerSupplier, final Channel c2p) {
super(handlerSupplier, channelInitializerSupplier);
@ -43,14 +44,14 @@ public class LegacyProxyConnection extends NetClient {
}
@Override
public void initialize(final Bootstrap bootstrap) {
public void initialize(final ChannelType channelType, final Bootstrap bootstrap) {
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4_000);
bootstrap.attr(LEGACY_PROXY_CONNECTION_ATTRIBUTE_KEY, this);
super.initialize(bootstrap);
super.initialize(channelType, bootstrap);
}
@Override
public ChannelFuture connect(final ServerAddress serverAddress) {
public ChannelFuture connect(final SocketAddress serverAddress) {
this.serverAddress = serverAddress;
return super.connect(serverAddress);
}
@ -59,7 +60,7 @@ public class LegacyProxyConnection extends NetClient {
return this.c2p;
}
public ServerAddress getServerAddress() {
public SocketAddress getServerAddress() {
return this.serverAddress;
}

View File

@ -41,7 +41,7 @@ import net.raphimc.netminecraft.packet.impl.login.S2CLoginCustomPayloadPacket;
import net.raphimc.netminecraft.packet.impl.login.S2CLoginDisconnectPacket1_20_3;
import net.raphimc.netminecraft.packet.impl.status.S2CStatusResponsePacket;
import net.raphimc.netminecraft.packet.registry.PacketRegistryUtil;
import net.raphimc.netminecraft.util.ServerAddress;
import net.raphimc.netminecraft.util.ChannelType;
import net.raphimc.vialoader.util.VersionEnum;
import net.raphimc.viaproxy.cli.ConsoleFormatter;
import net.raphimc.viaproxy.proxy.external_interface.OpenAuthModConstants;
@ -49,6 +49,7 @@ import net.raphimc.viaproxy.proxy.packethandler.PacketHandler;
import net.raphimc.viaproxy.proxy.util.CloseAndReturn;
import net.raphimc.viaproxy.util.logging.Logger;
import java.net.SocketAddress;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.util.ArrayList;
@ -71,7 +72,7 @@ public class ProxyConnection extends NetClient {
private final AtomicInteger customPayloadId = new AtomicInteger(0);
private final Map<Integer, CompletableFuture<ByteBuf>> customPayloadListener = new ConcurrentHashMap<>();
private ServerAddress serverAddress;
private SocketAddress serverAddress;
private VersionEnum serverVersion;
private VersionEnum clientVersion;
@ -101,18 +102,18 @@ public class ProxyConnection extends NetClient {
@Override
@Deprecated
public ChannelFuture connect(final ServerAddress serverAddress) {
public ChannelFuture connect(final SocketAddress address) {
throw new UnsupportedOperationException();
}
@Override
public void initialize(final Bootstrap bootstrap) {
public void initialize(final ChannelType channelType, final Bootstrap bootstrap) {
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4_000);
bootstrap.attr(PROXY_CONNECTION_ATTRIBUTE_KEY, this);
super.initialize(bootstrap);
super.initialize(channelType, bootstrap);
}
public ChannelFuture connectToServer(final ServerAddress serverAddress, final VersionEnum targetVersion) {
public ChannelFuture connectToServer(final SocketAddress serverAddress, final VersionEnum targetVersion) {
this.serverAddress = serverAddress;
this.serverVersion = targetVersion;
return super.connect(serverAddress);
@ -126,7 +127,7 @@ public class ProxyConnection extends NetClient {
return this.packetHandlers;
}
public ServerAddress getServerAddress() {
public SocketAddress getServerAddress() {
return this.serverAddress;
}

View File

@ -19,6 +19,7 @@ package net.raphimc.viaproxy.proxy.util;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.unix.DomainSocketAddress;
import io.netty.handler.codec.haproxy.*;
import net.raphimc.vialoader.util.VersionEnum;
@ -29,40 +30,35 @@ import java.util.List;
public class HAProxyUtil {
public static HAProxyMessage createMessage(final Channel sourceChannel, final Channel targetChannel, final VersionEnum clientVersion) {
final InetSocketAddress sourceAddress = (InetSocketAddress) sourceChannel.remoteAddress();
final InetSocketAddress targetAddress = (InetSocketAddress) targetChannel.remoteAddress();
final HAProxyProxiedProtocol protocol = sourceAddress.getAddress() instanceof Inet4Address ? HAProxyProxiedProtocol.TCP4 : HAProxyProxiedProtocol.TCP6;
final List<HAProxyTLV> tlvs = new ArrayList<>();
if (clientVersion != null) {
tlvs.add(new HAProxyTLV((byte) 0xE0, Unpooled.buffer().writeInt(clientVersion.getOriginalVersion())));
}
if (sourceChannel.remoteAddress() instanceof InetSocketAddress sourceAddress && targetChannel.remoteAddress() instanceof InetSocketAddress targetAddress) {
final HAProxyProxiedProtocol protocol = sourceAddress.getAddress() instanceof Inet4Address ? HAProxyProxiedProtocol.TCP4 : HAProxyProxiedProtocol.TCP6;
final String sourceAddressString = sourceAddress.getAddress().getHostAddress();
final String targetAddressString = protocol.addressFamily().equals(HAProxyProxiedProtocol.AddressFamily.AF_IPv6) ? getIPv6Address(targetAddress.getHostString()).getHostAddress() : getIPv4Address(targetAddress.getHostString()).getHostAddress();
final String targetAddressString;
if (protocol.addressFamily().equals(HAProxyProxiedProtocol.AddressFamily.AF_IPv4)) {
targetAddressString = getInetAddress(targetAddress.getHostString(), Inet4Address.class).getHostAddress();
} else {
targetAddressString = getInetAddress(targetAddress.getHostString(), Inet6Address.class).getHostAddress();
}
return new HAProxyMessage(HAProxyProtocolVersion.V2, HAProxyCommand.PROXY, protocol, sourceAddressString, targetAddressString, sourceAddress.getPort(), targetAddress.getPort(), tlvs);
} else if (targetChannel.remoteAddress() instanceof DomainSocketAddress targetAddress) {
return new HAProxyMessage(HAProxyProtocolVersion.V2, HAProxyCommand.PROXY, HAProxyProxiedProtocol.UNIX_STREAM, "", targetAddress.path(), 0, 0, tlvs);
} else {
throw new IllegalArgumentException("Unsupported address type: " + targetChannel.remoteAddress().getClass().getName());
}
}
private static Inet6Address getIPv6Address(final String host) {
private static <T extends InetAddress> T getInetAddress(final String host, final Class<T> addressClass) {
try {
final InetAddress[] addresses = InetAddress.getAllByName(host);
for (InetAddress addr : addresses) {
if (addr instanceof Inet6Address) {
return (Inet6Address) addr;
}
}
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
return null;
}
private static Inet4Address getIPv4Address(final String host) {
try {
final InetAddress[] addresses = InetAddress.getAllByName(host);
for (InetAddress addr : addresses) {
if (addr instanceof Inet4Address) {
return (Inet4Address) addr;
if (addressClass.isInstance(addr)) {
return (T) addr;
}
}
} catch (UnknownHostException e) {

View File

@ -17,12 +17,10 @@
*/
package net.raphimc.viaproxy.ui.impl;
import com.google.common.net.HostAndPort;
import net.lenni0451.lambdaevents.EventHandler;
import net.raphimc.vialoader.util.VersionEnum;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.cli.options.Options;
import net.raphimc.viaproxy.plugins.events.GetDefaultPortEvent;
import net.raphimc.viaproxy.saves.impl.UISave;
import net.raphimc.viaproxy.saves.impl.accounts.OfflineAccount;
import net.raphimc.viaproxy.ui.AUITab;
@ -30,6 +28,7 @@ import net.raphimc.viaproxy.ui.I18n;
import net.raphimc.viaproxy.ui.ViaProxyUI;
import net.raphimc.viaproxy.ui.events.UICloseEvent;
import net.raphimc.viaproxy.ui.events.UIInitEvent;
import net.raphimc.viaproxy.util.AddressUtil;
import net.raphimc.viaproxy.util.GBC;
import net.raphimc.viaproxy.util.logging.Logger;
@ -39,6 +38,7 @@ import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
@ -258,16 +258,22 @@ public class GeneralTab extends AUITab {
try {
if (serverAddress.startsWith("mc://")) { // ClassiCube Direct URL
final URI uri = new URI(serverAddress);
serverAddress = uri.getHost() + ":" + uri.getPort();
final String[] path = uri.getPath().substring(1).split("/");
if (path.length < 2) {
throw new IllegalArgumentException(I18n.get("tab.general.error.invalid_classicube_url"));
}
Options.CONNECT_ADDRESS = new InetSocketAddress(uri.getHost(), uri.getPort());
Options.MC_ACCOUNT = new OfflineAccount(path[0]);
Options.CLASSIC_MP_PASS = path[1];
} else { // Normal address
} else {
try {
Options.CONNECT_ADDRESS = AddressUtil.parse(serverAddress, serverVersion);
} catch (Throwable t) {
throw new IllegalArgumentException(I18n.get("tab.general.error.invalid_server_address"));
}
if (authMethod != 0) {
Options.MC_ACCOUNT = null;
} else if (Options.MC_ACCOUNT == null) {
@ -276,15 +282,7 @@ public class GeneralTab extends AUITab {
Options.CLASSIC_MP_PASS = null;
}
try {
HostAndPort hostAndPort = HostAndPort.fromString(serverAddress);
Options.CONNECT_ADDRESS = hostAndPort.getHost();
Options.CONNECT_PORT = hostAndPort.getPortOrDefault(ViaProxy.EVENT_MANAGER.call(new GetDefaultPortEvent(serverVersion, 25565)).getDefaultPort());
} catch (Throwable t) {
throw new IllegalArgumentException(I18n.get("tab.general.error.invalid_server_address"));
}
Options.BIND_PORT = bindPort;
Options.BIND_ADDRESS = new InetSocketAddress("0.0.0.0", bindPort);
Options.ONLINE_MODE = proxyOnlineMode;
Options.PROTOCOL_VERSION = serverVersion;
Options.BETACRAFT_AUTH = betaCraftAuth;

View File

@ -0,0 +1,88 @@
/*
* This file is part of ViaProxy - https://github.com/RaphiMC/ViaProxy
* Copyright (C) 2023 RK_01/RaphiMC and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.raphimc.viaproxy.util;
import com.google.common.net.HostAndPort;
import io.netty.channel.unix.DomainSocketAddress;
import net.raphimc.netminecraft.util.MinecraftServerAddress;
import net.raphimc.vialoader.util.VersionEnum;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnixDomainSocketAddress;
public class AddressUtil {
public static SocketAddress parse(final String serverAddress, final VersionEnum version) {
if (serverAddress.startsWith("file:///") || serverAddress.startsWith("unix:///")) { // Unix Socket
final String filePath = serverAddress.substring(7);
return new DomainSocketAddress(filePath);
} else { // IP Address
final HostAndPort hostAndPort = HostAndPort.fromString(serverAddress);
final int port;
if (version != null) {
port = hostAndPort.getPortOrDefault(getDefaultPort(version));
} else {
port = hostAndPort.getPort();
}
if (version == null || version.isOlderThan(VersionEnum.r1_3_1tor1_3_2) || version.equals(VersionEnum.bedrockLatest)) {
return new InetSocketAddress(hostAndPort.getHost(), port);
} else {
return MinecraftServerAddress.ofResolved(hostAndPort.getHost(), port);
}
}
}
public static String toString(final SocketAddress address) {
if (address instanceof InetSocketAddress inetSocketAddress) {
return inetSocketAddress.getHostString() + ":" + inetSocketAddress.getPort();
} else if (address instanceof DomainSocketAddress domainSocketAddress) {
return domainSocketAddress.path();
} else {
return address.toString();
}
}
public static int getDefaultPort(final VersionEnum version) {
if (VersionEnum.bedrockLatest.equals(version)) {
return 19132;
}
return 25565;
}
/**
* Converts the netty domain socket address to a Java 16 unix domain socket address if possible
*
* @param address The netty domain socket address
* @return The Java 16 unix domain socket address or the original address if it is not a domain socket address
*/
public static SocketAddress toJ16UnixSocketAddress(final SocketAddress address) {
try {
if (address instanceof DomainSocketAddress domainSocketAddress) {
return UnixDomainSocketAddress.of(domainSocketAddress.path());
}
} catch (Throwable ignored) {
}
return address;
}
}

View File

@ -19,18 +19,21 @@ package net.raphimc.viaproxy.util;
import com.viaversion.viaversion.api.protocol.version.ProtocolVersion;
import net.lenni0451.mcping.MCPing;
import net.lenni0451.mcping.pings.sockets.impl.factories.SocketChannelSocketFactory;
import net.lenni0451.mcping.responses.MCPingResponse;
import net.raphimc.netminecraft.util.ServerAddress;
import net.raphimc.vialoader.util.VersionEnum;
import java.net.SocketAddress;
public class ProtocolVersionDetector {
private static final int TIMEOUT = 3000;
public static VersionEnum get(final ServerAddress serverAddress, final VersionEnum clientVersion) {
public static VersionEnum get(final SocketAddress serverAddress, final VersionEnum clientVersion) {
MCPingResponse response = MCPing
.pingModern(clientVersion.getOriginalVersion())
.address(serverAddress.getAddress(), serverAddress.getPort())
.tcpSocketFactory(new SocketChannelSocketFactory())
.address(AddressUtil.toJ16UnixSocketAddress(serverAddress))
.noResolve()
.timeout(TIMEOUT, TIMEOUT)
.getSync();
@ -40,7 +43,8 @@ public class ProtocolVersionDetector {
} else { // Else ping again with protocol id -1 to get the protocol id of the server
response = MCPing
.pingModern(-1)
.address(serverAddress.getAddress(), serverAddress.getPort())
.tcpSocketFactory(new SocketChannelSocketFactory())
.address(AddressUtil.toJ16UnixSocketAddress(serverAddress))
.noResolve()
.timeout(TIMEOUT, TIMEOUT)
.getSync();

View File

@ -19,12 +19,12 @@ package net.raphimc.viaproxy.util.logging;
import com.mojang.authlib.GameProfile;
import com.viaversion.viaversion.api.connection.UserConnection;
import net.raphimc.viaproxy.util.AddressUtil;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.fusesource.jansi.AnsiConsole;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Locale;
@ -60,8 +60,7 @@ public class Logger {
}
public static void u_log(final Level level, final String title, final SocketAddress address, final GameProfile gameProfile, final String msg) {
final InetSocketAddress socketAddress = (InetSocketAddress) address;
LOGGER.log(level, "[" + title.toUpperCase(Locale.ROOT) + "] (" + socketAddress.getAddress().getHostAddress() + " | " + (gameProfile != null ? gameProfile.getName() : "null") + ") " + msg);
LOGGER.log(level, "[" + title.toUpperCase(Locale.ROOT) + "] (" + AddressUtil.toString(address) + " | " + (gameProfile != null ? gameProfile.getName() : "null") + ") " + msg);
}
}