Archive ayungee (server, 1.5.2, 1.8.8, clean)

This commit is contained in:
2026-11-27 22:13:28 -06:00
parent 838b705b65
commit fed8ba63fe
22 changed files with 1741 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
{
"slug": "ayungee",
"name": "ayungee",
"category": "server",
"mc_version": "1.5.2, 1.8.8",
"author": "ayunami2000",
"license": "BSD-3-Clause",
"upstream_ref": "master",
"sha256": "b633cfc480ca089ecf75058e73c291a6d895db69181236a8861fa67d804ad2a9",
"size": 3071954,
"storage": {
"git_path": null,
"fs_url": null
},
"play": null,
"sources": [
{
"url": "https://github.com/ayunami2000/ayungee",
"retrieved_at": "2026-11-28T03:12:00Z",
"type": "upstream",
"notes": "Official upstream repository"
}
],
"vetting": {
"verdict": "clean",
"tools": [
"vet-static.mjs",
"virustotal-hash",
"static-code-review"
],
"date": "2026-11-28",
"notes": "Standard Bungee/proxy Java plugin using HttpURLConnection (Main.java:92-93) and Socket (WebSocketProxy.java:142).",
"reviewer": "vet-gemini"
},
"large_files_omitted_from_git": []
}
+10
View File
@@ -0,0 +1,10 @@
# ayungee
Lightweight BungeeCord alternative designed for Eaglercraft servers running ProtocolSupport with built-in authentication support.
- **Archive page:** https://archive.eaglercraft.tech/entries/ayungee.html
- **MC Version:** 1.5.2, 1.8.8
- **Author:** ayunami2000
- **License:** BSD-3-Clause
- **SHA-256:** `b633cfc480ca089ecf75058e73c291a6d895db69181236a8861fa67d804ad2a9`
- **Vetting:** clean (2026-11-28)
+2
View File
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
+5
View File
@@ -0,0 +1,5 @@
.idea
web
target/*
!target/ayungee-1.0-SNAPSHOT-jar-with-dependencies.jar
test
+29
View File
@@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2022, ayunami2000
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+13
View File
@@ -0,0 +1,13 @@
# ayungee
~~lightweight~~ bungeecord alternative for eaglercraft servers running protocolsupport
now contains an optional **login system**!! :D
Thanks to LAX1DUDE and md-5 for very small snippets of EaglerBungee used in this project (specifically for the server icon, skins, & entity remapping)
**TODO: more bungee backwards compatibility, a few more kick messages/reasons, scoreboard & tab clearing, & automatic java player skins**
**if you have questions about the license, please, reach out to me. i just put the license i put on most of my projects on this, but if you have a problem with it, **let me know**.
+56
View File
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.ayunami2000</groupId>
<artifactId>ayungee</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.30</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>de.mkammerer</groupId>
<artifactId>argon2-jvm</artifactId>
<version>2.11</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>me.ayunami2000.ayungee.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,118 @@
package me.ayunami2000.ayungee;
import de.mkammerer.argon2.Argon2;
import de.mkammerer.argon2.Argon2Factory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
public class Auth {
private static class AuthData {
public String passHash;
public Set<String> ips;
public AuthData(String p, Set<String> i) {
passHash = p;
ips = i;
}
}
private static final Argon2 argon2 = Argon2Factory.create(Argon2Factory.Argon2Types.ARGON2id);
private static Map<String, AuthData> database = new HashMap<>();
public static boolean register(String username, char[] password, String ip) {
AuthData authData = database.get(username);
if (authData != null) return false;
if (isIpAtTheLimit(ip)) return false;
String hash = argon2.hash(10, 65536, 1, password);
Set<String> initIps = new HashSet<>();
initIps.add(ip);
database.put(username, new AuthData(hash, initIps));
writeDatabase();
return true;
// todo: registering & packet cancellation
}
public static boolean isRegistered(String username) {
return database.containsKey(username);
}
public static boolean changePass(String username, char[] password) {
AuthData authData = database.get(username);
authData.passHash = argon2.hash(10, 65536, 1, password);
writeDatabase();
return true;
}
public static boolean login(String username, char[] password) {
AuthData authData = database.get(username);
if (authData == null) return false;
return argon2.verify(authData.passHash, password);
}
private static boolean isIpAtTheLimit(String ip) {
if (Main.authIpLimit <= 0) return false;
Map<String, AuthData> cache = new HashMap<>(database);
int num = 0;
for (AuthData authData : cache.values()) {
if (authData.ips.contains(ip)) num++;
if (num >= Main.authIpLimit) {
cache.clear();
return true;
}
}
cache.clear();
return false;
}
// only use once, on load
public static void readDatabase() {
try {
File authFile = new File("auth.uwu");
if (!authFile.exists()) authFile.createNewFile();
Map<String, AuthData> cache = new HashMap<>();
String[] lines = new String(Files.readAllBytes(authFile.toPath())).trim().split("\n");
if (lines.length == 1 && lines[0].isEmpty()) return;
for (String line : lines) {
String[] pieces = line.split("\u0000");
cache.put(pieces[0], new AuthData(pieces[2], new HashSet<>(Arrays.asList(pieces[1].split("§")))));
}
database.clear();
database.putAll(cache);
cache.clear();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeDatabase() {
StringBuilder out = new StringBuilder();
Map<String, AuthData> cache = new HashMap<>(database);
for (String username : cache.keySet()) {
AuthData entry = cache.get(username);
out.append(username);
out.append("\u0000");
out.append(String.join("§", entry.ips));
out.append("\u0000");
out.append(entry.passHash);
out.append("\n");
}
cache.clear();
try {
Files.write(Paths.get("auth.uwu"), out.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,138 @@
package me.ayunami2000.ayungee;
import java.nio.ByteBuffer;
public class ChatHandler {
// return true to cancel being sent to server/client
public static boolean fromServer(Client client, String message) {
return false;
}
public static boolean fromClient(Client client, String message) {
if (!message.startsWith("/")) return false;
int ind = message.indexOf(' ');
String commandBase = message.substring(1, ind != -1 ? ind : message.length()).toLowerCase();
String args = ind == -1 ? "" : message.substring(ind + 1).trim();
String[] argsArr = args.split(" ");
switch (commandBase) {
case "server":
if (!client.authed) return false;
if (!Main.serverCmd) return false;
if (args.isEmpty()) {
//usage msg
client.conn.send(new byte[] { 3, 0, 25, 0, (byte) 167, 0, 57, 0, 85, 0, 115, 0, 97, 0, 103, 0, 101, 0, 58, 0, 32, 0, 47, 0, 115, 0, 101, 0, 114, 0, 118, 0, 101, 0, 114, 0, 32, 0, 60, 0, 110, 0, 117, 0, 109, 0, 98, 0, 101, 0, 114, 0, 62 });
} else {
try {
int destServer = Integer.parseInt(args);
client.server = Math.max(0, Math.min(Main.servers.size() - 1, destServer));
} catch (NumberFormatException e) {
//not a number
client.conn.send(new byte[] { 3, 0, 29, 0, (byte) 167, 0, 57, 0, 84, 0, 104, 0, 97, 0, 116, 0, 32, 0, 105, 0, 115, 0, 32, 0, 110, 0, 111, 0, 116, 0, 32, 0, 97, 0, 32, 0, 118, 0, 97, 0, 108, 0, 105, 0, 100, 0, 32, 0, 110, 0, 117, 0, 109, 0, 98, 0, 101, 0, 114, 0, 33 });
}
}
break;
case "register":
case "reg":
if (!Main.useAuth) return false;
if (client.authed) return false;
if (argsArr[0].isEmpty()) {
client.conn.send(new byte[] { 3, 0, 30, 0, (byte) 167, 0, 57, 0, 89, 0, 111, 0, 117, 0, 32, 0, 109, 0, 117, 0, 115, 0, 116, 0, 32, 0, 115, 0, 112, 0, 101, 0, 99, 0, 105, 0, 102, 0, 121, 0, 32, 0, 97, 0, 32, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 46 });
return true;
}
if (argsArr.length == 1 || !argsArr[0].equals(argsArr[1])) {
client.conn.send(new byte[] { 3, 0, 31, 0, (byte) 167, 0, 57, 0, 84, 0, 104, 0, 111, 0, 115, 0, 101, 0, 32, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 115, 0, 32, 0, 100, 0, 111, 0, 32, 0, 110, 0, 111, 0, 116, 0, 32, 0, 109, 0, 97, 0, 116, 0, 99, 0, 104, 0, 33 });
return true;
}
if (Auth.register(client.username, argsArr[0].toCharArray(), Main.getIp(client.conn))) {
Main.printMsg("Player " + client + " registered successfully!");
client.authed = true;
client.server = -1;
} else {
client.conn.send(new byte[] { (byte) 255, 0, 38, 0, (byte) 167, 0, 57, 0, 84, 0, 104, 0, 105, 0, 115, 0, 32, 0, 117, 0, 115, 0, 101, 0, 114, 0, 110, 0, 97, 0, 109, 0, 101, 0, 32, 0, 105, 0, 115, 0, 32, 0, 97, 0, 108, 0, 114, 0, 101, 0, 97, 0, 100, 0, 121, 0, 32, 0, 114, 0, 101, 0, 103, 0, 105, 0, 115, 0, 116, 0, 101, 0, 114, 0, 101, 0, 100, 0, 33 });
client.conn.close();
}
break;
case "login":
case "l":
if (!Main.useAuth) return false;
if (client.authed) return false;
if (argsArr[0].isEmpty()) {
client.conn.send(new byte[] { 3, 0, 30, 0, (byte) 167, 0, 57, 0, 89, 0, 111, 0, 117, 0, 32, 0, 109, 0, 117, 0, 115, 0, 116, 0, 32, 0, 115, 0, 112, 0, 101, 0, 99, 0, 105, 0, 102, 0, 121, 0, 32, 0, 97, 0, 32, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 46 });
return true;
}
if (Auth.login(client.username, argsArr[0].toCharArray())) {
Main.printMsg("Player " + client + " logged in!");
client.authed = true;
} else {
client.conn.send(new byte[] { (byte) 255, 0, 29, 0, (byte) 167, 0, 57, 0, 84, 0, 104, 0, 97, 0, 116, 0, 32, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 32, 0, 105, 0, 115, 0, 32, 0, 105, 0, 110, 0, 99, 0, 111, 0, 114, 0, 114, 0, 101, 0, 99, 0, 116, 0, 33 });
client.conn.close();
}
break;
case "changepass":
case "changepassword":
case "changeepasswd":
case "changepwd":
case "changepw":
if (!Main.useAuth) return false;
if (!client.authed) return false;
if (argsArr[0].isEmpty() || argsArr.length == 1) {
client.conn.send(new byte[] { 3, 0, 63, 0, (byte) 167, 0, 57, 0, 80, 0, 108, 0, 101, 0, 97, 0, 115, 0, 101, 0, 32, 0, 115, 0, 112, 0, 101, 0, 99, 0, 105, 0, 102, 0, 121, 0, 32, 0, 116, 0, 104, 0, 101, 0, 32, 0, 111, 0, 108, 0, 100, 0, 32, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 32, 0, 102, 0, 111, 0, 108, 0, 108, 0, 111, 0, 119, 0, 101, 0, 100, 0, 32, 0, 98, 0, 121, 0, 32, 0, 116, 0, 104, 0, 101, 0, 32, 0, 110, 0, 101, 0, 119, 0, 32, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 33 });
return true;
}
if (!Auth.isRegistered(client.username)) {
// register first...
client.conn.send(new byte[] { 3, 0, 60, 0, (byte) 167, 0, 57, 0, 89, 0, 111, 0, 117, 0, 32, 0, 109, 0, 117, 0, 115, 0, 116, 0, 32, 0, 114, 0, 101, 0, 103, 0, 105, 0, 115, 0, 116, 0, 101, 0, 114, 0, 32, 0, 97, 0, 110, 0, 32, 0, 97, 0, 99, 0, 99, 0, 111, 0, 117, 0, 110, 0, 116, 0, 32, 0, 102, 0, 105, 0, 114, 0, 115, 0, 116, 0, 32, 0, 116, 0, 111, 0, 32, 0, 99, 0, 104, 0, 97, 0, 110, 0, 103, 0, 101, 0, 32, 0, 105, 0, 116, 0, 115, 0, 32, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 33 });
return true;
}
if (!Auth.login(client.username, argsArr[0].toCharArray())) {
// invalid old password
client.conn.send(new byte[] { 3, 0, 29, 0, (byte) 167, 0, 57, 0, 84, 0, 104, 0, 97, 0, 116, 0, 32, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 32, 0, 105, 0, 115, 0, 32, 0, 105, 0, 110, 0, 99, 0, 111, 0, 114, 0, 114, 0, 101, 0, 99, 0, 116, 0, 33 });
return true;
}
if (Auth.changePass(client.username, argsArr[1].toCharArray())) {
// changed password!
Main.printMsg("Player " + client + " changed their password!");
client.conn.send(new byte[] { 3, 0, 33, 0, (byte) 167, 0, 57, 0, 89, 0, 111, 0, 117, 0, 114, 0, 32, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 32, 0, 104, 0, 97, 0, 115, 0, 32, 0, 98, 0, 101, 0, 101, 0, 110, 0, 32, 0, 99, 0, 104, 0, 97, 0, 110, 0, 103, 0, 101, 0, 100, 0, 33 });
}
break;
default:
return false;
}
return true;
}
public static boolean serverChatMessage(Client client, byte[] packet) {
return fireChatMessage(client, true, packet);
}
public static boolean clientChatMessage(Client client, byte[] packet) {
return fireChatMessage(client, false, packet);
}
private static boolean fireChatMessage(Client client, boolean fromServer, byte[] packet) {
if (packet.length >= 3 && packet[0] == 3) {
ByteBuffer bb = ByteBuffer.wrap(packet);
bb.get();
int msgLen = bb.getShort(); //(short) ((msg[1] << 8) + msg[2] & 0xff);
if (msgLen >= 0) {
if (packet.length >= 3 + msgLen * 2) {
//byte[] chatBytes = new byte[msgLen];
//for (int i = 0; i < chatBytes.length; i++) chatBytes[i] = msg[4 + i * 2];
//String chatMsg = new String(chatBytes);
StringBuilder chatBuilder = new StringBuilder();
for (int i = 0; i < msgLen; i++) chatBuilder.append(bb.getChar());
String chatMsg = chatBuilder.toString();
if (fromServer) {
return fromServer(client, chatMsg);
} else {
return fromClient(client, chatMsg);
}
}
}
}
return false;
}
}
@@ -0,0 +1,53 @@
package me.ayunami2000.ayungee;
import org.java_websocket.WebSocket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class Client {
public Socket socket = null;
public OutputStream socketOut = null;
public InputStream socketIn = null;
public List<byte[]> msgCache =new ArrayList<>();
public WebSocket conn;
public String username;
public int server = 0;
public byte[] handshake = null;
public boolean firstTime = true;
public boolean hasLoginHappened = false;
public boolean authed = !Main.useAuth;
public int clientEntityId;
public int serverEntityId;
public List<byte[]> packetCache = new ArrayList<>();
public byte[] positionPacket = null;
public void setSocket(Socket sock) throws IOException {
socket = sock;
socketOut = sock.getOutputStream();
socketIn = sock.getInputStream();
}
public Client(WebSocket c, String uname) {
conn = c;
username = uname;
}
public String toString() {
return username + " (" + Main.getIp(conn) + ")";
}
}
@@ -0,0 +1,81 @@
package me.ayunami2000.ayungee;
// https://github.com/LAX1DUDE/eaglercraft/blob/a8d5c856de28ba2a263abc055d7b26d50dc2bf7e/eaglercraftbungee/src/main/java/net/md_5/bungee/EntityMap.java
public class EntityMap {
public static final int[][] entityIds;
public static void rewrite(final byte[] packet, final int oldId, final int newId) {
final int packetId = packet[0] & 0xFF;
if (packetId == 29) {
for (int pos = 2; pos < (short) ((packet[1] << 8) + packet[2] & 0xff); pos += 4) {
final int readId = readInt(packet, pos);
if (readId == oldId) {
setInt(packet, pos, newId);
} else if (readId == newId) {
setInt(packet, pos, oldId);
}
}
} else {
final int[] idArray = EntityMap.entityIds[packetId];
if (idArray != null) {
for (final int pos2 : idArray) {
final int readId2 = readInt(packet, pos2);
if (readId2 == oldId) {
setInt(packet, pos2, newId);
} else if (readId2 == newId) {
setInt(packet, pos2, oldId);
}
}
}
}
if (packetId == 23) {
final int type = packet[5] & 0xFF;
if (type == 60 || type == 90) {
final int index20 = readInt(packet, 20);
if (packet.length > 24 && index20 == oldId) {
setInt(packet, 20, newId);
}
}
}
}
public static void setInt(final byte[] buf, final int pos, final int i) {
buf[pos] = (byte) (i >> 24);
buf[pos + 1] = (byte) (i >> 16);
buf[pos + 2] = (byte) (i >> 8);
buf[pos + 3] = (byte) i;
}
public static int readInt(final byte[] buf, final int pos) {
return (buf[pos] & 0xFF) << 24 | (buf[pos + 1] & 0xFF) << 16 | (buf[pos + 2] & 0xFF) << 8 | (buf[pos + 3] & 0xFF);
}
static {
(entityIds = new int[256][])[5] = new int[] { 1 };
EntityMap.entityIds[7] = new int[] { 1, 5 };
EntityMap.entityIds[17] = new int[] { 1 };
EntityMap.entityIds[18] = new int[] { 1 };
EntityMap.entityIds[19] = new int[] { 1 };
EntityMap.entityIds[20] = new int[] { 1 };
EntityMap.entityIds[22] = new int[] { 1, 5 };
EntityMap.entityIds[23] = new int[] { 1 };
EntityMap.entityIds[24] = new int[] { 1 };
EntityMap.entityIds[25] = new int[] { 1 };
EntityMap.entityIds[26] = new int[] { 1 };
EntityMap.entityIds[28] = new int[] { 1 };
EntityMap.entityIds[30] = new int[] { 1 };
EntityMap.entityIds[31] = new int[] { 1 };
EntityMap.entityIds[32] = new int[] { 1 };
EntityMap.entityIds[33] = new int[] { 1 };
EntityMap.entityIds[34] = new int[] { 1 };
EntityMap.entityIds[35] = new int[] { 1 };
EntityMap.entityIds[38] = new int[] { 1 };
EntityMap.entityIds[39] = new int[] { 1, 5 };
EntityMap.entityIds[40] = new int[] { 1 };
EntityMap.entityIds[41] = new int[] { 1 };
EntityMap.entityIds[42] = new int[] { 1 };
EntityMap.entityIds[55] = new int[] { 1 };
EntityMap.entityIds[71] = new int[] { 1 };
}
}
@@ -0,0 +1,71 @@
package me.ayunami2000.ayungee;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
// note that there's a few things not implemented, but I don't care.
public class ExpiringSet<T> extends HashSet<T> {
private final long expiration;
private final ExpiringEvent<T> event;
private final Map<T, Long> timestamps = new HashMap<>();
public ExpiringSet(long expiration) {
this.expiration = expiration;
this.event = null;
}
public ExpiringSet(long expiration, ExpiringEvent<T> event) {
this.expiration = expiration;
this.event = event;
}
public interface ExpiringEvent<T> {
void onExpiration(T item);
}
public void checkForExpirations() {
Iterator<T> iterator = this.timestamps.keySet().iterator();
long now = System.currentTimeMillis();
while (iterator.hasNext()) {
T element = iterator.next();
if (super.contains(element)) {
if (this.timestamps.get(element) + this.expiration < now) {
if (this.event != null) this.event.onExpiration(element);
iterator.remove();
super.remove(element);
}
} else {
iterator.remove();
super.remove(element);
}
}
}
public boolean add(T o) {
checkForExpirations();
boolean success = super.add(o);
if (success) timestamps.put(o, System.currentTimeMillis());
return success;
}
public boolean remove(Object o) {
checkForExpirations();
boolean success = super.remove(o);
if (success) timestamps.remove(o);
return success;
}
public void clear() {
this.timestamps.clear();
super.clear();
}
public boolean contains(Object o) {
checkForExpirations();
return super.contains(o);
}
}
@@ -0,0 +1,375 @@
package me.ayunami2000.ayungee;
import org.java_websocket.WebSocket;
import org.java_websocket.server.WebSocketServer;
import org.json.simple.JSONObject;
import org.yaml.snakeyaml.Yaml;
import javax.imageio.ImageIO;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.util.*;
import java.util.regex.Pattern;
public class Main {
public static List<ServerItem> servers = new ArrayList<>();
public static int webPort = 25565;
public static String motdJson = "";
public static byte[] serverIcon = null;
public static boolean forwarded = false;
public static boolean serverCmd = true;
public static boolean voiceEnabled = true;
public static List<String> voiceICE = new ArrayList<>();
public static boolean useAuth = false;
public static int authIpLimit = -1;
public static WebSocketServer webSocketServer = null;
public static Map<WebSocket, Client> clients = new HashMap<>();
public static Set<String> bans = new HashSet<>();
public static Set<Pattern> originBlacklist = new HashSet<>();
public static Set<String> originWhitelist = new HashSet<>();
public static void main(String[] args) throws IOException, InterruptedException {
Yaml yaml = new Yaml();
Map<String, Object> config;
try {
config = yaml.load(new FileReader("config.yml"));
} catch (FileNotFoundException e) {
Files.copy(Main.class.getResourceAsStream("/config.yml"), Paths.get("config.yml"), StandardCopyOption.REPLACE_EXISTING);
config = yaml.load(new FileReader("config.yml"));
}
File iconFile = new File("icon.png");
if (!iconFile.exists()) Files.copy(Main.class.getResourceAsStream("/icon.png"), Paths.get("icon.png"), StandardCopyOption.REPLACE_EXISTING);
int[] serverIconInt = ServerIcon.createServerIcon(ImageIO.read(iconFile));
byte[] iconPixels = new byte[16384];
for(int i = 0; i < 4096; ++i) {
iconPixels[i * 4] = (byte)((serverIconInt[i] >> 16) & 0xFF);
iconPixels[i * 4 + 1] = (byte)((serverIconInt[i] >> 8) & 0xFF);
iconPixels[i * 4 + 2] = (byte)(serverIconInt[i] & 0xFF);
iconPixels[i * 4 + 3] = (byte)((serverIconInt[i] >> 24) & 0xFF);
}
serverIcon = iconPixels;
try (BufferedReader br = new BufferedReader(new FileReader("bans.txt"))) {
String line;
while ((line = br.readLine()) != null) bans.add(line);
} catch (FileNotFoundException e) {
saveBans();
}
originWhitelist = new HashSet<>((List<String>) config.getOrDefault("origins", new ArrayList<>()));
String originBlacklistUrl = (String) config.getOrDefault("origin_blacklist", "https://g.eags.us/eaglercraft/origin_blacklist.txt");
if (originBlacklistUrl.isEmpty()) {
new Thread(() -> {
while (true) {
readUrlBlacklist();
try {
Thread.sleep(300000);
} catch (InterruptedException ignored) {}
}
}).start();
} else {
URL blacklistUrl = new URL(originBlacklistUrl);
new Thread(() -> {
while (true) {
try {
URLConnection cc = blacklistUrl.openConnection();
if (cc instanceof HttpURLConnection) {
HttpURLConnection ccc = (HttpURLConnection)cc;
ccc.setRequestProperty("Accept", "text/plain,text/html,application/xhtml+xml,application/xml");
ccc.setRequestProperty("User-Agent", "Mozilla/5.0 ayungee");
}
cc.connect();
Files.copy(cc.getInputStream(), Paths.get("origin_blacklist.txt"), StandardCopyOption.REPLACE_EXISTING);
readUrlBlacklist();
} catch (IOException e) {
printMsg("An error occurred attempting to update the origin blacklist!");
}
try {
Thread.sleep(300000);
} catch (InterruptedException ignored) {
}
}
}).start();
}
servers.add(new ServerItem("localhost", 25569));
List<String> stringServers = (List<String>) config.getOrDefault("servers", new ArrayList<>());
if (!stringServers.isEmpty()) {
servers.clear();
for (String serverEntry : stringServers) {
servers.add(new ServerItem(serverEntry));
}
}
voiceICE.add("stun:openrelay.metered.ca:80");
voiceICE.add("turn:openrelay.metered.ca:80;openrelayproject;openrelayproject");
voiceICE.add("turn:openrelay.metered.ca:443;openrelayproject;openrelayproject");
voiceICE.add("turn:openrelay.metered.ca:443?transport=tcp;openrelayproject;openrelayproject");
Map<String, Object> configVoice = new LinkedHashMap<>();
configVoice.put("enabled", true);
configVoice.put("ice", voiceICE);
configVoice = (LinkedHashMap<String, Object>) config.getOrDefault("voice", configVoice);
voiceEnabled = (boolean) configVoice.getOrDefault("enabled", true);
voiceICE = (List<String>) configVoice.getOrDefault("ice", voiceICE);
Map<String, Object> configAuth = new LinkedHashMap<>();
configAuth.put("enabled", false);
configAuth.put("ip_limit", -1);
configAuth = (LinkedHashMap<String, Object>) config.getOrDefault("auth", configAuth);
useAuth = (boolean) configAuth.getOrDefault("enabled", false);
if (useAuth) {
authIpLimit = (int) configAuth.getOrDefault("ip_limit", 0);
Auth.readDatabase();
}
webPort = (int) config.getOrDefault("web_port", 25565);
forwarded = (boolean) config.getOrDefault("forwarded", false);
serverCmd = (boolean) config.getOrDefault("server_cmd", true);
List<String> defaultMotd = new ArrayList<>();
defaultMotd.add("Welcome to my");
defaultMotd.add("ayungee-powered server!");
List<String> defaultPlayersMotd = new ArrayList<>();
defaultPlayersMotd.add("whar?");
Map<String, Object> defaultConfigMotd = new LinkedHashMap<>();
defaultConfigMotd.put("lines", defaultMotd);
defaultConfigMotd.put("max", 20);
defaultConfigMotd.put("online", 4);
defaultConfigMotd.put("name", "An ayungee-powered Eaglercraft server");
defaultConfigMotd.put("players", defaultPlayersMotd);
Map<String, Object> configMotd = (LinkedHashMap<String, Object>) config.getOrDefault("motd", defaultConfigMotd);
JSONObject motdObj = new JSONObject();
JSONObject motdObjObj = new JSONObject();
motdObjObj.put("motd", configMotd.getOrDefault("lines", defaultMotd));
motdObjObj.put("cache", true);
motdObjObj.put("max", configMotd.get("max"));
motdObjObj.put("icon", true);
motdObjObj.put("online", configMotd.get("online"));
motdObjObj.put("players", configMotd.getOrDefault("players", defaultPlayersMotd));
motdObj.put("data", motdObjObj);
motdObj.put("vers", "0.2.0");
motdObj.put("name", configMotd.get("name"));
motdObj.put("time", Instant.now().toEpochMilli());
motdObj.put("type", "motd");
motdObj.put("brand", "Eagtek");
motdObj.put("uuid", UUID.randomUUID().toString());
motdObj.put("cracked", true);
motdJson = motdObj.toJSONString();
webSocketServer = new WebSocketProxy(webPort);
webSocketServer.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
boolean running = true;
printMsg("ayungee started!");
while (running) {
String cmd = reader.readLine();
String[] pieces = cmd.split(" ");
pieces[0] = pieces[0].toLowerCase();
switch (pieces[0]) {
case "help":
case "?":
printMsg("help ; unban <ip> ; banip <ip> ; ban <username> ; kickip <ip> ; kick <username> ; send <username> <serverid> ; stop");
break;
case "kick":
if (pieces.length == 1) {
printMsg("Usage: " + pieces[0] + " <username>");
break;
}
//there should NEVER be duplicate usernames...
Client[] targetClientss = clients.values().stream().filter(client -> client.username.equals(pieces[1])).toArray(Client[]::new);
if (targetClientss.length == 0) targetClientss = clients.values().stream().filter(client -> client.username.equalsIgnoreCase(pieces[1])).toArray(Client[]::new);
if (targetClientss.length == 0) {
printMsg("Unable to find any user with that username!");
break;
}
for (Client targetClient : targetClientss) {
targetClient.conn.close();
printMsg("Successfully kicked user " + targetClient);
}
break;
case "kickip":
case "kick-ip":
if (pieces.length == 1) {
printMsg("Usage: " + pieces[0] + " <ip>");
break;
}
//there should NEVER be duplicate usernames...
Client[] targetClientsss = clients.values().stream().filter(client -> getIp(client.conn).equals(pieces[1])).toArray(Client[]::new);
if (targetClientsss.length == 0) {
printMsg("Unable to find any user with that IP!");
break;
}
for (Client targetClient : targetClientsss) {
targetClient.conn.close();
printMsg("Successfully kicked user " + targetClient);
}
break;
case "unban":
case "pardon":
case "unban-ip":
case "unbanip":
case "pardon-ip":
case "pardonip":
if (pieces.length == 1) {
printMsg("Usage: " + pieces[0] + " <ip>");
break;
}
if (bans.remove(pieces[1])) {
printMsg("Successfully unbanned IP " + pieces[1]);
saveBans();
} else {
printMsg("IP " + pieces[1] + " is not banned!");
}
break;
case "ban":
if (pieces.length == 1) {
printMsg("Usage: " + pieces[0] + " <username>");
break;
}
//there should NEVER be duplicate usernames...
Client[] targetClients = clients.values().stream().filter(client -> client.username.equals(pieces[1])).toArray(Client[]::new);
if (targetClients.length == 0) targetClients = clients.values().stream().filter(client -> client.username.equalsIgnoreCase(pieces[1])).toArray(Client[]::new);
if (targetClients.length == 0) {
printMsg("Unable to find any user with that username! (note: they must be online)");
break;
}
for (Client targetClient : targetClients) {
WebSocket targetWebSocket = targetClient.conn;
String ipToBan = getIp(targetWebSocket);
if (bans.add(ipToBan)) {
printMsg("Successfully banned user " + targetClient.username + " with IP " + ipToBan);
try {
saveBans();
} catch (IOException ignored) {}
} else {
printMsg("IP " + ipToBan + " is already banned!");
}
}
break;
case "ban-ip":
case "banip":
if (pieces.length == 1) {
printMsg("Usage: " + pieces[0] + " <ip>");
break;
}
if (bans.add(pieces[1])) {
Client[] targetClientssss = clients.values().stream().filter(client -> getIp(client.conn).equals(pieces[1])).toArray(Client[]::new);
for (Client client : targetClientssss) client.conn.close();
printMsg("Successfully banned IP " + pieces[1]);
saveBans();
} else {
printMsg("IP " + pieces[1] + " is already banned!");
}
break;
case "send":
case "server":
if (pieces.length == 1 || pieces.length == 2) {
printMsg("Usage: " + pieces[0] + " <username> <serverindex>");
break;
}
Client targetUser = clients.values().stream().filter(client -> client.username.equals(pieces[1])).findFirst().orElse(clients.values().stream().filter(client -> client.username.equalsIgnoreCase(pieces[1])).findFirst().orElse(null));
if (targetUser == null) {
printMsg("Unable to find any user with that username!");
break;
}
// 99% sure don't need to worry about this
/*
if (!targetUser.hasLoginHappened) {
printMsg("This user is still logging in to a server; please wait until they have logged in to change their server!");
break;
}
*/
if (!targetUser.authed) {
printMsg("That user is not yet authenticated!");
break;
}
try {
int destServer = Integer.parseInt(pieces[2]);
targetUser.server = Math.max(0, Math.min(servers.size() - 1, destServer));
printMsg("Successfully send user " + targetUser + " to server " + destServer + "!");
} catch (NumberFormatException e) {
printMsg("That is not a valid number!");
}
break;
case "stop":
case "end":
case "exit":
case "quit":
printMsg("Stopping!");
running = false;
webSocketServer.stop(10);
System.exit(0);
break;
default:
printMsg("Command not found!");
}
}
}
public static void printMsg(String msg) {
System.out.println(msg);
//System.out.print("> "); // todo: copy current input to after the >
}
public static String getIp(WebSocket conn) {
return conn.getAttachment();
}
private static void saveBans() throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("bans.txt"));
writer.write(String.join("\n", bans));
writer.close();
}
private static void readUrlBlacklist() {
try {
try (BufferedReader br = new BufferedReader(new FileReader("origin_blacklist.txt"))) {
originBlacklist.clear();
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("#")) continue;
if (line.trim().isEmpty()) continue;
originBlacklist.add(Pattern.compile(line, Pattern.CASE_INSENSITIVE));
}
} catch (FileNotFoundException e) {
new File("origin_blacklist.txt").createNewFile();
}
} catch (IOException ignored) {}
}
}
@@ -0,0 +1,66 @@
package me.ayunami2000.ayungee;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
public class PluginMessages {
// return true to cancel being sent to server/client
public static boolean fromServer(Client client, String name, byte[] data) {
if (name.equals("BungeeCord")) { // eat all bungeecord messages
DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(data));
try {
String bungeeTag = dataIn.readUTF();
if (bungeeTag.equals("Connect")) { // actually send current player to server :D
if (!client.authed) return true;
String destServer = dataIn.readUTF();
try {
int destServerInt = Integer.parseInt(destServer);
client.server = Math.max(0, Math.min(Main.servers.size() - 1, destServerInt));
} catch (NumberFormatException ignored) {}
}
} catch (IOException e) {
// broken packet
}
return true;
}
return false;
}
public static boolean fromClient(Client client, String name, byte[] data) {
return Skins.setSkin(client.username, client.conn, name, data) || Voice.handleVoice(client.username, client.conn, name, data);
}
public static boolean serverPluginMessage(Client client, byte[] packet) {
return firePluginMessage(client, true, packet);
}
public static boolean clientPluginMessage(Client client, byte[] packet) {
return firePluginMessage(client, false, packet);
}
private static boolean firePluginMessage(Client client, boolean fromServer, byte[] packet) {
if(packet.length >= 3 && packet[0] == (byte) 250) {
ByteBuffer bb = ByteBuffer.wrap(packet);
bb.get();
int tagLen = bb.getShort();
if (tagLen < 0 || tagLen * 2 > packet.length - 3) return false;
StringBuilder tagBuilder = new StringBuilder();
for (int i = 0; i < tagLen; i++) tagBuilder.append(bb.getChar());
//int dataLen = bb.getShort();
int dataLen = bb.remaining() - 2; // - 2 for the 2 bytes specifying data length
String tag = tagBuilder.toString();
int offset = 3 + tagLen * 2 + 2; // - 2 for the 2 bytes specifying data length
byte[] msg = new byte[dataLen];
System.arraycopy(packet, offset, msg, 0, dataLen);
if (fromServer) {
return fromServer(client, tag, msg);
} else {
return fromClient(client, tag, msg);
}
}
return false;
}
}
@@ -0,0 +1,45 @@
package me.ayunami2000.ayungee;
import java.awt.*;
import java.awt.image.BufferedImage;
public class ServerIcon {
// https://github.com/LAX1DUDE/eaglercraft/blob/bec1a03fa24bcb9e8d07fd67ba82a6a827f9c1d9/eaglercraftbungee/src/main/java/net/md_5/bungee/api/ServerIcon.java
public static int[] createServerIcon(BufferedImage awtIcon) {
BufferedImage icon = awtIcon;
boolean gotScaled = false;
if(icon.getWidth() != 64 || icon.getHeight() != 64) {
icon = new BufferedImage(64, 64, awtIcon.getType());
Graphics2D g = (Graphics2D) icon.getGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, (awtIcon.getWidth() < 64 || awtIcon.getHeight() < 64) ?
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR : RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setBackground(Color.BLACK);
g.clearRect(0, 0, 64, 64);
int ow = awtIcon.getWidth();
int oh = awtIcon.getHeight();
int nw, nh;
float aspectRatio = (float)oh / (float)ow;
if(aspectRatio >= 1.0f) {
nw = (int)(64 / aspectRatio);
nh = 64;
}else {
nw = 64;
nh = (int)(64 * aspectRatio);
}
g.drawImage(awtIcon, (64 - nw) / 2, (64 - nh) / 2, (64 - nw) / 2 + nw, (64 - nh) / 2 + nh, 0, 0, awtIcon.getWidth(), awtIcon.getHeight(), null);
g.dispose();
gotScaled = true;
}
int[] pxls = icon.getRGB(0, 0, 64, 64, new int[4096], 0, 64);
if(gotScaled) {
for(int i = 0; i < pxls.length; ++i) {
if((pxls[i] & 0xFFFFFF) == 0) {
pxls[i] = 0;
}
}
}
return pxls;
}
}
@@ -0,0 +1,17 @@
package me.ayunami2000.ayungee;
public class ServerItem {
public String host;
public int port = 25565;
public ServerItem(String h, int p) {
host = h;
port = p;
}
public ServerItem(String hp) {
String[] pieces = hp.split(":");
if (pieces.length > 1) port = Integer.parseInt(pieces[1]);
host = pieces[0];
}
}
@@ -0,0 +1,102 @@
package me.ayunami2000.ayungee;
import org.java_websocket.WebSocket;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
public class Skins {
private static final HashMap<String,byte[]> skinCollection = new HashMap();
private static final HashMap<String,byte[]> capeCollection = new HashMap();
private static final HashMap<String,Long> lastSkinLayerUpdate = new HashMap();
private static final int[] SKIN_DATA_SIZE = new int[] { 64*32*4, 64*64*4, -9, -9, 1, 64*64*4, -9 }; // 128 pixel skins crash clients
private static final int[] CAPE_DATA_SIZE = new int[] { 32*32*4, -9, 1 };
public static boolean setSkin(String user, WebSocket conn, String tag, byte[] msg) {
if(msg.length >= 3) {
try {
if("EAG|MySkin".equals(tag)) {
if(!skinCollection.containsKey(user)) {
int t = (int)msg[0] & 0xFF;
if(t >= 0 && t < SKIN_DATA_SIZE.length && msg.length == (SKIN_DATA_SIZE[t] + 1)) {
skinCollection.put(user, msg);
}
}
}else if("EAG|MyCape".equals(tag)) {
if(!capeCollection.containsKey(user)) {
int t = (int)msg[0] & 0xFF;
if(t >= 0 && t < CAPE_DATA_SIZE.length && msg.length == (CAPE_DATA_SIZE[t] + 2)) {
capeCollection.put(user, msg);
}
}
}else if("EAG|FetchSkin".equals(tag)) {
if(msg.length > 2) {
String fetch = new String(msg, 2, msg.length - 2, StandardCharsets.UTF_8);
byte[] data;
if((data = skinCollection.get(fetch)) != null) {
byte[] conc = new byte[data.length + 2];
conc[0] = msg[0]; conc[1] = msg[1]; //synchronization cookie
System.arraycopy(data, 0, conc, 2, data.length);
if((data = capeCollection.get(fetch)) != null) {
byte[] conc2 = new byte[conc.length + data.length];
System.arraycopy(conc, 0, conc2, 0, conc.length);
System.arraycopy(data, 0, conc2, conc.length, data.length);
conc = conc2;
}
byte[] packetPrefix = new byte[] { (byte) 250, 0, 12, 0, 69, 0, 65, 0, 71, 0, 124, 0, 85, 0, 115, 0, 101, 0, 114, 0, 83, 0, 107, 0, 105, 0, 110, (byte) ((conc.length >>> 8) & 0xFF), (byte) (conc.length & 0xFF) };
byte[] fullPacket = new byte[packetPrefix.length + conc.length];
System.arraycopy(packetPrefix, 0, fullPacket, 0, packetPrefix.length);
System.arraycopy(conc, 0, fullPacket, packetPrefix.length, conc.length);
conn.send(fullPacket);
}
}
}else if("EAG|SkinLayers".equals(tag)) {
long millis = System.currentTimeMillis();
Long lsu = lastSkinLayerUpdate.get(user);
if(lsu != null && millis - lsu.longValue() < 700l) { // DoS protection
return false;
}
lastSkinLayerUpdate.put(user, millis);
byte[] data;
if((data = capeCollection.get(user)) != null) {
data[1] = msg[0];
}else {
data = new byte[] { (byte)2, msg[0], (byte)0 };
capeCollection.put(user, data);
}
ByteArrayOutputStream bao = new ByteArrayOutputStream();
DataOutputStream dd = new DataOutputStream(bao);
dd.write(msg[0]);
dd.writeUTF(user);
byte[] bpacket = bao.toByteArray();
byte[] packetPrefix = new byte[] { (byte) 250, 0, 14, 0, 69, 0, 65, 0, 71, 0, 124, 0, 83, 0, 107, 0, 105, 0, 110, 0, 76, 0, 97, 0, 121, 0, 101, 0, 114, 0, 115, (byte) ((bpacket.length >>> 8) & 0xFF), (byte) (bpacket.length & 0xFF) };
int off = bpacket.length == 0 ? 2 : 0;
byte[] fullPacket = new byte[(packetPrefix.length - off) + bpacket.length];
System.arraycopy(packetPrefix, 0, fullPacket, 0, packetPrefix.length - off);
if (bpacket.length != 0) System.arraycopy(bpacket, 0, fullPacket, packetPrefix.length, bpacket.length);
for (WebSocket pl : Main.clients.keySet()) {
if (pl.equals(conn)) continue;
if (pl.isOpen()) pl.send(fullPacket);
}
} else {
return false;
}
}catch(Throwable t) {
// hacker
}
} else {
return false;
}
return true;
}
public static void removeSkin(String username) {
skinCollection.remove(username);
capeCollection.remove(username);
lastSkinLayerUpdate.remove(username);
}
}
@@ -0,0 +1,209 @@
package me.ayunami2000.ayungee;
import org.java_websocket.WebSocket;
import java.io.*;
import java.util.*;
public class Voice {
private static final Map<String, WebSocket> voicePlayers = new HashMap<>();
private static final Map<String, ExpiringSet<String>> voiceRequests = new HashMap<>();
private static final Set<String[]> voicePairs = new HashSet<>();
private static final int VOICE_SIGNAL_ALLOWED = 0;
private static final int VOICE_SIGNAL_REQUEST = 0;
private static final int VOICE_SIGNAL_CONNECT = 1;
private static final int VOICE_SIGNAL_DISCONNECT = 2;
private static final int VOICE_SIGNAL_ICE = 3;
private static final int VOICE_SIGNAL_DESC = 4;
private static final int VOICE_SIGNAL_GLOBAL = 5;
public static boolean handleVoice(String user, WebSocket connection, String tag, byte[] msg) {
synchronized (voicePlayers) {
if (!Main.voiceEnabled) return false;
if (!("EAG|Voice".equals(tag))) return false;
try {
if (msg.length == 0) return true;
DataInputStream streamIn = new DataInputStream(new ByteArrayInputStream(msg));
int sig = streamIn.read();
switch (sig) {
case VOICE_SIGNAL_CONNECT:
if (voicePlayers.containsKey(user)) return true; // user is already using voice chat
// send out packet for player joined voice
// notice: everyone on the server can see this packet!! however, it doesn't do anything but let clients know that the player has turned on voice chat
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.write(VOICE_SIGNAL_CONNECT);
dos.writeUTF(user);
byte[] out = baos.toByteArray();
for (WebSocket conn : voicePlayers.values()) sendVoicePacket(conn, out);
voicePlayers.put(user, connection);
for (String username : voicePlayers.keySet()) sendVoicePlayers(username);
break;
case VOICE_SIGNAL_DISCONNECT:
if (!voicePlayers.containsKey(user)) return true; // user is not using voice chat
try {
String user2 = streamIn.readUTF();
if (!voicePlayers.containsKey(user2)) return true;
if (voicePairs.removeIf(pair -> (pair[0].equals(user) && pair[1].equals(user2)) || (pair[0].equals(user2) && pair[1].equals(user)))) {
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
DataOutputStream dos2 = new DataOutputStream(baos2);
dos2.write(VOICE_SIGNAL_DISCONNECT);
dos2.writeUTF(user);
sendVoicePacket(voicePlayers.get(user2), baos2.toByteArray());
baos2 = new ByteArrayOutputStream();
dos2 = new DataOutputStream(baos2);
dos2.write(VOICE_SIGNAL_DISCONNECT);
dos2.writeUTF(user2);
sendVoicePacket(connection, baos2.toByteArray());
}
} catch (EOFException e) {
removeUser(user);
}
break;
case VOICE_SIGNAL_REQUEST:
if (!voicePlayers.containsKey(user)) return true; // user is not using voice chat
String targetUser = streamIn.readUTF();
if (user.equals(targetUser)) return true; // prevent duplicates
if (checkVoicePair(user, targetUser)) return true; // already paired
if (!voicePlayers.containsKey(targetUser)) return true; // target user is not using voice chat
if (!voiceRequests.containsKey(user)) voiceRequests.put(user, new ExpiringSet<>(2000));
if (voiceRequests.get(user).contains(targetUser)) return true;
voiceRequests.get(user).add(targetUser);
// check if other has requested earlier
if (voiceRequests.containsKey(targetUser) && voiceRequests.get(targetUser).contains(user)) {
if (voiceRequests.containsKey(targetUser)) {
voiceRequests.get(targetUser).remove(user);
if (voiceRequests.get(targetUser).isEmpty()) voiceRequests.remove(targetUser);
}
if (voiceRequests.containsKey(user)) {
voiceRequests.get(user).remove(targetUser);
if (voiceRequests.get(user).isEmpty()) voiceRequests.remove(user);
}
// send each other add data
voicePairs.add(new String[]{user, targetUser});
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
DataOutputStream dos2 = new DataOutputStream(baos2);
dos2.write(VOICE_SIGNAL_CONNECT);
dos2.writeUTF(user);
dos2.writeBoolean(false);
sendVoicePacket(voicePlayers.get(targetUser), baos2.toByteArray());
baos2 = new ByteArrayOutputStream();
dos2 = new DataOutputStream(baos2);
dos2.write(VOICE_SIGNAL_CONNECT);
dos2.writeUTF(targetUser);
dos2.writeBoolean(true);
sendVoicePacket(connection, baos2.toByteArray());
}
break;
case VOICE_SIGNAL_ICE:
case VOICE_SIGNAL_DESC:
if (!voicePlayers.containsKey(user)) return true; // user is not using voice chat
String targetUser2 = streamIn.readUTF();
if (checkVoicePair(user, targetUser2)) {
String data = streamIn.readUTF();
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
DataOutputStream dos2 = new DataOutputStream(baos2);
dos2.write(sig);
dos2.writeUTF(user);
dos2.writeUTF(data);
sendVoicePacket(voicePlayers.get(targetUser2), baos2.toByteArray());
}
break;
default:
break;
}
} catch (Throwable t) {
// hacker
// t.printStackTrace(); // todo: remove in production
removeUser(user);
}
}
return true;
}
public static void onLogin(String username, WebSocket conn) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.write(VOICE_SIGNAL_ALLOWED);
dos.writeBoolean(Main.voiceEnabled);
dos.write(Main.voiceICE.size());
for(String str : Main.voiceICE) {
dos.writeUTF(str);
}
sendVoicePacket(conn, baos.toByteArray());
sendVoicePlayers(username);
} catch (IOException ignored) { }
}
public static void onQuit(String username) {
removeUser(username);
}
private static void sendVoicePlayers(String name) {
synchronized (voicePlayers) {
if (!Main.voiceEnabled) return;
if (!voicePlayers.containsKey(name)) return;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.write(VOICE_SIGNAL_GLOBAL);
Set<String> mostlyGlobalPlayers = new HashSet<>();
for (String username : voicePlayers.keySet()) {
if (username.equals(name)) continue;
if (voicePairs.stream().anyMatch(pair -> (pair[0].equals(name) && pair[1].equals(username)) || (pair[0].equals(username) && pair[1].equals(name))))
continue;
mostlyGlobalPlayers.add(username);
}
if (mostlyGlobalPlayers.size() > 0) {
dos.writeInt(mostlyGlobalPlayers.size());
for (String username : mostlyGlobalPlayers) dos.writeUTF(username);
sendVoicePacket(voicePlayers.get(name), baos.toByteArray());
}
} catch (IOException ignored) {
}
}
}
private static void removeUser(String name) {
synchronized (voicePlayers) {
voicePlayers.remove(name);
for (String username : voicePlayers.keySet()) {
if (!name.equals(username)) sendVoicePlayers(username);
}
for (String[] voicePair : voicePairs) {
String target = null;
if (voicePair[0].equals(name)) {
target = voicePair[1];
} else if (voicePair[1].equals(name)) {
target = voicePair[0];
}
if (target != null && voicePlayers.containsKey(target)) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.write(VOICE_SIGNAL_DISCONNECT);
dos.writeUTF(name);
sendVoicePacket(voicePlayers.get(target), baos.toByteArray());
} catch (IOException ignored) {
}
}
}
voicePairs.removeIf(pair -> pair[0].equals(name) || pair[1].equals(name));
}
}
private static boolean checkVoicePair(String user1, String user2) {
return voicePairs.stream().anyMatch(pair -> (pair[0].equals(user1) && pair[1].equals(user2)) || (pair[0].equals(user2) && pair[1].equals(user1)));
}
private static void sendVoicePacket(WebSocket conn, byte[] msg) {
byte[] packetPrefix = new byte[] { (byte) 250, 0, 9, 0, 69, 0, 65, 0, 71, 0, 124, 0, 86, 0, 111, 0, 105, 0, 99, 0, 101, (byte) ((msg.length >>> 8) & 0xFF), (byte) (msg.length & 0xFF) };
byte[] fullPacket = new byte[packetPrefix.length + msg.length];
System.arraycopy(packetPrefix, 0, fullPacket, 0, packetPrefix.length);
System.arraycopy(msg, 0, fullPacket, packetPrefix.length, msg.length);
conn.send(fullPacket);
}
}
@@ -0,0 +1,267 @@
package me.ayunami2000.ayungee;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.util.*;
import java.util.regex.Pattern;
public class WebSocketProxy extends WebSocketServer {
private static final int maxBuffSize = 33000; // 4096;
public WebSocketProxy(int port) {
super(new InetSocketAddress(port));
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
// anti-concurrentmodificationexception
Set<Pattern> snapshotOriginBlacklist = new HashSet<>(Main.originBlacklist);
if (!snapshotOriginBlacklist.isEmpty() || !Main.originWhitelist.isEmpty()) {
String origin = handshake.getFieldValue("Origin");
if (origin == null) {
conn.close();
return;
}
if (origin.contains("://")) origin = origin.substring(origin.indexOf("://") + 3);
if (!Main.originWhitelist.isEmpty() && !Main.originWhitelist.contains(origin)) {
conn.close();
return;
}
for (Pattern pattern : snapshotOriginBlacklist) {
if (pattern.matcher(origin).matches()) {
conn.close();
return;
}
}
}
if (Main.forwarded) {
String forwardedIp = handshake.getFieldValue("X-Real-IP");
if (forwardedIp == null) {
conn.close();
return;
}
conn.setAttachment(forwardedIp);
} else {
conn.setAttachment(conn.getRemoteSocketAddress().getAddress().toString().split("/")[1]);
}
new Thread(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException ignored) {}
if (conn.isOpen() && (Main.bans.contains(Main.getIp(conn)) || !Main.clients.containsKey(conn) || !Main.clients.get(conn).authed)) conn.close();
}).start();
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
Client selfClient = Main.clients.remove(conn);
if (selfClient != null) {
Main.printMsg("Player " + selfClient + " left!");
Skins.removeSkin(selfClient.username);
Voice.onQuit(selfClient.username);
if (selfClient.socket.isClosed()) {
try {
selfClient.socket.close();
} catch (IOException e) {
//e.printStackTrace();
}
}
}
}
@Override
public void onMessage(WebSocket conn, String s) {
if (!conn.isOpen()) return;
if (s.equals("Accept: MOTD")) {
if (Main.bans.contains(Main.getIp(conn))) {
conn.send("{\"data\":{\"motd\":[\"§cYour IP is §4banned §cfrom this server.\"],\"cache\":true,\"max\":0,\"icon\":false,\"online\":0,\"players\":[\"§4Banned...\"]},\"vers\":\"0.2.0\",\"name\":\"Your IP is banned from this server.\",\"time\":" + Instant.now().toEpochMilli() + ",\"type\":\"motd\",\"brand\":\"Eagtek\",\"uuid\":\"" + UUID.randomUUID().toString() + "\",\"cracked\":true}");
} else {
conn.send(Main.motdJson);
conn.send(Main.serverIcon);
}
}
conn.close();
}
@Override
public void onMessage(WebSocket conn, ByteBuffer message) { // todo: make use of the fact that it's already a bytebuffer dumbass
if (Main.bans.contains(Main.getIp(conn))) {
conn.close();
return;
}
if (!conn.isOpen()) return;
byte[] msg = message.array();
if (!Main.clients.containsKey(conn)) {
if (msg.length > 3 && msg[0] == 2 && msg[1] == 69) {
message.get();
message.get();
short unameLen = message.getShort();
if (unameLen < 3 || unameLen > 16) {
conn.close();
return;
}
if (msg.length < 5 + unameLen * 2) {
conn.close();
return;
}
StringBuilder unameBuilder = new StringBuilder();
for (int i = 0; i < unameLen; i++) unameBuilder.append(message.getChar());
String username = unameBuilder.toString();
if (!username.equals(username.replaceAll("[^A-Za-z0-9_-]", "_"))) {
conn.close();
return;
}
if (Main.clients.values().stream().anyMatch(client -> client.username.equals(username) || client.conn == conn)) {
conn.close();
return;
}
Client selfClient = new Client(conn, username);
Main.clients.put(conn, selfClient);
new Thread(() -> {
try {
while (conn.isOpen()) {
int currServer = selfClient.server;
if (currServer == -1 && selfClient.authed) currServer = selfClient.server = 0;
selfClient.hasLoginHappened = false;
if (!selfClient.firstTime) Main.printMsg("Player " + selfClient + " joined server " + currServer + "!");
ServerItem chosenServer = Main.servers.get(currServer);
/*
if (chosenServer.host.equals(Main.authKey)) {
// todo: custom server here
return;
}
*/
Socket selfSocket = new Socket();
try {
// todo: pregenerate InetSocketAddresses
selfSocket.connect(new InetSocketAddress(chosenServer.host, chosenServer.port), 10000);
} catch (SocketTimeoutException e) {
conn.close();
return;
}
selfClient.setSocket(selfSocket);
if (!selfClient.firstTime) sendToServer(selfClient.handshake, selfClient);
if (selfClient.firstTime) {
while (selfClient.msgCache.size() > 0)
sendToServer(selfClient.msgCache.remove(0), selfClient);
}
while (conn.isOpen() && !selfSocket.isInputShutdown() && selfClient.server == currServer) {
byte[] dataa = new byte[maxBuffSize];
int read = selfClient.socketIn.read(dataa, 0, maxBuffSize);
byte[] data;
if (read == maxBuffSize) {
data = dataa;
} else if (read > 0) {
data = new byte[read];
System.arraycopy(dataa, 0, data, 0, read);
} else {
continue;
}
if (ChatHandler.serverChatMessage(selfClient, data)) continue;
if (PluginMessages.serverPluginMessage(selfClient, data)) continue;
if (!selfClient.authed && data[0] == 13) selfClient.positionPacket = data;
boolean loginPacket = data[0] == 1;
if (loginPacket && !selfClient.hasLoginHappened) selfClient.hasLoginHappened = true;
if (selfClient.firstTime && loginPacket) {
selfClient.clientEntityId = selfClient.serverEntityId = EntityMap.readInt(data, 1);
Voice.onLogin(username, conn);
}
if (!selfClient.firstTime && loginPacket) {
selfClient.serverEntityId = EntityMap.readInt(data, 1);
// assume server is giving valid data; we don't have to validate it because it isn't a potentially malicious client
short worldByteLen = (short) ((data[5] << 8) + data[6] & 0xff);
byte[] worldByte = new byte[worldByteLen * 2 + 2];
System.arraycopy(data, 5, worldByte, 0, worldByte.length);
byte gamemode = data[worldByte.length + 5];
byte dimension = data[worldByte.length + 6];
byte difficulty = data[worldByte.length + 7];
Arrays.fill(data, (byte) 0);
data[0] = 9;
EntityMap.setInt(data, 1, dimension);
data[5] = difficulty;
data[6] = gamemode;
data[7] = (byte)(256 & 0xff);
data[8] = (byte)((256 >> 8) & 0xff);
System.arraycopy(worldByte, 0, data, 9, worldByte.length);
read = 9 + worldByte.length;
byte[] trimData = new byte[read];
System.arraycopy(data, 0, trimData, 0, read);
data = trimData;
if (conn.isOpen()) conn.send(new byte[] { 9, 0, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 100, 0, 101, 0, 102, 0, 97, 0, 117, 0, 108, 0, 116 });
if (conn.isOpen()) conn.send(new byte[] { 9, 0, 0, 0, -1, 0, 0, 1, 0, 0, 7, 0, 100, 0, 101, 0, 102, 0, 97, 0, 117, 0, 108, 0, 116 });
}
EntityMap.rewrite(data, selfClient.serverEntityId, selfClient.clientEntityId);
if (selfClient.authed || ((loginPacket || data[0] == 51 || data[0] == 13 || data[0] == 6) || !selfClient.hasLoginHappened)) {
if (selfClient.authed) {
while (selfClient.packetCache.size() > 0) {
if (conn.isOpen()) conn.send(selfClient.packetCache.remove(0));
}
}
if (conn.isOpen()) conn.send(data);
} else {
// cache data
selfClient.packetCache.add(data);
}
if (loginPacket) sendToServer(new byte[] { (byte) 250, 0, 8, 0, 82, 0, 69, 0, 71, 0, 73, 0, 83, 0, 84, 0, 69, 0, 82, 0, 10, 66, 117, 110, 103, 101, 101, 67, 111, 114, 100 }, selfClient);
}
if (conn.isOpen() && selfClient.server == currServer) conn.close();
if (!selfSocket.isClosed()) selfSocket.close();
selfClient.socketOut = null;
selfClient.firstTime = false;
}
} catch (IOException ex) {
conn.close();
}
}).start();
msg[1] = (byte) 61;
selfClient.handshake = msg;
Main.printMsg("Player " + selfClient + " joined!");
} else {
conn.close();
return;
}
}
Client currClient = Main.clients.get(conn);
if (ChatHandler.clientChatMessage(currClient, msg)) return;
if (PluginMessages.clientPluginMessage(currClient, msg)) return;
if (!currClient.firstTime && !currClient.hasLoginHappened && !(msg[0] == 1 || msg[0] == 2)) return;
if (currClient.socketOut == null || currClient.socket.isOutputShutdown()) {
currClient.msgCache.add(msg);
} else {
try {
sendToServer(msg, currClient);
} catch (IOException ignored) {}
}
}
public void sendToServer(byte[] orig, Client client) throws IOException {
if (!client.authed) {
if (orig.length > 0) {
if (orig[0] == 2 || orig[0] == 3) client.conn.send(new byte[] { 3, 0, 114, 0, (byte) 167, 0, 57, 0, 80, 0, 108, 0, 101, 0, 97, 0, 115, 0, 101, 0, 32, 0, 114, 0, 101, 0, 103, 0, 105, 0, 115, 0, 116, 0, 101, 0, 114, 0, 32, 0, 111, 0, 114, 0, 32, 0, 108, 0, 111, 0, 103, 0, 105, 0, 110, 0, 32, 0, 116, 0, 111, 0, 32, 0, 99, 0, 111, 0, 110, 0, 116, 0, 105, 0, 110, 0, 117, 0, 101, 0, 32, 0, 116, 0, 111, 0, 32, 0, 116, 0, 104, 0, 105, 0, 115, 0, 32, 0, 115, 0, 101, 0, 114, 0, 118, 0, 101, 0, 114, 0, 33, 0, 32, 0, 47, 0, 114, 0, 101, 0, 103, 0, 105, 0, 115, 0, 116, 0, 101, 0, 114, 0, 32, 0, 60, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 62, 0, 32, 0, 60, 0, 99, 0, 111, 0, 110, 0, 102, 0, 105, 0, 114, 0, 109, 0, 80, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 62, 0, 32, 0, 111, 0, 114, 0, 32, 0, 47, 0, 108, 0, 111, 0, 103, 0, 105, 0, 110, 0, 32, 0, 60, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 62 });
if (orig[0] == 10 || orig[0] == 11 || orig[0] == 12 || orig[0] == 13 || orig[0] == 14 || orig[0] == 15) client.conn.send(client.positionPacket);
}
if (client.hasLoginHappened) return; // drop client packets :trol:
}
byte[] data = orig.clone();
EntityMap.rewrite(data, client.clientEntityId, client.serverEntityId);
client.socketOut.write(data);
}
@Override
public void onError(WebSocket conn, Exception ex) {
//
}
@Override
public void onStart() {
setConnectionLostTimeout(0);
}
}
@@ -0,0 +1,48 @@
# mc servers in network. first one is default/hub
servers:
- localhost:25569
# ayungee port
web_port: 25565
# if this is behind a reverse proxy, such as caddy or nginx. uses X-Real-IP header.
forwarded: false
# origin blacklist URL (leave empty to disable syncing)
origin_blacklist: "https://g.eags.us/eaglercraft/origin_blacklist.txt"
# whitelisted origins -- if specified, only allows the listed origins to connect
# for example,
# - "https://g.eags.us"
origins: []
# enable /server command?
server_cmd: true
# voice chat
voice:
# enable voice chat
enabled: true
# voice chat ICE servers
# format is like <server> OR <server>;<username>;<password>
# chances are you won't have to change these
ice:
- "stun:openrelay.metered.ca:80"
- "turn:openrelay.metered.ca:80;openrelayproject;openrelayproject"
- "turn:openrelay.metered.ca:443;openrelayproject;openrelayproject"
- "turn:openrelay.metered.ca:443?transport=tcp;openrelayproject;openrelayproject"
# authentication info
auth:
# use auth
enabled: false
# max registers per ip (set to 0 for unlimited, not recommended, but necessary for servers that cannot see user IPs)
ip_limit: 0
# motd info
motd:
# the motd itself
lines:
- "Welcome to my"
- "ayungee-powered server!"
# max players (purely visual)
max: 20
# online players (purely visual)
online: 4
# name of server
name: An ayungee-powered Eaglercraft server
# players online (purely visual)
players:
- "whar?"
Binary file not shown.

After

Width:  |  Height:  |  Size: 450 B