Skip to content

Commit

Permalink
Structural refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
RaphiMC committed Nov 2, 2023
1 parent f974056 commit ac5fe12
Show file tree
Hide file tree
Showing 24 changed files with 173 additions and 149 deletions.
56 changes: 42 additions & 14 deletions src/main/java/net/raphimc/viaproxy/ViaProxy.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,11 @@
import net.lenni0451.classtransform.utils.loader.EnumLoaderPriority;
import net.lenni0451.classtransform.utils.loader.InjectionClassLoader;
import net.lenni0451.classtransform.utils.tree.IClassProvider;
import net.lenni0451.lambdaevents.LambdaManager;
import net.lenni0451.lambdaevents.generator.LambdaMetaFactoryGenerator;
import net.lenni0451.reflect.Agents;
import net.lenni0451.reflect.ClassLoaders;
import net.lenni0451.reflect.JavaBypass;
import net.lenni0451.reflect.Methods;
import net.raphimc.netminecraft.constants.MCPipeline;
import net.raphimc.netminecraft.netty.connection.NetServer;
Expand Down Expand Up @@ -61,11 +64,14 @@ public class ViaProxy {
public static final String VERSION = "${version}";
public static final String IMPL_VERSION = "${impl_version}";

public static final LambdaManager EVENT_MANAGER = LambdaManager.threadSafe(new LambdaMetaFactoryGenerator(JavaBypass.TRUSTED_LOOKUP));
private static /*final*/ SaveManager SAVE_MANAGER;
private static /*final*/ PluginManager PLUGIN_MANAGER;
private static /*final*/ ChannelGroup CLIENT_CHANNELS;

private static Instrumentation instrumentation;
public static SaveManager saveManager;
public static NetServer currentProxyServer;
public static ChannelGroup c2pChannels;
public static ViaProxyUI ui;
private static NetServer currentProxyServer;
private static ViaProxyUI ui;

public static void agentmain(final String args, final Instrumentation instrumentation) {
ViaProxy.instrumentation = instrumentation;
Expand Down Expand Up @@ -96,8 +102,8 @@ public static void main(String[] args) throws Throwable {

public static void injectedMain(final String injectionMethod, final String[] args) throws InterruptedException, IOException {
Logger.setup();

final boolean hasUI = args.length == 0 && !GraphicsEnvironment.isHeadless();
ConsoleHandler.hookConsole();
Logger.LOGGER.info("Initializing ViaProxy {} v{} ({}) (Injected using {})...", hasUI ? "GUI" : "CLI", VERSION, IMPL_VERSION, injectionMethod);
Logger.LOGGER.info("Using java version: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ") on " + System.getProperty("os.name"));
Logger.LOGGER.info("Available memory (bytes): " + Runtime.getRuntime().maxMemory());
Expand Down Expand Up @@ -125,11 +131,13 @@ public static void injectedMain(final String injectionMethod, final String[] arg
}
}

ConsoleHandler.hookConsole();
ClassLoaderPriorityUtil.loadOverridingJars();
loadNetty();
saveManager = new SaveManager();
PluginManager.loadPlugins();
PluginManager.EVENT_MANAGER.register(EventListener.class);

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");
Expand All @@ -152,7 +160,7 @@ public static void injectedMain(final String injectionMethod, final String[] arg
Logger.LOGGER.info("Waiting for UI to be initialized...");
Thread.sleep(1000);
}
ViaProxyUI.EVENT_MANAGER.call(new UIInitEvent());
ui.eventManager.call(new UIInitEvent());
Logger.LOGGER.info("ViaProxy started successfully!");
} else {
Options.parse(args);
Expand All @@ -177,8 +185,8 @@ public static void startProxy() {
}
try {
Logger.LOGGER.info("Starting proxy server");
currentProxyServer = new NetServer(() -> PluginManager.EVENT_MANAGER.call(new Client2ProxyHandlerCreationEvent(new Client2ProxyHandler(), false)).getHandler(), Client2ProxyChannelInitializer::new);
PluginManager.EVENT_MANAGER.call(new ProxyStartEvent());
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);
} catch (Throwable e) {
Expand All @@ -190,12 +198,12 @@ public static void startProxy() {
public static void stopProxy() {
if (currentProxyServer != null) {
Logger.LOGGER.info("Stopping proxy server");
PluginManager.EVENT_MANAGER.call(new ProxyStopEvent());
EVENT_MANAGER.call(new ProxyStopEvent());

currentProxyServer.getChannel().close();
currentProxyServer = null;

for (Channel channel : c2pChannels) {
for (Channel channel : CLIENT_CHANNELS) {
try {
ProxyConnection.fromChannel(channel).kickClient("§cViaProxy has been stopped");
} catch (Throwable ignored) {
Expand All @@ -210,7 +218,27 @@ private static void loadNetty() {
System.setProperty("io.netty.allocator.maxOrder", "9");
}
MCPipeline.useOptimizedPipeline();
c2pChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
CLIENT_CHANNELS = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}

public static SaveManager getSaveManager() {
return SAVE_MANAGER;
}

public static PluginManager getPluginManager() {
return PLUGIN_MANAGER;
}

public static ChannelGroup getConnectedClients() {
return CLIENT_CHANNELS;
}

public static NetServer getCurrentProxyServer() {
return currentProxyServer;
}

public static ViaProxyUI getUI() {
return ui;
}

}
4 changes: 2 additions & 2 deletions src/main/java/net/raphimc/viaproxy/cli/ConsoleHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
package net.raphimc.viaproxy.cli;

import com.viaversion.viaversion.api.Via;
import net.raphimc.viaproxy.plugins.PluginManager;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.plugins.events.ConsoleCommandEvent;
import net.raphimc.viaproxy.protocolhack.viaproxy.ConsoleCommandSender;
import net.raphimc.viaproxy.util.ArrayHelper;
Expand Down Expand Up @@ -67,7 +67,7 @@ private static void listen() {
for (StackTraceElement element : thread.getStackTrace()) System.out.println(" " + element.toString());
}
} else {
if (PluginManager.EVENT_MANAGER.call(new ConsoleCommandEvent(command, args.getAsArray())).isCancelled()) continue;
if (ViaProxy.EVENT_MANAGER.call(new ConsoleCommandEvent(command, args.getAsArray())).isCancelled()) continue;
System.out.println("Invalid Command!");
System.out.println(" gc | Run the garbage collector");
System.out.println(" exit | Shutdown ViaProxy");
Expand Down
9 changes: 4 additions & 5 deletions src/main/java/net/raphimc/viaproxy/cli/options/Options.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import joptsimple.OptionSpec;
import net.raphimc.vialoader.util.VersionEnum;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.plugins.PluginManager;
import net.raphimc.viaproxy.plugins.events.GetDefaultPortEvent;
import net.raphimc.viaproxy.plugins.events.PostOptionsParseEvent;
import net.raphimc.viaproxy.plugins.events.PreOptionsParseEvent;
Expand Down Expand Up @@ -87,7 +86,7 @@ public static void parse(final String[] args) throws IOException {
final OptionSpec<Void> legacyClientPassthrough = parser.acceptsAll(asList("legacy_client_passthrough", "legacy_passthrough"), "Allow <= 1.6.4 clients to connect to the backend server (No protocol translation)");
final OptionSpec<Void> playerInfoForwarding = parser.acceptsAll(asList("player_info_forwarding", "pif"), "Enabled BungeeCord player info forwarding");
final OptionSpec<Void> ignorePacketTranslationErrors = parser.acceptsAll(List.of("ignore-packet-translation-errors"), "Enabling this will prevent getting disconnected from the server when a packet translation error occurs and instead only print the error in the console. This may cause issues depending on the type of packet which failed to translate");
PluginManager.EVENT_MANAGER.call(new PreOptionsParseEvent(parser));
ViaProxy.EVENT_MANAGER.call(new PreOptionsParseEvent(parser));

final OptionSet options;
try {
Expand All @@ -109,12 +108,12 @@ public static void parse(final String[] args) throws IOException {
if (options.has(connectPort)) {
CONNECT_PORT = options.valueOf(connectPort);
} else {
CONNECT_PORT = PluginManager.EVENT_MANAGER.call(new GetDefaultPortEvent(PROTOCOL_VERSION, 25565)).getDefaultPort();
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)) {
final List<Account> accounts = ViaProxy.saveManager.accountsSave.getAccounts();
final List<Account> accounts = ViaProxy.getSaveManager().accountsSave.getAccounts();
final int index = options.valueOf(guiAccountIndex);
if (index < 0 || index >= accounts.size()) {
Logger.LOGGER.error("Invalid account index: " + index);
Expand Down Expand Up @@ -150,7 +149,7 @@ public static void parse(final String[] args) throws IOException {
LEGACY_CLIENT_PASSTHROUGH = options.has(legacyClientPassthrough);
PLAYER_INFO_FORWARDING = options.has(playerInfoForwarding);
IGNORE_PACKET_TRANSLATION_ERRORS = options.has(ignorePacketTranslationErrors);
PluginManager.EVENT_MANAGER.call(new PostOptionsParseEvent(options));
ViaProxy.EVENT_MANAGER.call(new PostOptionsParseEvent(options));
} catch (OptionException e) {
Logger.LOGGER.error("Error parsing options: " + e.getMessage());
parser.formatHelpWith(new BetterHelpFormatter());
Expand Down
35 changes: 18 additions & 17 deletions src/main/java/net/raphimc/viaproxy/plugins/PluginManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@
import net.lenni0451.classtransform.additionalclassprovider.LazyFileClassProvider;
import net.lenni0451.classtransform.utils.loader.InjectionClassLoader;
import net.lenni0451.classtransform.utils.tree.IClassProvider;
import net.lenni0451.lambdaevents.LambdaManager;
import net.lenni0451.lambdaevents.generator.LambdaMetaFactoryGenerator;
import net.lenni0451.reflect.stream.RStream;
import net.raphimc.javadowngrader.impl.classtransform.JavaDowngraderTransformer;
import net.raphimc.viaproxy.ViaProxy;
Expand All @@ -41,19 +39,22 @@

public class PluginManager {

public static final LambdaManager EVENT_MANAGER = LambdaManager.threadSafe(new LambdaMetaFactoryGenerator());
public static final File PLUGINS_DIR = new File("plugins");

private static final Yaml YAML = new Yaml();
private static final IClassProvider ROOT_CLASS_PROVIDER = new GuavaClassPathProvider();
private static final List<ViaProxyPlugin> PLUGINS = new ArrayList<>();
private final Yaml yaml = new Yaml();
private final IClassProvider rootClassProvider = new GuavaClassPathProvider();
private final List<ViaProxyPlugin> plugins = new ArrayList<>();

public static List<ViaProxyPlugin> getPlugins() {
return Collections.unmodifiableList(PLUGINS);
public PluginManager() {
this.loadPlugins();
}

public static ViaProxyPlugin getPlugin(String name) {
for (ViaProxyPlugin plugin : PLUGINS) {
public List<ViaProxyPlugin> getPlugins() {
return Collections.unmodifiableList(this.plugins);
}

public ViaProxyPlugin getPlugin(String name) {
for (ViaProxyPlugin plugin : this.plugins) {
if (plugin.getName().equalsIgnoreCase(name)) {
return plugin;
}
Expand All @@ -62,7 +63,7 @@ public static ViaProxyPlugin getPlugin(String name) {
return null;
}

public static void loadPlugins() {
private void loadPlugins() {
if (!PLUGINS_DIR.exists() || !PLUGINS_DIR.isDirectory()) {
if (!PLUGINS_DIR.mkdirs()) {
return;
Expand All @@ -81,21 +82,21 @@ public static void loadPlugins() {
}
}

for (ViaProxyPlugin plugin : PLUGINS) {
for (ViaProxyPlugin plugin : this.plugins) {
if (!plugin.isEnabled()) {
enablePlugin(plugin);
}
}
}

private static void loadAndScanJar(final File file) throws Throwable {
private void loadAndScanJar(final File file) throws Throwable {
final URL url = file.toURI().toURL();
final TransformerManager transformerManager = new TransformerManager(new LazyFileClassProvider(Collections.singletonList(file), ROOT_CLASS_PROVIDER));
final TransformerManager transformerManager = new TransformerManager(new LazyFileClassProvider(Collections.singletonList(file), this.rootClassProvider));
transformerManager.addBytecodeTransformer(new JavaDowngraderTransformer(transformerManager));
final InjectionClassLoader loader = new InjectionClassLoader(transformerManager, PluginManager.class.getClassLoader(), url);
final InputStream viaproxyYml = loader.getResourceAsStream("viaproxy.yml");
if (viaproxyYml == null) throw new IllegalStateException("Plugin '" + file.getName() + "' does not have a viaproxy.yml");
final Map<String, Object> yaml = YAML.load(viaproxyYml);
final Map<String, Object> yaml = this.yaml.load(viaproxyYml);
if (!yaml.containsKey("name")) throw new IllegalStateException("Plugin '" + file.getName() + "' does not have a name attribute in the viaproxy.yml");
if (!yaml.containsKey("author")) throw new IllegalStateException("Plugin '" + file.getName() + "' does not have a author attribute in the viaproxy.yml");
if (!yaml.containsKey("version")) throw new IllegalStateException("Plugin '" + file.getName() + "' does not have a version attribute in the viaproxy.yml");
Expand All @@ -122,10 +123,10 @@ private static void loadAndScanJar(final File file) throws Throwable {
}

Logger.LOGGER.info("Loaded plugin '" + plugin.getName() + "' by " + plugin.getAuthor() + " (v" + plugin.getVersion() + ")");
PLUGINS.add(plugin);
this.plugins.add(plugin);
}

private static void enablePlugin(final ViaProxyPlugin plugin) {
private void enablePlugin(final ViaProxyPlugin plugin) {
for (String depend : plugin.getDepends()) {
final ViaProxyPlugin dependPlugin = getPlugin(depend);
if (dependPlugin == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import net.raphimc.vialoader.impl.platform.ViaBackwardsPlatformImpl;
import net.raphimc.vialoader.impl.platform.ViaBedrockPlatformImpl;
import net.raphimc.vialoader.impl.platform.ViaRewindPlatformImpl;
import net.raphimc.viaproxy.plugins.PluginManager;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.plugins.events.ProtocolHackInitEvent;
import net.raphimc.viaproxy.protocolhack.impl.ViaProxyVLLoader;
import net.raphimc.viaproxy.protocolhack.impl.ViaProxyViaLegacyPlatformImpl;
Expand All @@ -37,7 +37,7 @@ public class ProtocolHack {

public static void init() {
patchConfigs();
final Supplier<?>[] platformSuppliers = PluginManager.EVENT_MANAGER.call(new ProtocolHackInitEvent(ViaBackwardsPlatformImpl::new, ViaRewindPlatformImpl::new, ViaProxyViaLegacyPlatformImpl::new, ViaAprilFoolsPlatformImpl::new, ViaBedrockPlatformImpl::new)).getPlatformSuppliers().toArray(new Supplier[0]);
final Supplier<?>[] platformSuppliers = ViaProxy.EVENT_MANAGER.call(new ProtocolHackInitEvent(ViaBackwardsPlatformImpl::new, ViaRewindPlatformImpl::new, ViaProxyViaLegacyPlatformImpl::new, ViaAprilFoolsPlatformImpl::new, ViaBedrockPlatformImpl::new)).getPlatformSuppliers().toArray(new Supplier[0]);
ViaLoader.init(new ViaProxyViaVersionPlatformImpl(), new ViaProxyVLLoader(), null, null, platformSuppliers);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
import net.raphimc.vialegacy.protocols.release.protocol1_7_2_5to1_6_4.providers.EncryptionProvider;
import net.raphimc.vialegacy.protocols.release.protocol1_8to1_7_6_10.providers.GameProfileFetcher;
import net.raphimc.vialoader.impl.viaversion.VLLoader;
import net.raphimc.viaproxy.plugins.PluginManager;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.plugins.events.ViaLoadingEvent;
import net.raphimc.viaproxy.protocolhack.providers.*;

Expand Down Expand Up @@ -58,7 +58,7 @@ public void load() {
Via.getManager().getProviders().use(TransferProvider.class, new ViaProxyTransferProvider());

// ViaProxy plugins
PluginManager.EVENT_MANAGER.call(new ViaLoadingEvent());
ViaProxy.EVENT_MANAGER.call(new ViaLoadingEvent());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import net.raphimc.vialoader.impl.platform.ViaVersionPlatformImpl;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.cli.ConsoleFormatter;
import net.raphimc.viaproxy.plugins.PluginManager;
import net.raphimc.viaproxy.plugins.ViaProxyPlugin;

import java.util.UUID;
Expand All @@ -46,7 +45,7 @@ public JsonObject getDump() {
root.addProperty("impl_version", ViaProxy.IMPL_VERSION);

final JsonArray plugins = new JsonArray();
for (ViaProxyPlugin plugin : PluginManager.getPlugins()) {
for (ViaProxyPlugin plugin : ViaProxy.getPluginManager().getPlugins()) {
final JsonObject pluginObj = new JsonObject();
pluginObj.addProperty("name", plugin.getName());
pluginObj.addProperty("version", plugin.getVersion());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
import net.raphimc.netminecraft.constants.MCPipeline;
import net.raphimc.netminecraft.netty.connection.MinecraftChannelInitializer;
import net.raphimc.netminecraft.packet.registry.PacketRegistryUtil;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.cli.options.Options;
import net.raphimc.viaproxy.plugins.PluginManager;
import net.raphimc.viaproxy.plugins.events.Client2ProxyChannelInitializeEvent;
import net.raphimc.viaproxy.plugins.events.types.ITyped;
import net.raphimc.viaproxy.proxy.client2proxy.passthrough.LegacyPassthroughInitialHandler;
Expand All @@ -40,7 +40,7 @@ public Client2ProxyChannelInitializer(final Supplier<ChannelHandler> handlerSupp

@Override
protected void initChannel(Channel channel) {
if (PluginManager.EVENT_MANAGER.call(new Client2ProxyChannelInitializeEvent(ITyped.Type.PRE, channel, false)).isCancelled()) {
if (ViaProxy.EVENT_MANAGER.call(new Client2ProxyChannelInitializeEvent(ITyped.Type.PRE, channel, false)).isCancelled()) {
channel.close();
return;
}
Expand All @@ -52,7 +52,7 @@ protected void initChannel(Channel channel) {
super.initChannel(channel);
channel.attr(MCPipeline.PACKET_REGISTRY_ATTRIBUTE_KEY).set(PacketRegistryUtil.getHandshakeRegistry(false));

if (PluginManager.EVENT_MANAGER.call(new Client2ProxyChannelInitializeEvent(ITyped.Type.POST, channel, false)).isCancelled()) {
if (ViaProxy.EVENT_MANAGER.call(new Client2ProxyChannelInitializeEvent(ITyped.Type.POST, channel, false)).isCancelled()) {
channel.close();
}
}
Expand Down
Loading

0 comments on commit ac5fe12

Please sign in to comment.