Starting with remove Instance-Getter of ProtocolBridge

This commit is contained in:
Finn
2025-11-03 18:31:29 +01:00
parent c9b6d50be6
commit f5afd9c3e7
11 changed files with 176 additions and 112 deletions

View File

@@ -50,6 +50,12 @@ public abstract class ProtocolClient extends DefaultMethodsOverrider {
*/
private ProtocolVersion serverVersion = null;
/**
* The reference to the ProtocolBridge Object
*/
@Getter
private ProtocolBridge protocolBridge;
/**
* Initializes the ProtocolClient, setting up certificate folders and the DNS client connection.
*
@@ -61,9 +67,9 @@ public abstract class ProtocolClient extends DefaultMethodsOverrider {
folderStructure = new ClientCertificateFolderStructure();
// Initialize connection to DNS server
clientToDNS = new NetworkClient.ClientBuilder().setLogger(ProtocolBridge.getInstance().getLogger()).setProxy(ProtocolBridge.getInstance().getProxy()).
setHost(ProtocolBridge.getInstance().getProtocolSettings().host).setPort(ProtocolBridge.getInstance().getProtocolSettings().port).
setPacketHandler(ProtocolBridge.getInstance().getProtocolSettings().packetHandler).setEventManager(ProtocolBridge.getInstance().getProtocolSettings().eventManager).
clientToDNS = new NetworkClient.ClientBuilder().setLogger(protocolBridge.getLogger()).setProxy(protocolBridge.getProxy()).
setHost(protocolBridge.getProtocolSettings().host).setPort(protocolBridge.getProtocolSettings().port).
setPacketHandler(protocolBridge.getProtocolSettings().packetHandler).setEventManager(protocolBridge.getProtocolSettings().eventManager).
setRootCAFolder(folderStructure.publicCAFolder).setClientCertificatesFolder(folderStructure.publicClientFolder, folderStructure.privateClientFolder).
build();
}
@@ -87,7 +93,7 @@ public abstract class ProtocolClient extends DefaultMethodsOverrider {
*/
public final void createWebConnection(Domain domain, int pipelinePort, int webPort) throws Exception {
// Ensure the protocol supports web connections
if (!ProtocolBridge.getInstance().isProtocolSupported(ProtocolVersion.Protocol.OAC))
if (!protocolBridge.isProtocolSupported(ProtocolVersion.Protocol.OAC))
throw new UnsupportedProtocolException();
// Check if web client is already connected and close it
@@ -95,13 +101,13 @@ public abstract class ProtocolClient extends DefaultMethodsOverrider {
try {
webClient.closeConnection();
} catch (IOException e) {
ProtocolBridge.getInstance().getLogger().exception("Failed to close connection to web server", e);
protocolBridge.getLogger().exception("Failed to close connection to web server", e);
return;
}
}
// Verify necessary certificate files exist
webClient = new WebClient(domain, pipelinePort, webPort);
webClient = new WebClient(domain, pipelinePort, webPort, this);
}
/**
@@ -169,7 +175,7 @@ public abstract class ProtocolClient extends DefaultMethodsOverrider {
try {
webClient.closeConnection();
} catch (IOException e) {
ProtocolBridge.getInstance().getLogger().exception("Failed to close connection to web server", e);
protocolBridge.getLogger().exception("Failed to close connection to web server", e);
}
}
}
@@ -305,10 +311,10 @@ public abstract class ProtocolClient extends DefaultMethodsOverrider {
public final void validateDomain(Domain domain) throws IOException, ClassNotFoundException {
// Send Classic_PingPacket if classic protocol is supported
Classic_PingPacket cPingPacket = new Classic_PingPacket(new Classic_RequestDomain(domain.getName(), domain.getTopLevelName(), domain.getPath()), null, false);
if (ProtocolBridge.getInstance().isClassicSupported()) clientToDNS.sendPacket(cPingPacket);
if (protocolBridge.isClassicSupported()) clientToDNS.sendPacket(cPingPacket);
// Send ValidateDomainPacket
clientToDNS.sendPacket(new ValidateDomainPacket(domain));
clientToDNS.sendPacket(new ValidateDomainPacket(domain, protocolBridge));
}
/**
@@ -322,12 +328,20 @@ public abstract class ProtocolClient extends DefaultMethodsOverrider {
public final void requestDestination(Domain domain, DNSResponseCode responseCode) throws IOException, ClassNotFoundException {
// Send Classic_DomainPacket if classic protocol is supported
Classic_DomainPacket cDomainPacket = new Classic_DomainPacket(0, new Classic_RequestDomain(domain.getName(), domain.getTopLevelName(), domain.getPath()), null);
if (ProtocolBridge.getInstance().isClassicSupported()) clientToDNS.sendPacket(cDomainPacket);
if (protocolBridge.isClassicSupported()) clientToDNS.sendPacket(cDomainPacket);
// Send GetDestinationPacket
clientToDNS.sendPacket(new GetDestinationPacket(domain, responseCode));
}
/**
* Set protocol bridge
* @param protocolBridge The ProtocolBridge object
*/
public void setProtocolBridge(ProtocolBridge protocolBridge) {
if (this.protocolBridge == null) this.protocolBridge = protocolBridge;
}
/**
* Callback method invoked when domain validation is completed.
*

View File

@@ -1,6 +1,8 @@
package org.openautonomousconnection.protocol.side.client;
import dev.unlegitdqrk.unlegitlibrary.network.system.client.NetworkClient;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.ConnectionHandler;
import lombok.Getter;
import org.openautonomousconnection.protocol.ProtocolBridge;
import org.openautonomousconnection.protocol.annotations.ProtocolInfo;
import org.openautonomousconnection.protocol.versions.ProtocolVersion;
@@ -42,34 +44,43 @@ public final class WebClient {
*/
private ObjectInputStream inputStream;
/**
* The Protocol Client associated with this protocol client.
*/
@Getter
private final ProtocolClient protocolClient;
/**
* Constructs a WebClient instance and establishes a secure connection to the web server.
*
* @param domain The domain information for the web server.
* @param pipelinePort The port for the pipeline connection.
* @param webPort The port for the web server connection.
* @param protocolClient The Protocol Client associated with this protocol client.
* @throws Exception If an error occurs during connection setup.
*/
public WebClient(Domain domain, int pipelinePort, int webPort) throws Exception {
public WebClient(Domain domain, int pipelinePort, int webPort, ProtocolClient protocolClient) throws Exception {
this.protocolClient = protocolClient;
// Initialize and connect the pipeline client
clientToWebPipeline = new NetworkClient.ClientBuilder().
// Set logger from ProtocolBridge
setLogger(ProtocolBridge.getInstance().getLogger()).
setLogger(protocolClient.getProtocolBridge().getLogger()).
// Set the destination and port for the pipeline connection
setHost(domain.getDestination()).setPort(pipelinePort).
// Configure packet handler and event manager
setPacketHandler(ProtocolBridge.getInstance().getProtocolSettings().packetHandler).
setEventManager(ProtocolBridge.getInstance().getProtocolSettings().eventManager).
setPacketHandler(protocolClient.getProtocolBridge().getProtocolSettings().packetHandler).
setEventManager(protocolClient.getProtocolBridge().getProtocolSettings().eventManager).
// Set proxy and ssl parameters from DNS connection settings
setProxy(ProtocolBridge.getInstance().getProtocolClient().getClientDNSConnection().getProxy()).
setSSLParameters(ProtocolBridge.getInstance().getProtocolClient().getClientDNSConnection().getSocket().getSSLParameters()).
setProxy(protocolClient.getProtocolBridge().getProtocolClient().getClientDNSConnection().getProxy()).
setSSLParameters(protocolClient.getProtocolBridge().getProtocolClient().getClientDNSConnection().getSocket().getSSLParameters()).
// Set certificates and folders for SSL
setRootCAFolder(ProtocolBridge.getInstance().getProtocolClient().getFolderStructure().publicCAFolder).
setClientCertificatesFolder(ProtocolBridge.getInstance().getProtocolClient().getFolderStructure().publicClientFolder,
ProtocolBridge.getInstance().getProtocolClient().getFolderStructure().privateClientFolder).
setRootCAFolder(protocolClient.getProtocolBridge().getProtocolClient().getFolderStructure().publicCAFolder).
setClientCertificatesFolder(protocolClient.getProtocolBridge().getProtocolClient().getFolderStructure().publicClientFolder,
protocolClient.getProtocolBridge().getProtocolClient().getFolderStructure().privateClientFolder).
// Finalize the client setup
@@ -83,9 +94,9 @@ public final class WebClient {
// Create SSL socket factory using client certificates
SSLSocketFactory sslSocketFactory = NetworkClient.ClientBuilder.
createSSLSocketFactory(ProtocolBridge.getInstance().getProtocolClient().getFolderStructure().publicCAFolder,
ProtocolBridge.getInstance().getProtocolClient().getFolderStructure().publicClientFolder,
ProtocolBridge.getInstance().getProtocolClient().getFolderStructure().privateClientFolder);
createSSLSocketFactory(protocolClient.getProtocolBridge().getProtocolClient().getFolderStructure().publicCAFolder,
protocolClient.getProtocolBridge().getProtocolClient().getFolderStructure().publicClientFolder,
protocolClient.getProtocolBridge().getProtocolClient().getFolderStructure().privateClientFolder);
// Get proxy settings from the pipeline client
Proxy proxy = clientToWebPipeline.getProxy();
@@ -166,7 +177,7 @@ public final class WebClient {
public boolean isConnected() {
return this.clientToWebServer != null && this.clientToWebServer.isConnected() && !this.clientToWebServer.isClosed()
&& this.receiveThread.isAlive() && !this.receiveThread.isInterrupted() &&
ProtocolBridge.getInstance().getProtocolClient().getClientDNSConnection().isConnected() && clientToWebPipeline.isConnected();
protocolClient.getProtocolBridge().getProtocolClient().getClientDNSConnection().isConnected() && clientToWebPipeline.isConnected();
}
/**
@@ -183,7 +194,7 @@ public final class WebClient {
try {
this.closeConnection();
} catch (IOException exception) {
ProtocolBridge.getInstance().getLogger().exception("Failed to close connection to web server", var2);
protocolClient.getProtocolBridge().getLogger().exception("Failed to close connection to web server", var2);
}
}
}

View File

@@ -4,6 +4,7 @@ import dev.unlegitdqrk.unlegitlibrary.network.system.server.ConnectionHandler;
import lombok.Getter;
import org.openautonomousconnection.protocol.annotations.ProtocolInfo;
import org.openautonomousconnection.protocol.packets.OACPacket;
import org.openautonomousconnection.protocol.side.web.ProtocolWebServer;
import org.openautonomousconnection.protocol.versions.ProtocolVersion;
/**
@@ -18,13 +19,20 @@ public final class ConnectedProtocolClient {
@Getter
private final ConnectionHandler connectionHandler;
/**
* The Protocol Server associated with this protocol client.
*/
@Getter
private final ProtocolDNSServer protocolDNSServer;
/**
* The protocol version of the connected client.
*/
private ProtocolVersion clientVersion = null;
public ConnectedProtocolClient(ConnectionHandler connectionHandler) {
public ConnectedProtocolClient(ConnectionHandler connectionHandler, ProtocolDNSServer protocolDNSServer) {
this.connectionHandler = connectionHandler;
this.protocolDNSServer = protocolDNSServer;
}
/**

View File

@@ -46,6 +46,12 @@ public abstract class ProtocolDNSServer extends DefaultMethodsOverrider {
@Getter
private ServerCertificateFolderStructure folderStructure;
/**
* The reference to the ProtocolBridge Object
*/
@Getter
private ProtocolBridge protocolBridge;
/**
* Constructs a ProtocolDNSServer with the specified configuration file.
*
@@ -88,7 +94,6 @@ public abstract class ProtocolDNSServer extends DefaultMethodsOverrider {
File keyFile = new File(folderStructure.privateServerFolder, folderStructure.certPrefix + NetworkUtils.getPublicIPAddress() + ".key");
// Initialize the protocol bridge and clients list
ProtocolBridge protocolBridge = ProtocolBridge.getInstance();
this.clients = new ArrayList<>();
// Build the network server with the specified settings
@@ -148,6 +153,14 @@ public abstract class ProtocolDNSServer extends DefaultMethodsOverrider {
return null;
}
/**
* Set protocol bridge
* @param protocolBridge The ProtocolBridge object
*/
public void setProtocolBridge(ProtocolBridge protocolBridge) {
if (this.protocolBridge == null) this.protocolBridge = protocolBridge;
}
/**
* Gets the DNS information site URL from the configuration.
*
@@ -208,7 +221,6 @@ public abstract class ProtocolDNSServer extends DefaultMethodsOverrider {
/**
* Abstract method called when a validation packet fails to send.
*
* @param domain The domain associated with the validation.
* @param client The connected protocol client.
* @param exception The exception that occurred during sending.
@@ -217,7 +229,6 @@ public abstract class ProtocolDNSServer extends DefaultMethodsOverrider {
/**
* Abstract method called when a domain destination packet fails to send.
*
* @param client The connected protocol client.
* @param domain The domain associated with the packet.
* @param validationResponse The DNS response code from validation.

View File

@@ -68,6 +68,12 @@ public final class ConnectedWebClient {
*/
private final Thread receiveThread = new Thread(this::receive);
/**
* The reference to the ProtocolWebServer Object
*/
@Getter
private ProtocolWebServer protocolWebServer;
/**
* Sends an HTTP redirect response to the client.
*
@@ -629,7 +635,7 @@ public final class ConnectedWebClient {
path = URLDecoder.decode(path, StandardCharsets.UTF_8);
path = normalizePath(path);
File file = new File(ProtocolBridge.getInstance().getProtocolWebServer().getContentFolder(), path);
File file = new File(protocolWebServer.getProtocolBridge().getProtocolWebServer().getContentFolder(), path);
String sessionId = null;
if (headers.containsKey("cookie")) {
@@ -642,14 +648,14 @@ public final class ConnectedWebClient {
}
if (!file.exists() || !file.isFile()) {
sendResponse(out, 404, new File(ProtocolBridge.getInstance().getProtocolWebServer().getErrorsFolder(), "404.html"));
sendResponse(out, 404, new File(protocolWebServer.getProtocolBridge().getProtocolWebServer().getErrorsFolder(), "404.html"));
return;
}
String clientIp = webSocket.getInetAddress().getHostAddress();
String userAgent = headers.getOrDefault("user-agent", null);
boolean loggedIn = sessionId != null && SessionManager.isValid(sessionId, clientIp, userAgent);
boolean loggedIn = sessionId != null && SessionManager.isValid(sessionId, clientIp, userAgent, protocolWebServer);
if (path.equals("/403-login") && headers.getOrDefault("content-type", "").startsWith("application/x-www-form-urlencoded")) {
Map<String, String> postParams = parsePostParams(in);
@@ -657,7 +663,7 @@ public final class ConnectedWebClient {
String password = postParams.get("password");
if (AuthManager.checkAuth(login, password)) {
String newSessionId = SessionManager.create(login, clientIp, userAgent);
String newSessionId = SessionManager.create(login, clientIp, userAgent, protocolWebServer);
Map<String, String> cookies = Map.of("Set-Cookie", "SESSIONID=" + newSessionId + "; HttpOnly; Path=/");
sendRedirect(out, "/main.html", cookies);
return;
@@ -668,18 +674,18 @@ public final class ConnectedWebClient {
}
if (isMultipart(headers)) {
handleMultipart(in, headers, new File(ProtocolBridge.getInstance().getProtocolWebServer().getContentFolder(), "uploads"));
handleMultipart(in, headers, new File(protocolWebServer.getProtocolBridge().getProtocolWebServer().getContentFolder(), "uploads"));
}
if (RuleManager.requiresAuth(path) && !loggedIn) {
PHPResponse phpResp = renderPHPWithCookies(new File(ProtocolBridge.getInstance().getProtocolWebServer().getContentFolder(), "403.php"));
PHPResponse phpResp = renderPHPWithCookies(new File(protocolWebServer.getProtocolBridge().getProtocolWebServer().getContentFolder(), "403.php"));
sendResponse(out, 200, phpResp.body.getBytes(StandardCharsets.UTF_8), "text/html", phpResp.cookies);
return;
}
if (RuleManager.isDenied(path) && !RuleManager.isAllowed(path)) {
sendResponse(out, 403, new File(ProtocolBridge.getInstance().getProtocolWebServer().getErrorsFolder(), "403.php"));
sendResponse(out, 403, new File(protocolWebServer.getProtocolBridge().getProtocolWebServer().getErrorsFolder(), "403.php"));
return;
}
@@ -701,6 +707,14 @@ public final class ConnectedWebClient {
}
}
/**
* Set protocol bridge
* @param protocolWebServer The ProtocolWebServer object
*/
public void setProtocolWebServer(ProtocolWebServer protocolWebServer) {
if (this.protocolWebServer == null) this.protocolWebServer = protocolWebServer;
}
/**
* Represents the response from a PHP script, including body and cookies.
*/

View File

@@ -83,6 +83,12 @@ public final class ProtocolWebServer {
@Getter
private String uniqueSessionString;
/**
* The reference to the ProtocolBridge Object
*/
@Getter
private ProtocolBridge protocolBridge;
/**
* Initializes the web server with the given configuration, authentication, and rules files.
*
@@ -159,8 +165,8 @@ public final class ProtocolWebServer {
// Initialize the pipeline server
pipelineServer = new NetworkServer.ServerBuilder().
setPort(configurationManager.getInt("port.pipeline")).setTimeout(0).
setPacketHandler(ProtocolBridge.getInstance().getProtocolSettings().packetHandler).setEventManager(ProtocolBridge.getInstance().getProtocolSettings().eventManager).
setLogger(ProtocolBridge.getInstance().getLogger()).
setPacketHandler(protocolBridge.getProtocolSettings().packetHandler).setEventManager(protocolBridge.getProtocolSettings().eventManager).
setLogger(protocolBridge.getLogger()).
setServerCertificate(certFile, keyFile).setRootCAFolder(folderStructure.publicCAFolder).
build();
}
@@ -177,6 +183,14 @@ public final class ProtocolWebServer {
return null;
}
/**
* Set protocol bridge
* @param protocolBridge The ProtocolBridge object
*/
public void setProtocolBridge(ProtocolBridge protocolBridge) {
if (this.protocolBridge == null) this.protocolBridge = protocolBridge;
}
/**
* Starts the web server to accept and handle client connections.
*
@@ -228,6 +242,7 @@ public final class ProtocolWebServer {
if (connectedWebClient.getPipelineConnection().getClientID() != -1 && connectedWebClient.isClientVersionLoaded()) {
// Assign socket to an existing connected client
connectedWebClient.setWebSocket(client);
connectedWebClient.setProtocolWebServer(this);
}
}
} catch (IOException e) {

View File

@@ -3,6 +3,7 @@ package org.openautonomousconnection.protocol.side.web.managers;
import lombok.Getter;
import org.openautonomousconnection.protocol.ProtocolBridge;
import org.openautonomousconnection.protocol.annotations.ProtocolInfo;
import org.openautonomousconnection.protocol.side.web.ProtocolWebServer;
import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import java.io.IOException;
@@ -34,19 +35,20 @@ public final class SessionManager {
* @param login The username associated with the session.
* @param ip The IP address of the client.
* @param userAgent The User-Agent string of the client.
* @param protocolWebServer The Protocol WebServer for the unique Session
* @return The generated session ID.
* @throws IOException If an I/O error occurs.
*/
public static String create(String login, String ip, String userAgent) throws IOException {
public static String create(String login, String ip, String userAgent, ProtocolWebServer protocolWebServer) throws IOException {
// Generate a secure random session ID
byte[] bytes = new byte[32];
secureRandom.nextBytes(bytes);
// Encode the bytes to a URL-safe Base64 string
String sessionId = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) + ProtocolBridge.getInstance().getProtocolWebServer().getUniqueSessionString();
String sessionId = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) + protocolWebServer.getUniqueSessionString();
// Create and store the new session
sessions.put(sessionId, new Session(login, ip, userAgent));
sessions.put(sessionId, new Session(login, ip, userAgent, protocolWebServer));
return sessionId;
}
@@ -56,10 +58,11 @@ public final class SessionManager {
* @param sessionId The session ID to validate.
* @param ip The IP address of the client.
* @param userAgent The User-Agent string of the client.
* @param protocolWebServer The Protocol WebServer to get the config for refreshing
* @return True if the session is valid, false otherwise.
* @throws IOException If an I/O error occurs.
*/
public static boolean isValid(String sessionId, String ip, String userAgent) throws IOException {
public static boolean isValid(String sessionId, String ip, String userAgent, ProtocolWebServer protocolWebServer) throws IOException {
// Retrieve the session associated with the session ID
Session session = sessions.get(sessionId);
@@ -70,7 +73,7 @@ public final class SessionManager {
}
// Refresh the session expiration time
session.refresh();
session.refresh(protocolWebServer);
return true;
}
@@ -122,11 +125,11 @@ public final class SessionManager {
String userAgent;
long expiresAt;
Session(String login, String ip, String userAgent) throws IOException {
Session(String login, String ip, String userAgent, ProtocolWebServer protocolWebServer) throws IOException {
this.login = login;
this.ip = ip;
this.userAgent = userAgent;
this.expiresAt = System.currentTimeMillis() + (long) ProtocolBridge.getInstance().getProtocolWebServer().getConfigurationManager().getInt("sessionexpireminutes") * 60 * 1000;
this.expiresAt = System.currentTimeMillis() + (long) protocolWebServer.getConfigurationManager().getInt("sessionexpireminutes") * 60 * 1000;
}
/**
@@ -151,11 +154,11 @@ public final class SessionManager {
/**
* Refreshes the session's expiration time.
*
* @param protocolWebServer The Protocol WebServer to get the Config setting
* @throws IOException If an I/O error occurs.
*/
void refresh() throws IOException {
this.expiresAt = System.currentTimeMillis() + (long) ProtocolBridge.getInstance().getProtocolWebServer().getConfigurationManager().getInt("sessionexpireminutes") * 60 * 1000;
void refresh(ProtocolWebServer protocolWebServer) throws IOException {
this.expiresAt = System.currentTimeMillis() + (long) protocolWebServer.getConfigurationManager().getInt("sessionexpireminutes") * 60 * 1000;
}
}
}