Skip to content

Commit

Permalink
chore: Refactor project structure
Browse files Browse the repository at this point in the history
  • Loading branch information
CarmJos committed Jan 4, 2024
1 parent dcd1825 commit 6a52980
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 42 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package com.artformgames.injector.bungeeauthproxy;

import cc.carm.lib.configuration.EasyConfiguration;
import com.artformgames.injector.bungeeauthproxy.handler.AuthHandler;
import com.artformgames.injector.bungeeauthproxy.handler.ProxiedAuthHandler;
import com.artformgames.injector.bungeeauthproxy.transformer.ProxyHandlerTransformer;
import com.artformgames.injector.bungeeauthproxy.transformer.HttpClientTransformer;
import io.netty.channel.EventLoop;
import net.md_5.bungee.api.Callback;
import net.md_5.bungee.http.HttpClient;
Expand All @@ -17,18 +18,18 @@ public class BungeeAuthProxy {
private BungeeAuthProxy() {
}

private static ProxiedAuthHandler handler;
private static AuthHandler handler;

public static void premain(String args, Instrumentation instrumentation) {
log(Logging.Level.INFO, "Loading auth configurations...");
String configFileName = args == null || args.isBlank() ? "auth.yml" : args;
EasyConfiguration.from(configFileName).initialize(Config.class);

log(Logging.Level.INFO, "Initializing auth handler...");
handler = new ProxiedAuthHandler();
setHandler(new ProxiedAuthHandler()); // Use ProxiedAuthHandler by default

log(Logging.Level.INFO, "Registering transformer...");
instrumentation.addTransformer(new ProxyHandlerTransformer(), true);
instrumentation.addTransformer(new HttpClientTransformer(), true);

log(Logging.Level.INFO, "Preload target class...");
debug(" -> Target class: " + HttpClient.class.getName());
Expand All @@ -41,11 +42,11 @@ public static void submitRequest(String url, EventLoop loop, Callback<String> ca
handler.submit(url, loop, callback);
}

public static ProxiedAuthHandler getHandler() {
public static AuthHandler getHandler() {
return handler;
}

public static void setHandler(ProxiedAuthHandler handler) {
public static void setHandler(AuthHandler handler) {
BungeeAuthProxy.handler = handler;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,26 @@
import cc.carm.lib.configuration.core.Configuration;
import cc.carm.lib.configuration.core.annotation.HeaderComment;
import cc.carm.lib.configuration.core.value.type.ConfiguredValue;
import com.artformgames.injector.bungeeauthproxy.channel.ProxyProtocolType;

@HeaderComment({
"BungeeAuthProxy injector configurations",
"See https://github.com/ArtformGames/BungeeAuthProxy for more information."
})
public interface Config extends Configuration {

static ProxyProtocolType getProxyProtocol() {
return ProxyProtocolType.parse(PROXY.PROTOCOL.getNotNull());
}

static int getTimeoutDuration() {
return Math.max(SERVICE.TIME_OUT.getNotNull().intValue(), 100);
}

static long getDNSCacheDuration() {
return Math.max(SERVICE.DNS_CACHE_EXPIRE.getNotNull(), -1L);
}

@HeaderComment("Debug mode for developers, with more detailed logs.")
ConfiguredValue<Boolean> DEBUG = ConfiguredValue.of(false);

Expand Down Expand Up @@ -55,5 +68,15 @@ interface AUTH extends Configuration {

}

interface ADVANCE extends Configuration {

@HeaderComment({
"Remove unused field after injection.",
"If any 'NoSuchFieldException' or 'IllegalAccessException' occurred, try to set this to false."
})
ConfiguredValue<Boolean> REMOVE_UNUSED_FILED = ConfiguredValue.of(true);

}


}
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@
import java.util.regex.Pattern;

public final class Logging {
private Logging() {
}

private static final String PREFIX = "BungeeAuthProxy";
private static final Pattern CONTROL_CHARACTERS_FILTER = Pattern.compile("\\p{Cc}&&[^\r\n\t]");

private Logging() {
}

public enum Level {
DEBUG, INFO, WARNING, ERROR
}
Expand Down Expand Up @@ -53,7 +55,7 @@ public static void warning(String message) {
public static void log(Level level, String message, Throwable e) {
if (level == Level.DEBUG && !Config.DEBUG.getNotNull()) return;

String log = "[BungeeAuthProxy] [" + level + "] " + message;
String log = "[" + PREFIX + "] [" + level + "] " + message;
if (e != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.artformgames.injector.bungeeauthproxy.handler;
package com.artformgames.injector.bungeeauthproxy.channel;

import com.artformgames.injector.bungeeauthproxy.Config;
import io.netty.channel.Channel;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.artformgames.injector.bungeeauthproxy.handler;
package com.artformgames.injector.bungeeauthproxy.channel;

import io.netty.handler.proxy.HttpProxyHandler;
import io.netty.handler.proxy.ProxyHandler;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.artformgames.injector.bungeeauthproxy.handler;

import io.netty.channel.EventLoop;
import net.md_5.bungee.api.Callback;

public interface AuthHandler {

void submit(String url, EventLoop loop, Callback<String> callback) throws Exception;

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.artformgames.injector.bungeeauthproxy.handler;

import com.artformgames.injector.bungeeauthproxy.Config;
import com.artformgames.injector.bungeeauthproxy.channel.ProxiedHttpInitializer;
import com.artformgames.injector.bungeeauthproxy.channel.ProxyProtocolType;
import com.google.common.base.Preconditions;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
Expand All @@ -21,18 +23,19 @@

import static com.artformgames.injector.bungeeauthproxy.Logging.debug;

public class ProxiedAuthHandler {
public class ProxiedAuthHandler implements AuthHandler {

protected Cache<String, InetAddress> addressCache;

public ProxiedAuthHandler() {
if (Config.SERVICE.DNS_CACHE_EXPIRE.getNotNull() > 0) {
if (Config.getDNSCacheDuration() > 0) {
addressCache = CacheBuilder.newBuilder()
.expireAfterWrite(Config.SERVICE.DNS_CACHE_EXPIRE.getNotNull(), TimeUnit.MILLISECONDS)
.build();
.expireAfterWrite(Config.getDNSCacheDuration(), TimeUnit.MILLISECONDS)
.maximumSize(5).build();
}
}

@Override
public void submit(String authURL, EventLoop loop, Callback<String> callback) throws Exception {
URI uri = new URI(authURL);
Preconditions.checkNotNull((Object) uri.getScheme(), "scheme");
Expand All @@ -43,14 +46,14 @@ public void submit(String authURL, EventLoop loop, Callback<String> callback) th
Bootstrap bootstrap = new Bootstrap().channel(PipelineUtils.getChannel(null)).group(loop);

InetAddress address = resolveAddress(uri.getHost());
ProxyProtocolType proxyProtocol = getProxyProtocol();
ProxyProtocolType proxyProtocol = Config.getProxyProtocol();
if (proxyProtocol != null) {
debug("Using proxy protocol [" + proxyProtocol.name() + "] for " + uri.getHost() + ":" + port);
bootstrap.handler(new ProxiedHttpInitializer(proxyProtocol, callback, ssl, uri.getHost(), port));
} else {
bootstrap.handler(new HttpInitializer(callback, ssl, uri.getHost(), port));
}
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.max(Config.SERVICE.TIME_OUT.getNotNull().intValue(), 100))
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Config.getTimeoutDuration())
.remoteAddress(address, port).connect().addListener((ChannelFutureListener) channel -> {
if (channel.isSuccess()) {
String path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
Expand All @@ -69,24 +72,11 @@ private InetAddress resolveAddress(String host) throws UnknownHostException, Exe
else return addressCache.get(host, () -> InetAddress.getByName(host));
}

public ProxyProtocolType getProxyProtocol() {
return ProxyProtocolType.parse(Config.PROXY.PROTOCOL.getNotNull());
}

private static int getPort(URI uri) {
int port = uri.getPort();
if (port != -1) return port;
switch (uri.getScheme()) {
case "http": {
return 80;
}
case "https": {
return 443;
}
default: {
throw new IllegalArgumentException("Unknown scheme " + uri.getScheme());
}
}
if (uri.getPort() != -1) return uri.getPort();
else if (uri.getScheme().equals("https")) return 443;
else if (uri.getScheme().equals("http")) return 80;
throw new IllegalArgumentException("Unknown scheme " + uri.getScheme());
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.artformgames.injector.bungeeauthproxy.transformer;

import com.artformgames.injector.bungeeauthproxy.Config;
import javassist.*;

import java.io.ByteArrayInputStream;
Expand All @@ -10,7 +11,7 @@
import static com.artformgames.injector.bungeeauthproxy.Logging.debug;
import static com.artformgames.injector.bungeeauthproxy.Logging.error;

public class ProxyHandlerTransformer implements ClassFileTransformer {
public class HttpClientTransformer implements ClassFileTransformer {

@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
Expand All @@ -29,14 +30,15 @@ public byte[] transform(ClassLoader loader, String className, Class<?> classBein

handleMethod.setBody("{com.artformgames.injector.bungeeauthproxy.BungeeAuthProxy.submitRequest($1, $2, $3);}");

// remove unused static initializer
CtConstructor staticBlock = clazz.getClassInitializer();
if (staticBlock != null) clazz.removeConstructor(staticBlock);

// remove unused cache field
CtField cacheField = clazz.getField("addressCache");
clazz.removeField(cacheField);
if (Config.ADVANCE.REMOVE_UNUSED_FILED.getNotNull()) {
// remove unused static initializer
CtConstructor staticBlock = clazz.getClassInitializer();
if (staticBlock != null) clazz.removeConstructor(staticBlock);

// remove unused cache field
CtField cacheField = clazz.getField("addressCache");
clazz.removeField(cacheField);
}

return clazz.toBytecode();
} catch (Exception e) {
Expand Down

0 comments on commit 6a52980

Please sign in to comment.