master #1

Merged
bedohswe merged 27 commits from pixtaded/crab:master into master 2025-02-11 18:05:01 +00:00
13 changed files with 248 additions and 68 deletions

View File

@ -24,12 +24,12 @@ To get started with CRAB, follow these steps:
```
2. **Build the project:**
Ensure you have Java Development Kit (JDK) of version 17 or higher installed. You can build the project using Maven:
Ensure you have Java Development Kit (JDK) of version 17 or higher installed. You can build the project using Gradle:
```bash
./gradlew clean build
```
3. **Run the bundle**: You will have the built .tar and .zip packages in ./build/distributions directory.
3. **Run the bundle**: You will have the built .jar package in ./build/libs directory.
## Usage
@ -37,4 +37,46 @@ Once the server is running, clients can connect to it and send messages accordin
## RAC Protocol
You can see the RAC protocol documentation [here](https://bedohswe.eu.org/text/rac/protocol.md.html).
1. Message Retrieval
a. The client initiates a message retrieval session by sending the byte `0x00` to the server.
b. In response, the server transmits the size of the available messages as an ASCII-encoded string.
c. After receiving the size, the client must send one of the following bytes or close the connection:
i. Sending `0x01` instructs the server to transmit all messages in full.
ii. Sending `0x02` followed by the clients cached messages length (as an ASCII string, e.g., `0x02"1024"`) instructs the server to transmit only new messages added since the cached length. The server sends messages starting from the cached length offset, and the client updates its cached length to the total size received in step 1b after processing the new messages.
2. Message Transmission
a. To send a message, the client issues a request in one of the following formats:
i. Unauthenticated Message: The client sends the byte `0x01` followed immediately by the message content. The server does not send a response.
ii. Authenticated Message: The client sends the byte `0x02` followed by the username, a newline character (`\n`), the password, a newline character and the message content. The server responds with a single byte:
- `0x01` indicates the user does not exist.
- `0x02` indicates the password is incorrect.
- A successful authentication results in the server accepting the message without sending a response.
3. User Registration
a. To register a new user, the client sends a request formatted as:
- The byte `0x03`.
- The username, followed by a newline character (`\n`).
- The password.
b. The server processes the request and responds with a single byte:
- `0x01` if the username already exists.
- A successful registration is assumed if no error byte (`0x01`) is received. The client should close the connection after handling the response.
### Additional Notes:
- The current specification of RACv2 is implemented in `lRACd` version 2.0.0 and `clRAC` version 2.0.0.
- When using `0x02` for incremental retrieval, the client must ensure the cached length is synchronized with the servers total message length (retrieved via `0x00`). The server sends messages from the cached length onward, and the client calculates the read size as `(total_length - cached_length)`.
- After receiving incremental messages, the client must update its cached length to the total length provided in step 1b to maintain consistency in subsequent requests.
- For authenticated message transmission (`0x02`) or user registration (`0x03`), the client must follow the specified format precisely. The server validates the structure of the request and responds with error codes only for specific failure conditions (e.g., invalid credentials or duplicate usernames).

View File

@ -1,19 +1,31 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
id 'java'
id 'application'
id 'com.gradleup.shadow' version '9.0.0-beta4'
}
group = 'net.pixtaded'
version = '1.0-SNAPSHOT'
version = projectVersion
repositories {
mavenCentral()
}
application {
mainClass = 'net.pixtaded.crab.Main'
}
dependencies {
implementation('org.xerial:sqlite-jdbc:3.47.1.0')
}
tasks.build.dependsOn tasks.shadowJar
tasks.named('jar', Jar) {
manifest {
attributes 'Main-Class': 'net.pixtaded.crab.Main'
}
}
tasks.named('shadowJar', ShadowJar) {
archiveBaseName = 'crab'
archiveClassifier = ''
archiveVersion = projectVersion
}

1
gradle.properties Normal file
View File

@ -0,0 +1 @@
projectVersion=2.0.0-SNAPSHOT

View File

@ -0,0 +1,4 @@
package net.pixtaded.crab.client;
public record ClientColor(String regex, String color) {
}

View File

@ -0,0 +1,28 @@
package net.pixtaded.crab.client;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ClientUtil {
public static final String COLOR_KEY = "\u2550\u2550\u2550";
public static final ClientColor[] colors = {
new ClientColor( COLOR_KEY + "(<.*?>)", "\033[0;31m$1\033[0m"),
new ClientColor("\uB9AC\u3E70(<.*?>)", "\033[0;32m$1\033[0m"),
new ClientColor(" (<.*?>)", " \033[0;34m$1\033[0m"),
new ClientColor("\u00B0\u0298(<.*?>)", "\033[0;35m$1\033[0m")
};
public static String clientColors(String s) {
for (ClientColor color : colors) s = matchClientKey(s, color);
return s;
}
private static String matchClientKey(String s, ClientColor color) {
Pattern p = Pattern.compile(color.regex());
Matcher m = p.matcher(s);
return m.replaceAll(color.color());
}
}

View File

@ -1,7 +1,9 @@
package net.pixtaded.crab.client;
import net.pixtaded.crab.common.Crab;
import net.pixtaded.crab.common.Logs;
import net.pixtaded.crab.common.Sanitizer;
import net.pixtaded.crab.common.Util;
import java.io.*;
import java.net.InetSocketAddress;
@ -18,6 +20,7 @@ public class CrabClient implements Crab {
private BufferedReader in;
private int lastBufferLength = 0;
private String nickname;
private Logs cache = new Logs(0, "");
public CrabClient() {
this.nickname = "";
@ -27,7 +30,7 @@ public class CrabClient implements Crab {
this.serverAddress = serverAddress;
this.port = port;
if (nickname != null)
this.nickname = "<" + nickname + "> ";
this.nickname = ClientUtil.COLOR_KEY + "<" + nickname + "> ";
else
this.nickname = "";
}
@ -37,7 +40,6 @@ public class CrabClient implements Crab {
try {
if (this.serverAddress == null)
setup();
connect();
communicate();
} catch (IOException e) {
System.err.println("Error connecting to the server: " + e.getMessage());
@ -68,8 +70,8 @@ public class CrabClient implements Crab {
System.out.print("Enter your nickname (leave empty for no nickname): ");
nickname = scanner.nextLine();
if (nickname != "")
nickname = "<" + nickname + "> ";
if (!nickname.isEmpty())
nickname = ClientUtil.COLOR_KEY + "<" + nickname + "> ";
}
private void connect() throws IOException {
@ -82,9 +84,7 @@ public class CrabClient implements Crab {
private void communicate() throws IOException {
Scanner scanner = new Scanner(System.in);
String message;
while (true) {
System.out.print("\033[H\033[2J");
getLogs();
System.out.print("Enter a message (or type '/exit' to exit): ");
message = scanner.nextLine();
@ -93,33 +93,44 @@ public class CrabClient implements Crab {
break;
}
if (!message.isEmpty()) sendPacket(MESSAGE, this.nickname + message);
if (!message.isEmpty()) sendMessage(message);
}
}
private void sendPacket(byte PID, String argument) throws IOException {
String formattedMessage = String.valueOf((char) PID) + argument + "\n";
private void sendPacket(byte PID, String argument, boolean receiveResponse) throws IOException {
if (socket == null || socket.isClosed()) connect();
String formattedMessage = (char) PID + argument;
out.print(formattedMessage);
out.flush();
receiveResponse(PID);
if (receiveResponse) receiveResponse(PID);
}
private void printLogs() {
clearScreen();
System.out.print(ClientUtil.clientColors(Sanitizer.sanitizeString(cache.content(), false)));
}
private void sendMessage(String msg) throws IOException {
sendPacket(MESSAGE, this.nickname + msg, false);
closeConnection();
}
private void receiveResponse(byte PID) throws IOException {
switch (PID) {
case LOGS_SIZE -> {
char[] buffer = new char[10];
int response = in.read(buffer);
lastBufferLength = Integer.parseInt(new String(buffer).trim());
String convertedString = Util.readAsciiNumber(in);
if (!convertedString.isEmpty()) lastBufferLength = Integer.parseInt(convertedString);
} case CACHED_LOGS -> {
byte[] bytes = socket.getInputStream().readNBytes(lastBufferLength - cache.sizeInBytes());
cache = new Logs(lastBufferLength, cache.content() + new String(bytes, StandardCharsets.UTF_8));
} case LOGS -> {
byte[] bytes = socket.getInputStream().readNBytes(lastBufferLength);
System.out.print(Sanitizer.sanitizeString(new String(bytes, StandardCharsets.UTF_8), false));
cache = new Logs(lastBufferLength, new String(bytes, StandardCharsets.UTF_8));
} default -> {
}
}
closeConnection();
connect();
}
private void closeConnection() {
@ -133,7 +144,18 @@ public class CrabClient implements Crab {
}
private void getLogs() throws IOException {
sendPacket(LOGS_SIZE, "");
sendPacket(LOGS, "");
sendPacket(LOGS_SIZE, "", true);
if (this.cache.sizeInBytes() < lastBufferLength) {
sendPacket(CACHED_LOGS, String.valueOf(cache.sizeInBytes()), true);
} else if (this.cache.sizeInBytes() != lastBufferLength) {
sendPacket(LOGS, "", true);
}
closeConnection();
printLogs();
}
}
private void clearScreen() {
System.out.print("\033[999999S\033[H\033[2J");
}
}

View File

@ -0,0 +1,4 @@
package net.pixtaded.crab.common;
public record Logs(int sizeInBytes, String content) {
}

View File

@ -1,7 +1,10 @@
package net.pixtaded.crab.common;
public class PID {
public static final byte MESSAGE = 0x30;
public static final byte LOGS_SIZE = 0x31;
public static final byte LOGS = 0x32;
}
public static final byte LOGS_SIZE = 0x00;
public static final byte LOGS = 0x01;
public static final byte MESSAGE = 0x01;
public static final byte CACHED_LOGS = 0x02;
public static final byte AUTHENTICATED_MESSAGE = 0x02;
public static final byte REGISTER = 0x03;
}

View File

@ -2,11 +2,17 @@ package net.pixtaded.crab.common;
public class Sanitizer {
public static String sanitizeString(String s, boolean sanitizeNewlines) {
String sanitized = s.replaceAll("\033", "");
String sanitized = s.replaceAll("[\010\015\033]", "");
if (sanitizeNewlines) {
sanitized = sanitized.replaceAll("\n", "\\\\n");
if (!s.endsWith("\n")) sanitized += '\n';
} else {
sanitized = sanitized.replaceAll("\n\n+", "\n");
}
return sanitized;
}
}
public static String formatMessage(long timeMillis, String address, String content) {
return String.format("[%td.%1$tm.%1$tY %1$tR] {%s} %s", timeMillis, address, content);
}
}

View File

@ -0,0 +1,12 @@
package net.pixtaded.crab.common;
import java.io.BufferedReader;
import java.io.IOException;
public class Util {
public static String readAsciiNumber(BufferedReader in) throws IOException {
char[] buffer = new char[10];
int response = in.read(buffer);
return new String(buffer).trim();
}
}

View File

@ -1,5 +1,6 @@
package net.pixtaded.crab.server;
import net.pixtaded.crab.common.Crab;
import net.pixtaded.crab.common.Logs;
import java.io.IOException;
import java.net.ServerSocket;
@ -9,10 +10,10 @@ import java.util.Scanner;
public class CrabServer implements Crab {
private ServerSocket serverSocket;
private Socket socket;
private boolean isStopped = false;
private int port;
private Database db;
private final Database db;
public Logs cache = new Logs(0, "");
public CrabServer() {
this.db = new Database("data.db");
@ -28,6 +29,7 @@ public class CrabServer implements Crab {
try {
if (this.port == 0)
setup();
this.cache = getDb().getLogs();
listen();
} catch (IOException e) {
if (!isStopped) System.err.println("Error starting server: " + e.getMessage());
@ -66,10 +68,9 @@ public class CrabServer implements Crab {
}
}
public void stop() {
public synchronized void stop() {
isStopped = true;
try {
isStopped = true;
if (socket != null) socket.close();
if (serverSocket != null) serverSocket.close();
} catch (IOException e) {
System.err.println("An error occured while closing the socket: " + e.getMessage());

View File

@ -1,15 +1,14 @@
package net.pixtaded.crab.server;
import net.pixtaded.crab.common.Logs;
import net.pixtaded.crab.common.Sanitizer;
import java.sql.*;
import java.util.Date;
import java.util.Locale;
public class Database {
private Connection connection;
private String logs = "";
public Database(String dbName) {
try {
@ -50,22 +49,16 @@ public class Database {
}
}
public String getLogs() {
public Logs getLogs() {
StringBuilder s = new StringBuilder();
try (ResultSet rs = query("SELECT time, address, msg FROM messages")) {
while (rs.next()) {
s.append(String.format("[%td.%1$tm.%1$tY %1$tR] {%s} %s", rs.getLong(1), rs.getString(2), rs.getString(3)));
s.append(Sanitizer.formatMessage(rs.getLong(1), rs.getString(2), rs.getString(3)));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
logs = s.toString();
return logs;
String logsString = s.toString();
return new Logs(logsString.isEmpty() ? 0 : logsString.getBytes().length, logsString);
}
public int getLogSize() {
if (logs.isEmpty()) return 0;
else return logs.getBytes().length;
}
}

View File

@ -1,5 +1,9 @@
package net.pixtaded.crab.server;
import net.pixtaded.crab.common.Logs;
import net.pixtaded.crab.common.Sanitizer;
import net.pixtaded.crab.common.Util;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
@ -9,13 +13,12 @@ import static net.pixtaded.crab.common.PID.*;
public class ServerThread implements Runnable {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private OutputStream output;
private InputStream input;
private byte PID;
private CrabServer server;
private final Socket socket;
private final PrintWriter out;
private final BufferedReader in;
private final OutputStream output;
private final InputStream input;
private final CrabServer server;
public ServerThread(Socket socket, CrabServer server) throws IOException {
this.socket = socket;
@ -29,31 +32,80 @@ public class ServerThread implements Runnable {
@Override
public void run() {
try {
byte[] PID = input.readNBytes(1);
byte[] PID = readPID();
if (PID.length == 0) {
socket.close();
return;
}
switch (PID[0]) {
case MESSAGE -> {
server.getDb().logMessage(new Date(), socket.getInetAddress().getHostAddress(), new String(input.readNBytes(4096), StandardCharsets.UTF_8).trim());
socket.close();
} case LOGS -> {
respond(server.getDb().getLogs());
String msg = new String(input.readNBytes(4096), StandardCharsets.UTF_8).trim();
Date date = new Date();
String address = socket.getInetAddress().getHostAddress();
String s = Sanitizer.sanitizeString(msg, true);
String newContent = server.cache.content() + Sanitizer.formatMessage(date.getTime(), address, s);
server.cache = new Logs(newContent.getBytes().length, newContent);
new Thread(new LogDBThread(date, address, msg)).start();
} case LOGS_SIZE -> {
respond(String.valueOf(server.getDb().getLogSize()));
} default -> {
System.out.println("PID not implemented: " + PID[0]);
}
respond(String.valueOf(server.cache.sizeInBytes()));
byte[] logPID = readPID();
if (logPID.length == 0) {
socket.close();
return;
}
sendLogs(logPID[0]);
} default -> System.out.println("PID not implemented: " + PID[0]);
}
socket.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private byte[] readPID() throws IOException {
return input.readNBytes(1);
}
private void sendLogs(byte PID) throws IOException {
if (PID == LOGS) {
respond(server.cache.content());
} else if (PID == CACHED_LOGS) {
String clientSize = Util.readAsciiNumber(in);
int clientSizeNum = Integer.parseInt(clientSize);
byte[] serverLogs = server.cache.content().getBytes(StandardCharsets.UTF_8);
int logPartSize = serverLogs.length - clientSizeNum;
byte[] logPart = new byte[logPartSize];
System.arraycopy(serverLogs, serverLogs.length - logPartSize, logPart, 0, logPartSize);
respond(logPart);
}
}
private void respond(byte[] data) throws IOException {
socket.getOutputStream().write(data);
socket.getOutputStream().flush();
socket.close();
}
private void respond(String utf8) throws IOException {
respond(utf8.getBytes(StandardCharsets.UTF_8));
}
private class LogDBThread implements Runnable {
Date date;
String msg;
String address;
public LogDBThread(Date date, String address, String msg) {
this.date = date;
this.msg = msg;
this.address = address;
}
@Override
public void run() {
server.getDb().logMessage(date, address, msg);
}
}
}