Updated to latest UnlegitLibrary Version

This commit is contained in:
Finn
2026-02-01 17:13:33 +01:00
parent 0a0618a680
commit 3ea6723cf9
22 changed files with 516 additions and 687 deletions

View File

@@ -6,7 +6,7 @@
<groupId>org.openautonomousconnection</groupId> <groupId>org.openautonomousconnection</groupId>
<artifactId>Protocol</artifactId> <artifactId>Protocol</artifactId>
<version>1.0.0-BETA.6.1</version> <version>1.0.0-BETA.7.0</version>
<organization> <organization>
<name>Open Autonomous Connection</name> <name>Open Autonomous Connection</name>
<url>https://open-autonomous-connection.org/</url> <url>https://open-autonomous-connection.org/</url>
@@ -119,7 +119,7 @@
<dependency> <dependency>
<groupId>dev.unlegitdqrk</groupId> <groupId>dev.unlegitdqrk</groupId>
<artifactId>unlegitlibrary</artifactId> <artifactId>unlegitlibrary</artifactId>
<version>1.7.0</version> <version>1.7.8</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
@@ -164,6 +164,9 @@
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>3.6.3</version> <version>3.6.3</version>
<configuration> <configuration>
<failOnError>false</failOnError>
<failOnWarnings>false</failOnWarnings>
<doclint>none</doclint>
<locale>en_US</locale> <locale>en_US</locale>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
<docencoding>UTF-8</docencoding> <docencoding>UTF-8</docencoding>

View File

@@ -1,5 +1,6 @@
package org.openautonomousconnection.protocol; package org.openautonomousconnection.protocol;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.ClientAuthMode;
import dev.unlegitdqrk.unlegitlibrary.utils.Logger; import dev.unlegitdqrk.unlegitlibrary.utils.Logger;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@@ -77,13 +78,17 @@ public final class ProtocolBridge {
* @param logFolder The folder to store the log files * @param logFolder The folder to store the log files
* @throws Exception if an error occurs while initializing the ProtocolBridge * @throws Exception if an error occurs while initializing the ProtocolBridge
*/ */
@ProtocolInfo(protocolSide = ProtocolVersion.ProtocolSide.CLIENT)
public ProtocolBridge(ProtocolCustomServer protocolServer, ProtocolValues protocolValues, ProtocolVersion protocolVersion, File logFolder) throws Exception { public ProtocolBridge(ProtocolCustomServer protocolServer, ProtocolValues protocolValues, ProtocolVersion protocolVersion, File logFolder) throws Exception {
// Assign the parameters to the class fields // Assign the parameters to the class fields
this.protocolServer = protocolServer; this.protocolServer = protocolServer;
this.protocolValues = protocolValues; this.protocolValues = protocolValues;
this.protocolVersion = protocolVersion; this.protocolVersion = protocolVersion;
if (protocolServer instanceof ProtocolINSServer) {
protocolServer.attachBridge(this, null, false, ClientAuthMode.NONE);
} else
protocolServer.attachBridge(this, protocolValues.keyPass, protocolValues.ssl, protocolValues.authMode);
// Initialize the logger and protocol version // Initialize the logger and protocol version
initializeLogger(logFolder); initializeLogger(logFolder);
initializeProtocolVersion(); initializeProtocolVersion();
@@ -91,8 +96,6 @@ public final class ProtocolBridge {
// Register the appropriate listeners and packets // Register the appropriate listeners and packets
registerListeners(); registerListeners();
registerPackets(); registerPackets();
protocolServer.attachBridge(this);
} }
/** /**
@@ -111,6 +114,8 @@ public final class ProtocolBridge {
this.protocolValues = protocolValues; this.protocolValues = protocolValues;
this.protocolVersion = protocolVersion; this.protocolVersion = protocolVersion;
protocolClient.attachBridge(this);
// Initialize the logger and protocol version // Initialize the logger and protocol version
initializeLogger(logFolder); initializeLogger(logFolder);
initializeProtocolVersion(); initializeProtocolVersion();
@@ -118,8 +123,6 @@ public final class ProtocolBridge {
// Register the appropriate listeners and packets // Register the appropriate listeners and packets
registerListeners(); registerListeners();
registerPackets(); registerPackets();
protocolClient.attachBridge(this);
} }
/** /**
@@ -127,30 +130,17 @@ public final class ProtocolBridge {
*/ */
private void registerPackets() { private void registerPackets() {
// 1.0.0-BETA packets // 1.0.0-BETA packets
AuthPacket v100bAuthPath = new AuthPacket(); if (isPacketSupported(new AuthPacket(this))) protocolValues.packetHandler.registerPacket(() -> new AuthPacket(this));
INSQueryPacket v100BINSQueryPacket = new INSQueryPacket(); if (isPacketSupported(new INSQueryPacket())) protocolValues.packetHandler.registerPacket(INSQueryPacket::new);
INSResponsePacket v100BINSResponsePacket = new INSResponsePacket(this); if (isPacketSupported(new INSResponsePacket(this))) protocolValues.packetHandler.registerPacket(() -> new INSResponsePacket(this));
WebRequestPacket v100BWebRequestPacket = new WebRequestPacket(); if (isPacketSupported(new WebRequestPacket())) protocolValues.packetHandler.registerPacket(WebRequestPacket::new);
WebResponsePacket v100BResponsePacket = new WebResponsePacket(); if (isPacketSupported(new WebResponsePacket())) protocolValues.packetHandler.registerPacket(WebResponsePacket::new);
WebStreamChunkPacket v100BStreamChunkPacket = new WebStreamChunkPacket(); if (isPacketSupported(new WebStreamChunkPacket())) protocolValues.packetHandler.registerPacket(WebStreamChunkPacket::new);
WebStreamStartPacket v100BStreamStartPacket = new WebStreamStartPacket(); if (isPacketSupported(new WebStreamStartPacket())) protocolValues.packetHandler.registerPacket(WebStreamStartPacket::new);
WebStreamEndPacket v100BStreamEndPacket = new WebStreamEndPacket(); if (isPacketSupported(new WebStreamEndPacket())) protocolValues.packetHandler.registerPacket(WebStreamEndPacket::new);
if (isPacketSupported(v100bAuthPath)) protocolValues.packetHandler.registerPacket(v100bAuthPath);
if (isPacketSupported(v100BINSQueryPacket)) protocolValues.packetHandler.registerPacket(v100BINSQueryPacket);
if (isPacketSupported(v100BINSResponsePacket))
protocolValues.packetHandler.registerPacket(v100BINSResponsePacket);
if (isPacketSupported(v100BWebRequestPacket))
protocolValues.packetHandler.registerPacket(v100BWebRequestPacket);
if (isPacketSupported(v100BResponsePacket)) protocolValues.packetHandler.registerPacket(v100BResponsePacket);
if (isPacketSupported(v100BStreamChunkPacket))
protocolValues.packetHandler.registerPacket(v100BStreamChunkPacket);
if (isPacketSupported(v100BStreamStartPacket))
protocolValues.packetHandler.registerPacket(v100BStreamStartPacket);
if (isPacketSupported(v100BStreamEndPacket))
protocolValues.packetHandler.registerPacket(v100BStreamEndPacket);
} }
/** /**
* Register the appropriate listeners based on the current side * Register the appropriate listeners based on the current side
* *
@@ -159,17 +149,13 @@ public final class ProtocolBridge {
private void registerListeners() throws Exception { private void registerListeners() throws Exception {
// Client Listeners // Client Listeners
if (isRunningAsClient()) { if (isRunningAsClient()) {
ClientListener clientListener = new ClientListener(); protocolValues.eventManager.registerListener(new ClientListener(protocolClient));
clientListener.setClient(protocolClient);
protocolValues.eventManager.registerListener(clientListener.getClass());
protocolValues.eventManager.unregisterListener(CustomServerListener.class); protocolValues.eventManager.unregisterListener(CustomServerListener.class);
} }
// Server Listeners // Server Listeners
if (isRunningAsServer()) { if (isRunningAsServer()) {
CustomServerListener serverListener = new CustomServerListener(); protocolValues.eventManager.registerListener(new CustomServerListener(protocolServer));
serverListener.setServer(protocolServer);
protocolValues.eventManager.registerListener(serverListener.getClass());
protocolValues.eventManager.unregisterListener(ClientListener.class); protocolValues.eventManager.unregisterListener(ClientListener.class);
} }
} }

View File

@@ -2,6 +2,7 @@ package org.openautonomousconnection.protocol;
import dev.unlegitdqrk.unlegitlibrary.event.EventManager; import dev.unlegitdqrk.unlegitlibrary.event.EventManager;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler; import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.ClientAuthMode;
import dev.unlegitdqrk.unlegitlibrary.utils.DefaultMethodsOverrider; import dev.unlegitdqrk.unlegitlibrary.utils.DefaultMethodsOverrider;
/** /**
@@ -9,7 +10,7 @@ import dev.unlegitdqrk.unlegitlibrary.utils.DefaultMethodsOverrider;
*/ */
public final class ProtocolValues extends DefaultMethodsOverrider { public final class ProtocolValues extends DefaultMethodsOverrider {
/** /**
* The protocol version to use. * The packet handler to use.
*/ */
public PacketHandler packetHandler; public PacketHandler packetHandler;
@@ -18,4 +19,9 @@ public final class ProtocolValues extends DefaultMethodsOverrider {
*/ */
public EventManager eventManager; public EventManager eventManager;
public String keyPass = null;
public boolean ssl = true;
public ClientAuthMode authMode = ClientAuthMode.NONE;
} }

View File

@@ -2,9 +2,8 @@ package org.openautonomousconnection.protocol.listeners;
import dev.unlegitdqrk.unlegitlibrary.event.EventListener; import dev.unlegitdqrk.unlegitlibrary.event.EventListener;
import dev.unlegitdqrk.unlegitlibrary.event.Listener; import dev.unlegitdqrk.unlegitlibrary.event.Listener;
import dev.unlegitdqrk.unlegitlibrary.network.system.client.events.state.connect.ClientConnectedEvent; import dev.unlegitdqrk.unlegitlibrary.network.system.client.events.state.ClientConnectedEvent;
import dev.unlegitdqrk.unlegitlibrary.network.system.client.events.state.disconnect.ClientFullyDisconnectedEvent; import dev.unlegitdqrk.unlegitlibrary.network.system.utils.TransportProtocol;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.Transport;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.annotations.ProtocolInfo; import org.openautonomousconnection.protocol.annotations.ProtocolInfo;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.AuthPacket; import org.openautonomousconnection.protocol.packets.v1_0_0.beta.AuthPacket;
@@ -23,15 +22,14 @@ public final class ClientListener extends EventListener {
* The reference to the ProtocolClient object * The reference to the ProtocolClient object
*/ */
@Getter @Getter
private ProtocolClient client; private final ProtocolClient client;
/** /**
* Sets the client variable * Sets the client variable
* *
* @param client The Instance of the ProtocolClient * @param client The Instance of the ProtocolClient
*/ */
public void setClient(ProtocolClient client) { public ClientListener(ProtocolClient client) {
if (this.client != null) return;
this.client = client; this.client = client;
} }
@@ -44,23 +42,11 @@ public final class ClientListener extends EventListener {
@Listener @Listener
public void onConnect(ClientConnectedEvent event) { public void onConnect(ClientConnectedEvent event) {
try { try {
if (event.getTransport() != Transport.TCP) return; event.getClient().sendPacket(new AuthPacket(client.getProtocolBridge()), TransportProtocol.TCP);
event.getClient().sendPacket(new AuthPacket(client.getProtocolBridge()), Transport.TCP); } catch (Exception exception) {
} catch (IOException | ClassNotFoundException exception) {
client.getProtocolBridge().getLogger().exception("Failed to send auth packet", exception); client.getProtocolBridge().getLogger().exception("Failed to send auth packet", exception);
event.getClient().disconnect(); event.getClient().disconnect();
} }
} }
/**
* Handles the event when a client disconnects.
* Notifies the protocol client of the disconnection.
*
* @param event The client disconnected event.
*/
@Listener
public void onDisconnect(ClientFullyDisconnectedEvent event) {
client.onDisconnect(event);
}
} }

View File

@@ -2,50 +2,42 @@ package org.openautonomousconnection.protocol.listeners;
import dev.unlegitdqrk.unlegitlibrary.event.EventListener; import dev.unlegitdqrk.unlegitlibrary.event.EventListener;
import dev.unlegitdqrk.unlegitlibrary.event.Listener; import dev.unlegitdqrk.unlegitlibrary.event.Listener;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.ConnectionHandler; import dev.unlegitdqrk.unlegitlibrary.network.system.server.events.client.S_ClientConnectedEvent;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.events.packets.receive.S_PacketReceivedEvent; import dev.unlegitdqrk.unlegitlibrary.network.system.server.events.client.S_ClientDisconnectedEvent;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.events.state.connect.ConnectionHandlerConnectedEvent; import dev.unlegitdqrk.unlegitlibrary.network.system.server.events.packets.S_PacketReadEvent;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.events.state.disconnect.ConnectionHandlerDisconnectedEvent; import dev.unlegitdqrk.unlegitlibrary.network.system.utils.TransportProtocol;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.events.state.disconnect.ConnectionHandlerFullyDisconnectedEvent;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.Transport;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.annotations.ProtocolInfo;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.INSQueryPacket; import org.openautonomousconnection.protocol.packets.v1_0_0.beta.INSQueryPacket;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.INSResponsePacket; import org.openautonomousconnection.protocol.packets.v1_0_0.beta.INSResponsePacket;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.WebRequestPacket; import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.WebRequestPacket;
import org.openautonomousconnection.protocol.side.ins.ProtocolINSServer; import org.openautonomousconnection.protocol.side.ins.ProtocolINSServer;
import org.openautonomousconnection.protocol.side.server.CustomConnectedClient; import org.openautonomousconnection.protocol.side.server.CustomConnectedClient;
import org.openautonomousconnection.protocol.side.server.ProtocolCustomServer; import org.openautonomousconnection.protocol.side.server.ProtocolCustomServer;
import org.openautonomousconnection.protocol.side.server.events.S_CustomClientDisconnectedEvent;
import org.openautonomousconnection.protocol.side.web.ProtocolWebServer; import org.openautonomousconnection.protocol.side.web.ProtocolWebServer;
import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecord; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecord;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSResponseStatus; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSResponseStatus;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* Listener for web server connection events. * Listener for web server connection events.
*/ */
@ProtocolInfo(protocolSide = ProtocolVersion.ProtocolSide.WEB)
public final class CustomServerListener extends EventListener { public final class CustomServerListener extends EventListener {
/** /**
* The reference to the CustomProtocolServer object * The reference to the CustomProtocolServer object
*/ */
@Getter @Getter
private ProtocolCustomServer server; private final ProtocolCustomServer server;
/** /**
* Sets the webServer variable * Sets the webServer variable
* *
* @param server The Instance of the CustomProtocolServer * @param server The Instance of the CustomProtocolServer
*/ */
public void setServer(ProtocolCustomServer server) { public CustomServerListener(ProtocolCustomServer server) {
if (this.server != null) return;
this.server = server; this.server = server;
} }
@@ -56,34 +48,21 @@ public final class CustomServerListener extends EventListener {
* @param event The connection handler connected event. * @param event The connection handler connected event.
*/ */
@Listener @Listener
public void onConnect(ConnectionHandlerConnectedEvent event) { public void onConnect(S_ClientConnectedEvent event) {
Class<? extends CustomConnectedClient> serverClass = server.getCustomClient();
try { try {
CustomConnectedClient client = serverClass.getConstructor(ConnectionHandler.class, ProtocolCustomServer.class).newInstance(event.getConnectionHandler(), server); server.getClients().add(new CustomConnectedClient(event.getClient(), (ProtocolCustomServer) server));
server.getClients().add(client); } catch (Exception e) {
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | server.getProtocolBridge().getLogger().exception("Failed to add client to server", e);
NoSuchMethodException e) { event.getClient().disconnect();
server.getProtocolBridge().getLogger().exception("Failed to instantiate connected client", e);
} }
} }
/**
* Handles the event when a connection is disconnected.
* Removes the disconnected client from the protocol web server's client list.
*
* @param event The connection handler disconnected event.
*/
@Listener @Listener
public void onDisconnect(ConnectionHandlerFullyDisconnectedEvent event) { public void onPacketWeb(S_PacketReadEvent event) {
server.getClients().removeIf(client -> client.getConnection().getClientId().equals(client.getConnection().getClientId()));
}
@Listener
public void onPacketWeb(S_PacketReceivedEvent event) {
if (!server.getProtocolBridge().isRunningAsWebServer()) return; if (!server.getProtocolBridge().isRunningAsWebServer()) return;
if (!(event.getPacket() instanceof WebRequestPacket packet)) return; if (!(event.getPacket() instanceof WebRequestPacket packet)) return;
((ProtocolWebServer) server).onWebRequest(server.getClientByID(event.getConnectionHandler().getClientId()), packet); ((ProtocolWebServer) server).onWebRequest(server.getClientByID(event.getClient().getUniqueID()), packet);
} }
/** /**
@@ -103,7 +82,7 @@ public final class CustomServerListener extends EventListener {
* @param event The packet event received by the network system. * @param event The packet event received by the network system.
*/ */
@Listener @Listener
public void onPacketINS(S_PacketReceivedEvent event) { public void onPacketINS(S_PacketReadEvent event) {
if (!(event.getPacket() instanceof INSQueryPacket q)) return; if (!(event.getPacket() instanceof INSQueryPacket q)) return;
if (!server.getProtocolBridge().isRunningAsINSServer()) return; if (!server.getProtocolBridge().isRunningAsINSServer()) return;
@@ -143,9 +122,9 @@ public final class CustomServerListener extends EventListener {
INSResponsePacket response = new INSResponsePacket(status, resolved, q.getClientId(), insServer.getProtocolBridge()); INSResponsePacket response = new INSResponsePacket(status, resolved, q.getClientId(), insServer.getProtocolBridge());
try { try {
event.getConnectionHandler().sendPacket(response, Transport.TCP); event.getClient().sendPacket(response, TransportProtocol.TCP);
insServer.onResponseSent(q.getTLN(), q.getName(), q.getSub(), q.getType(), resolved); insServer.onResponseSent(q.getTLN(), q.getName(), q.getSub(), q.getType(), resolved);
} catch (IOException | ClassNotFoundException e) { } catch (Exception e) {
insServer.onResponseSentFailed(q.getTLN(), q.getName(), q.getSub(), q.getType(), resolved, e); insServer.onResponseSentFailed(q.getTLN(), q.getName(), q.getSub(), q.getType(), resolved, e);
} }
} }

View File

@@ -1,14 +1,12 @@
package org.openautonomousconnection.protocol.packets; package org.openautonomousconnection.protocol.packets;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.Packet; import dev.unlegitdqrk.unlegitlibrary.network.system.packets.Packet;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.versions.ProtocolVersion; import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSResponseStatus; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSResponseStatus;
import java.io.IOException; import java.io.*;
import java.io.ObjectInputStream; import java.util.UUID;
import java.io.ObjectOutputStream;
/** /**
* Abstract class representing a packet in the Open Autonomous Connection (OAC) protocol. * Abstract class representing a packet in the Open Autonomous Connection (OAC) protocol.
@@ -27,6 +25,13 @@ public abstract class OACPacket extends Packet {
*/ */
private INSResponseStatus responseCode = INSResponseStatus.RESPONSE_NOT_REQUIRED; private INSResponseStatus responseCode = INSResponseStatus.RESPONSE_NOT_REQUIRED;
private final int id;
@Override
public int getPacketID() {
return id;
}
/** /**
* Constructor for OACPacket. * Constructor for OACPacket.
* *
@@ -34,7 +39,7 @@ public abstract class OACPacket extends Packet {
* @param protocolVersion The protocol version associated with this packet. * @param protocolVersion The protocol version associated with this packet.
*/ */
public OACPacket(int id, ProtocolVersion protocolVersion) { public OACPacket(int id, ProtocolVersion protocolVersion) {
super(id); this.id = id;
this.protocolVersion = protocolVersion; this.protocolVersion = protocolVersion;
} }
@@ -59,61 +64,54 @@ public abstract class OACPacket extends Packet {
/** /**
* Writes the packet data to the output stream. * Writes the packet data to the output stream.
* *
* @param packetHandler The packet handler managing the packet. * @param outputStream The output stream to write the packet data to.
* @param objectOutputStream The output stream to write the packet data to.
* @throws IOException If an I/O error occurs. * @throws IOException If an I/O error occurs.
* @throws ClassNotFoundException If a class cannot be found during serialization.
*/ */
@Override @Override
public final void write(PacketHandler packetHandler, ObjectOutputStream objectOutputStream) throws IOException, ClassNotFoundException { public final void write(DataOutputStream outputStream) throws IOException {
// Write the specific packet data // Write the specific packet data
onWrite(packetHandler, objectOutputStream); onWrite(outputStream);
// Write the response code if the protocol version is not classic // Write the response code if the protocol version is not classic
if (protocolVersion != ProtocolVersion.PV_1_0_0_CLASSIC) objectOutputStream.writeObject(responseCode); if (protocolVersion != ProtocolVersion.PV_1_0_0_CLASSIC) outputStream.writeUTF(responseCode.name());
} }
@Override @Override
public final void read(PacketHandler packetHandler, ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException { public final void read(DataInputStream inputStream, UUID clientID) throws IOException {
// Read the specific packet data // Read the specific packet data
onRead(packetHandler, objectInputStream); onRead(inputStream, clientID);
// Read the response code if the protocol version is not classic // Read the response code if the protocol version is not classic
if (protocolVersion != ProtocolVersion.PV_1_0_0_CLASSIC) if (protocolVersion != ProtocolVersion.PV_1_0_0_CLASSIC)
responseCode = (INSResponseStatus) objectInputStream.readObject(); responseCode = INSResponseStatus.valueOf(inputStream.readUTF());
else responseCode = INSResponseStatus.RESPONSE_NOT_REQUIRED; else responseCode = INSResponseStatus.RESPONSE_NOT_REQUIRED;
// Call the response code read handler // Call the response code read handler
onResponseCodeRead(packetHandler, objectInputStream); onResponseCodeRead(inputStream, clientID);
} }
/** /**
* Abstract method to be implemented by subclasses for writing specific packet data. * Abstract method to be implemented by subclasses for writing specific packet data.
* *
* @param packetHandler The packet handler managing the packet. * @param outputStream The output stream to write the packet data to.
* @param objectOutputStream The output stream to write the packet data to.
* @throws IOException If an I/O error occurs. * @throws IOException If an I/O error occurs.
* @throws ClassNotFoundException If a class cannot be found during serialization.
*/ */
public abstract void onWrite(PacketHandler packetHandler, ObjectOutputStream objectOutputStream) throws IOException, ClassNotFoundException; public abstract void onWrite(DataOutputStream outputStream) throws IOException;
/** /**
* Abstract method to be implemented by subclasses for reading specific packet data. * Abstract method to be implemented by subclasses for reading specific packet data.
* *
* @param packetHandler The packet handler managing the packet. * @param inputStream The input stream to read the packet data from.
* @param objectInputStream The input stream to read the packet data from.
* @throws IOException If an I/O error occurs. * @throws IOException If an I/O error occurs.
* @throws ClassNotFoundException If a class cannot be found during deserialization.
*/ */
public abstract void onRead(PacketHandler packetHandler, ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException; public abstract void onRead(DataInputStream inputStream, UUID clientID) throws IOException;
/** /**
* Method called after the response code has been read from the input stream. * Method called after the response code has been read from the input stream.
* Subclasses can override this method to handle any additional logic based on the response code. * Subclasses can override this method to handle any additional logic based on the response code.
* *
* @param packetHandler The packet handler managing the packet. * @param inputStream The input stream from which the response code was read.
* @param objectInputStream The input stream from which the response code was read.
*/ */
protected void onResponseCodeRead(PacketHandler packetHandler, ObjectInputStream objectInputStream) { protected void onResponseCodeRead(DataInputStream inputStream, UUID clientID) {
} }
} }

View File

@@ -1,9 +1,8 @@
package org.openautonomousconnection.protocol.packets.v1_0_0.beta; package org.openautonomousconnection.protocol.packets.v1_0_0.beta;
import dev.unlegitdqrk.unlegitlibrary.file.FileUtils; import dev.unlegitdqrk.unlegitlibrary.file.FileUtils;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler; import dev.unlegitdqrk.unlegitlibrary.network.system.server.ConnectedClient;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.ConnectionHandler; import dev.unlegitdqrk.unlegitlibrary.network.system.server.NetworkServer;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.ClientID;
import dev.unlegitdqrk.unlegitlibrary.network.utils.NetworkUtils; import dev.unlegitdqrk.unlegitlibrary.network.utils.NetworkUtils;
import org.openautonomousconnection.protocol.ProtocolBridge; import org.openautonomousconnection.protocol.ProtocolBridge;
import org.openautonomousconnection.protocol.packets.OACPacket; import org.openautonomousconnection.protocol.packets.OACPacket;
@@ -14,18 +13,16 @@ import org.openautonomousconnection.protocol.side.server.events.S_CustomClientCo
import org.openautonomousconnection.protocol.versions.ProtocolVersion; import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSResponseStatus; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSResponseStatus;
import java.io.File; import java.io.*;
import java.io.IOException; import java.util.UUID;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/** /**
* Authentication packet used between client and INS/Web servers. * Authentication packet used between client and INS/Web servers.
* <p> *
* Responsibilities: * <p>Responsibilities:
* <ul> * <ul>
* <li>Client → Server: Sends client ID and protocol version</li> * <li>Client → Server: Sends client connection id and protocol version</li>
* <li>Server → Client: Sends CA key, CA certificate and CA serial files</li> * <li>INS Server → Client: Sends CA key, CA certificate and CA serial files</li>
* <li>Performs version compatibility validation</li> * <li>Performs version compatibility validation</li>
* <li>Triggers authentication callbacks on both sides</li> * <li>Triggers authentication callbacks on both sides</li>
* </ul> * </ul>
@@ -45,95 +42,122 @@ public final class AuthPacket extends OACPacket {
} }
/** /**
* Registration constructor * Registration constructor.
*/ */
public AuthPacket() { public AuthPacket() {
super(4, ProtocolVersion.PV_1_0_0_BETA); super(8, ProtocolVersion.PV_1_0_0_BETA);
} }
/**
* Writes authentication data to the output stream.
* <p>
* Behavior differs based on the running side:
* <ul>
* <li>INS Server → sends CA bundle to the client</li>
* <li>Client → sends client ID + protocol version</li>
* </ul>
*/
@Override @Override
public void onWrite(PacketHandler packetHandler, ObjectOutputStream objectOutputStream) throws IOException, ClassNotFoundException { public void onWrite(DataOutputStream objectOutputStream) throws IOException {
if (protocolBridge.isRunningAsWebServer()) objectOutputStream.writeObject(protocolBridge.getProtocolVersion()); if (protocolBridge.isRunningAsWebServer()) {
else if (protocolBridge.isRunningAsINSServer()) { objectOutputStream.writeUTF(protocolBridge.getProtocolVersion().name());
objectOutputStream.writeObject(protocolBridge.getProtocolVersion()); return;
}
if (protocolBridge.isRunningAsINSServer()) {
objectOutputStream.writeUTF(protocolBridge.getProtocolVersion().name());
// Read ca files
String caKey = "N/A"; String caKey = "N/A";
String caPem = "N/A"; String caPem = "N/A";
String caSrl = "N/A"; String caSrl = "N/A";
try { try {
objectOutputStream.writeUTF(protocolBridge.getProtocolServer().getFolderStructure().getCaPrefix() + NetworkUtils.getPublicIPAddress()); String caPrefix = protocolBridge.getProtocolServer().getFolderStructure().getCaPrefix()
+ NetworkUtils.getPublicIPAddress();
objectOutputStream.writeUTF(caPrefix);
caKey = FileUtils.readFileFull(new File( caKey = FileUtils.readFileFull(new File(
protocolBridge.getProtocolServer().getFolderStructure().privateCAFolder, protocolBridge.getProtocolServer().getFolderStructure().privateCAFolder,
protocolBridge.getProtocolServer().getFolderStructure().getCaPrefix() + NetworkUtils.getPublicIPAddress() + ".key")); caPrefix + ".key"));
caPem = FileUtils.readFileFull(new File( caPem = FileUtils.readFileFull(new File(
protocolBridge.getProtocolServer().getFolderStructure().publicCAFolder, protocolBridge.getProtocolServer().getFolderStructure().publicCAFolder,
protocolBridge.getProtocolServer().getFolderStructure().getCaPrefix() + NetworkUtils.getPublicIPAddress() + ".pem")); caPrefix + ".pem"));
caSrl = FileUtils.readFileFull(new File( caSrl = FileUtils.readFileFull(new File(
protocolBridge.getProtocolServer().getFolderStructure().publicCAFolder, protocolBridge.getProtocolServer().getFolderStructure().publicCAFolder,
protocolBridge.getProtocolServer().getFolderStructure().getCaPrefix() + NetworkUtils.getPublicIPAddress() + ".srl")); caPrefix + ".srl"));
} catch (Exception exception) { } catch (Exception exception) {
protocolBridge.getLogger().exception("Failed to read ca-files", exception); protocolBridge.getLogger().exception("Failed to read ca-files", exception);
setResponseCode(INSResponseStatus.RESPONSE_AUTH_FAILED); setResponseCode(INSResponseStatus.RESPONSE_AUTH_FAILED);
} }
// Send ca data
objectOutputStream.writeUTF(caKey); objectOutputStream.writeUTF(caKey);
objectOutputStream.writeUTF(caPem); objectOutputStream.writeUTF(caPem);
objectOutputStream.writeUTF(caSrl); objectOutputStream.writeUTF(caSrl);
} else if (protocolBridge.isRunningAsClient()) { return;
objectOutputStream.writeObject(protocolBridge.getProtocolClient().getClientINSConnection().getClientId()); }
objectOutputStream.writeObject(protocolBridge.getProtocolVersion());
if (protocolBridge.isRunningAsClient()) {
// FIX: Send the connection id of the connection this auth is meant for.
// If we are connecting/authing against INS, use INS connectionId.
// Otherwise use Server connectionId.
UUID clientConnectionId = null;
if (protocolBridge.getProtocolClient() != null) {
if (protocolBridge.getProtocolClient().getClientINSConnection() != null
&& (protocolBridge.getProtocolClient().getClientServerConnection() == null)) {
clientConnectionId = protocolBridge.getProtocolClient().getClientINSConnection().getUniqueID();
} else if (protocolBridge.getProtocolClient().getClientServerConnection() != null) {
clientConnectionId = protocolBridge.getProtocolClient().getClientServerConnection().getUniqueID();
} else if (protocolBridge.getProtocolClient().getClientINSConnection() != null) {
clientConnectionId = protocolBridge.getProtocolClient().getClientINSConnection().getUniqueID();
}
}
objectOutputStream.writeUTF(clientConnectionId.toString());
objectOutputStream.writeUTF(protocolBridge.getProtocolVersion().name());
} }
} }
/**
* Reads authentication data and updates protocol state.
* <p>
* Behavior:
* <ul>
* <li>Server validates version and registers new connected client</li>
* <li>Client saves received CA files and completes TLS initialization</li>
* </ul>
*/
@Override @Override
public void onRead(PacketHandler packetHandler, ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException { public void onRead(DataInputStream objectInputStream, UUID id) throws IOException {
if (protocolBridge.isRunningAsServer()) { if (protocolBridge.isRunningAsServer()) {
ClientID clientID = (ClientID) objectInputStream.readObject(); UUID clientID = UUID.fromString(objectInputStream.readUTF());
ProtocolVersion clientVersion = (ProtocolVersion) objectInputStream.readObject(); ProtocolVersion clientVersion = ProtocolVersion.valueOf(objectInputStream.readUTF());
ConnectionHandler connectionHandler = protocolBridge.getProtocolServer().getNetwork().getConnectionHandlerByClientId(clientID);
ConnectedClient connectionHandler = getConnection(protocolBridge.getProtocolServer().getNetwork(), clientID);
if (connectionHandler == null) {
setResponseCode(INSResponseStatus.RESPONSE_AUTH_FAILED);
return;
}
if (!protocolBridge.isVersionSupported(clientVersion)) { if (!protocolBridge.isVersionSupported(clientVersion)) {
setResponseCode(INSResponseStatus.RESPONSE_AUTH_FAILED); setResponseCode(INSResponseStatus.RESPONSE_AUTH_FAILED);
connectionHandler.disconnect(); try {
connectionHandler.disconnect();
} catch (Exception ignored) {
}
return; return;
} else setResponseCode(INSResponseStatus.RESPONSE_AUTH_SUCCESS); }
setResponseCode(INSResponseStatus.RESPONSE_AUTH_SUCCESS);
CustomConnectedClient client = protocolBridge.getProtocolServer().getClientByID(clientID); CustomConnectedClient client = protocolBridge.getProtocolServer().getClientByID(clientID);
client.setClientVersion(clientVersion); if (client != null) {
protocolBridge.getProtocolValues().eventManager.executeEvent(new S_CustomClientConnectedEvent(client)); client.setClientVersion(clientVersion);
} else if (protocolBridge.isRunningAsClient()) { protocolBridge.getProtocolValues().eventManager.executeEvent(new S_CustomClientConnectedEvent(client));
ProtocolVersion serverVersion = (ProtocolVersion) objectInputStream.readObject(); }
return;
}
if (protocolBridge.isRunningAsClient()) {
ProtocolVersion serverVersion = ProtocolVersion.valueOf(objectInputStream.readUTF());
try { try {
if (!protocolBridge.isVersionSupported(serverVersion)) { if (!protocolBridge.isVersionSupported(serverVersion)) {
setResponseCode(INSResponseStatus.RESPONSE_AUTH_FAILED); setResponseCode(INSResponseStatus.RESPONSE_AUTH_FAILED);
protocolBridge.getProtocolClient().getClientINSConnection().disconnect(); if (protocolBridge.getProtocolClient() != null
&& protocolBridge.getProtocolClient().getClientINSConnection() != null) {
protocolBridge.getProtocolClient().getClientINSConnection().disconnect();
}
return; return;
} else setResponseCode(INSResponseStatus.RESPONSE_AUTH_SUCCESS); }
setResponseCode(INSResponseStatus.RESPONSE_AUTH_SUCCESS);
String caPrefix = objectInputStream.readUTF(); String caPrefix = objectInputStream.readUTF();
@@ -141,10 +165,9 @@ public final class AuthPacket extends OACPacket {
String caPem = objectInputStream.readUTF(); String caPem = objectInputStream.readUTF();
String caSrl = objectInputStream.readUTF(); String caSrl = objectInputStream.readUTF();
if (caKey.equalsIgnoreCase("N/A") || caPem.equalsIgnoreCase("N/A") || caSrl.equalsIgnoreCase("N/A")) if (caKey.equalsIgnoreCase("N/A") || caPem.equalsIgnoreCase("N/A") || caSrl.equalsIgnoreCase("N/A")) {
setResponseCode(INSResponseStatus.RESPONSE_AUTH_FAILED); setResponseCode(INSResponseStatus.RESPONSE_AUTH_FAILED);
else { } else {
File caPemFile = new File(protocolBridge.getProtocolClient().getFolderStructure().publicCAFolder, caPrefix + ".pem"); File caPemFile = new File(protocolBridge.getProtocolClient().getFolderStructure().publicCAFolder, caPrefix + ".pem");
File caSrlFile = new File(protocolBridge.getProtocolClient().getFolderStructure().publicCAFolder, caPrefix + ".srl"); File caSrlFile = new File(protocolBridge.getProtocolClient().getFolderStructure().publicCAFolder, caPrefix + ".srl");
File caKeyFile = new File(protocolBridge.getProtocolClient().getFolderStructure().privateCAFolder, caPrefix + ".key"); File caKeyFile = new File(protocolBridge.getProtocolClient().getFolderStructure().privateCAFolder, caPrefix + ".key");
@@ -154,9 +177,10 @@ public final class AuthPacket extends OACPacket {
if (!caSrlFile.exists()) caSrlFile.createNewFile(); if (!caSrlFile.exists()) caSrlFile.createNewFile();
if (!caKeyFile.exists()) caKeyFile.createNewFile(); if (!caKeyFile.exists()) caKeyFile.createNewFile();
// FIX: Correct file assignments.
FileUtils.writeFile(caPemFile, caPem); FileUtils.writeFile(caPemFile, caPem);
FileUtils.writeFile(caSrlFile, caKey); FileUtils.writeFile(caSrlFile, caSrl);
FileUtils.writeFile(caKeyFile, caSrl); FileUtils.writeFile(caKeyFile, caKey);
} catch (Exception exception) { } catch (Exception exception) {
protocolBridge.getLogger().exception("Failed to create/save ca-files", exception); protocolBridge.getLogger().exception("Failed to create/save ca-files", exception);
setResponseCode(INSResponseStatus.RESPONSE_AUTH_FAILED); setResponseCode(INSResponseStatus.RESPONSE_AUTH_FAILED);
@@ -164,11 +188,27 @@ public final class AuthPacket extends OACPacket {
} }
protocolBridge.getProtocolClient().setInsVersion(serverVersion); protocolBridge.getProtocolClient().setInsVersion(serverVersion);
protocolBridge.getProtocolValues().eventManager.executeEvent(new ConnectedToProtocolINSServerEvent(protocolBridge.getProtocolClient())); protocolBridge.getProtocolValues().eventManager.executeEvent(
new ConnectedToProtocolINSServerEvent(protocolBridge.getProtocolClient())
);
} catch (Exception ignored) { } catch (Exception ignored) {
protocolBridge.getProtocolClient().setServerVersion(serverVersion); protocolBridge.getProtocolClient().setServerVersion(serverVersion);
protocolBridge.getProtocolValues().eventManager.executeEvent(new ConnectedToProtocolServerEvent(protocolBridge.getProtocolClient())); protocolBridge.getProtocolValues().eventManager.executeEvent(
new ConnectedToProtocolServerEvent(protocolBridge.getProtocolClient())
);
} }
} }
} }
private ConnectedClient getConnection(NetworkServer server, UUID connectionId) {
if (server == null || connectionId == null) return null;
for (ConnectedClient connection : server.getConnectedClients()) {
if (connection != null && connection.getUniqueID().equals(connectionId)) {
return connection;
}
}
return null;
}
} }

View File

@@ -1,15 +1,12 @@
package org.openautonomousconnection.protocol.packets.v1_0_0.beta; package org.openautonomousconnection.protocol.packets.v1_0_0.beta;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.ClientID;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.packets.OACPacket; import org.openautonomousconnection.protocol.packets.OACPacket;
import org.openautonomousconnection.protocol.versions.ProtocolVersion; import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecordType; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecordType;
import java.io.IOException; import java.io.*;
import java.io.ObjectInputStream; import java.util.UUID;
import java.io.ObjectOutputStream;
/** /**
* Packet used by clients to query INS records from an INS server. * Packet used by clients to query INS records from an INS server.
@@ -34,7 +31,7 @@ public final class INSQueryPacket extends OACPacket {
@Getter @Getter
private INSRecordType type; private INSRecordType type;
@Getter @Getter
private ClientID clientId; private UUID clientId;
/** /**
* Creates a new INS query packet with all required parameters. * Creates a new INS query packet with all required parameters.
@@ -45,8 +42,8 @@ public final class INSQueryPacket extends OACPacket {
* @param type Record type requested. * @param type Record type requested.
* @param clientId Sender client ID for routing. * @param clientId Sender client ID for routing.
*/ */
public INSQueryPacket(String tln, String name, String sub, INSRecordType type, ClientID clientId) { public INSQueryPacket(String tln, String name, String sub, INSRecordType type, UUID clientId) {
super(5, ProtocolVersion.PV_1_0_0_BETA); super(7, ProtocolVersion.PV_1_0_0_BETA);
this.TLN = tln; this.TLN = tln;
this.name = name; this.name = name;
this.sub = sub; this.sub = sub;
@@ -58,36 +55,36 @@ public final class INSQueryPacket extends OACPacket {
* Registration constructor * Registration constructor
*/ */
public INSQueryPacket() { public INSQueryPacket() {
super(5, ProtocolVersion.PV_1_0_0_BETA); super(7, ProtocolVersion.PV_1_0_0_BETA);
} }
/** /**
* Serializes the INS query into the stream. * Serializes the INS query into the stream.
*/ */
@Override @Override
public void onWrite(PacketHandler handler, ObjectOutputStream out) throws IOException { public void onWrite(DataOutputStream out) throws IOException {
out.writeUTF(TLN); out.writeUTF(TLN);
out.writeUTF(name); out.writeUTF(name);
out.writeBoolean(sub != null); out.writeBoolean(sub != null);
if (sub != null) out.writeUTF(sub); if (sub != null) out.writeUTF(sub);
out.writeObject(type); out.writeUTF(type.name());
out.writeObject(clientId); out.writeUTF(clientId.toString());
} }
/** /**
* Deserializes the INS query from the stream. * Deserializes the INS query from the stream.
*/ */
@Override @Override
public void onRead(PacketHandler handler, ObjectInputStream in) throws IOException, ClassNotFoundException { public void onRead(DataInputStream in, UUID clientID) throws IOException {
TLN = in.readUTF(); TLN = in.readUTF();
name = in.readUTF(); name = in.readUTF();
boolean hasSub = in.readBoolean(); boolean hasSub = in.readBoolean();
sub = hasSub ? in.readUTF() : null; sub = hasSub ? in.readUTF() : null;
type = (INSRecordType) in.readObject(); type = INSRecordType.valueOf(in.readUTF());
clientId = (ClientID) in.readObject(); clientId = UUID.fromString(in.readUTF());
} }
} }

View File

@@ -1,7 +1,5 @@
package org.openautonomousconnection.protocol.packets.v1_0_0.beta; package org.openautonomousconnection.protocol.packets.v1_0_0.beta;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.ClientID;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.ProtocolBridge; import org.openautonomousconnection.protocol.ProtocolBridge;
import org.openautonomousconnection.protocol.packets.OACPacket; import org.openautonomousconnection.protocol.packets.OACPacket;
@@ -9,11 +7,10 @@ import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecord; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecord;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSResponseStatus; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSResponseStatus;
import java.io.IOException; import java.io.*;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID;
/** /**
* Response packet returned by an INS server after resolving a query. * Response packet returned by an INS server after resolving a query.
@@ -36,7 +33,7 @@ public final class INSResponsePacket extends OACPacket {
@Getter @Getter
private List<INSRecord> records; private List<INSRecord> records;
@Getter @Getter
private ClientID clientId; private UUID clientId;
/** /**
* Creates a populated response packet. * Creates a populated response packet.
@@ -46,7 +43,7 @@ public final class INSResponsePacket extends OACPacket {
* @param clientId ID of requesting client. * @param clientId ID of requesting client.
* @param bridge Protocol runtime context. * @param bridge Protocol runtime context.
*/ */
public INSResponsePacket(INSResponseStatus status, List<INSRecord> records, ClientID clientId, ProtocolBridge bridge) { public INSResponsePacket(INSResponseStatus status, List<INSRecord> records, UUID clientId, ProtocolBridge bridge) {
super(6, ProtocolVersion.PV_1_0_0_BETA); super(6, ProtocolVersion.PV_1_0_0_BETA);
this.status = status; this.status = status;
this.records = records; this.records = records;
@@ -68,32 +65,32 @@ public final class INSResponsePacket extends OACPacket {
* Serializes the response status, records and client ID. * Serializes the response status, records and client ID.
*/ */
@Override @Override
public void onWrite(PacketHandler handler, ObjectOutputStream out) throws IOException { public void onWrite(DataOutputStream out) throws IOException {
out.writeObject(status); out.writeUTF(status.name());
out.writeInt(records.size()); out.writeInt(records.size());
for (INSRecord rec : records) { for (INSRecord rec : records) {
out.writeObject(rec); writeObject(out, rec);
} }
out.writeObject(clientId); out.writeUTF(clientId.toString());
} }
/** /**
* Deserializes the response, reconstructing the record list. * Deserializes the response, reconstructing the record list.
*/ */
@Override @Override
public void onRead(PacketHandler handler, ObjectInputStream in) throws IOException, ClassNotFoundException { public void onRead(DataInputStream in, UUID clientID) throws IOException {
status = (INSResponseStatus) in.readObject(); status = INSResponseStatus.valueOf(in.readUTF());
int size = in.readInt(); int size = in.readInt();
records = new ArrayList<>(size); records = new ArrayList<>(size);
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
records.add((INSRecord) in.readObject()); records.add((INSRecord) readObject(in));
} }
clientId = (ClientID) in.readObject(); clientId = UUID.fromString(in.readUTF());
} }
/** /**
@@ -102,7 +99,7 @@ public final class INSResponsePacket extends OACPacket {
* If running on a client, forwards the result to the client-side API. * If running on a client, forwards the result to the client-side API.
*/ */
@Override @Override
protected void onResponseCodeRead(PacketHandler handler, ObjectInputStream in) { protected void onResponseCodeRead(DataInputStream in, UUID clientID) {
if (bridge.isRunningAsClient()) { if (bridge.isRunningAsClient()) {
bridge.getProtocolClient().onResponse(status, records); bridge.getProtocolClient().onResponse(status, records);
} }

View File

@@ -1,15 +1,13 @@
package org.openautonomousconnection.protocol.packets.v1_0_0.beta.web; package org.openautonomousconnection.protocol.packets.v1_0_0.beta.web;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.packets.OACPacket; import org.openautonomousconnection.protocol.packets.OACPacket;
import org.openautonomousconnection.protocol.versions.ProtocolVersion; import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.WebRequestMethod; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.WebRequestMethod;
import java.io.IOException; import java.io.*;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map; import java.util.Map;
import java.util.UUID;
public final class WebRequestPacket extends OACPacket { public final class WebRequestPacket extends OACPacket {
@@ -26,11 +24,11 @@ public final class WebRequestPacket extends OACPacket {
private byte[] body; private byte[] body;
public WebRequestPacket() { public WebRequestPacket() {
super(8, ProtocolVersion.PV_1_0_0_BETA); super(10, ProtocolVersion.PV_1_0_0_BETA);
} }
public WebRequestPacket(String path, WebRequestMethod method, Map<String, String> headers, byte[] body) { public WebRequestPacket(String path, WebRequestMethod method, Map<String, String> headers, byte[] body) {
super(8, ProtocolVersion.PV_1_0_0_BETA); super(10, ProtocolVersion.PV_1_0_0_BETA);
this.path = path; this.path = path;
this.method = method; this.method = method;
this.headers = headers; this.headers = headers;
@@ -38,10 +36,10 @@ public final class WebRequestPacket extends OACPacket {
} }
@Override @Override
public void onWrite(PacketHandler handler, ObjectOutputStream out) throws IOException { public void onWrite(DataOutputStream out) throws IOException {
out.writeUTF(path != null ? path : "/"); out.writeUTF(path != null ? path : "/");
out.writeUTF(method != null ? method.name() : WebRequestMethod.GET.name()); out.writeUTF(method != null ? method.name() : WebRequestMethod.GET.name());
out.writeObject(headers); writeMap(out, headers);
if (body == null) body = new byte[0]; if (body == null) body = new byte[0];
out.writeInt(body.length); out.writeInt(body.length);
@@ -50,10 +48,10 @@ public final class WebRequestPacket extends OACPacket {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public void onRead(PacketHandler handler, ObjectInputStream in) throws IOException, ClassNotFoundException { public void onRead(DataInputStream in, UUID clientID) throws IOException {
this.path = in.readUTF(); this.path = in.readUTF();
this.method = WebRequestMethod.valueOf(in.readUTF()); this.method = WebRequestMethod.valueOf(in.readUTF());
this.headers = (Map<String, String>) in.readObject(); this.headers = (Map<String, String>) readMap(in);
int len = in.readInt(); int len = in.readInt();
if (len < 0) { if (len < 0) {

View File

@@ -1,14 +1,12 @@
package org.openautonomousconnection.protocol.packets.v1_0_0.beta.web; package org.openautonomousconnection.protocol.packets.v1_0_0.beta.web;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.packets.OACPacket; import org.openautonomousconnection.protocol.packets.OACPacket;
import org.openautonomousconnection.protocol.versions.ProtocolVersion; import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import java.io.IOException; import java.io.*;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map; import java.util.Map;
import java.util.UUID;
public final class WebResponsePacket extends OACPacket { public final class WebResponsePacket extends OACPacket {
@@ -37,10 +35,10 @@ public final class WebResponsePacket extends OACPacket {
} }
@Override @Override
public void onWrite(PacketHandler handler, ObjectOutputStream out) throws IOException { public void onWrite(DataOutputStream out) throws IOException {
out.writeInt(statusCode); out.writeInt(statusCode);
out.writeUTF(contentType != null ? contentType : "text/plain"); out.writeUTF(contentType != null ? contentType : "text/plain");
out.writeObject(headers); writeMap(out, headers);
if (body == null) body = new byte[0]; if (body == null) body = new byte[0];
out.writeInt(body.length); out.writeInt(body.length);
@@ -48,10 +46,10 @@ public final class WebResponsePacket extends OACPacket {
} }
@Override @Override
public void onRead(PacketHandler handler, ObjectInputStream in) throws IOException, ClassNotFoundException { public void onRead(DataInputStream in, UUID clientID) throws IOException {
this.statusCode = in.readInt(); this.statusCode = in.readInt();
this.contentType = in.readUTF(); this.contentType = in.readUTF();
this.headers = (Map<String, String>) in.readObject(); this.headers = (Map<String, String>) readMap(in);
int len = in.readInt(); int len = in.readInt();
if (len < 0) { if (len < 0) {

View File

@@ -1,13 +1,11 @@
package org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.stream; package org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.stream;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.packets.OACPacket; import org.openautonomousconnection.protocol.packets.OACPacket;
import org.openautonomousconnection.protocol.versions.ProtocolVersion; import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import java.io.IOException; import java.io.*;
import java.io.ObjectInputStream; import java.util.UUID;
import java.io.ObjectOutputStream;
public final class WebStreamChunkPacket extends OACPacket { public final class WebStreamChunkPacket extends OACPacket {
@@ -17,24 +15,24 @@ public final class WebStreamChunkPacket extends OACPacket {
private byte[] data; private byte[] data;
public WebStreamChunkPacket() { public WebStreamChunkPacket() {
super(11, ProtocolVersion.PV_1_0_0_BETA); super(13, ProtocolVersion.PV_1_0_0_BETA);
} }
public WebStreamChunkPacket(int seq, byte[] data) { public WebStreamChunkPacket(int seq, byte[] data) {
super(11, ProtocolVersion.PV_1_0_0_BETA); super(13, ProtocolVersion.PV_1_0_0_BETA);
this.seq = seq; this.seq = seq;
this.data = (data != null) ? data : new byte[0]; this.data = (data != null) ? data : new byte[0];
} }
@Override @Override
public void onWrite(PacketHandler handler, ObjectOutputStream out) throws IOException { public void onWrite(DataOutputStream out) throws IOException {
out.writeInt(seq); out.writeInt(seq);
out.writeInt(data.length); out.writeInt(data.length);
out.write(data); out.write(data);
} }
@Override @Override
public void onRead(PacketHandler handler, ObjectInputStream in) throws IOException { public void onRead(DataInputStream in, UUID clientID) throws IOException {
seq = in.readInt(); seq = in.readInt();
int len = in.readInt(); int len = in.readInt();
if (len < 0) throw new IOException("Negative chunk length"); if (len < 0) throw new IOException("Negative chunk length");

View File

@@ -1,13 +1,11 @@
package org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.stream; package org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.stream;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.packets.OACPacket; import org.openautonomousconnection.protocol.packets.OACPacket;
import org.openautonomousconnection.protocol.versions.ProtocolVersion; import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import java.io.IOException; import java.io.*;
import java.io.ObjectInputStream; import java.util.UUID;
import java.io.ObjectOutputStream;
public final class WebStreamEndPacket extends OACPacket { public final class WebStreamEndPacket extends OACPacket {
@@ -24,12 +22,12 @@ public final class WebStreamEndPacket extends OACPacket {
} }
@Override @Override
public void onWrite(PacketHandler handler, ObjectOutputStream out) throws IOException { public void onWrite(DataOutputStream out) throws IOException {
out.writeBoolean(ok); out.writeBoolean(ok);
} }
@Override @Override
public void onRead(PacketHandler handler, ObjectInputStream in) throws IOException { public void onRead(DataInputStream in, UUID clientID) throws IOException {
ok = in.readBoolean(); ok = in.readBoolean();
} }
} }

View File

@@ -1,14 +1,12 @@
package org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.stream; package org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.stream;
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.packets.OACPacket; import org.openautonomousconnection.protocol.packets.OACPacket;
import org.openautonomousconnection.protocol.versions.ProtocolVersion; import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import java.io.IOException; import java.io.*;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map; import java.util.Map;
import java.util.UUID;
public final class WebStreamStartPacket extends OACPacket { public final class WebStreamStartPacket extends OACPacket {
@@ -22,11 +20,11 @@ public final class WebStreamStartPacket extends OACPacket {
private long totalLength; private long totalLength;
public WebStreamStartPacket() { public WebStreamStartPacket() {
super(10, ProtocolVersion.PV_1_0_0_BETA); super(11, ProtocolVersion.PV_1_0_0_BETA);
} }
public WebStreamStartPacket(int statusCode, String contentType, Map<String, String> headers, long totalLength) { public WebStreamStartPacket(int statusCode, String contentType, Map<String, String> headers, long totalLength) {
super(10, ProtocolVersion.PV_1_0_0_BETA); super(11, ProtocolVersion.PV_1_0_0_BETA);
this.statusCode = statusCode; this.statusCode = statusCode;
this.contentType = contentType; this.contentType = contentType;
this.headers = headers; this.headers = headers;
@@ -34,19 +32,19 @@ public final class WebStreamStartPacket extends OACPacket {
} }
@Override @Override
public void onWrite(PacketHandler handler, ObjectOutputStream out) throws IOException { public void onWrite(DataOutputStream out) throws IOException {
out.writeInt(statusCode); out.writeInt(statusCode);
out.writeUTF(contentType != null ? contentType : "application/octet-stream"); out.writeUTF(contentType != null ? contentType : "application/octet-stream");
out.writeObject(headers); writeMap(out, headers);
out.writeLong(totalLength); out.writeLong(totalLength);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public void onRead(PacketHandler handler, ObjectInputStream in) throws IOException, ClassNotFoundException { public void onRead(DataInputStream in, UUID clientID) throws IOException {
statusCode = in.readInt(); statusCode = in.readInt();
contentType = in.readUTF(); contentType = in.readUTF();
headers = (Map<String, String>) in.readObject(); headers = (Map<String, String>) readMap(in);
totalLength = in.readLong(); totalLength = in.readLong();
} }
} }

View File

@@ -1,9 +1,13 @@
package org.openautonomousconnection.protocol.side.client; package org.openautonomousconnection.protocol.side.client;
import dev.unlegitdqrk.unlegitlibrary.event.EventListener;
import dev.unlegitdqrk.unlegitlibrary.event.Listener;
import dev.unlegitdqrk.unlegitlibrary.file.FileUtils;
import dev.unlegitdqrk.unlegitlibrary.network.system.client.NetworkClient; import dev.unlegitdqrk.unlegitlibrary.network.system.client.NetworkClient;
import dev.unlegitdqrk.unlegitlibrary.network.system.client.events.state.disconnect.ClientFullyDisconnectedEvent; import dev.unlegitdqrk.unlegitlibrary.network.system.client.events.state.ClientDisconnectedEvent;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.Transport; import dev.unlegitdqrk.unlegitlibrary.network.system.utils.TransportProtocol;
import dev.unlegitdqrk.unlegitlibrary.network.utils.NetworkUtils; import dev.unlegitdqrk.unlegitlibrary.network.utils.NetworkUtils;
import dev.unlegitdqrk.unlegitlibrary.network.utils.PemUtils;
import dev.unlegitdqrk.unlegitlibrary.utils.DefaultMethodsOverrider; import dev.unlegitdqrk.unlegitlibrary.utils.DefaultMethodsOverrider;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.ProtocolBridge; import org.openautonomousconnection.protocol.ProtocolBridge;
@@ -15,543 +19,321 @@ import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecord;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecordType; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecordType;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSResponseStatus; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSResponseStatus;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* Abstract class defining the client-side protocol operations and interactions with INS and servers. * Abstract class defining the client-side protocol operations and interactions with INS and servers.
*/ */
@ProtocolInfo(protocolSide = ProtocolVersion.ProtocolSide.CLIENT) @ProtocolInfo(protocolSide = ProtocolVersion.ProtocolSide.CLIENT)
public abstract class ProtocolClient extends DefaultMethodsOverrider { public abstract class ProtocolClient extends EventListener {
/**
* Manages the folder structure for client certificates.
*/
@Getter @Getter
private final ClientCertificateFolderStructure folderStructure; private final ClientCertificateFolderStructure folderStructure;
/**
* Handles everything with INS-Connection.
*/
private NetworkClient clientToINS; private NetworkClient clientToINS;
/**
* Handles everything with Server-Connection.
*/
private NetworkClient clientToServer; private NetworkClient clientToServer;
/**
* The reference to the ProtocolBridge Object
*/
@Getter @Getter
private ProtocolBridge protocolBridge; private ProtocolBridge protocolBridge;
/**
* Stores the protocol version of the connected insserver.
*/
private ProtocolVersion insVersion = null; private ProtocolVersion insVersion = null;
/**
* Stores the protocol version of the connected server.
*/
private ProtocolVersion serverVersion = null; private ProtocolVersion serverVersion = null;
/**
* Initializes the ProtocolClient, setting up certificate folders and the INS client connection.
*/
public ProtocolClient() { public ProtocolClient() {
// Initialize and verify certificate folders and files
folderStructure = new ClientCertificateFolderStructure(); folderStructure = new ClientCertificateFolderStructure();
} }
/** public final void buildINSConnection(String host, int tcpPort, int udpPort) throws NoSuchAlgorithmException, KeyManagementException {
* Connects to a INS Server.
*
* @param host Server host
* @param tcpPort TCP port
* @param udpPort UDP port
*/
public final void buildINSConnection(String host, int tcpPort, int udpPort) {
if (!protocolBridge.isRunningAsClient()) if (!protocolBridge.isRunningAsClient())
throw new IllegalStateException("Not running as client"); throw new IllegalStateException("Not running as client");
if (clientToINS != null && if (clientToINS != null &&
(clientToINS.isFullyConnected() || clientToINS.isTcpConnected() || clientToINS.isUdpConnected())) (clientToINS.isConnected() || clientToINS.isTCPConnected() || clientToINS.isUDPConnected()))
return; return;
createINSConnection(host, tcpPort, udpPort); clientToINS = new NetworkClient.Builder().sslEnabled(false).
packetHandler(protocolBridge.getProtocolValues().packetHandler)
.eventManager(protocolBridge.getProtocolValues().eventManager)
.build();
} }
/** public final void buildServerConnection(String keyPassword, boolean ssl) throws Exception {
* Initialize connection to INS server
*/
private void createINSConnection(String host, int tcpPort, int udpPort) {
clientToINS = new NetworkClient.ClientBuilder().setLogger(protocolBridge.getLogger()).setProxy(protocolBridge.getProxy()).
setHost(host).setTcpPort(tcpPort).setUdpPort(udpPort).
setPacketHandler(protocolBridge.getProtocolValues().packetHandler).setEventManager(protocolBridge.getProtocolValues().eventManager).
setRootCAFolder(folderStructure.publicCAFolder).setClientCertificatesFolder(folderStructure.publicClientFolder, folderStructure.privateClientFolder).
build();
}
/**
* Connects to a Server.
*
* @param host Server host
* @param tcpPort TCP port
* @param udpPort UDP port
*/
public final void buildServerConnection(String host, int tcpPort, int udpPort) {
if (!protocolBridge.isRunningAsClient()) if (!protocolBridge.isRunningAsClient())
throw new IllegalStateException("Not running as client"); throw new IllegalStateException("Not running as client");
if (clientToServer != null && if (clientToServer != null &&
(clientToServer.isFullyConnected() || clientToServer.isTcpConnected() || clientToServer.isUdpConnected())) (clientToServer.isConnected() || clientToServer.isTCPConnected() || clientToServer.isUDPConnected()))
return; return;
createServerConnection(host, tcpPort, udpPort); if (ssl) {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
int caIndex = 0;
for (File caPem : FileUtils.listFiles(folderStructure.publicCAFolder, ".pem", ".crt", ".cer")) {
if (caPem.getName().endsWith(".srl")) continue;
X509Certificate caCert = PemUtils.loadCertificate(caPem);
trustStore.setCertificateEntry("root-ca-" + (caIndex++), caCert);
}
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
char[] keyPass = new char[0];
if (keyPassword != null) keyPass = keyPassword.toCharArray();
Map<String, File> keyFiles = new HashMap<>();
Map<String, File> certFiles = new HashMap<>();
for (File f : FileUtils.listFiles(folderStructure.privateClientFolder, ".key", ".pem")) {
if (f.getName().endsWith(".srl")) continue;
String base = FileUtils.stripExt(f.getName());
if (f.getName().endsWith(".key")) keyFiles.put(base, f);
if (f.getName().endsWith(".pem")) certFiles.put(base, f);
}
int clientIndex = 0;
for (String base : keyFiles.keySet()) {
File keyFile = keyFiles.get(base);
File certFile = certFiles.get(base);
if (certFile == null) {
File alt = new File(folderStructure.publicClientFolder, base + ".pem");
if (alt.exists()) certFile = alt;
}
if (certFile == null) continue;
PrivateKey key = PemUtils.loadPrivateKey(keyFile);
X509Certificate cert = PemUtils.loadCertificate(certFile);
String alias = "client-" + (clientIndex++);
keyStore.setKeyEntry(alias, key, keyPass, new X509Certificate[]{cert});
}
clientToServer = new NetworkClient.Builder().sslEnabled(ssl).
packetHandler(protocolBridge.getProtocolValues().packetHandler)
.eventManager(protocolBridge.getProtocolValues().eventManager)
.keyStore(keyStore, keyPass)
.trustStore(trustStore)
.build();
} else {
clientToServer = new NetworkClient.Builder().sslEnabled(ssl).
packetHandler(protocolBridge.getProtocolValues().packetHandler)
.eventManager(protocolBridge.getProtocolValues().eventManager)
.build();
}
} }
/**
* Gets the Server connection client.
*
* @return the NetworkClient handling the Server connection.
*/
public final NetworkClient getClientServerConnection() { public final NetworkClient getClientServerConnection() {
return clientToServer; return clientToServer;
} }
/** public final void attachBridge(ProtocolBridge bridge) throws Exception {
* Initialize connection to Server
*
* @param host Server host
* @param tcpPort Server port
* @param udpPort Server port
*/
private final void createServerConnection(String host, int tcpPort, int udpPort) {
clientToServer = new NetworkClient.ClientBuilder()
.setLogger(protocolBridge.getLogger())
.setProxy(protocolBridge.getProxy())
.setHost(host)
.setTcpPort(tcpPort)
.setUdpPort(udpPort)
.setPacketHandler(protocolBridge.getProtocolValues().packetHandler)
.setEventManager(protocolBridge.getProtocolValues().eventManager)
.setRootCAFolder(folderStructure.publicCAFolder)
.setClientCertificatesFolder(
folderStructure.publicClientFolder,
folderStructure.privateClientFolder
)
.build();
}
/**
* Injects the ProtocolBridge.
*
* @param bridge the Bridge instance.
* @throws IOException when NetworkServer failed to create.
*/
public final void attachBridge(ProtocolBridge bridge) throws IOException {
if (this.protocolBridge != null) if (this.protocolBridge != null)
throw new IllegalStateException("ProtocolBridge already attached!"); throw new IllegalStateException("ProtocolBridge already attached!");
this.protocolBridge = bridge; this.protocolBridge = bridge;
protocolBridge.getProtocolValues().eventManager.registerListener(this.getClass());
} }
/**
* Gets the INS connection client.
*
* @return the NetworkClient handling the INS connection.
*/
public final NetworkClient getClientINSConnection() { public final NetworkClient getClientINSConnection() {
return clientToINS; return clientToINS;
} }
/** private void checkFileExists(File folder, String prefix, String extension) throws CertificateException, IOException {
* Checks if the required certificate files exist in the specified folder.
*
* @param folder the folder to check for certificate files.
* @param prefix the prefix of the certificate files.
* @param extension the extension of the certificate files.
* @throws CertificateException if any required certificate file is missing or invalid.
* @throws IOException if there are I/O issues during the check.
*/
private final void checkFileExists(File folder, String prefix, String extension) throws CertificateException, IOException {
boolean found = false; boolean found = false;
// Check if folder exists
if (folder == null) throw new FileNotFoundException("Folder does not exist"); if (folder == null) throw new FileNotFoundException("Folder does not exist");
// List files in the folder
File[] files = folder.listFiles(); File[] files = folder.listFiles();
// Check if folder is empty
if (files == null || files.length == 0) if (files == null || files.length == 0)
throw new FileNotFoundException("Folder " + folder.getAbsolutePath() + " is empty"); throw new FileNotFoundException("Folder " + folder.getAbsolutePath() + " is empty");
// Validate each file in the folder
for (File file : files) { for (File file : files) {
if (!file.getName().startsWith(prefix)) if (!file.getName().startsWith(prefix))
throw new CertificateException(file.getAbsolutePath() + " is not valid"); throw new CertificateException(file.getAbsolutePath() + " is not valid");
// Check for specific files
if (!found) found = file.getName().equalsIgnoreCase(prefix + NetworkUtils.getPublicIPAddress() + extension); if (!found) found = file.getName().equalsIgnoreCase(prefix + NetworkUtils.getPublicIPAddress() + extension);
} }
// If the specific file is not found, throw an exception
if (!found) throw new CertificateException("Missing " + prefix + NetworkUtils.getPublicIPAddress() + extension); if (!found) throw new CertificateException("Missing " + prefix + NetworkUtils.getPublicIPAddress() + extension);
} }
/**
* Gets the protocol version of the connected server.
*
* @return the ProtocolVersion of the server, or PV_1_0_0_CLASSIC if not set.
*/
public final ProtocolVersion getServerVersion() { public final ProtocolVersion getServerVersion() {
return serverVersion == null ? ProtocolVersion.PV_1_0_0_CLASSIC : serverVersion; return serverVersion == null ? ProtocolVersion.PV_1_0_0_CLASSIC : serverVersion;
} }
/**
* Sets the protocol version of the connected server.
*
* @param serverVersion the ProtocolVersion to set for the server.
*/
public final void setServerVersion(ProtocolVersion serverVersion) { public final void setServerVersion(ProtocolVersion serverVersion) {
if (serverVersion == null) this.serverVersion = serverVersion; if (serverVersion == null) this.serverVersion = serverVersion;
} }
/**
* Gets the protocol version of the connected server.
*
* @return the ProtocolVersion of the server, or PV_1_0_0_CLASSIC if not set.
*/
public final ProtocolVersion getInsVersion() { public final ProtocolVersion getInsVersion() {
return insVersion == null ? ProtocolVersion.PV_1_0_0_CLASSIC : insVersion; return insVersion == null ? ProtocolVersion.PV_1_0_0_CLASSIC : insVersion;
} }
/**
* Sets the protocol version of the connected server.
*
* @param insVersion the ProtocolVersion to set for the server.
*/
public final void setInsVersion(ProtocolVersion insVersion) { public final void setInsVersion(ProtocolVersion insVersion) {
if (insVersion == null) this.insVersion = insVersion; if (insVersion == null) this.insVersion = insVersion;
} }
/** @Listener
* Handles disconnect events, resetting the server version and closing the server client connection if necessary. public final void onDisconnect(ClientDisconnectedEvent event) {
* if (clientToINS != null && !clientToINS.isConnected()) {
* @param event the ClientDisconnectedEvent triggered on INS disconnection.
*/
public final void onDisconnect(ClientFullyDisconnectedEvent event) {
// Reset server version on INS disconnect
if (!clientToINS.isFullyConnected() && clientToINS != null) {
insVersion = null; insVersion = null;
clientToINS = null; clientToINS = null;
disconnectFromServer(); disconnectFromServer();
} }
if (!clientToServer.isFullyConnected() && clientToServer != null) { if (clientToServer != null && !clientToServer.isConnected()) {
serverVersion = null; serverVersion = null;
clientToServer = null; clientToServer = null;
} }
} }
/**
* Checks if the connected insserver is a stable server.
*
* @return true if the server is stable, false otherwise.
*/
public final boolean isINSStableServer() { public final boolean isINSStableServer() {
// Check if the server version is stable
return !isINSBetaServer() && !isINSClassicServer(); return !isINSBetaServer() && !isINSClassicServer();
} }
/**
* Checks if the connected insserver or its compatible versions support stable protocol.
*
* @return true if stable protocol is supported, false otherwise.
*/
public final boolean supportINSServerStable() { public final boolean supportINSServerStable() {
boolean yes = false; boolean yes = false;
for (ProtocolVersion compatibleVersion : getServerVersion().getCompatibleVersions()) { for (ProtocolVersion compatibleVersion : getServerVersion().getCompatibleVersions()) {
// Check if compatible version is stable
yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.STABLE; yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.STABLE;
if (yes) break; if (yes) break;
} }
// Check if the server version is stable
return isINSStableServer() || yes; return isINSStableServer() || yes;
} }
/**
* Checks if the connected insserver is a beta server.
*
* @return true if the server is beta, false otherwise.
*/
public final boolean isINSBetaServer() { public final boolean isINSBetaServer() {
// Check if the server version is beta
return getInsVersion().getProtocolType() == ProtocolVersion.ProtocolType.BETA; return getInsVersion().getProtocolType() == ProtocolVersion.ProtocolType.BETA;
} }
/**
* Checks if the connected insserver or its compatible versions support beta protocol.
*
* @return true if beta protocol is supported, false otherwise.
*/
public final boolean supportINSServerBeta() { public final boolean supportINSServerBeta() {
boolean yes = false; boolean yes = false;
for (ProtocolVersion compatibleVersion : getInsVersion().getCompatibleVersions()) { for (ProtocolVersion compatibleVersion : getInsVersion().getCompatibleVersions()) {
// Check if compatible version is beta
yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.BETA; yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.BETA;
if (yes) break; if (yes) break;
} }
// Check if the server version is beta
return isINSBetaServer() || yes; return isINSBetaServer() || yes;
} }
/**
* Checks if the connected insserver is a classic server.
*
* @return true if the server is classic, false otherwise.
*/
public final boolean isINSClassicServer() { public final boolean isINSClassicServer() {
// Check if the server version is classic
return getInsVersion().getProtocolType() == ProtocolVersion.ProtocolType.CLASSIC; return getInsVersion().getProtocolType() == ProtocolVersion.ProtocolType.CLASSIC;
} }
/**
* Checks if the connected insserver or its compatible versions support classic protocol.
*
* @return true if classic protocol is supported, false otherwise.
*/
public final boolean supportINSServerClassic() { public final boolean supportINSServerClassic() {
boolean yes = false; boolean yes = false;
for (ProtocolVersion compatibleVersion : getInsVersion().getCompatibleVersions()) { for (ProtocolVersion compatibleVersion : getInsVersion().getCompatibleVersions()) {
// Check if compatible version is classic
yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.CLASSIC; yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.CLASSIC;
if (yes) break; if (yes) break;
} }
// Check if the server version is classic
return isINSClassicServer() || yes; return isINSClassicServer() || yes;
} }
/**
* Checks if the connected insserver supports the protocol version of the given packet.
*
* @param packet the OACPacket to check against the server's supported protocol version.
* @return true if the server supports the packet's protocol version, false otherwise.
*/
public final boolean supportINSServerPacket(OACPacket packet) { public final boolean supportINSServerPacket(OACPacket packet) {
// Check if the server supports the protocol version of the packet
return supportINSServerVersion(packet.getProtocolVersion()); return supportINSServerVersion(packet.getProtocolVersion());
} }
/**
* Checks if the connected insserver or its compatible versions support the specified protocol version.
*
* @param targetVersion the ProtocolVersion to check for support.
* @return true if the server or its compatible versions support the target version, false otherwise.
*/
public final boolean supportINSServerVersion(ProtocolVersion targetVersion) { public final boolean supportINSServerVersion(ProtocolVersion targetVersion) {
// Directly check if the server version matches or is in the list of compatible versions
return getInsVersion() == targetVersion || getInsVersion().getCompatibleVersions().contains(targetVersion); return getInsVersion() == targetVersion || getInsVersion().getCompatibleVersions().contains(targetVersion);
} }
/**
* Checks if the connected insserver or its compatible versions support the specified protocol.
*
* @param protocol the Protocol to check for support.
* @return true if the server or its compatible versions support the protocol, false otherwise.
*/
public final boolean supportINSServerProtocol(ProtocolVersion.Protocol protocol) { public final boolean supportINSServerProtocol(ProtocolVersion.Protocol protocol) {
boolean yes = false; boolean yes = false;
for (ProtocolVersion compatibleVersion : getInsVersion().getCompatibleVersions()) { for (ProtocolVersion compatibleVersion : getInsVersion().getCompatibleVersions()) {
// Check if compatible version supports the protocol
yes = compatibleVersion.getSupportedProtocols().contains(protocol); yes = compatibleVersion.getSupportedProtocols().contains(protocol);
if (yes) break; if (yes) break;
} }
// Check if the server version supports the protocol
return getInsVersion().getSupportedProtocols().contains(protocol) || yes; return getInsVersion().getSupportedProtocols().contains(protocol) || yes;
} }
//fwfwef
/**
* Checks if the connected server is a stable server.
*
* @return true if the server is stable, false otherwise.
*/
public final boolean isStableServer() { public final boolean isStableServer() {
// Check if the server version is stable
return !isBetaServer() && !isClassicServer(); return !isBetaServer() && !isClassicServer();
} }
/**
* Checks if the connected server or its compatible versions support stable protocol.
*
* @return true if stable protocol is supported, false otherwise.
*/
public final boolean supportServerStable() { public final boolean supportServerStable() {
boolean yes = false; boolean yes = false;
for (ProtocolVersion compatibleVersion : getServerVersion().getCompatibleVersions()) { for (ProtocolVersion compatibleVersion : getServerVersion().getCompatibleVersions()) {
// Check if compatible version is stable
yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.STABLE; yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.STABLE;
if (yes) break; if (yes) break;
} }
// Check if the server version is stable
return isBetaServer() || yes; return isBetaServer() || yes;
} }
/**
* Checks if the connected server is a beta server.
*
* @return true if the server is beta, false otherwise.
*/
public final boolean isBetaServer() { public final boolean isBetaServer() {
// Check if the server version is beta
return getServerVersion().getProtocolType() == ProtocolVersion.ProtocolType.BETA; return getServerVersion().getProtocolType() == ProtocolVersion.ProtocolType.BETA;
} }
/**
* Checks if the connected server or its compatible versions support beta protocol.
*
* @return true if beta protocol is supported, false otherwise.
*/
public final boolean supportServerBeta() { public final boolean supportServerBeta() {
boolean yes = false; boolean yes = false;
for (ProtocolVersion compatibleVersion : getServerVersion().getCompatibleVersions()) { for (ProtocolVersion compatibleVersion : getServerVersion().getCompatibleVersions()) {
// Check if compatible version is beta
yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.BETA; yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.BETA;
if (yes) break; if (yes) break;
} }
// Check if the server version is beta
return isStableServer() || yes; return isStableServer() || yes;
} }
/**
* Checks if the connected server is a classic server.
*
* @return true if the server is classic, false otherwise.
*/
public final boolean isClassicServer() { public final boolean isClassicServer() {
// Check if the server version is classic
return getServerVersion().getProtocolType() == ProtocolVersion.ProtocolType.CLASSIC; return getServerVersion().getProtocolType() == ProtocolVersion.ProtocolType.CLASSIC;
} }
/**
* Checks if the connected server or its compatible versions support classic protocol.
*
* @return true if classic protocol is supported, false otherwise.
*/
public final boolean supportServerClassic() { public final boolean supportServerClassic() {
boolean yes = false; boolean yes = false;
for (ProtocolVersion compatibleVersion : getServerVersion().getCompatibleVersions()) { for (ProtocolVersion compatibleVersion : getServerVersion().getCompatibleVersions()) {
// Check if compatible version is classic
yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.CLASSIC; yes = compatibleVersion.getProtocolType() == ProtocolVersion.ProtocolType.CLASSIC;
if (yes) break; if (yes) break;
} }
// Check if the server version is classic
return isClassicServer() || yes; return isClassicServer() || yes;
} }
/**
* Checks if the connected server supports the protocol version of the given packet.
*
* @param packet the OACPacket to check against the server's supported protocol version.
* @return true if the server supports the packet's protocol version, false otherwise.
*/
public final boolean supportServerPacket(OACPacket packet) { public final boolean supportServerPacket(OACPacket packet) {
// Check if the server supports the protocol version of the packet
return supportServerVersion(packet.getProtocolVersion()); return supportServerVersion(packet.getProtocolVersion());
} }
/**
* Checks if the connected server or its compatible versions support the specified protocol version.
*
* @param targetVersion the ProtocolVersion to check for support.
* @return true if the server or its compatible versions support the target version, false otherwise.
*/
public final boolean supportServerVersion(ProtocolVersion targetVersion) { public final boolean supportServerVersion(ProtocolVersion targetVersion) {
// Directly check if the server version matches or is in the list of compatible versions
return getServerVersion() == targetVersion || getServerVersion().getCompatibleVersions().contains(targetVersion); return getServerVersion() == targetVersion || getServerVersion().getCompatibleVersions().contains(targetVersion);
} }
/**
* Checks if the connected server or its compatible versions support the specified protocol.
*
* @param protocol the Protocol to check for support.
* @return true if the server or its compatible versions support the protocol, false otherwise.
*/
public final boolean supportServerProtocol(ProtocolVersion.Protocol protocol) { public final boolean supportServerProtocol(ProtocolVersion.Protocol protocol) {
boolean yes = false; boolean yes = false;
for (ProtocolVersion compatibleVersion : getServerVersion().getCompatibleVersions()) { for (ProtocolVersion compatibleVersion : getServerVersion().getCompatibleVersions()) {
// Check if compatible version supports the protocol
yes = compatibleVersion.getSupportedProtocols().contains(protocol); yes = compatibleVersion.getSupportedProtocols().contains(protocol);
if (yes) break; if (yes) break;
} }
// Check if the server version supports the protocol
return getServerVersion().getSupportedProtocols().contains(protocol) || yes; return getServerVersion().getSupportedProtocols().contains(protocol) || yes;
} }
/** public final void sendINSQuery(String tln, String name, String sub, INSRecordType type) throws Exception {
* Sends an INS query to the INS server.
* <p>
* The client requests a specific record type for a given TLN, name and optional subname.
* After sending the packet, {@link #onQuerySent(String, String, String, INSRecordType)} is invoked.
*
* @param tln The TLN.
* @param name The InfoName.
* @param sub Optional subname or {@code null}.
* @param type The requested record type.
* @throws IOException If sending the packet fails.
* @throws ClassNotFoundException If packet serialization fails.
*/
public final void sendINSQuery(String tln, String name, String sub, INSRecordType type) throws IOException, ClassNotFoundException {
if (!protocolBridge.isRunningAsClient()) return; if (!protocolBridge.isRunningAsClient()) return;
getClientINSConnection().sendPacket(new INSQueryPacket(tln, name, sub, type, getClientINSConnection().getClientId()), Transport.TCP); getClientINSConnection().sendPacket(
new INSQueryPacket(tln, name, sub, type, getClientINSConnection().getUniqueID()),
TransportProtocol.TCP
);
onQuerySent(tln, name, sub, type); onQuerySent(tln, name, sub, type);
} }
/**
* Disconnects from the Server.
*/
public final void disconnectFromServer() { public final void disconnectFromServer() {
if (clientToServer != null) { if (clientToServer != null) {
protocolBridge.getProtocolValues().eventManager.unregisterListener(this.getClass());
clientToServer.disconnect(); clientToServer.disconnect();
clientToServer = null; clientToServer = null;
} }
} }
/**
* Called when the client receives an INS response from the server.
* <p>
*
* @param status The response status from the server.
* @param records The list of records returned by the server.
*/
public void onResponse(INSResponseStatus status, List<INSRecord> records) { public void onResponse(INSResponseStatus status, List<INSRecord> records) {
} }
/**
* Called after a query was sent to the INS server.
* <p>
*
* @param tln The TLN requested.
* @param name The InfoName.
* @param sub Optional subname.
* @param type The requested record type.
*/
public void onQuerySent(String tln, String name, String sub, INSRecordType type) { public void onQuerySent(String tln, String name, String sub, INSRecordType type) {
} }
/**
* Manages the folder structure for client certificates.
*/
public static final class ClientCertificateFolderStructure { public static final class ClientCertificateFolderStructure {
public final File certificatesFolder; public final File certificatesFolder;

View File

@@ -1,11 +0,0 @@
package org.openautonomousconnection.protocol.side.client;
import org.openautonomousconnection.protocol.annotations.ProtocolInfo;
import org.openautonomousconnection.protocol.versions.ProtocolVersion;
/**
* Abstract class defining the client-side protocol operations and interactions with INS and servers.
*/
@ProtocolInfo(protocolSide = ProtocolVersion.ProtocolSide.CLIENT)
public class ProtocolWebClient extends ProtocolClient {
}

View File

@@ -1,17 +0,0 @@
package org.openautonomousconnection.protocol.side.ins;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.ConnectionHandler;
import org.openautonomousconnection.protocol.annotations.ProtocolInfo;
import org.openautonomousconnection.protocol.side.server.CustomConnectedClient;
import org.openautonomousconnection.protocol.versions.ProtocolVersion;
/**
* Represents a connected protocol client on the INS server side.
*/
@ProtocolInfo(protocolSide = ProtocolVersion.ProtocolSide.INS)
public final class ConnectedProtocolClient extends CustomConnectedClient {
public ConnectedProtocolClient(ConnectionHandler connectionHandler, ProtocolINSServer protocolINSServer) {
super(connectionHandler, protocolINSServer);
}
}

View File

@@ -1,7 +1,8 @@
package org.openautonomousconnection.protocol.side.ins; package org.openautonomousconnection.protocol.side.ins;
import dev.unlegitdqrk.unlegitlibrary.file.ConfigurationManager; import dev.unlegitdqrk.unlegitlibrary.file.ConfigurationManager;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.TransportPolicy; import dev.unlegitdqrk.unlegitlibrary.network.system.server.NetworkServer;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.ClientAuthMode;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.annotations.ProtocolInfo; import org.openautonomousconnection.protocol.annotations.ProtocolInfo;
import org.openautonomousconnection.protocol.side.server.ProtocolCustomServer; import org.openautonomousconnection.protocol.side.server.ProtocolCustomServer;
@@ -9,6 +10,8 @@ import org.openautonomousconnection.protocol.versions.ProtocolVersion;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecord; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecord;
import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecordType; import org.openautonomousconnection.protocol.versions.v1_0_0.beta.INSRecordType;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
@@ -25,17 +28,22 @@ public abstract class ProtocolINSServer extends ProtocolCustomServer {
* *
* @return The INS information site URL. * @return The INS information site URL.
*/ */
@Getter
private final String insInfoSite; private final String insInfoSite;
public final String getInsInfoSite() {
return insInfoSite;
}
/** /**
* Gets the INS registration site URL from the configuration. * Gets the INS registration site URL from the configuration.
* *
* @return The INS registration site URL. * @return The INS registration site URL.
*/ */
@Getter
private String insFrontendSite; private String insFrontendSite;
public final String getInsFrontendSite() {
return insFrontendSite;
}
/** /**
* Constructs a ProtocolINSServer with the specified configuration file. * Constructs a ProtocolINSServer with the specified configuration file.
* *
@@ -44,11 +52,14 @@ public abstract class ProtocolINSServer extends ProtocolCustomServer {
* @throws IOException If an I/O error occurs. * @throws IOException If an I/O error occurs.
* @throws CertificateException If a certificate error occurs. * @throws CertificateException If a certificate error occurs.
*/ */
public ProtocolINSServer(String insInfoSite, String insFrontendSite, int tcpPort, int udpPort) throws Exception { public ProtocolINSServer(String insInfoSite, String insFrontendSite) throws Exception {
super("ins", "ins", tcpPort, udpPort); super("ins", "ins");
this.insInfoSite = insInfoSite; this.insInfoSite = insInfoSite;
this.insFrontendSite = insFrontendSite; this.insFrontendSite = insFrontendSite;
setCustomClient(ConnectedProtocolClient.class); }
public void start(int tcpPort) throws IOException, InterruptedException {
getNetwork().start(tcpPort, -1);
} }
/** /**

View File

@@ -1,14 +1,19 @@
package org.openautonomousconnection.protocol.side.server; package org.openautonomousconnection.protocol.side.server;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.ConnectionHandler; import dev.unlegitdqrk.unlegitlibrary.event.EventListener;
import dev.unlegitdqrk.unlegitlibrary.event.EventManager;
import dev.unlegitdqrk.unlegitlibrary.event.EventPriority;
import dev.unlegitdqrk.unlegitlibrary.event.Listener;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.ConnectedClient;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.events.client.S_ClientDisconnectedEvent;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.packets.OACPacket; import org.openautonomousconnection.protocol.packets.OACPacket;
import org.openautonomousconnection.protocol.versions.ProtocolVersion; import org.openautonomousconnection.protocol.versions.ProtocolVersion;
public abstract class CustomConnectedClient { public class CustomConnectedClient extends EventListener {
@Getter @Getter
private final ConnectionHandler connection; private final ConnectedClient connection;
@Getter @Getter
private final ProtocolCustomServer server; private final ProtocolCustomServer server;
@@ -18,16 +23,15 @@ public abstract class CustomConnectedClient {
@Getter @Getter
private boolean clientVersionLoaded = false; private boolean clientVersionLoaded = false;
public CustomConnectedClient(ConnectionHandler connection, ProtocolCustomServer protocolServer) { public CustomConnectedClient(ConnectedClient connection, ProtocolCustomServer protocolServer) throws Exception {
this.connection = connection; this.connection = connection;
this.server = protocolServer; this.server = protocolServer;
server.getProtocolBridge().getProtocolValues().eventManager.registerListener(this.getClass());
} }
public synchronized void disconnect() { public synchronized void disconnect() {
try { server.getProtocolBridge().getProtocolValues().eventManager.unregisterListener(this.getClass());
server.clientDisconnected(this);
} catch (Exception ignored) {
}
try { try {
connection.disconnect(); connection.disconnect();
} catch (Exception ignored) { } catch (Exception ignored) {
@@ -36,6 +40,13 @@ public abstract class CustomConnectedClient {
clientVersion = null; clientVersion = null;
} }
@Listener(priority = EventPriority.HIGH)
public void onDisconnect(S_ClientDisconnectedEvent event) {
if (event.getClient().getUniqueID().equals(this.connection.getUniqueID())) {
clientVersion = null;
}
}
/** /**
* Gets the protocol version of the connected client. * Gets the protocol version of the connected client.

View File

@@ -1,28 +1,42 @@
package org.openautonomousconnection.protocol.side.server; package org.openautonomousconnection.protocol.side.server;
import dev.unlegitdqrk.unlegitlibrary.event.EventListener;
import dev.unlegitdqrk.unlegitlibrary.event.EventPriority;
import dev.unlegitdqrk.unlegitlibrary.event.Listener;
import dev.unlegitdqrk.unlegitlibrary.file.FileUtils;
import dev.unlegitdqrk.unlegitlibrary.network.system.client.events.state.ClientDisconnectedEvent;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.NetworkServer; import dev.unlegitdqrk.unlegitlibrary.network.system.server.NetworkServer;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.ClientID; import dev.unlegitdqrk.unlegitlibrary.network.system.server.events.state.ServerStoppedEvent;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.TransportPolicy; import dev.unlegitdqrk.unlegitlibrary.network.system.utils.ClientAuthMode;
import dev.unlegitdqrk.unlegitlibrary.network.utils.NetworkUtils; import dev.unlegitdqrk.unlegitlibrary.network.utils.NetworkUtils;
import dev.unlegitdqrk.unlegitlibrary.network.utils.PemUtils;
import lombok.Getter; import lombok.Getter;
import lombok.Setter;
import org.openautonomousconnection.protocol.ProtocolBridge; import org.openautonomousconnection.protocol.ProtocolBridge;
import org.openautonomousconnection.protocol.side.server.events.S_CustomClientDisconnectedEvent;
import org.openautonomousconnection.protocol.side.web.managers.AuthManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.ArrayList; import java.security.cert.X509Certificate;
import java.util.List; import java.util.*;
public abstract class ProtocolCustomServer { public abstract class ProtocolCustomServer extends EventListener {
/** /**
* Structure for server. * Structure for server.
*/ */
@Getter
private final ServerCertificateFolderStructure folderStructure; private final ServerCertificateFolderStructure folderStructure;
public final ServerCertificateFolderStructure getFolderStructure() {
return folderStructure;
}
/** /**
* Certificate files for SSL. * Certificate files for SSL.
*/ */
@@ -35,43 +49,43 @@ public abstract class ProtocolCustomServer {
/** /**
* The reference to the ProtocolBridge Object * The reference to the ProtocolBridge Object
*/ */
@Getter
private ProtocolBridge protocolBridge; private ProtocolBridge protocolBridge;
public final ProtocolBridge getProtocolBridge() {
return protocolBridge;
}
/** /**
* List of connected web clients. * List of connected web clients.
*/ */
@Getter private final List<CustomConnectedClient> clients;
private List<CustomConnectedClient> clients;
@Setter public final List<CustomConnectedClient> getClients() {
@Getter return clients;
private Class<? extends CustomConnectedClient> customClient; }
/** /**
* The network server handling pipeline connections. * The network server handling pipeline connections.
*/ */
@Getter
private NetworkServer network; private NetworkServer network;
@Getter public final NetworkServer getNetwork() {
private int tcpPort; return network;
}
@Getter protected final void setNetwork(NetworkServer network) {
private int udpPort; this.network = network;
}
/** /**
* Initializes the web server with the given configuration, authentication, and rules files. * Initializes the web server with the given configuration, authentication, and rules files.
* *
* @throws Exception If an error occurs during initialization. * @throws Exception If an error occurs during initialization.
*/ */
public ProtocolCustomServer(String caPrefix, String certPrefix, int tcpPort, int udpPort) throws Exception { public ProtocolCustomServer(String caPrefix, String certPrefix) throws Exception {
// Initialize the list of connected clients // Initialize the list of connected clients
this.clients = new ArrayList<>(); this.clients = new ArrayList<>();
this.tcpPort = tcpPort;
this.udpPort = udpPort;
// Set up folder structure for certificates // Set up folder structure for certificates
folderStructure = new ServerCertificateFolderStructure(caPrefix, certPrefix); folderStructure = new ServerCertificateFolderStructure(caPrefix, certPrefix);
@@ -90,36 +104,95 @@ public abstract class ProtocolCustomServer {
* @param bridge the Bridge instance. * @param bridge the Bridge instance.
* @throws IOException when NetworkServer failed to create. * @throws IOException when NetworkServer failed to create.
*/ */
public final void attachBridge(ProtocolBridge bridge) throws IOException { public final void attachBridge(ProtocolBridge bridge, String keyPassword, boolean ssl, ClientAuthMode authMode) throws Exception {
if (this.protocolBridge != null) if (this.protocolBridge != null)
throw new IllegalStateException("ProtocolBridge already attached!"); throw new IllegalStateException("ProtocolBridge already attached!");
this.protocolBridge = bridge; if (ssl) {
createNetworkServer(); char[] keyPass = new char[0];
if (keyPassword != null) keyPass = keyPassword.toCharArray();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
int caIndex = 0;
for (File caPem : FileUtils.listFiles(folderStructure.publicCAFolder, ".pem", ".crt", ".cer")) {
if (caPem.getName().endsWith(".srl")) continue;
if (!caPem.getName().startsWith(folderStructure.getCaPrefix())) continue;
X509Certificate caCert = PemUtils.loadCertificate(caPem);
trustStore.setCertificateEntry("root-ca-" + (caIndex++), caCert);
}
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
Map<String, File> keyFiles = new HashMap<>();
Map<String, File> certFiles = new HashMap<>();
for (File f : FileUtils.listFiles(folderStructure.privateServerFolder, ".key", ".pem")) {
if (f.getName().endsWith(".srl")) continue;
if (!f.getName().startsWith(folderStructure.getCertPrefix())) continue;
String base = FileUtils.stripExt(f.getName());
if (f.getName().endsWith(".key")) keyFiles.put(base, f);
if (f.getName().endsWith(".pem")) certFiles.put(base, f);
}
int serverIndex = 0;
for (String base : keyFiles.keySet()) {
File keyFile = keyFiles.get(base);
File certFile = certFiles.get(base);
if (certFile == null) {
File alt = new File(folderStructure.publicServerFolder, base + ".pem");
if (alt.exists()) certFile = alt;
}
if (certFile == null) continue;
PrivateKey key = PemUtils.loadPrivateKey(keyFile);
X509Certificate cert = PemUtils.loadCertificate(certFile);
String alias = "server-" + (serverIndex++);
keyStore.setKeyEntry(alias, key, keyPass, new X509Certificate[]{cert});
}
bridge.getProtocolValues().eventManager.registerListener(this.getClass());
network = new NetworkServer.Builder()
.packetHandler(bridge.getProtocolValues().packetHandler)
.eventManager(bridge.getProtocolValues().eventManager)
.sslEnabled(true)
.clientAuthMode(authMode)
.keyStore(keyStore, keyPass)
.trustStore(trustStore)
.build();
} else {
network = new NetworkServer.Builder()
.packetHandler(bridge.getProtocolValues().packetHandler)
.eventManager(bridge.getProtocolValues().eventManager)
.sslEnabled(false)
.clientAuthMode(ClientAuthMode.NONE)
.build();
}
} }
/** @Listener
* Initialize the pipeline server public void onStop(ServerStoppedEvent event) {
*/ if (event.getServer() == network) {
private void createNetworkServer() { protocolBridge.getProtocolValues().eventManager.unregisterListener(this.getClass());
network = new NetworkServer.ServerBuilder(). }
setTcpPort(tcpPort).setUdpPort(udpPort).setTransportPolicy(TransportPolicy.bothRequired()).
setTimeout(0).
setPacketHandler(protocolBridge.getProtocolValues().packetHandler).
setEventManager(protocolBridge.getProtocolValues().eventManager).setLogger(protocolBridge.getLogger()).
setServerCertificate(certFile, keyFile).setRootCAFolder(folderStructure.publicCAFolder).
build();
} }
/** /**
* Retrieves a connected web client by its client ID. * Retrieves a connected web client by its client ID.
* *
* @param clientID The client ID to search for. * @param clientID The client ID to search for.
* @return The connected web client with the specified ID, or null if not found. * @return The connected web client with the specified ID, or null if not found.
*/ */
public final <T extends CustomConnectedClient> T getClientByID(ClientID clientID) { public final <T extends CustomConnectedClient> T getClientByID(UUID clientID) {
for (CustomConnectedClient client : clients) for (CustomConnectedClient client : clients)
if (client.getConnection().getClientId() == clientID) return (T) client; if (client.getConnection().getUniqueID().equals(clientID)) return (T) client;
return null; return null;
} }
@@ -156,15 +229,14 @@ public abstract class ProtocolCustomServer {
if (!found) throw new CertificateException("Missing " + prefix + NetworkUtils.getPublicIPAddress() + extension); if (!found) throw new CertificateException("Missing " + prefix + NetworkUtils.getPublicIPAddress() + extension);
} }
public final void clientDisconnected(CustomConnectedClient client) { @Listener(priority = EventPriority.NORMAL)
clients.remove(client); public final void clientDisconnected(ClientDisconnectedEvent event) {
onDisconnect(client); for (CustomConnectedClient client : new ArrayList<>(clients)) {
} if (client.getConnection().getUniqueID().equals(event.getClient().getUniqueID())) {
protocolBridge.getProtocolValues().eventManager.executeEvent(new S_CustomClientDisconnectedEvent(client));
/** clients.remove(client);
* Optional callback when the connection closes. }
*/ }
public void onDisconnect(CustomConnectedClient client) {
} }
/** /**

View File

@@ -1,15 +0,0 @@
package org.openautonomousconnection.protocol.side.web;
import dev.unlegitdqrk.unlegitlibrary.network.system.server.ConnectionHandler;
import lombok.Getter;
import org.openautonomousconnection.protocol.side.server.CustomConnectedClient;
/**
* A connected web client using pure protocol packets.
*/
public final class ConnectedWebClient extends CustomConnectedClient {
public ConnectedWebClient(ConnectionHandler pipelineConnection, ProtocolWebServer webServer) {
super(pipelineConnection, webServer);
}
}

View File

@@ -1,12 +1,13 @@
package org.openautonomousconnection.protocol.side.web; package org.openautonomousconnection.protocol.side.web;
import dev.unlegitdqrk.unlegitlibrary.file.FileUtils; import dev.unlegitdqrk.unlegitlibrary.file.FileUtils;
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.TransportPolicy; import dev.unlegitdqrk.unlegitlibrary.network.system.utils.ClientAuthMode;
import dev.unlegitdqrk.unlegitlibrary.string.RandomString; import dev.unlegitdqrk.unlegitlibrary.string.RandomString;
import lombok.Getter; import lombok.Getter;
import org.openautonomousconnection.protocol.annotations.ProtocolInfo; import org.openautonomousconnection.protocol.annotations.ProtocolInfo;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.WebRequestPacket; import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.WebRequestPacket;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.WebResponsePacket; import org.openautonomousconnection.protocol.packets.v1_0_0.beta.web.WebResponsePacket;
import org.openautonomousconnection.protocol.side.server.CustomConnectedClient;
import org.openautonomousconnection.protocol.side.server.ProtocolCustomServer; import org.openautonomousconnection.protocol.side.server.ProtocolCustomServer;
import org.openautonomousconnection.protocol.side.web.managers.AuthManager; import org.openautonomousconnection.protocol.side.web.managers.AuthManager;
import org.openautonomousconnection.protocol.side.web.managers.RuleManager; import org.openautonomousconnection.protocol.side.web.managers.RuleManager;
@@ -23,31 +24,47 @@ public abstract class ProtocolWebServer extends ProtocolCustomServer {
/** /**
* Folder for web content. * Folder for web content.
*/ */
@Getter
private final File contentFolder; private final File contentFolder;
public final File getContentFolder() {
return contentFolder;
}
/** /**
* Folder for error pages. * Folder for error pages.
*/ */
@Getter
private final File errorsFolder; private final File errorsFolder;
public final File getErrorsFolder() {
return errorsFolder;
}
/** /**
* A unique secret for session management. * A unique secret for session management.
*/ */
@Getter private final String uniqueSessionString;
private String uniqueSessionString;
public final String getUniqueSessionString() {
return uniqueSessionString;
}
/** /**
* The expiration time of a Session in minutes * The expiration time of a Session in minutes
*/ */
@Getter private final int sessionExpire;
private int sessionExpire;
public final int getSessionExpire() {
return sessionExpire;
}
/** /**
* The max upload size in MB * The max upload size in MB
*/ */
@Getter private final int maxUploadSize;
private int maxUploadSize;
public final int getMaxUploadSize() {
return maxUploadSize;
}
/** /**
* Initializes the web server with the given configuration, authentication, and rules files. * Initializes the web server with the given configuration, authentication, and rules files.
@@ -58,9 +75,8 @@ public abstract class ProtocolWebServer extends ProtocolCustomServer {
* @param uploadSize The max upload size in MB * @param uploadSize The max upload size in MB
* @throws Exception If an error occurs during initialization. * @throws Exception If an error occurs during initialization.
*/ */
public ProtocolWebServer(File authFile, File rulesFile, int tcpPort, int udpPort, public ProtocolWebServer(File authFile, File rulesFile, int sessionExpire, int uploadSize) throws Exception {
int sessionExpire, int uploadSize) throws Exception { super("server", "server");
super("server", "server", tcpPort, udpPort);
this.sessionExpire = sessionExpire; this.sessionExpire = sessionExpire;
this.maxUploadSize = uploadSize; this.maxUploadSize = uploadSize;
@@ -108,8 +124,6 @@ public abstract class ProtocolWebServer extends ProtocolCustomServer {
AuthManager.loadAuthFile(authFile); AuthManager.loadAuthFile(authFile);
RuleManager.loadRules(rulesFile); RuleManager.loadRules(rulesFile);
setCustomClient(ConnectedWebClient.class);
} }
/** /**
@@ -119,5 +133,5 @@ public abstract class ProtocolWebServer extends ProtocolCustomServer {
* @param request The full decoded request packet. * @param request The full decoded request packet.
* @return The response packet that should be sent back to the client. * @return The response packet that should be sent back to the client.
*/ */
public abstract WebResponsePacket onWebRequest(ConnectedWebClient client, WebRequestPacket request); public abstract WebResponsePacket onWebRequest(CustomConnectedClient client, WebRequestPacket request);
} }