Archive ayunviaproxyeagutils (tool, any, clean)

This commit is contained in:
2026-11-28 00:50:01 -06:00
parent ac1791047f
commit 94e73f6abe
32 changed files with 4088 additions and 0 deletions
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
+8
View File
@@ -0,0 +1,8 @@
.gradle
.idea
build
gradle
libs
gradlew
gradlew.bat
src/main/resources/*.png
+29
View File
@@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2023, 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.
+4
View File
@@ -0,0 +1,4 @@
# ayunViaProxyEagUtils
eaglercraft support for viaproxy. ws:// on same port as java. supports both 1.5.2 and 1.8.8 eaglercraft depending on the configuration (e.g. use legacy passthrough & protocolsupport if the backend server doesn't support 1.5.2)
note: skin files are excluded
+14
View File
@@ -0,0 +1,14 @@
plugins {
id 'java'
}
group 'me.ayunami2000.ayunViaProxyEagUtils'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation files("libs/ViaProxy-3.3.1+java8.jar")
}
@@ -0,0 +1,2 @@
rootProject.name = 'ayunViaProxyEagUtils'
@@ -0,0 +1,357 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import com.google.gson.JsonObject;
import com.mojang.authlib.GameProfile;
import com.viaversion.viaversion.util.ChatColorUtil;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.util.AttributeKey;
import net.lenni0451.mcstructs.text.serializer.TextComponentSerializer;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.proxy.session.ProxyConnection;
import net.raphimc.viaproxy.util.logging.Logger;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
/**
* Copyright (c) 2022-2023 LAX1DUDE. All Rights Reserved.
*
* WITH THE EXCEPTION OF PATCH FILES, MINIFIED JAVASCRIPT, AND ALL FILES
* NORMALLY FOUND IN AN UNMODIFIED MINECRAFT RESOURCE PACK, YOU ARE NOT ALLOWED
* TO SHARE, DISTRIBUTE, OR REPURPOSE ANY FILE USED BY OR PRODUCED BY THE
* SOFTWARE IN THIS REPOSITORY WITHOUT PRIOR PERMISSION FROM THE PROJECT AUTHOR.
*
* NOT FOR COMMERCIAL OR MALICIOUS USE
*
* (please read the 'LICENSE' file this repo's root directory for more info)
*
*/
public class ConnectionHandshake {
private static final AttributeKey<Integer> serverVersKey = AttributeKey.newInstance("eag-server-vers");
private static final int protocolV2 = 2;
private static final int protocolV3 = 3;
public static void attemptHandshake(List<Object> out, Channel ch, ProxyConnection proxyConnection, String password) {
try {
ByteArrayOutputStream bao = new ByteArrayOutputStream();
DataOutputStream d = new DataOutputStream(bao);
d.writeByte(HandshakePacketTypes.PROTOCOL_CLIENT_VERSION);
d.writeByte(2); // legacy protocol version
d.writeShort(2); // supported eagler protocols count
d.writeShort(protocolV2); // client supports v2
d.writeShort(protocolV3); // client supports v3
d.writeShort(1); // supported game protocols count
d.writeShort(proxyConnection.getServerVersion().getVersion()); // client supports this protocol
String clientBrand = "ViaProxy";
d.writeByte(clientBrand.length());
d.writeBytes(clientBrand);
String clientVers = ViaProxy.VERSION;
d.writeByte(clientVers.length());
d.writeBytes(clientVers);
d.writeBoolean(password != null);
String username = proxyConnection.getGameProfile().getName();
d.writeByte(username.length());
d.writeBytes(username);
out.add(new BinaryWebSocketFrame(ch.alloc().buffer(bao.size()).writeBytes(bao.toByteArray())));
} catch (Throwable t) {
Logger.LOGGER.error("Exception in handshake");
Logger.LOGGER.error(t);
}
}
public static void attemptHandshake2(Channel ch, byte[] read, ProxyConnection proxyConnection, String password) {
try {
ByteArrayOutputStream bao = new ByteArrayOutputStream();
DataOutputStream d = new DataOutputStream(bao);
String username = proxyConnection.getGameProfile().getName();
DataInputStream di = new DataInputStream(new ByteArrayInputStream(read));
int type = di.read();
if (type == HandshakePacketTypes.PROTOCOL_VERSION_MISMATCH) {
StringBuilder protocols = new StringBuilder();
int c = di.readShort();
for (int i = 0; i < c; ++i) {
if (i > 0) {
protocols.append(", ");
}
protocols.append("v").append(di.readShort());
}
StringBuilder games = new StringBuilder();
c = di.readShort();
for (int i = 0; i < c; ++i) {
if (i > 0) {
games.append(", ");
}
games.append("mc").append(di.readShort());
}
Logger.LOGGER.info("Incompatible client: v2 & mc" + proxyConnection.getServerVersion().getVersion());
Logger.LOGGER.info("Server supports: {}", protocols);
Logger.LOGGER.info("Server supports: {}", games);
int msgLen = di.read();
byte[] dat = new byte[msgLen];
di.read(dat);
String msg = new String(dat, StandardCharsets.UTF_8);
proxyConnection.kickClient(msg);
} else if (type == HandshakePacketTypes.PROTOCOL_SERVER_VERSION) {
int serverVers = di.readShort();
if (serverVers != protocolV2 && serverVers != protocolV3) {
Logger.LOGGER.info("Incompatible server version: {}", serverVers);
proxyConnection.kickClient(serverVers < protocolV2 ? "Outdated Server" : "Outdated Client");
return;
}
ch.attr(serverVersKey).set(serverVers);
int gameVers = di.readShort();
if (gameVers != proxyConnection.getServerVersion().getVersion()) {
Logger.LOGGER.info("Incompatible minecraft protocol version: {}", gameVers);
proxyConnection.kickClient("This server does not support " + proxyConnection.getServerVersion().getName() + "!");
return;
}
Logger.LOGGER.info("Server protocol: {}", serverVers);
int msgLen = di.read();
byte[] dat = new byte[msgLen];
di.read(dat);
String brandStr = asciiString(dat);
msgLen = di.read();
dat = new byte[msgLen];
di.read(dat);
String versionStr = asciiString(dat);
Logger.LOGGER.info("Server version: {}", versionStr);
Logger.LOGGER.info("Server brand: {}", brandStr);
int authType = di.read();
int saltLength = (int) di.readShort() & 0xFFFF;
byte[] salt = new byte[saltLength];
di.read(salt);
bao.reset();
d.writeByte(HandshakePacketTypes.PROTOCOL_CLIENT_REQUEST_LOGIN);
d.writeByte(username.length());
d.writeBytes(username);
String requestedServer = "default";
d.writeByte(requestedServer.length());
d.writeBytes(requestedServer);
if (authType != 0 && password != null && !password.isEmpty()) {
if (authType == HandshakePacketTypes.AUTH_METHOD_PLAINTEXT) {
Logger.LOGGER.warn("Server is using insecure plaintext authentication");
d.writeByte(password.length() << 1);
d.writeChars(password);
} else if (authType == HandshakePacketTypes.AUTH_METHOD_EAGLER_SHA256) {
SHA256Digest digest = new SHA256Digest();
int passLen = password.length();
digest.update((byte) ((passLen >> 8) & 0xFF));
digest.update((byte) (passLen & 0xFF));
for (int i = 0; i < passLen; ++i) {
char codePoint = password.charAt(i);
digest.update((byte) ((codePoint >> 8) & 0xFF));
digest.update((byte) (codePoint & 0xFF));
}
digest.update(HandshakePacketTypes.EAGLER_SHA256_SALT_SAVE, 0, 32);
byte[] hashed = new byte[32];
digest.doFinal(hashed, 0);
digest.reset();
digest.update(hashed, 0, 32);
digest.update(salt, 0, 32);
digest.update(HandshakePacketTypes.EAGLER_SHA256_SALT_BASE, 0, 32);
digest.doFinal(hashed, 0);
digest.reset();
digest.update(hashed, 0, 32);
digest.update(salt, 32, 32);
digest.update(HandshakePacketTypes.EAGLER_SHA256_SALT_BASE, 0, 32);
digest.doFinal(hashed, 0);
d.writeByte(32);
d.write(hashed);
} else if (authType == HandshakePacketTypes.AUTH_METHOD_AUTHME_SHA256) {
SHA256Digest digest = new SHA256Digest();
byte[] passwd = password.getBytes(StandardCharsets.UTF_8);
digest.update(passwd, 0, passwd.length);
byte[] hashed = new byte[32];
digest.doFinal(hashed, 0);
byte[] toHexAndSalt = new byte[64];
for (int i = 0; i < 32; ++i) {
toHexAndSalt[i << 1] = HEX[(hashed[i] >> 4) & 0xF];
toHexAndSalt[(i << 1) + 1] = HEX[hashed[i] & 0xF];
}
digest.reset();
digest.update(toHexAndSalt, 0, 64);
digest.update(salt, 0, salt.length);
digest.doFinal(hashed, 0);
for (int i = 0; i < 32; ++i) {
toHexAndSalt[i << 1] = HEX[(hashed[i] >> 4) & 0xF];
toHexAndSalt[(i << 1) + 1] = HEX[hashed[i] & 0xF];
}
d.writeByte(64);
d.write(toHexAndSalt);
} else {
Logger.LOGGER.error("Unsupported authentication type: {}", authType);
proxyConnection.kickClient(ChatColorUtil.COLOR_CHAR + "cUnsupported authentication type: " + authType + "\n\n" + ChatColorUtil.COLOR_CHAR + "7(Use a newer version of the client)");
return;
}
} else {
d.writeByte(0);
}
ch.writeAndFlush(new BinaryWebSocketFrame(ch.alloc().buffer(bao.size()).writeBytes(bao.toByteArray())));
} else if (type == HandshakePacketTypes.PROTOCOL_SERVER_ERROR) {
showError(proxyConnection, di, true);
}
} catch (Throwable t) {
Logger.LOGGER.error("Exception in handshake");
Logger.LOGGER.error(t);
}
}
public static void attemptHandshake3(Channel ch, byte[] read, ProxyConnection proxyConnection) {
try {
int serverVers = ch.attr(serverVersKey).get();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
DataOutputStream d = new DataOutputStream(bao);
int msgLen;
byte[] dat;
DataInputStream di = new DataInputStream(new ByteArrayInputStream(read));
int type = di.read();
if (type == HandshakePacketTypes.PROTOCOL_SERVER_ALLOW_LOGIN) {
msgLen = di.read();
dat = new byte[msgLen];
di.read(dat);
String serverUsername = asciiString(dat);
JsonObject json = new JsonObject();
json.addProperty("name", serverUsername);
UUID uuid = new UUID(di.readLong(), di.readLong());
json.addProperty("uuid", uuid.toString());
proxyConnection.setGameProfile(new GameProfile(uuid, serverUsername));
if (proxyConnection.getC2P().hasAttr(EaglercraftHandler.profileDataKey)) {
EaglercraftHandler.ProfileData profileData = proxyConnection.getC2P().attr(EaglercraftHandler.profileDataKey).get();
bao.reset();
d.writeByte(HandshakePacketTypes.PROTOCOL_CLIENT_PROFILE_DATA);
d.writeByte(profileData.type.length());
d.writeBytes(profileData.type);
d.writeShort(profileData.data.length);
d.write(profileData.data);
ch.writeAndFlush(new BinaryWebSocketFrame(ch.alloc().buffer(bao.size()).writeBytes(bao.toByteArray())));
}
bao.reset();
d.writeByte(HandshakePacketTypes.PROTOCOL_CLIENT_FINISH_LOGIN);
ch.writeAndFlush(new BinaryWebSocketFrame(ch.alloc().buffer(bao.size()).writeBytes(bao.toByteArray())));
} else if (type == HandshakePacketTypes.PROTOCOL_SERVER_DENY_LOGIN) {
if (serverVers == protocolV2) {
msgLen = di.read();
} else {
msgLen = di.readUnsignedShort();
}
dat = new byte[msgLen];
di.read(dat);
String errStr = new String(dat, StandardCharsets.UTF_8);
proxyConnection.kickClient(TextComponentSerializer.V1_8.deserialize(errStr).asLegacyFormatString());
} else if (type == HandshakePacketTypes.PROTOCOL_SERVER_ERROR) {
showError(proxyConnection, di, serverVers == protocolV2);
}
} catch (Throwable t) {
Logger.LOGGER.error("Exception in handshake");
Logger.LOGGER.error(t);
}
}
public static void attemptHandshake4(Channel ch, byte[] read, ProxyConnection proxyConnection) {
try {
int serverVers = ch.attr(serverVersKey).get();
DataInputStream di = new DataInputStream(new ByteArrayInputStream(read));
int type = di.read();
if (type == HandshakePacketTypes.PROTOCOL_SERVER_ERROR) {
showError(proxyConnection, di, serverVers == protocolV2);
}
} catch (Throwable t) {
Logger.LOGGER.error("Exception in handshake");
Logger.LOGGER.error(t);
}
}
private static void showError(ProxyConnection proxyConnection, DataInputStream err, boolean v2) throws IOException {
int errorCode = err.read();
int msgLen = v2 ? err.read() : err.readUnsignedShort();
byte[] dat = new byte[msgLen];
err.read(dat);
String errStr = new String(dat, StandardCharsets.UTF_8);
Logger.LOGGER.info("Server Error Code {}: {}", errorCode, errStr);
if(errorCode == HandshakePacketTypes.SERVER_ERROR_RATELIMIT_BLOCKED) {
proxyConnection.kickClient("Server Error Ratelimited (blocked)");
}else if(errorCode == HandshakePacketTypes.SERVER_ERROR_RATELIMIT_LOCKED) {
proxyConnection.kickClient("Server Error Ratelimited (locked)");
}else if(errorCode == HandshakePacketTypes.SERVER_ERROR_CUSTOM_MESSAGE) {
proxyConnection.kickClient("Server Error Message " + TextComponentSerializer.V1_8.deserialize(errStr).asLegacyFormatString());
}else if(errorCode == HandshakePacketTypes.SERVER_ERROR_AUTHENTICATION_REQUIRED) {
proxyConnection.kickClient("Server Error Authentication required " + TextComponentSerializer.V1_8.deserialize(errStr).asLegacyFormatString());
}else {
proxyConnection.kickClient("Server Error Code " + errorCode + "\n" + TextComponentSerializer.V1_8.deserialize(errStr).asLegacyFormatString());
}
}
private static final byte[] HEX = new byte[]{
(byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
(byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f'
};
public static String asciiString(byte[] bytes) {
char[] str = new char[bytes.length];
for(int i = 0; i < bytes.length; ++i) {
str[i] = (char)((int) bytes[i] & 0xFF);
}
return new String(str);
}
}
@@ -0,0 +1,603 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import com.google.common.primitives.Ints;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.viaversion.viaversion.api.protocol.version.ProtocolVersion;
import com.viaversion.viaversion.util.ChatColorUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.AttributeKey;
import net.jodah.expiringmap.ExpiringMap;
import net.raphimc.netminecraft.constants.MCPackets;
import net.raphimc.netminecraft.netty.connection.NetClient;
import net.raphimc.netminecraft.packet.PacketTypes;
import net.raphimc.vialegacy.api.LegacyProtocolVersion;
import net.raphimc.vialegacy.protocol.release.r1_5_2tor1_6_1.packet.ClientboundPackets1_5_2;
import net.raphimc.vialegacy.protocol.release.r1_5_2tor1_6_1.packet.ServerboundPackets1_5_2;
import net.raphimc.vialegacy.protocol.release.r1_6_4tor1_7_2_5.types.Types1_6_4;
import net.raphimc.viaproxy.proxy.session.LegacyProxyConnection;
import net.raphimc.viaproxy.proxy.session.ProxyConnection;
import net.raphimc.viaproxy.proxy.util.ExceptionUtil;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class EaglerServerHandler extends MessageToMessageCodec<WebSocketFrame, ByteBuf> {
private final ProtocolVersion version;
private final String password;
private final NetClient proxyConnection;
private final Map<UUID, String> uuidStringMap = new HashMap<>();
private final Map<Integer, UUID> eidUuidMap = new HashMap<>();
private final ExpiringMap<Short, UUID> skinsBeingFetched = ExpiringMap.builder().expiration(1, TimeUnit.MINUTES).build();
private short skinFetchCounter = 0;
private ByteBuf serverBoundPartialPacket = Unpooled.EMPTY_BUFFER;
private ByteBuf clientBoundPartialPacket = Unpooled.EMPTY_BUFFER;
public EaglerServerHandler(NetClient proxyConnection, String password) {
this.version = proxyConnection instanceof ProxyConnection ? ((ProxyConnection) proxyConnection).getServerVersion() : LegacyProtocolVersion.r1_5_2;
this.password = password;
this.proxyConnection = proxyConnection;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ExceptionUtil.handleNettyException(ctx, cause, null, true);
}
private int handshakeState = 0;
@Override
public void encode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
if (handshakeState < 0) {
out.add(Unpooled.EMPTY_BUFFER);
return;
}
if (version.newerThanOrEqualTo(ProtocolVersion.v1_7_2)) {
if (in.readableBytes() >= 2 && in.getUnsignedByte(0) == 0xFE && in.getUnsignedByte(1) == 0x01) {
handshakeState = -1;
out.add(new TextWebSocketFrame("Accept: MOTD"));
return;
}
if (handshakeState == 0) {
handshakeState = 1;
int id = PacketTypes.readVarInt(in);
if (id == 0x00) {
PacketTypes.readVarInt(in);
PacketTypes.readString(in, 32767);
in.readUnsignedShort();
int nextState = PacketTypes.readVarInt(in);
if (nextState == 1) {
handshakeState = -2;
out.add(new TextWebSocketFrame("Accept: MOTD"));
return;
}
}
in.resetReaderIndex();
if (((ProxyConnection) proxyConnection).getGameProfile() == null) {
out.add(Unpooled.EMPTY_BUFFER);
ctx.close();
return;
}
ConnectionHandshake.attemptHandshake(out, ctx.channel(), (ProxyConnection) proxyConnection, password);
if (out.isEmpty()) {
out.add(Unpooled.EMPTY_BUFFER);
}
} else if (handshakeState < 4) {
out.add(Unpooled.EMPTY_BUFFER);
} else {
out.add(new BinaryWebSocketFrame(in.retain()));
}
} else {
ByteBuf bb = ctx.alloc().buffer(serverBoundPartialPacket.readableBytes() + in.readableBytes());
bb.writeBytes(serverBoundPartialPacket);
serverBoundPartialPacket.release();
serverBoundPartialPacket = Unpooled.EMPTY_BUFFER;
bb.writeBytes(in);
int readerIndex = 0;
try {
while (bb.isReadable()) {
readerIndex = bb.readerIndex();
ServerboundPackets1_5_2 pkt = ServerboundPackets1_5_2.getPacket(bb.readUnsignedByte());
pkt.getPacketReader().accept(null, bb);
int len = bb.readerIndex() - readerIndex;
ByteBuf packet = ctx.alloc().buffer(len);
bb.readerIndex(readerIndex);
bb.readBytes(packet, len);
encodeOld(ctx, packet, out);
if (!ctx.channel().isOpen()) {
out.add(Unpooled.EMPTY_BUFFER);
return;
}
}
} catch (Exception e) {
bb.readerIndex(readerIndex);
if (bb.readableBytes() > 65535) {
ctx.close();
out.add(Unpooled.EMPTY_BUFFER);
return;
}
serverBoundPartialPacket = ctx.alloc().buffer(bb.readableBytes());
serverBoundPartialPacket.writeBytes(bb);
}
}
if (out.isEmpty()) {
out.add(Unpooled.EMPTY_BUFFER);
}
}
public void encodeOld(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
if (in.readableBytes() >= 2 && in.getUnsignedByte(0) == 0xFE && in.getUnsignedByte(1) == 0x01) {
handshakeState = -1;
out.add(new TextWebSocketFrame("Accept: MOTD"));
return;
}
if (in.readableBytes() >= 2 && in.getUnsignedByte(0) == 2) {
in.setByte(1, in.getUnsignedByte(1) + 8);
out.add(new BinaryWebSocketFrame(in.retain()));
Channel c2p;
if (proxyConnection instanceof ProxyConnection) {
c2p = ((ProxyConnection) proxyConnection).getC2P();
} else {
c2p = ((LegacyProxyConnection) proxyConnection).getC2P();
}
if (c2p.hasAttr(EaglercraftHandler.profileDataKey)) {
EaglercraftHandler.ProfileData profileData = c2p.attr(EaglercraftHandler.profileDataKey).get();
if (profileData.type.equals("skin_v1")) {
int packetType = profileData.data[0] & 0xFF;
if (packetType == 1 || packetType == 2) {
try {
byte[] res = SkinService.newToOldSkin(profileData.data);
ByteBuf bb = ctx.alloc().buffer();
bb.writeByte((byte) 250);
Types1_6_4.STRING.write(bb, "EAG|MySkin");
bb.writeShort(res.length);
bb.writeBytes(res);
out.add(new BinaryWebSocketFrame(bb));
} catch (Exception ignored) {}
}
}
}
return;
}
if (in.getUnsignedByte(0) == 0xFD) {
return;
}
if (proxyConnection instanceof ProxyConnection) {
if (in.readableBytes() >= 3 && in.getUnsignedByte(0) == 250) {
in.skipBytes(1);
String tag;
byte[] msg;
try {
tag = Types1_6_4.STRING.read(in);
if (tag.equals("EAG|Skins-1.8")) {
msg = new byte[in.readShort()];
in.readBytes(msg);
if (msg.length == 0) {
throw new IOException("Zero-length packet recieved");
}
final int packetId = msg[0] & 0xFF;
switch (packetId) {
case 3: {
if (msg.length != 17) {
throw new IOException("Invalid length " + msg.length + " for skin request packet");
}
final UUID searchUUID = SkinPackets.bytesToUUID(msg, 1);
if (uuidStringMap.containsKey(searchUUID)) {
short id = skinFetchCounter++;
skinsBeingFetched.put(id, searchUUID);
String name = uuidStringMap.get(searchUUID);
ByteBuf bb = ctx.alloc().buffer();
bb.writeByte((byte) 250);
Types1_6_4.STRING.write(bb, "EAG|FetchSkin");
ByteBuf bbb = ctx.alloc().buffer();
bbb.writeByte((byte) ((id >> 8) & 0xFF));
bbb.writeByte((byte) (id & 0xFF));
bbb.writeBytes(name.getBytes(StandardCharsets.UTF_8));
bb.writeShort(bbb.readableBytes());
bb.writeBytes(bbb);
bbb.release();
out.add(new BinaryWebSocketFrame(bb));
}
break;
}
case 6: {
break;
}
default: {
throw new IOException("Unknown packet type " + packetId);
}
}
return;
}
} catch (Exception ignored) {
}
in.resetReaderIndex();
}
}
out.add(new BinaryWebSocketFrame(in.retain()));
}
private static class ServerInfo {
public final String motd;
public final int online;
public final int max;
public final String[] players;
public ServerInfo(String motd, int online, int max, String[] players) {
this.motd = motd;
this.online = online;
this.max = max;
this.players = players;
}
}
private static final AttributeKey<ServerInfo> serverInfoKey = AttributeKey.newInstance("server-info");
public static final AttributeKey<ByteBuf> eagIconKey = AttributeKey.newInstance("eag-icon");
private static final AttributeKey<ByteBuf> eagLegacyStatusKey = AttributeKey.newInstance("eag-legacy-status");
@Override
public void decode(ChannelHandlerContext ctx, WebSocketFrame in, List<Object> out) {
if (in instanceof TextWebSocketFrame && handshakeState < 0) {
JsonObject json = JsonParser.parseString(((TextWebSocketFrame) in).text()).getAsJsonObject();
if (!(json.has("data") && json.get("data").isJsonObject() && (json = json.getAsJsonObject("data")).has("motd") && json.get("motd").isJsonArray() && json.has("icon") && json.get("icon").isJsonPrimitive() && json.has("online") && json.get("online").isJsonPrimitive() && json.has("max") && json.get("max").isJsonPrimitive() && json.has("players") && json.get("players").isJsonArray())) {
out.add(Unpooled.EMPTY_BUFFER);
return;
}
JsonArray motd = json.getAsJsonArray("motd");
StringBuilder motdSb = new StringBuilder();
for (JsonElement line : motd) {
motdSb.append(line.getAsString()).append("\n");
}
if (motdSb.length() > 0) {
motdSb.setLength(motdSb.length() - 1);
}
boolean icon = json.get("icon").getAsBoolean();
int online = json.get("online").getAsInt();
int max = json.get("max").getAsInt();
JsonArray players = json.getAsJsonArray("players");
if (handshakeState == -1) {
ByteBuf bb = ctx.alloc().buffer();
bb.writeByte((byte) 0xFF);
StringBuilder sb = new StringBuilder("\u00A71\0");
sb.append(version.getVersion()).append("\0");
sb.append(version.getName()).append("\0");
sb.append(motdSb).append("\0");
sb.append(online).append("\0");
sb.append(max);
try {
Types1_6_4.STRING.write(bb, sb.toString());
} catch (Exception ignored) {
}
if (icon) {
ctx.channel().attr(eagLegacyStatusKey).set(bb);
handshakeState = -3;
} else {
out.add(bb);
}
} else if (icon) {
List<String> playerList = new ArrayList<>();
for (JsonElement player : players) {
playerList.add(player.toString());
}
ctx.channel().attr(serverInfoKey).set(new ServerInfo(motdSb.toString(), online, max, playerList.toArray(new String[0])));
} else {
JsonObject resp = new JsonObject();
JsonObject versionObj = new JsonObject();
versionObj.addProperty("name", version.getName());
versionObj.addProperty("protocol", version.getVersion());
resp.add("version", versionObj);
JsonObject playersObj = new JsonObject();
playersObj.addProperty("max", max);
playersObj.addProperty("online", online);
if (!players.isEmpty()) {
JsonArray sampleArr = new JsonArray();
for (JsonElement player : players) {
JsonObject playerObj = new JsonObject();
playerObj.addProperty("name", player.toString());
playerObj.addProperty("id", UUID.nameUUIDFromBytes(("OfflinePlayer:" + player).getBytes(StandardCharsets.UTF_8)).toString());
sampleArr.add(playerObj);
}
playersObj.add("sample", sampleArr);
}
resp.add("players", playersObj);
JsonObject descriptionObj = new JsonObject();
descriptionObj.addProperty("text", motdSb.toString());
resp.add("description", descriptionObj);
ByteBuf bb = ctx.alloc().buffer();
PacketTypes.writeVarInt(bb, 0);
PacketTypes.writeString(bb, resp.toString());
out.add(bb);
handshakeState = -1;
}
}
if (!(in instanceof BinaryWebSocketFrame)) {
if (out.isEmpty()) {
out.add(Unpooled.EMPTY_BUFFER);
}
return;
}
if (handshakeState < 0) {
if (handshakeState == -3) {
handshakeState = -1;
if (proxyConnection instanceof ProxyConnection) {
((ProxyConnection) proxyConnection).getC2P().attr(eagIconKey).set(in.content().retain());
} else {
((LegacyProxyConnection) proxyConnection).getC2P().attr(eagIconKey).set(in.content().retain());
}
out.add(ctx.channel().attr(eagLegacyStatusKey).getAndSet(null));
return;
}
if (handshakeState == -1) {
out.add(Unpooled.EMPTY_BUFFER);
return;
}
ServerInfo serverInfo = ctx.channel().attr(serverInfoKey).getAndSet(null);
JsonObject resp = new JsonObject();
JsonObject versionObj = new JsonObject();
versionObj.addProperty("name", version.getName());
versionObj.addProperty("protocol", version.getVersion());
resp.add("version", versionObj);
JsonObject playersObj = new JsonObject();
playersObj.addProperty("max", serverInfo.max);
playersObj.addProperty("online", serverInfo.online);
if (serverInfo.players.length > 0) {
JsonArray sampleArr = new JsonArray();
for (String player : serverInfo.players) {
JsonObject playerObj = new JsonObject();
playerObj.addProperty("name", player);
playerObj.addProperty("id", UUID.nameUUIDFromBytes(("OfflinePlayer:" + player).getBytes(StandardCharsets.UTF_8)).toString());
sampleArr.add(playerObj);
}
playersObj.add("sample", sampleArr);
}
resp.add("players", playersObj);
JsonObject descriptionObj = new JsonObject();
descriptionObj.addProperty("text", serverInfo.motd);
resp.add("description", descriptionObj);
if (in.content().readableBytes() == 16384) {
BufferedImage image = new BufferedImage(64, 64, BufferedImage.TYPE_4BYTE_ABGR);
byte[] pixels = new byte[16384];
for (int i = 0; i < 4096; i++) {
pixels[i * 4] = in.content().getByte(i * 4 + 3);
pixels[i * 4 + 1] = in.content().getByte(i * 4 + 2);
pixels[i * 4 + 2] = in.content().getByte(i * 4 + 1);
pixels[i * 4 + 3] = in.content().getByte(i * 4);
}
image.setData(Raster.createRaster(image.getSampleModel(), new DataBufferByte(pixels, 16384), new Point()));
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", os);
resp.addProperty("favicon", "data:image/png;base64," + Base64.getEncoder().encodeToString(os.toByteArray()));
} catch (IOException ignored) {
}
}
ByteBuf bb = ctx.alloc().buffer();
PacketTypes.writeVarInt(bb, 0);
PacketTypes.writeString(bb, resp.toString());
out.add(bb);
handshakeState = -1;
return;
}
if (version.newerThanOrEqualTo(ProtocolVersion.v1_7_2)) {
if (handshakeState == 0) {
out.add(Unpooled.EMPTY_BUFFER);
} else if (handshakeState == 1) {
handshakeState = 2;
ConnectionHandshake.attemptHandshake2(ctx.channel(), ByteBufUtil.getBytes(in.content()), (ProxyConnection) proxyConnection, password);
out.add(Unpooled.EMPTY_BUFFER);
} else if (handshakeState == 2) {
handshakeState = 3;
ConnectionHandshake.attemptHandshake3(ctx.channel(), ByteBufUtil.getBytes(in.content()), (ProxyConnection) proxyConnection);
ByteBuf bb = ctx.alloc().buffer();
PacketTypes.writeVarInt(bb, MCPackets.S2C_LOGIN_GAME_PROFILE.getId(version.getVersion()));
PacketTypes.writeString(bb, ((ProxyConnection) proxyConnection).getGameProfile().getId().toString());
PacketTypes.writeString(bb, ((ProxyConnection) proxyConnection).getGameProfile().getName());
out.add(bb);
} else if (handshakeState == 3) {
handshakeState = 4;
ConnectionHandshake.attemptHandshake4(ctx.channel(), ByteBufUtil.getBytes(in.content()), (ProxyConnection) proxyConnection);
out.add(Unpooled.EMPTY_BUFFER);
} else {
if (in.content().getByte(0) == MCPackets.S2C_LOGIN_GAME_PROFILE.getId(version.getVersion()) && in.content().getByte(1) == 0 && in.content().getByte(2) == 2) {
out.add(Unpooled.EMPTY_BUFFER);
return;
}
if (in.content().getByte(0) == 0) {
in.content().skipBytes(1);
PacketTypes.readVarInt(in.content());
if (in.content().readableBytes() > 0) {
in.content().setByte(0, 0x40);
}
in.content().resetReaderIndex();
}
out.add(in.content().retain());
}
} else {
ByteBuf bb = ctx.alloc().buffer(clientBoundPartialPacket.readableBytes() + in.content().readableBytes());
bb.writeBytes(clientBoundPartialPacket);
clientBoundPartialPacket.release();
clientBoundPartialPacket = Unpooled.EMPTY_BUFFER;
bb.writeBytes(in.content()); // todo: do i need to reset this??????
int readerIndex = 0;
try {
while (bb.isReadable()) {
readerIndex = bb.readerIndex();
ClientboundPackets1_5_2 pkt = ClientboundPackets1_5_2.getPacket(bb.readUnsignedByte());
pkt.getPacketReader().accept(null, bb);
int len = bb.readerIndex() - readerIndex;
ByteBuf packet = ctx.alloc().buffer(len);
bb.readerIndex(readerIndex);
bb.readBytes(packet, len);
decodeOld(ctx, packet, out);
}
} catch (Exception e) {
bb.readerIndex(readerIndex);
if (bb.readableBytes() > 65535) {
ctx.close();
out.add(Unpooled.EMPTY_BUFFER);
return;
}
clientBoundPartialPacket = ctx.alloc().buffer(bb.readableBytes());
clientBoundPartialPacket.writeBytes(bb);
}
}
if (out.isEmpty()) {
out.add(Unpooled.EMPTY_BUFFER);
}
}
public void decodeOld(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
if (proxyConnection instanceof ProxyConnection) {
if (in.getUnsignedByte(0) == 0x14) {
try {
in.skipBytes(1);
int eid = in.readInt();
String name = Types1_6_4.STRING.read(in);
UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8));
eidUuidMap.put(eid, uuid);
uuidStringMap.put(uuid, name);
} catch (Exception ignored) {
}
in.resetReaderIndex();
}
if (in.getUnsignedByte(0) == 0x1D) {
try {
in.skipBytes(1);
short count = in.readUnsignedByte();
for (short i = 0; i < count; i++) {
int eid = in.readInt();
if (eidUuidMap.containsKey(eid)) {
uuidStringMap.remove(eidUuidMap.remove(eid));
}
}
} catch (Exception ignored) {
}
in.resetReaderIndex();
}
if (in.getUnsignedByte(0) == 0x09) {
eidUuidMap.clear();
uuidStringMap.clear();
}
}
if (in.getUnsignedByte(0) == 0xFD) {
in.writerIndex(0);
in.writeByte((byte) 0xCD);
in.writeByte((byte) 0x00);
ctx.writeAndFlush(new BinaryWebSocketFrame(in.retain()));
return;
}
if (in.readableBytes() >= 3 && in.getUnsignedByte(0) == 250) {
in.skipBytes(1);
String tag;
byte[] msg;
try {
tag = Types1_6_4.STRING.read(in);
if (proxyConnection instanceof ProxyConnection && tag.equals("EAG|UserSkin")) {
msg = new byte[in.readShort()];
in.readBytes(msg);
short id = (short) ((msg[0] << 8) + msg[1]);
if (!skinsBeingFetched.containsKey(id)) {
return;
}
byte[] res = new byte[Math.min(16384, msg.length - 3)];
System.arraycopy(msg, 3, res, 0, res.length);
if (res.length <= 16) {
int presetId = res[0] & 0xFF;
InputStream stream = Main.class.getResourceAsStream("/n" + presetId + ".png");
if (stream != null) {
try {
res = ((DataBufferByte) ImageIO.read(stream).getRaster().getDataBuffer()).getData();
for (int i = 0; i < res.length; i += 4) {
final byte tmp = res[i];
res[i] = res[i + 1];
res[i + 1] = res[i + 2];
res[i + 2] = res[i + 3];
res[i + 3] = tmp;
}
} catch (IOException ignored) {}
}
}
if (res.length >= 8192 && res.length < 16384) {
final int[] tmp1 = new int[2048];
final int[] tmp2 = new int[4096];
for (int i = 0; i < tmp1.length; ++i) {
tmp1[i] = Ints.fromBytes(res[i * 4 + 3], res[i * 4], res[i * 4 + 1], res[i * 4 + 2]);
}
SkinConverter.convert64x32to64x64(tmp1, tmp2);
res = new byte[16384];
for (int i = 0; i < tmp2.length; ++i) {
System.arraycopy(Ints.toByteArray(tmp2[i]), 0, res, i * 4, 4);
}
} else if (res.length == 16384) {
for (int j = 0; j < res.length; j += 4) {
final byte tmp3 = res[j + 3];
res[j + 3] = res[j + 2];
res[j + 2] = res[j + 1];
res[j + 1] = res[j];
res[j] = tmp3;
}
} else {
ByteBuf bb = ctx.alloc().buffer();
bb.writeByte((byte) 250);
Types1_6_4.STRING.write(bb, "EAG|Skins-1.8");
byte[] data = SkinPackets.makePresetResponse(skinsBeingFetched.remove(id));
bb.writeShort(data.length);
bb.writeBytes(data);
out.add(bb);
return;
}
UUID uuid = skinsBeingFetched.remove(id);
ByteBuf bb = ctx.alloc().buffer();
bb.writeByte((byte) 250);
Types1_6_4.STRING.write(bb, "EAG|Skins-1.8");
byte[] data = SkinPackets.makeCustomResponse(uuid, 0, res);
bb.writeShort(data.length);
bb.writeBytes(data);
out.add(bb);
return;
} else if (tag.equals("EAG|Reconnect")) {
msg = new byte[in.readShort()];
in.readBytes(msg);
in.resetReaderIndex();
in.resetWriterIndex();
in.writeByte((byte) 0xFF);
Types1_6_4.STRING.write(in, "Please use the IP: " + ChatColorUtil.COLOR_CHAR + "n" + new String(msg, StandardCharsets.UTF_8));
in.resetReaderIndex();
ctx.fireChannelRead(in.retain()).close();
if (!(proxyConnection instanceof ProxyConnection)) {
((LegacyProxyConnection) proxyConnection).getC2P().close();
}
return;
}
} catch (Exception ignored) {
}
in.resetReaderIndex();
}
if (in.getByte(0) == (byte) 0x83 && in.getShort(1) != 358) {
return;
}
out.add(in.retain());
}
}
@@ -0,0 +1,223 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import com.google.gson.JsonObject;
import com.viaversion.viaversion.util.GsonUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import net.raphimc.vialegacy.protocol.release.r1_6_4tor1_7_2_5.types.Types1_6_4;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.proxy.util.ExceptionUtil;
import javax.imageio.ImageIO;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class EaglerSkinHandler extends ChannelInboundHandlerAdapter {
public static final ConcurrentHashMap<UUID, byte[]> skinCollection;
private static final ConcurrentHashMap<UUID, byte[]> capeCollection;
private static final ConcurrentHashMap<UUID, Long> lastSkinLayerUpdate;
private static final int[] SKIN_DATA_SIZE;
private static final int[] CAPE_DATA_SIZE;
private static final ConcurrentHashMap<UUID, ChannelHandlerContext> users;
private final String user;
private static void sendData(final ChannelHandlerContext ctx, final String channel, final byte[] data) throws IOException {
final ByteBuf bb = ctx.alloc().buffer();
bb.writeByte(250);
try {
Types1_6_4.STRING.write(bb, channel);
} catch (Exception e) {
throw new IOException(e);
}
bb.writeShort(data.length);
bb.writeBytes(data);
ctx.writeAndFlush(new BinaryWebSocketFrame(bb));
}
public EaglerSkinHandler(final String username) {
this.user = username;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ExceptionUtil.handleNettyException(ctx, cause, null, true);
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object obj) throws Exception {
final UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + this.user).getBytes(StandardCharsets.UTF_8));
if (!EaglerSkinHandler.users.containsKey(uuid) && ctx.channel().isActive()) {
EaglerSkinHandler.users.put(uuid, ctx);
}
if (obj instanceof BinaryWebSocketFrame) {
final ByteBuf bb = ((BinaryWebSocketFrame) obj).content();
if (bb.readableBytes() >= 3 && bb.readByte() == -6) {
String tag;
byte[] msg;
try {
tag = Types1_6_4.STRING.read(bb);
msg = new byte[bb.readShort()];
bb.readBytes(msg);
} catch (Exception e) {
bb.resetReaderIndex();
super.channelRead(ctx, obj);
return;
}
try {
if ("EAG|MySkin".equals(tag)) {
if (!FunnyConfig.eaglerSkins) {
bb.release();
return;
}
if (!EaglerSkinHandler.skinCollection.containsKey(uuid)) {
final int t = msg[0] & 0xFF;
if (t < EaglerSkinHandler.SKIN_DATA_SIZE.length && msg.length == EaglerSkinHandler.SKIN_DATA_SIZE[t] + 1) {
EaglerSkinHandler.skinCollection.put(uuid, msg);
}
}
bb.release();
return;
}
if ("EAG|MyCape".equals(tag)) {
if (!FunnyConfig.eaglerSkins) {
bb.release();
return;
}
if (!EaglerSkinHandler.capeCollection.containsKey(uuid)) {
final int t = msg[0] & 0xFF;
if (t < EaglerSkinHandler.CAPE_DATA_SIZE.length && msg.length == EaglerSkinHandler.CAPE_DATA_SIZE[t] + 2) {
EaglerSkinHandler.capeCollection.put(uuid, msg);
}
}
bb.release();
return;
}
if ("EAG|FetchSkin".equals(tag)) {
if (msg.length > 2) {
final String fetch = new String(msg, 2, msg.length - 2, StandardCharsets.UTF_8);
final UUID uuidFetch = UUID.nameUUIDFromBytes(("OfflinePlayer:" + fetch).getBytes(StandardCharsets.UTF_8));
byte[] data;
if ((data = EaglerSkinHandler.skinCollection.get(uuidFetch)) != null) {
byte[] conc = new byte[data.length + 2];
conc[0] = msg[0];
conc[1] = msg[1];
System.arraycopy(data, 0, conc, 2, data.length);
if ((data = EaglerSkinHandler.capeCollection.get(uuidFetch)) != null) {
final 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;
}
sendData(ctx, "EAG|UserSkin", conc);
} else if (FunnyConfig.premiumSkins) {
try {
URL url = new URL("https://playerdb.co/api/player/minecraft/" + fetch);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("user-agent", "Mozilla/5.0 ViaProxy/" + ViaProxy.VERSION);
JsonObject json = GsonUtil.getGson().fromJson(new InputStreamReader(urlConnection.getInputStream()), JsonObject.class);
if (json.get("success").getAsBoolean()) {
String premiumUUID = json.getAsJsonObject("data").getAsJsonObject("player").getAsJsonObject("meta").get("id").getAsString();
byte[] tmp = EaglerXSkinHandler.skinService.fetchSkinPacket(uuidFetch, "https://crafatar.com/skins/" + premiumUUID);
if (tmp != null) {
EaglerXSkinHandler.skinService.registerEaglercraftPlayer(uuidFetch, tmp);
if ((data = EaglerSkinHandler.skinCollection.get(uuidFetch)) != null) {
byte[] conc = new byte[data.length + 2];
conc[0] = msg[0];
conc[1] = msg[1];
System.arraycopy(data, 0, conc, 2, data.length);
if ((data = EaglerSkinHandler.capeCollection.get(uuidFetch)) != null) {
final 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;
} else {
try {
tmp = ((DataBufferByte) ImageIO.read(new URL("https://crafatar.com/capes/" + premiumUUID)).getRaster().getDataBuffer()).getData();
data = new byte[4098];
data[0] = data[1] = 0;
// todo: figure out if we need to shuffle around colors
System.arraycopy(tmp, 0, data, 2, tmp.length);
EaglerSkinHandler.capeCollection.put(uuid, data);
final 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;
} catch (Exception ignored) {
}
}
sendData(ctx, "EAG|UserSkin", conc);
}
}
}
} catch (Exception ignored) {
}
}
}
bb.release();
return;
}
if ("EAG|SkinLayers".equals(tag)) {
final long millis = System.currentTimeMillis();
final Long lsu = EaglerSkinHandler.lastSkinLayerUpdate.get(uuid);
if (lsu != null && millis - lsu < 700L) {
return;
}
EaglerSkinHandler.lastSkinLayerUpdate.put(uuid, millis);
byte[] conc2;
if ((conc2 = EaglerSkinHandler.capeCollection.get(uuid)) != null) {
conc2[1] = msg[0];
} else {
conc2 = new byte[]{2, msg[0], 0};
EaglerSkinHandler.capeCollection.put(uuid, conc2);
}
final ByteArrayOutputStream bao = new ByteArrayOutputStream();
final DataOutputStream dd = new DataOutputStream(bao);
dd.write(msg[0]);
dd.writeUTF(this.user);
final byte[] bpacket = bao.toByteArray();
for (final UUID pl : EaglerSkinHandler.users.keySet()) {
if (!pl.equals(uuid)) {
sendData(EaglerSkinHandler.users.get(pl), "EAG|SkinLayers", bpacket);
}
}
bb.release();
return;
}
} catch (Throwable var18) {
var18.printStackTrace();
}
}
bb.resetReaderIndex();
}
super.channelRead(ctx, obj);
}
@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
final UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + this.user).getBytes(StandardCharsets.UTF_8));
EaglerSkinHandler.users.remove(uuid);
EaglerSkinHandler.skinCollection.remove(uuid);
EaglerSkinHandler.capeCollection.remove(uuid);
EaglerSkinHandler.lastSkinLayerUpdate.remove(uuid);
}
static {
skinCollection = new ConcurrentHashMap<>();
capeCollection = new ConcurrentHashMap<>();
lastSkinLayerUpdate = new ConcurrentHashMap<>();
SKIN_DATA_SIZE = new int[]{8192, 16384, -9, -9, 1, 16384, -9};
CAPE_DATA_SIZE = new int[]{4096, -9, 1};
users = new ConcurrentHashMap<>();
}
}
@@ -0,0 +1,150 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import net.raphimc.netminecraft.packet.PacketTypes;
import net.raphimc.vialegacy.protocol.release.r1_6_4tor1_7_2_5.types.Types1_6_4;
import net.raphimc.viaproxy.proxy.util.ExceptionUtil;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class EaglerVoiceHandler extends ChannelInboundHandlerAdapter {
public static final VoiceServerImpl voiceService = new VoiceServerImpl();
public String user;
public UUID uuid;
public final boolean old;
private int pluginMessageId = -1;
public EaglerVoiceHandler(final String username) {
this.user = username;
if (this.user == null) {
this.uuid = null;
old = false;
} else {
old = true;
this.uuid = nameToUUID(this.user);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ExceptionUtil.handleNettyException(ctx, cause, null, true);
}
private static UUID nameToUUID(String name) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8));
}
private boolean sent = false;
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object obj) throws Exception {
if (!FunnyConfig.eaglerVoice) {
super.channelRead(ctx, obj);
return;
}
if (((EaglercraftHandler) ctx.pipeline().get("eaglercraft-handler")).state == EaglercraftHandler.State.LOGIN_COMPLETE && !sent) {
if (this.user == null) {
this.user = ((EaglercraftHandler) ctx.pipeline().get("eaglercraft-handler")).username;
this.uuid = nameToUUID(this.user);
}
sent = true;
voiceService.handlePlayerLoggedIn(ctx);
}
if (obj instanceof BinaryWebSocketFrame) {
final ByteBuf bb = ((BinaryWebSocketFrame) obj).content();
if (old) {
if (bb.readableBytes() >= 3 && bb.readByte() == -6) {
String tag;
byte[] msg;
try {
tag = Types1_6_4.STRING.read(bb);
msg = new byte[bb.readShort()];
bb.readBytes(msg);
} catch (Exception e) {
bb.resetReaderIndex();
super.channelRead(ctx, obj);
return;
}
try {
if (!tag.equals("EAG|Voice")) {
bb.resetReaderIndex();
super.channelRead(ctx, obj);
return;
}
final DataInputStream streamIn = new DataInputStream(new ByteArrayInputStream(msg));
final int sig = streamIn.read();
switch (sig) {
case 0: {
voiceService.handleVoiceSignalPacketTypeRequest(nameToUUID(streamIn.readUTF()), ctx);
bb.release();
return;
}
case 1: {
voiceService.handleVoiceSignalPacketTypeConnect(ctx);
bb.release();
return;
}
case 2: {
try {
voiceService.handleVoiceSignalPacketTypeDisconnect(nameToUUID(streamIn.readUTF()), ctx);
} catch (EOFException e) {
voiceService.handleVoiceSignalPacketTypeDisconnect(null, ctx);
}
bb.release();
return;
}
case 3: {
voiceService.handleVoiceSignalPacketTypeICE(nameToUUID(streamIn.readUTF()), streamIn.readUTF(), ctx);
bb.release();
return;
}
case 4: {
voiceService.handleVoiceSignalPacketTypeDesc(nameToUUID(streamIn.readUTF()), streamIn.readUTF(), ctx);
bb.release();
return;
}
default: {
bb.release();
return;
}
}
} catch (Throwable var8) {
voiceService.handlePlayerLoggedOut(uuid);
bb.release();
return;
}
}
bb.resetReaderIndex();
} else {
if (this.pluginMessageId <= 0) {
this.pluginMessageId = ((EaglercraftHandler) ctx.pipeline().get("eaglercraft-handler")).pluginMessageId;
}
try {
if (PacketTypes.readVarInt(bb) == this.pluginMessageId && PacketTypes.readString(bb, 32767).equals("EAG|Voice-1.8")) {
final byte[] data = new byte[bb.readableBytes()];
bb.readBytes(data);
VoiceSignalPackets.processPacket(data, ctx);
bb.release();
return;
}
} catch (Exception ignored) {
}
bb.resetReaderIndex();
}
}
super.channelRead(ctx, obj);
}
@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
voiceService.handlePlayerLoggedOut(uuid);
}
}
@@ -0,0 +1,38 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import net.raphimc.netminecraft.packet.PacketTypes;
import net.raphimc.viaproxy.proxy.util.ExceptionUtil;
public class EaglerXLoginHandler extends ChannelOutboundHandlerAdapter {
private int counter;
public EaglerXLoginHandler() {
this.counter = 0;
}
@Override
@SuppressWarnings("deprecation")
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ExceptionUtil.handleNettyException(ctx, cause, null, true);
}
@Override
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception {
if (msg instanceof BinaryWebSocketFrame) {
final ByteBuf bb = ((BinaryWebSocketFrame) msg).content();
if (PacketTypes.readVarInt(bb) == 2 && ++this.counter == 2) {
ctx.pipeline().remove("ayun-eag-x-login");
bb.writerIndex(bb.readerIndex());
PacketTypes.writeString(bb, "");
bb.writeByte(2);
}
bb.resetReaderIndex();
}
super.write(ctx, msg, promise);
}
}
@@ -0,0 +1,106 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import net.raphimc.netminecraft.packet.PacketTypes;
import net.raphimc.viaproxy.proxy.util.ExceptionUtil;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class EaglerXSkinHandler extends ChannelInboundHandlerAdapter {
private final ConcurrentHashMap<String, byte[]> profileData;
public static SkinService skinService;
private String user;
private int pluginMessageId;
public EaglerXSkinHandler() {
this.profileData = new ConcurrentHashMap<>();
this.pluginMessageId = -1;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ExceptionUtil.handleNettyException(ctx, cause, null, true);
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object obj) throws Exception {
final EaglercraftHandler.State state = ((EaglercraftHandler) ctx.pipeline().get("eaglercraft-handler")).state;
if (state == EaglercraftHandler.State.LOGIN && obj instanceof BinaryWebSocketFrame) {
final ByteBuf bb = ((BinaryWebSocketFrame) obj).content();
if (bb.readUnsignedByte() == 7) {
if (this.profileData.size() > 12) {
ctx.close();
bb.release();
return;
}
int strlen = bb.readUnsignedByte();
final String dataType = bb.readCharSequence(strlen, StandardCharsets.US_ASCII).toString();
strlen = bb.readUnsignedShort();
final byte[] readData = new byte[strlen];
bb.readBytes(readData);
if (bb.isReadable()) {
ctx.close();
bb.release();
return;
}
if (this.profileData.containsKey(dataType)) {
ctx.close();
bb.release();
return;
}
this.profileData.put(dataType, readData);
}
bb.resetReaderIndex();
}
if (state != EaglercraftHandler.State.LOGIN_COMPLETE) {
super.channelRead(ctx, obj);
return;
}
if (this.user == null) {
this.user = ((EaglercraftHandler) ctx.pipeline().get("eaglercraft-handler")).username;
if (FunnyConfig.eaglerSkins) {
final UUID clientUUID = UUID.nameUUIDFromBytes(("OfflinePlayer:" + this.user).getBytes(StandardCharsets.UTF_8));
if (this.profileData.containsKey("skin_v1")) {
try {
SkinPackets.registerEaglerPlayer(clientUUID, this.profileData.get("skin_v1"), EaglerXSkinHandler.skinService);
} catch (Throwable ex) {
SkinPackets.registerEaglerPlayerFallback(clientUUID, EaglerXSkinHandler.skinService);
}
} else {
SkinPackets.registerEaglerPlayerFallback(clientUUID, EaglerXSkinHandler.skinService);
}
}
}
if (this.pluginMessageId <= 0) {
this.pluginMessageId = ((EaglercraftHandler) ctx.pipeline().get("eaglercraft-handler")).pluginMessageId;
}
if (obj instanceof BinaryWebSocketFrame) {
final ByteBuf bb = ((BinaryWebSocketFrame) obj).content();
try {
if (PacketTypes.readVarInt(bb) == this.pluginMessageId && PacketTypes.readString(bb, 32767).equals("EAG|Skins-1.8")) {
final byte[] data = new byte[bb.readableBytes()];
bb.readBytes(data);
SkinPackets.processPacket(data, ctx, EaglerXSkinHandler.skinService);
bb.release();
return;
}
} catch (Exception ignored) {
}
bb.resetReaderIndex();
}
super.channelRead(ctx, obj);
}
@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
if (this.user != null) {
EaglerXSkinHandler.skinService.unregisterPlayer(UUID.nameUUIDFromBytes(("OfflinePlayer:" + this.user).getBytes(StandardCharsets.UTF_8)));
}
}
}
@@ -0,0 +1,378 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import com.google.common.net.HostAndPort;
import com.viaversion.viaversion.api.protocol.version.ProtocolVersion;
import com.viaversion.viaversion.libs.gson.JsonArray;
import com.viaversion.viaversion.libs.gson.JsonObject;
import com.viaversion.viaversion.libs.gson.JsonParser;
import com.viaversion.viaversion.protocols.base.ClientboundStatusPackets;
import com.viaversion.viaversion.protocols.base.ServerboundHandshakePackets;
import com.viaversion.viaversion.protocols.base.ServerboundLoginPackets;
import com.viaversion.viaversion.protocols.base.ServerboundStatusPackets;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.AttributeKey;
import net.lenni0451.mcstructs.text.serializer.TextComponentSerializer;
import net.raphimc.netminecraft.constants.ConnectionState;
import net.raphimc.netminecraft.constants.MCPackets;
import net.raphimc.netminecraft.constants.MCPipeline;
import net.raphimc.netminecraft.packet.PacketTypes;
import net.raphimc.vialegacy.api.LegacyProtocolVersion;
import net.raphimc.vialegacy.protocol.release.r1_5_2tor1_6_1.packet.ServerboundPackets1_5_2;
import net.raphimc.vialegacy.protocol.release.r1_6_4tor1_7_2_5.types.Types1_6_4;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.proxy.client2proxy.Client2ProxyChannelInitializer;
import net.raphimc.viaproxy.proxy.util.ExceptionUtil;
import net.raphimc.viaproxy.util.logging.Logger;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
public class EaglercraftHandler extends MessageToMessageCodec<WebSocketFrame, ByteBuf> {
public static class ProfileData {
public final String type;
public final byte[] data;
public ProfileData(String type, byte[] data) {
this.type = type;
this.data = data;
}
}
public static final AttributeKey<ProfileData> profileDataKey = AttributeKey.newInstance("eagx-profile-data");
public static final AttributeKey<HttpHeaders> httpHeadersKey = AttributeKey.newInstance("eag-http-headers");
private HostAndPort host;
public State state;
public ProtocolVersion version;
public int pluginMessageId;
public String username;
public EaglercraftHandler() {
this.state = State.PRE_HANDSHAKE;
}
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
ctx.channel().attr(MCPipeline.COMPRESSION_THRESHOLD_ATTRIBUTE_KEY).set(-2);
if (ctx.pipeline().get(MCPipeline.SIZER_HANDLER_NAME) != null) {
ctx.pipeline().remove(MCPipeline.SIZER_HANDLER_NAME);
}
super.channelActive(ctx);
}
protected void encode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws IOException {
if (this.state == State.STATUS) {
final int packetId = PacketTypes.readVarInt(in);
if (packetId != ClientboundStatusPackets.STATUS_RESPONSE.getId()) {
throw new IllegalStateException("Unexpected packet id " + packetId);
}
final JsonObject root = JsonParser.parseString(PacketTypes.readString(in, 32767)).getAsJsonObject();
final JsonObject response = new JsonObject();
response.addProperty("name", "ViaProxy");
response.addProperty("brand", "ViaProxy");
if (root.has("version")) {
response.add("vers", root.getAsJsonObject("version").get("name"));
} else {
response.addProperty("vers", "Unknown");
}
response.addProperty("cracked", Boolean.TRUE);
response.addProperty("secure", Boolean.FALSE);
response.addProperty("time", System.currentTimeMillis());
response.addProperty("uuid", UUID.randomUUID().toString());
response.addProperty("type", "motd");
final JsonObject data = new JsonObject();
data.addProperty("cache", Boolean.FALSE);
final JsonArray motd = new JsonArray();
if (root.has("description")) {
final String[] split = TextComponentSerializer.V1_8.deserialize(root.get("description").toString()).asLegacyFormatString().split("\n");
for (final String motdLine : split) {
motd.add(motdLine);
}
}
data.add("motd", motd);
boolean hasIcon = root.has("favicon") || ctx.channel().hasAttr(EaglerServerHandler.eagIconKey);
data.addProperty("icon", hasIcon);
if (root.has("players")) {
final JsonObject javaPlayers = root.getAsJsonObject("players");
data.add("online", javaPlayers.get("online"));
data.add("max", javaPlayers.get("max"));
final JsonArray players = new JsonArray();
if (javaPlayers.has("sample")) {
javaPlayers.getAsJsonArray("sample").forEach(player -> players.add(TextComponentSerializer.V1_8.deserialize(player.getAsJsonObject().get("name").getAsString()).asLegacyFormatString()));
}
data.add("players", players);
}
response.add("data", data);
out.add(new TextWebSocketFrame(response.toString()));
if (root.has("favicon")) {
final BufferedImage icon = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(root.get("favicon").getAsString().substring(22).replace("\n", "").getBytes(StandardCharsets.UTF_8))));
final int[] pixels = icon.getRGB(0, 0, 64, 64, null, 0, 64);
final byte[] iconPixels = new byte[16384];
for (int i = 0; i < 4096; ++i) {
iconPixels[i * 4] = (byte) (pixels[i] >> 16 & 0xFF);
iconPixels[i * 4 + 1] = (byte) (pixels[i] >> 8 & 0xFF);
iconPixels[i * 4 + 2] = (byte) (pixels[i] & 0xFF);
iconPixels[i * 4 + 3] = (byte) (pixels[i] >> 24 & 0xFF);
}
out.add(new BinaryWebSocketFrame(ctx.alloc().buffer().writeBytes(iconPixels)));
} else if (hasIcon) {
out.add(new BinaryWebSocketFrame(ctx.channel().attr(EaglerServerHandler.eagIconKey).get()));
}
} else {
if (this.state != State.LOGIN_COMPLETE) {
throw new IllegalStateException("Cannot send packets before login is completed");
}
out.add(new BinaryWebSocketFrame(in.retain()));
}
}
protected void decode(final ChannelHandlerContext ctx, final WebSocketFrame in, final List<Object> out) throws Exception {
if (in instanceof BinaryWebSocketFrame) {
final ByteBuf data = in.content();
switch (this.state) {
case PRE_HANDSHAKE: {
if (data.readableBytes() >= 2 && data.getByte(0) == 2 && data.getByte(1) == 69) {
data.setByte(1, 61);
this.state = State.LOGIN_COMPLETE;
this.version = LegacyProtocolVersion.r1_5_2;
out.add(data.retain());
break;
}
this.state = State.HANDSHAKE;
}
case HANDSHAKE: {
final int packetId = data.readUnsignedByte();
if (packetId != 1) {
throw new IllegalStateException("Unexpected packet id " + packetId + " in state " + this.state);
}
int eaglercraftVersion = data.readUnsignedByte();
int minecraftVersion;
if (eaglercraftVersion == 1) {
minecraftVersion = data.readUnsignedByte();
} else {
if (eaglercraftVersion != 2) {
throw new IllegalArgumentException("Unknown Eaglercraft version: " + eaglercraftVersion);
}
int count = data.readUnsignedShort();
final List<Integer> eaglercraftVersions = new ArrayList<>(count);
for (int i = 0; i < count; ++i) {
eaglercraftVersions.add(data.readUnsignedShort());
}
if (!eaglercraftVersions.contains(2) && !eaglercraftVersions.contains(3)) {
Logger.LOGGER.error("No supported eaglercraft versions found");
ctx.close();
return;
}
if (eaglercraftVersions.contains(3)) {
eaglercraftVersion = 3;
}
count = data.readUnsignedShort();
final List<Integer> minecraftVersions = new ArrayList<>(count);
for (int j = 0; j < count; ++j) {
minecraftVersions.add(data.readUnsignedShort());
}
if (minecraftVersions.size() != 1) {
Logger.LOGGER.error("No supported minecraft versions found");
ctx.close();
}
minecraftVersion = minecraftVersions.get(0);
}
final String clientBrand = data.readCharSequence(data.readUnsignedByte(), StandardCharsets.US_ASCII).toString();
final String clientVersionString = data.readCharSequence(data.readUnsignedByte(), StandardCharsets.US_ASCII).toString();
if (eaglercraftVersion >= 2) {
data.skipBytes(1);
data.skipBytes(data.readUnsignedByte());
}
if (data.isReadable()) {
throw new IllegalArgumentException("Too much data in packet: " + data.readableBytes() + " bytes");
}
Logger.LOGGER.info("Eaglercraft client connected: " + clientBrand + " " + clientVersionString);
this.state = State.HANDSHAKE_COMPLETE;
this.version = ProtocolVersion.getProtocol(minecraftVersion);
if (this.version.equals(ProtocolVersion.unknown)) {
Logger.LOGGER.error("Unsupported protocol version: " + minecraftVersion);
ctx.close();
return;
}
final ByteBuf response = ctx.alloc().buffer();
response.writeByte(2);
if (eaglercraftVersion == 1) {
response.writeByte(1);
} else {
response.writeShort(eaglercraftVersion);
response.writeShort(minecraftVersion);
}
response.writeByte("ViaProxy".length()).writeCharSequence("ViaProxy", StandardCharsets.US_ASCII);
response.writeByte(ViaProxy.VERSION.length()).writeCharSequence(ViaProxy.VERSION, StandardCharsets.US_ASCII);
response.writeByte(0);
response.writeShort(0);
ctx.writeAndFlush(new BinaryWebSocketFrame(response));
break;
}
case HANDSHAKE_COMPLETE: {
final int packetId = data.readUnsignedByte();
if (packetId != 4) {
throw new IllegalStateException("Unexpected packet id " + packetId + " in state " + this.state);
}
final String username = data.readCharSequence(data.readUnsignedByte(), StandardCharsets.US_ASCII).toString();
data.readCharSequence(data.readUnsignedByte(), StandardCharsets.US_ASCII);
data.skipBytes(data.readUnsignedByte());
if (data.isReadable()) {
throw new IllegalArgumentException("Too much data in packet: " + data.readableBytes() + " bytes");
}
this.state = State.LOGIN;
this.username = username;
final UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + username).getBytes(StandardCharsets.UTF_8));
final ByteBuf response2 = ctx.alloc().buffer();
response2.writeByte(5);
response2.writeByte(username.length()).writeCharSequence(username, StandardCharsets.US_ASCII);
response2.writeLong(uuid.getMostSignificantBits()).writeLong(uuid.getLeastSignificantBits());
ctx.writeAndFlush(new BinaryWebSocketFrame(response2));
break;
}
case LOGIN: {
final int packetId = data.readUnsignedByte();
if (packetId == 7) {
String type = data.readCharSequence(data.readUnsignedByte(), StandardCharsets.US_ASCII).toString();
final byte[] dataBytes = new byte[data.readUnsignedShort()];
data.readBytes(dataBytes);
if (data.isReadable()) {
throw new IllegalArgumentException("Too much data in packet: " + data.readableBytes() + " bytes");
}
ctx.channel().attr(profileDataKey).set(new ProfileData(type, dataBytes));
} else {
if (packetId != 8) {
throw new IllegalStateException("Unexpected packet id " + packetId + " in state " + this.state);
}
if (data.isReadable()) {
throw new IllegalArgumentException("Too much data in packet: " + data.readableBytes() + " bytes");
}
this.state = State.LOGIN_COMPLETE;
this.pluginMessageId = MCPackets.C2S_CUSTOM_PAYLOAD.getId(this.version.getVersion());
if (this.pluginMessageId == -1) {
Logger.LOGGER.error("Unsupported protocol version: " + this.version.getVersion());
ctx.close();
return;
}
if (ctx.pipeline().get(Client2ProxyChannelInitializer.LEGACY_PASSTHROUGH_INITIAL_HANDLER_NAME) != null) {
ctx.pipeline().remove(Client2ProxyChannelInitializer.LEGACY_PASSTHROUGH_INITIAL_HANDLER_NAME);
}
out.add(this.writeHandshake(ctx.alloc().buffer(), ConnectionState.LOGIN));
final ByteBuf loginHello = ctx.alloc().buffer();
PacketTypes.writeVarInt(loginHello, ServerboundLoginPackets.HELLO.getId());
PacketTypes.writeString(loginHello, this.username);
out.add(loginHello);
final ByteBuf response3 = ctx.alloc().buffer();
response3.writeByte(9);
ctx.writeAndFlush(new BinaryWebSocketFrame(response3));
}
break;
}
case LOGIN_COMPLETE: {
if (this.version.equals(LegacyProtocolVersion.r1_5_2)) {
final int packetId = data.readUnsignedByte();
if (packetId == ServerboundPackets1_5_2.SHARED_KEY.getId()) {
ctx.channel().writeAndFlush(new BinaryWebSocketFrame(data.readerIndex(0).retain()));
break;
}
if (!ctx.channel().hasAttr(Main.secureWs) || ctx.channel().attr(Main.secureWs) == null) {
if (packetId == ServerboundPackets1_5_2.CUSTOM_PAYLOAD.getId() && Types1_6_4.STRING.read(data).startsWith("EAG|")) {
break;
}
}
} else if (this.version.newerThanOrEqualTo(ProtocolVersion.v1_7_2) && (!ctx.channel().hasAttr(Main.secureWs) || ctx.channel().attr(Main.secureWs) == null)) {
final int packetId = PacketTypes.readVarInt(data);
if (packetId == this.pluginMessageId && PacketTypes.readString(data, 32767).startsWith("EAG|")) {
break;
}
}
out.add(data.readerIndex(0).retain());
break;
}
default: {
throw new IllegalStateException("Unexpected binary frame in state " + this.state);
}
}
} else {
if (!(in instanceof TextWebSocketFrame)) {
throw new UnsupportedOperationException("Unsupported frame type: " + in.getClass().getName());
}
final String text = ((TextWebSocketFrame) in).text();
if (this.state != State.PRE_HANDSHAKE) {
throw new IllegalStateException("Unexpected text frame in state " + this.state);
}
if (!text.equalsIgnoreCase("accept: motd")) {
ctx.close();
return;
}
this.state = State.STATUS;
this.version = ProtocolVersion.v1_8;
if (ctx.pipeline().get(Client2ProxyChannelInitializer.LEGACY_PASSTHROUGH_INITIAL_HANDLER_NAME) != null) {
ctx.pipeline().remove(Client2ProxyChannelInitializer.LEGACY_PASSTHROUGH_INITIAL_HANDLER_NAME);
}
out.add(this.writeHandshake(ctx.alloc().buffer(), ConnectionState.STATUS));
final ByteBuf statusRequest = ctx.alloc().buffer();
PacketTypes.writeVarInt(statusRequest, ServerboundStatusPackets.STATUS_REQUEST.getId());
out.add(statusRequest);
}
}
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
final WebSocketServerProtocolHandler.HandshakeComplete handshake = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
if (!handshake.requestHeaders().contains("Host")) {
ctx.close();
return;
}
this.host = HostAndPort.fromString(handshake.requestHeaders().get("Host").replaceAll("__", ".")).withDefaultPort(80);
ctx.channel().attr(httpHeadersKey).set(handshake.requestHeaders());
}
super.userEventTriggered(ctx, evt);
}
private ByteBuf writeHandshake(final ByteBuf byteBuf, final ConnectionState state) {
PacketTypes.writeVarInt(byteBuf, ServerboundHandshakePackets.CLIENT_INTENTION.getId());
PacketTypes.writeVarInt(byteBuf, this.version.getVersion());
PacketTypes.writeString(byteBuf, this.host.getHost());
byteBuf.writeShort(this.host.getPort());
int i;
switch (state) {
case PLAY:
i = 0;
break;
case STATUS:
i = 1;
break;
case LOGIN:
i = 2;
break;
default:
i = -1;
}
PacketTypes.writeVarInt(byteBuf, i);
return byteBuf;
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ExceptionUtil.handleNettyException(ctx, cause, null, true);
}
public enum State {
STATUS,
PRE_HANDSHAKE,
HANDSHAKE,
HANDSHAKE_COMPLETE,
LOGIN,
LOGIN_COMPLETE
}
}
@@ -0,0 +1,135 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.plugins.events.Client2ProxyHandlerCreationEvent;
import net.raphimc.viaproxy.proxy.client2proxy.Client2ProxyChannelInitializer;
import net.raphimc.viaproxy.proxy.client2proxy.passthrough.LegacyPassthroughInitialHandler;
import net.raphimc.viaproxy.proxy.client2proxy.passthrough.PassthroughClient2ProxyChannelInitializer;
import net.raphimc.viaproxy.proxy.client2proxy.passthrough.PassthroughClient2ProxyHandler;
import net.raphimc.viaproxy.proxy.util.ExceptionUtil;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
public class EaglercraftInitialHandler extends ByteToMessageDecoder {
private static final Method initChannelMethod;
public static SslContext sslContext;
private static long lastTime = 0;
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
if (!ctx.channel().isOpen()) {
return;
}
if (!in.isReadable()) {
return;
}
if (in.readableBytes() >= 3 || in.getByte(0) != 71) {
renewCerts();
boolean ssl = sslContext != null && in.readableBytes() >= 3 && in.getByte(0) == 22;
if (ssl || (in.readableBytes() >= 3 && in.getCharSequence(0, 3, StandardCharsets.UTF_8).equals("GET")) || (in.readableBytes() >= 4 && in.getCharSequence(0, 4, StandardCharsets.UTF_8).equals("POST"))) {
if (ssl) {
ctx.pipeline().addBefore("eaglercraft-initial-handler", "ws-ssl-handler", sslContext.newHandler(ctx.alloc()));
}
ctx.pipeline().addBefore("eaglercraft-initial-handler", "ws-http-codec", new HttpServerCodec());
ctx.pipeline().addBefore("eaglercraft-initial-handler", "ws-http-aggregator", new HttpObjectAggregator(65535, true));
ctx.pipeline().addBefore("eaglercraft-initial-handler", "ws-compression", new WebSocketServerCompressionHandler());
ctx.pipeline().addBefore("eaglercraft-initial-handler", "ws-handler", new WebSocketServerProtocolHandler("/", null, true));
ctx.pipeline().addBefore("eaglercraft-initial-handler", "ws-active-notifier", new WebSocketActiveNotifier());
ctx.pipeline().addBefore("eaglercraft-initial-handler", "eaglercraft-handler", new EaglercraftHandler());
if (ctx.pipeline().get(Client2ProxyChannelInitializer.LEGACY_PASSTHROUGH_INITIAL_HANDLER_NAME) != null) {
ctx.pipeline().replace(Client2ProxyChannelInitializer.LEGACY_PASSTHROUGH_INITIAL_HANDLER_NAME, Client2ProxyChannelInitializer.LEGACY_PASSTHROUGH_INITIAL_HANDLER_NAME, new LegacyPassthroughInitialHandler() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
if (ctx.channel().isOpen()) {
if (msg.isReadable()) {
int lengthOrPacketId = msg.getUnsignedByte(0);
if (lengthOrPacketId == 0 || lengthOrPacketId == 1 || lengthOrPacketId == 2 || lengthOrPacketId == 254) {
boolean fard = false;
for (Map.Entry<String, ChannelHandler> entry : ctx.pipeline()) {
if (entry.getKey().equals(Client2ProxyChannelInitializer.LEGACY_PASSTHROUGH_INITIAL_HANDLER_NAME)) {
fard = true;
} else {
if (fard) {
ctx.pipeline().remove(entry.getValue());
}
}
}
Supplier<ChannelHandler> handlerSupplier = () -> ViaProxy.EVENT_MANAGER.call(new Client2ProxyHandlerCreationEvent(new PassthroughClient2ProxyHandler(), true)).getHandler();
PassthroughClient2ProxyChannelInitializer channelInitializer = new PassthroughClient2ProxyChannelInitializer(handlerSupplier);
try {
initChannelMethod.invoke(channelInitializer, ctx.channel());
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
ctx.fireChannelActive();
ctx.fireChannelRead(msg.retain());
ctx.pipeline().remove(this);
} else {
ctx.pipeline().remove(this);
ctx.pipeline().fireChannelRead(msg.retain());
}
}
}
}
});
}
ctx.fireUserEventTriggered(EaglercraftClientConnected.INSTANCE);
ctx.pipeline().fireChannelRead(in.readBytes(in.readableBytes()));
} else {
out.add(in.readBytes(in.readableBytes()));
}
ctx.pipeline().remove(this);
}
}
public static void renewCerts() {
final long currTime = System.currentTimeMillis();
if (currTime - lastTime <= 1000 * 60 * 60) return;
lastTime = currTime;
final File certFolder = new File("certs");
if (certFolder.exists()) {
try {
sslContext = SslContextBuilder.forServer(new File(certFolder, "fullchain.pem"), new File(certFolder, "privkey.pem")).build();
} catch (Throwable e) {
throw new RuntimeException("Failed to load SSL context", e);
}
}
}
static {
renewCerts();
try {
initChannelMethod = PassthroughClient2ProxyChannelInitializer.class.getDeclaredMethod("initChannel", Channel.class);
initChannelMethod.setAccessible(true);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public static final class EaglercraftClientConnected {
public static final EaglercraftClientConnected INSTANCE = new EaglercraftClientConnected();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ExceptionUtil.handleNettyException(ctx, cause, null, true);
}
}
@@ -0,0 +1,78 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class ExpiringSet<T> extends AbstractSet<T> {
private final Set<T> realSet;
private final long expiration;
private final Map<T, Long> timestamps;
public ExpiringSet(final long expiration) {
this.realSet = ConcurrentHashMap.newKeySet();
this.timestamps = new ConcurrentHashMap<>();
this.expiration = expiration;
}
public void checkForExpirations() {
final Iterator<T> iterator = this.timestamps.keySet().iterator();
final long now = System.currentTimeMillis();
while (iterator.hasNext()) {
final T element = iterator.next();
if (this.realSet.contains(element)) {
if (this.timestamps.get(element) + this.expiration >= now) {
continue;
}
}
iterator.remove();
this.realSet.remove(element);
}
}
@Override
public boolean add(final T o) {
this.checkForExpirations();
final boolean success = this.realSet.add(o);
if (success) {
this.timestamps.put(o, System.currentTimeMillis());
}
return success;
}
@Override
public boolean remove(final Object o) {
this.checkForExpirations();
final boolean success = this.realSet.remove(o);
if (success) {
this.timestamps.remove(o);
}
return success;
}
@Override
public void clear() {
this.timestamps.clear();
this.realSet.clear();
}
@Override
public Iterator<T> iterator() {
this.checkForExpirations();
return this.realSet.iterator();
}
@Override
public int size() {
this.checkForExpirations();
return this.realSet.size();
}
@Override
public boolean contains(final Object o) {
this.checkForExpirations();
return this.realSet.contains(o);
}
}
@@ -0,0 +1,51 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import com.viaversion.viaversion.util.Config;
import java.io.File;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
public class FunnyConfig extends Config {
public static boolean premiumSkins = false;
public static boolean eaglerSkins = true;
public static boolean eaglerVoice = true;
public static int eaglerServerMode = 0;
protected FunnyConfig(File configFile) {
super(configFile, Logger.getLogger("FunnyConfig"));
}
@Override
public URL getDefaultConfigURL() {
return Main.class.getResource("/vpeagutils.yml");
}
@Override
protected void handleConfig(Map<String, Object> map) {
Object item = map.get("premium-skins");
if (item instanceof Boolean) {
premiumSkins = (Boolean) item;
}
item = map.get("eagler-skins");
if (item instanceof Boolean) {
eaglerSkins = (Boolean) item;
}
item = map.get("eagler-voice");
if (item instanceof Boolean) {
eaglerVoice = (Boolean) item;
}
item = map.get("eagler-server-mode");
if (item instanceof Integer) {
eaglerServerMode = (Integer) item;
}
}
@Override
public List<String> getUnsupportedOptions() {
return Collections.emptyList();
}
}
@@ -0,0 +1,108 @@
package me.ayunami2000.ayunViaProxyEagUtils;
/**
* base implementation of MD4 family style digest as outlined in "Handbook of
* Applied Cryptography", pages 344 - 347.
*/
public abstract class GeneralDigest {
private byte[] xBuf;
private int xBufOff;
private long byteCount;
/**
* Standard constructor
*/
protected GeneralDigest() {
xBuf = new byte[4];
xBufOff = 0;
}
/**
* Copy constructor. We are using copy constructors in place of the
* Object.clone() interface as this interface is not supported by J2ME.
*/
protected GeneralDigest(GeneralDigest t) {
xBuf = new byte[t.xBuf.length];
System.arraycopy(t.xBuf, 0, xBuf, 0, t.xBuf.length);
xBufOff = t.xBufOff;
byteCount = t.byteCount;
}
public void update(byte in) {
xBuf[xBufOff++] = in;
if (xBufOff == xBuf.length) {
processWord(xBuf, 0);
xBufOff = 0;
}
byteCount++;
}
public void update(byte[] in, int inOff, int len) {
//
// fill the current word
//
while ((xBufOff != 0) && (len > 0)) {
update(in[inOff]);
inOff++;
len--;
}
//
// process whole words.
//
while (len > xBuf.length) {
processWord(in, inOff);
inOff += xBuf.length;
len -= xBuf.length;
byteCount += xBuf.length;
}
//
// load in the remainder.
//
while (len > 0) {
update(in[inOff]);
inOff++;
len--;
}
}
public void finish() {
long bitLength = (byteCount << 3);
//
// add the pad bytes.
//
update((byte) 128);
while (xBufOff != 0) {
update((byte) 0);
}
processLength(bitLength);
processBlock();
}
public void reset() {
byteCount = 0;
xBufOff = 0;
for (int i = 0; i < xBuf.length; i++) {
xBuf[i] = 0;
}
}
protected abstract void processWord(byte[] in, int inOff);
protected abstract void processLength(long bitLength);
protected abstract void processBlock();
}
@@ -0,0 +1,63 @@
package me.ayunami2000.ayunViaProxyEagUtils;
/**
* Copyright (c) 2022-2023 LAX1DUDE. All Rights Reserved.
*
* WITH THE EXCEPTION OF PATCH FILES, MINIFIED JAVASCRIPT, AND ALL FILES
* NORMALLY FOUND IN AN UNMODIFIED MINECRAFT RESOURCE PACK, YOU ARE NOT ALLOWED
* TO SHARE, DISTRIBUTE, OR REPURPOSE ANY FILE USED BY OR PRODUCED BY THE
* SOFTWARE IN THIS REPOSITORY WITHOUT PRIOR PERMISSION FROM THE PROJECT AUTHOR.
*
* NOT FOR COMMERCIAL OR MALICIOUS USE
*
* (please read the 'LICENSE' file this repo's root directory for more info)
*
*/
public class HandshakePacketTypes {
public static final String AUTHENTICATION_REQUIRED = "Authentication Required:";
public static final int PROTOCOL_CLIENT_VERSION = 0x01;
public static final int PROTOCOL_SERVER_VERSION = 0x02;
public static final int PROTOCOL_VERSION_MISMATCH = 0x03;
public static final int PROTOCOL_CLIENT_REQUEST_LOGIN = 0x04;
public static final int PROTOCOL_SERVER_ALLOW_LOGIN = 0x05;
public static final int PROTOCOL_SERVER_DENY_LOGIN = 0x06;
public static final int PROTOCOL_CLIENT_PROFILE_DATA = 0x07;
public static final int PROTOCOL_CLIENT_FINISH_LOGIN = 0x08;
public static final int PROTOCOL_SERVER_FINISH_LOGIN = 0x09;
public static final int PROTOCOL_SERVER_ERROR = 0xFF;
public static final int STATE_OPENED = 0x00;
public static final int STATE_CLIENT_VERSION = 0x01;
public static final int STATE_CLIENT_LOGIN = 0x02;
public static final int STATE_CLIENT_COMPLETE = 0x03;
public static final int SERVER_ERROR_UNKNOWN_PACKET = 0x01;
public static final int SERVER_ERROR_INVALID_PACKET = 0x02;
public static final int SERVER_ERROR_WRONG_PACKET = 0x03;
public static final int SERVER_ERROR_EXCESSIVE_PROFILE_DATA = 0x04;
public static final int SERVER_ERROR_DUPLICATE_PROFILE_DATA = 0x05;
public static final int SERVER_ERROR_RATELIMIT_BLOCKED = 0x06;
public static final int SERVER_ERROR_RATELIMIT_LOCKED = 0x07;
public static final int SERVER_ERROR_CUSTOM_MESSAGE = 0x08;
public static final int SERVER_ERROR_AUTHENTICATION_REQUIRED = 0x09;
public static final int AUTH_METHOD_NONE = 0x0;
public static final int AUTH_METHOD_EAGLER_SHA256 = 0x01;
public static final int AUTH_METHOD_AUTHME_SHA256 = 0x02;
public static final int AUTH_METHOD_PLAINTEXT = 0xFF;
public static final byte[] EAGLER_SHA256_SALT_BASE = new byte[] { (byte) 117, (byte) 43, (byte) 1, (byte) 112,
(byte) 75, (byte) 3, (byte) 188, (byte) 61, (byte) 121, (byte) 31, (byte) 34, (byte) 181, (byte) 234,
(byte) 31, (byte) 247, (byte) 72, (byte) 12, (byte) 168, (byte) 138, (byte) 45, (byte) 143, (byte) 77,
(byte) 118, (byte) 245, (byte) 187, (byte) 242, (byte) 188, (byte) 219, (byte) 160, (byte) 235, (byte) 235,
(byte) 68 };
public static final byte[] EAGLER_SHA256_SALT_SAVE = new byte[] { (byte) 49, (byte) 25, (byte) 39, (byte) 38,
(byte) 253, (byte) 85, (byte) 70, (byte) 245, (byte) 71, (byte) 150, (byte) 253, (byte) 206, (byte) 4,
(byte) 26, (byte) 198, (byte) 249, (byte) 145, (byte) 251, (byte) 232, (byte) 174, (byte) 186, (byte) 98,
(byte) 27, (byte) 232, (byte) 55, (byte) 144, (byte) 83, (byte) 21, (byte) 36, (byte) 55, (byte) 170,
(byte) 118 };
}
@@ -0,0 +1,272 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import com.viaversion.viaversion.api.protocol.version.ProtocolVersion;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.codec.http.websocketx.extensions.WebSocketClientExtensionHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.DeflateFrameClientExtensionHandshaker;
import io.netty.handler.codec.http.websocketx.extensions.compression.PerMessageDeflateClientExtensionHandshaker;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.AsciiString;
import io.netty.util.AttributeKey;
import net.lenni0451.lambdaevents.EventHandler;
import net.raphimc.netminecraft.constants.MCPipeline;
import net.raphimc.netminecraft.netty.codec.PacketCodec;
import net.raphimc.netminecraft.netty.connection.NetClient;
import net.raphimc.netminecraft.packet.IPacket;
import net.raphimc.vialegacy.protocol.release.r1_6_4tor1_7_2_5.types.Types1_6_4;
import net.raphimc.viaproxy.ViaProxy;
import net.raphimc.viaproxy.plugins.ViaProxyPlugin;
import net.raphimc.viaproxy.plugins.events.Client2ProxyChannelInitializeEvent;
import net.raphimc.viaproxy.plugins.events.Proxy2ServerChannelInitializeEvent;
import net.raphimc.viaproxy.plugins.events.types.ITyped;
import net.raphimc.viaproxy.proxy.session.LegacyProxyConnection;
import net.raphimc.viaproxy.proxy.session.ProxyConnection;
import net.raphimc.viaproxy.proxy.util.ChannelUtil;
import net.raphimc.viaproxy.proxy.util.ExceptionUtil;
import javax.net.ssl.*;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
public class Main extends ViaProxyPlugin {
public static final AttributeKey<Boolean> secureWs = AttributeKey.newInstance("eag-secure-ws");
public static final AttributeKey<String> wsPath = AttributeKey.newInstance("eag-ws-path");
public static final AttributeKey<String> eagxPass = AttributeKey.newInstance("eag-x-pass");
private static final SSLContext sc;
static {
try {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
// Ignore differences between given hostname and certificate hostname
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
} catch (KeyManagementException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public void onEnable() {
ViaProxy.EVENT_MANAGER.register(this);
(new FunnyConfig(new File("ViaLoader", "vpeagutils.yml"))).reload();
EaglerXSkinHandler.skinService = new SkinService();
}
@EventHandler
public void onEvent(final Proxy2ServerChannelInitializeEvent event) throws URISyntaxException {
if (event.getType() == ITyped.Type.POST) {
Channel ch = event.getChannel();
NetClient proxyConnection;
Channel c2p;
SocketAddress addr;
if (event.isLegacyPassthrough()) {
proxyConnection = LegacyProxyConnection.fromChannel(ch);
c2p = ((LegacyProxyConnection) proxyConnection).getC2P();
addr = ((LegacyProxyConnection) proxyConnection).getServerAddress();
} else {
proxyConnection = ProxyConnection.fromChannel(ch);
c2p = ((ProxyConnection) proxyConnection).getC2P();
addr = ((ProxyConnection) proxyConnection).getServerAddress();
}
if (FunnyConfig.eaglerServerMode == 1) {
c2p.attr(secureWs).set(false);
} else if (FunnyConfig.eaglerServerMode == 2) {
c2p.attr(secureWs).set(true);
}
if (c2p.hasAttr(secureWs) && c2p.attr(secureWs).get() != null && addr instanceof InetSocketAddress) {
doWsServerStuff(ch, proxyConnection, c2p, (InetSocketAddress) addr);
if (!event.isLegacyPassthrough()) {
ch.pipeline().addFirst("handshake-waiter", new ChannelOutboundHandlerAdapter() {
private boolean hasHandshake = false;
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof ByteBuf) {
hasHandshake = true;
ChannelUtil.restoreAutoRead(c2p);
}
super.write(ctx, msg, promise);
}
@Override
public void flush(ChannelHandlerContext ctx) throws Exception {
super.flush(ctx);
if (hasHandshake) {
ch.pipeline().remove(this);
ChannelUtil.disableAutoRead(c2p);
}
}
});
}
}
}
}
static {
try {
Field field = HttpHeaderValues.class.getDeclaredField("UPGRADE");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, AsciiString.cached("Upgrade")); // some servers need it to be uppercase :/
} catch (NoSuchFieldException | IllegalAccessException ignored) {
}
}
private static void doWsServerStuff(Channel ch, NetClient proxyConnection, Channel c2p, InetSocketAddress addr) throws URISyntaxException {
ch.attr(MCPipeline.COMPRESSION_THRESHOLD_ATTRIBUTE_KEY).set(-2);
if (proxyConnection instanceof ProxyConnection && ((ProxyConnection) proxyConnection).getServerVersion().newerThanOrEqualTo(ProtocolVersion.v1_7_2)) {
ch.pipeline().remove(MCPipeline.SIZER_HANDLER_NAME);
} else if (ch.pipeline().get(MCPipeline.ENCRYPTION_HANDLER_NAME) != null) {
ch.pipeline().remove(MCPipeline.ENCRYPTION_HANDLER_NAME);
}
if (c2p.pipeline().get("ayun-eag-voice") != null) {
c2p.pipeline().remove("ayun-eag-voice");
}
if (c2p.pipeline().get("ayun-eag-skin") != null) {
c2p.pipeline().remove("ayun-eag-skin");
}
if (c2p.pipeline().get("ayun-eag-x-login") != null) {
c2p.pipeline().remove("ayun-eag-x-login");
}
if (c2p.pipeline().get("ayun-eag-skin-x") != null) {
c2p.pipeline().remove("ayun-eag-skin-x");
}
StringBuilder url = new StringBuilder("ws");
boolean secure = c2p.attr(secureWs).get();
if (secure) {
final SSLEngine sslEngine = sc.createSSLEngine(addr.getHostString(), addr.getPort());
sslEngine.setUseClientMode(true);
sslEngine.setNeedClientAuth(false);
ch.pipeline().addFirst("eag-server-ssl", new SslHandler(sslEngine) {
@Override
public void channelInactive(ChannelHandlerContext ctx) {
if (this.handshakeFuture().cause() != null) {
ExceptionUtil.handleNettyException(ctx, this.handshakeFuture().cause(), null, true);
}
super.closeOutbound();
}
});
url.append("s");
ch.pipeline().addAfter("eag-server-ssl", "eag-server-http-codec", new HttpClientCodec());
} else {
ch.pipeline().addFirst("eag-server-http-codec", new HttpClientCodec());
}
url.append("://").append(addr.getHostString());
if ((secure && addr.getPort() != 443) || (!secure && addr.getPort() != 80)) {
url.append(":").append(addr.getPort());
}
url.append("/");
String path = c2p.attr(wsPath).get();
if (path != null) {
url.append(path);
}
URI uri = new URI(url.toString());
HttpHeaders headers = c2p.hasAttr(EaglercraftHandler.httpHeadersKey) ? c2p.attr(EaglercraftHandler.httpHeadersKey).get() : new DefaultHttpHeaders().clear().set(HttpHeaderNames.ORIGIN, "https://via.shhnowisnottheti.me");
ch.pipeline().addAfter("eag-server-http-codec", "eag-server-http-aggregator", new HttpObjectAggregator(2097152, true));
ch.pipeline().addAfter("eag-server-http-aggregator", "eag-server-ws-compression", new WebSocketClientExtensionHandler(new PerMessageDeflateClientExtensionHandshaker(1, ZlibCodecFactory.isSupportingWindowSizeAndMemLevel(), 15, false, false), new DeflateFrameClientExtensionHandshaker(1, false), new DeflateFrameClientExtensionHandshaker(1, true)));
ch.pipeline().addAfter("eag-server-ws-compression", "eag-server-ws-handshaker", new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, headers, 2097152)));
ch.pipeline().addAfter("eag-server-ws-handshaker", "eag-server-ws-ready", new WebSocketConnectedNotifier());
ch.pipeline().addAfter("eag-server-ws-ready", "eag-server-handler", new EaglerServerHandler(proxyConnection, c2p.attr(eagxPass).get()));
ch.pipeline().replace(MCPipeline.PACKET_CODEC_HANDLER_NAME, MCPipeline.PACKET_CODEC_HANDLER_NAME, new PacketCodec() {
protected void encode(ChannelHandlerContext ctx, IPacket in, ByteBuf out) {
try {
super.encode(ctx, in, out);
} catch (IllegalStateException e) {
//
}
}
});
}
@EventHandler
public void onEvent(final Client2ProxyChannelInitializeEvent event) {
if (event.isLegacyPassthrough()) return;
if (event.getType() == ITyped.Type.PRE) {
event.getChannel().pipeline().addLast("eaglercraft-initial-handler", new EaglercraftInitialHandler());
}
if (event.getType() == ITyped.Type.POST) {
event.getChannel().pipeline().addAfter("eaglercraft-initial-handler", "ayun-eag-detector", new EaglerConnectionHandler());
}
}
static class EaglerConnectionHandler extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
if (evt instanceof EaglercraftInitialHandler.EaglercraftClientConnected) {
ctx.pipeline().remove("ayun-eag-detector");
ctx.pipeline().addBefore("eaglercraft-handler", "ayun-eag-utils-init", new EaglerUtilsInitHandler());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ExceptionUtil.handleNettyException(ctx, cause, null, true);
}
}
static class EaglerUtilsInitHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
if (msg instanceof BinaryWebSocketFrame) {
final ByteBuf bb = ((BinaryWebSocketFrame) msg).content();
try {
if (bb.readByte() == 2 && bb.readByte() == 69) {
final String username = Types1_6_4.STRING.read(bb);
ctx.pipeline().addBefore("eaglercraft-handler", "ayun-eag-voice", new EaglerVoiceHandler(username));
ctx.pipeline().addBefore("eaglercraft-handler", "ayun-eag-skin", new EaglerSkinHandler(username));
} else {
ctx.pipeline().addBefore("eaglercraft-handler", "ayun-eag-x-login", new EaglerXLoginHandler());
ctx.pipeline().addBefore("eaglercraft-handler", "ayun-eag-skin-x", new EaglerXSkinHandler());
ctx.pipeline().addBefore("eaglercraft-handler", "ayun-eag-voice", new EaglerVoiceHandler(null));
}
} catch (Exception ignored) {
}
bb.resetReaderIndex();
}
ctx.pipeline().remove("ayun-eag-utils-init");
super.channelRead(ctx, msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ExceptionUtil.handleNettyException(ctx, cause, null, true);
}
}
}
@@ -0,0 +1,12 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import io.netty.channel.ChannelPromise;
public class MsgPromise {
public Object msg;
public ChannelPromise promise;
public MsgPromise(Object msg, ChannelPromise promise) {
this.msg = msg;
this.promise = promise;
}
}
@@ -0,0 +1,233 @@
package me.ayunami2000.ayunViaProxyEagUtils;
public class SHA256Digest extends GeneralDigest {
private static final int DIGEST_LENGTH = 32;
private int H1, H2, H3, H4, H5, H6, H7, H8;
private int[] X = new int[64];
private int xOff;
public SHA256Digest() {
reset();
}
public static int bigEndianToInt(byte[] bs, int off) {
int n = bs[off] << 24;
n |= (bs[++off] & 0xff) << 16;
n |= (bs[++off] & 0xff) << 8;
n |= (bs[++off] & 0xff);
return n;
}
public static void bigEndianToInt(byte[] bs, int off, int[] ns) {
for (int i = 0; i < ns.length; ++i) {
ns[i] = bigEndianToInt(bs, off);
off += 4;
}
}
public static byte[] intToBigEndian(int n) {
byte[] bs = new byte[4];
intToBigEndian(n, bs, 0);
return bs;
}
public static void intToBigEndian(int n, byte[] bs, int off) {
bs[off] = (byte) (n >>> 24);
bs[++off] = (byte) (n >>> 16);
bs[++off] = (byte) (n >>> 8);
bs[++off] = (byte) (n);
}
protected void processWord(byte[] in, int inOff) {
X[xOff] = bigEndianToInt(in, inOff);
if (++xOff == 16) {
processBlock();
}
}
protected void processLength(long bitLength) {
if (xOff > 14) {
processBlock();
}
X[14] = (int) (bitLength >>> 32);
X[15] = (int) (bitLength & 0xffffffff);
}
public int doFinal(byte[] out, int outOff) {
finish();
intToBigEndian(H1, out, outOff);
intToBigEndian(H2, out, outOff + 4);
intToBigEndian(H3, out, outOff + 8);
intToBigEndian(H4, out, outOff + 12);
intToBigEndian(H5, out, outOff + 16);
intToBigEndian(H6, out, outOff + 20);
intToBigEndian(H7, out, outOff + 24);
intToBigEndian(H8, out, outOff + 28);
reset();
return DIGEST_LENGTH;
}
/**
* reset the chaining variables
*/
public void reset() {
super.reset();
/*
* SHA-256 initial hash value The first 32 bits of the fractional parts of the
* square roots of the first eight prime numbers
*/
H1 = 0x6a09e667;
H2 = 0xbb67ae85;
H3 = 0x3c6ef372;
H4 = 0xa54ff53a;
H5 = 0x510e527f;
H6 = 0x9b05688c;
H7 = 0x1f83d9ab;
H8 = 0x5be0cd19;
xOff = 0;
for (int i = 0; i != X.length; i++) {
X[i] = 0;
}
}
protected void processBlock() {
//
// expand 16 word block into 64 word blocks.
//
for (int t = 16; t <= 63; t++) {
X[t] = Theta1(X[t - 2]) + X[t - 7] + Theta0(X[t - 15]) + X[t - 16];
}
//
// set up working variables.
//
int a = H1;
int b = H2;
int c = H3;
int d = H4;
int e = H5;
int f = H6;
int g = H7;
int h = H8;
int t = 0;
for (int i = 0; i < 8; i++) {
// t = 8 * i
h += Sum1(e) + Ch(e, f, g) + K[t] + X[t];
d += h;
h += Sum0(a) + Maj(a, b, c);
++t;
// t = 8 * i + 1
g += Sum1(d) + Ch(d, e, f) + K[t] + X[t];
c += g;
g += Sum0(h) + Maj(h, a, b);
++t;
// t = 8 * i + 2
f += Sum1(c) + Ch(c, d, e) + K[t] + X[t];
b += f;
f += Sum0(g) + Maj(g, h, a);
++t;
// t = 8 * i + 3
e += Sum1(b) + Ch(b, c, d) + K[t] + X[t];
a += e;
e += Sum0(f) + Maj(f, g, h);
++t;
// t = 8 * i + 4
d += Sum1(a) + Ch(a, b, c) + K[t] + X[t];
h += d;
d += Sum0(e) + Maj(e, f, g);
++t;
// t = 8 * i + 5
c += Sum1(h) + Ch(h, a, b) + K[t] + X[t];
g += c;
c += Sum0(d) + Maj(d, e, f);
++t;
// t = 8 * i + 6
b += Sum1(g) + Ch(g, h, a) + K[t] + X[t];
f += b;
b += Sum0(c) + Maj(c, d, e);
++t;
// t = 8 * i + 7
a += Sum1(f) + Ch(f, g, h) + K[t] + X[t];
e += a;
a += Sum0(b) + Maj(b, c, d);
++t;
}
H1 += a;
H2 += b;
H3 += c;
H4 += d;
H5 += e;
H6 += f;
H7 += g;
H8 += h;
//
// reset the offset and clean out the word buffer.
//
xOff = 0;
for (int i = 0; i < 16; i++) {
X[i] = 0;
}
}
/* SHA-256 functions */
private static int Ch(int x, int y, int z) {
return (x & y) ^ ((~x) & z);
// return z ^ (x & (y ^ z));
}
private static int Maj(int x, int y, int z) {
// return (x & y) ^ (x & z) ^ (y & z);
return (x & y) | (z & (x ^ y));
}
private static int Sum0(int x) {
return ((x >>> 2) | (x << 30)) ^ ((x >>> 13) | (x << 19)) ^ ((x >>> 22) | (x << 10));
}
private static int Sum1(int x) {
return ((x >>> 6) | (x << 26)) ^ ((x >>> 11) | (x << 21)) ^ ((x >>> 25) | (x << 7));
}
private static int Theta0(int x) {
return ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
}
private static int Theta1(int x) {
return ((x >>> 17) | (x << 15)) ^ ((x >>> 19) | (x << 13)) ^ (x >>> 10);
}
/*
* SHA-256 Constants (represent the first 32 bits of the fractional parts of the
* cube roots of the first sixty-four prime numbers)
*/
static final int K[] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138,
0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70,
0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa,
0xa4506ceb, 0xbef9a3f7, 0xc67178f2 };
}
@@ -0,0 +1,42 @@
package me.ayunami2000.ayunViaProxyEagUtils;
public class SkinConverter {
public static void convert64x32to64x64(final int[] skinIn, final int[] skinOut) {
copyRawPixels(skinIn, skinOut, 0, 0, 0, 0, 64, 32, false);
copyRawPixels(skinIn, skinOut, 24, 48, 20, 4, 16, 8, 20);
copyRawPixels(skinIn, skinOut, 28, 48, 24, 8, 16, 12, 20);
copyRawPixels(skinIn, skinOut, 20, 52, 16, 8, 20, 12, 32);
copyRawPixels(skinIn, skinOut, 24, 52, 20, 4, 20, 8, 32);
copyRawPixels(skinIn, skinOut, 28, 52, 24, 0, 20, 4, 32);
copyRawPixels(skinIn, skinOut, 32, 52, 28, 12, 20, 16, 32);
copyRawPixels(skinIn, skinOut, 40, 48, 36, 44, 16, 48, 20);
copyRawPixels(skinIn, skinOut, 44, 48, 40, 48, 16, 52, 20);
copyRawPixels(skinIn, skinOut, 36, 52, 32, 48, 20, 52, 32);
copyRawPixels(skinIn, skinOut, 40, 52, 36, 44, 20, 48, 32);
copyRawPixels(skinIn, skinOut, 44, 52, 40, 40, 20, 44, 32);
copyRawPixels(skinIn, skinOut, 48, 52, 44, 52, 20, 56, 32);
}
private static void copyRawPixels(final int[] imageIn, final int[] imageOut, final int dx1, final int dy1, final int dx2, final int sx1, final int sy1, final int sx2, final int sy2) {
if (dx1 > dx2) {
copyRawPixels(imageIn, imageOut, sx1, sy1, dx2, dy1, sx2 - sx1, sy2 - sy1, true);
} else {
copyRawPixels(imageIn, imageOut, sx1, sy1, dx1, dy1, sx2 - sx1, sy2 - sy1, false);
}
}
private static void copyRawPixels(final int[] imageIn, final int[] imageOut, final int srcX, final int srcY, final int dstX, final int dstY, final int width, final int height, final boolean flip) {
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
final int i = imageIn[(srcY + y) * 64 + srcX + x];
int j;
if (flip) {
j = (dstY + y) * 64 + dstX + width - x - 1;
} else {
j = (dstY + y) * 64 + dstX + x;
}
imageOut[j] = i;
}
}
}
}
@@ -0,0 +1,197 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import io.netty.channel.ChannelHandlerContext;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
public class SkinPackets {
public static void processPacket(final byte[] data, final ChannelHandlerContext sender, final SkinService skinService) throws IOException {
if (data.length == 0) {
throw new IOException("Zero-length packet recieved");
}
final int packetId = data[0] & 0xFF;
try {
switch (packetId) {
case 3: {
processGetOtherSkin(data, sender, skinService);
break;
}
case 6: {
if (FunnyConfig.premiumSkins) {
processGetOtherSkinByURL(data, sender, skinService);
}
break;
}
default: {
throw new IOException("Unknown packet type " + packetId);
}
}
} catch (IOException ex) {
throw ex;
} catch (Throwable t) {
throw new IOException("Unhandled exception handling packet type " + packetId, t);
}
}
private static void processGetOtherSkin(final byte[] data, final ChannelHandlerContext sender, final SkinService skinService) throws IOException {
if (data.length != 17) {
throw new IOException("Invalid length " + data.length + " for skin request packet");
}
final UUID searchUUID = bytesToUUID(data, 1);
skinService.processGetOtherSkin(searchUUID, sender);
}
private static void processGetOtherSkinByURL(byte[] data, ChannelHandlerContext sender, SkinService skinService) throws IOException {
if(data.length < 20) {
throw new IOException("Invalid length " + data.length + " for skin request packet");
}
UUID searchUUID = bytesToUUID(data, 1);
int urlLength = (data[17] << 8) | data[18];
if(data.length < 19 + urlLength) {
throw new IOException("Invalid length " + data.length + " for skin request packet with " + urlLength + " length URL");
}
String urlStr = bytesToAscii(data, 19, urlLength);
urlStr = SkinService.sanitizeTextureURL(urlStr);
if(urlStr == null) {
throw new IOException("Invalid URL for skin request packet");
}
URL url;
try {
url = new URL(urlStr);
}catch(MalformedURLException t) {
throw new IOException("Invalid URL for skin request packet", t);
}
String host = url.getHost();
if(host.equalsIgnoreCase("textures.minecraft.net")) {
UUID validUUID = createEaglerURLSkinUUID(urlStr);
if(!searchUUID.equals(validUUID)) {
throw new IOException("Invalid generated UUID from skin URL");
}
skinService.processGetOtherSkin(searchUUID, urlStr, sender);
}else {
throw new IOException("Invalid host in skin packet: " + host);
}
}
public static void registerEaglerPlayer(final UUID clientUUID, final byte[] bs, final SkinService skinService) throws IOException {
if (bs.length == 0) {
throw new IOException("Zero-length packet recieved");
}
final int packetType = bs[0] & 0xFF;
byte[] generatedPacket;
switch (packetType) {
case 1: {
if (bs.length != 5) {
throw new IOException("Invalid length " + bs.length + " for preset skin packet");
}
generatedPacket = makePresetResponse(clientUUID, bs[1] << 24 | bs[2] << 16 | bs[3] << 8 | (bs[4] & 0xFF));
break;
}
case 2: {
final byte[] pixels = new byte[16384];
if (bs.length != 2 + pixels.length) {
throw new IOException("Invalid length " + bs.length + " for custom skin packet");
}
setAlphaForChest(pixels, (byte) (-1));
System.arraycopy(bs, 2, pixels, 0, pixels.length);
generatedPacket = makeCustomResponse(clientUUID, bs[1] & 0xFF, pixels);
break;
}
default: {
throw new IOException("Unknown skin packet type: " + packetType);
}
}
skinService.registerEaglercraftPlayer(clientUUID, generatedPacket);
}
public static byte[] asciiString(String string) {
byte[] str = new byte[string.length()];
for(int i = 0; i < str.length; ++i) {
str[i] = (byte)string.charAt(i);
}
return str;
}
public static UUID createEaglerURLSkinUUID(String skinUrl) {
return UUID.nameUUIDFromBytes(asciiString("EaglercraftSkinURL:" + skinUrl));
}
public static void registerEaglerPlayerFallback(final UUID clientUUID, final SkinService skinService) throws IOException {
final int skinModel = ((clientUUID.hashCode() & 0x1) != 0x0) ? 1 : 0;
final byte[] generatedPacket = makePresetResponse(clientUUID, skinModel);
skinService.registerEaglercraftPlayer(clientUUID, generatedPacket);
}
public static void setAlphaForChest(final byte[] skin64x64, final byte alpha) {
if (skin64x64.length != 16384) {
throw new IllegalArgumentException("Skin is not 64x64!");
}
for (int y = 20; y < 32; ++y) {
for (int x = 16; x < 40; ++x) {
skin64x64[y << 8 | x << 2] = alpha;
}
}
}
public static byte[] makePresetResponse(final UUID uuid) {
return makePresetResponse(uuid, ((uuid.hashCode() & 0x1) != 0x0) ? 1 : 0);
}
public static byte[] makePresetResponse(final UUID uuid, final int presetId) {
final byte[] ret = new byte[21];
ret[0] = 4;
UUIDToBytes(uuid, ret, 1);
ret[17] = (byte) (presetId >> 24);
ret[18] = (byte) (presetId >> 16);
ret[19] = (byte) (presetId >> 8);
ret[20] = (byte) (presetId & 0xFF);
return ret;
}
public static byte[] makeCustomResponse(final UUID uuid, final int model, final byte[] pixels) {
final byte[] ret = new byte[18 + pixels.length];
ret[0] = 5;
UUIDToBytes(uuid, ret, 1);
ret[17] = (byte) model;
System.arraycopy(pixels, 0, ret, 18, pixels.length);
return ret;
}
public static String bytesToAscii(byte[] bytes, int off, int len) {
char[] ret = new char[len];
for(int i = 0; i < len; ++i) {
ret[i] = (char)((int)bytes[off + i] & 0xFF);
}
return new String(ret);
}
public static UUID bytesToUUID(final byte[] bytes, final int off) {
final long msb = ((long) bytes[off] & 0xFFL) << 56 | ((long) bytes[off + 1] & 0xFFL) << 48 | ((long) bytes[off + 2] & 0xFFL) << 40 | ((long) bytes[off + 3] & 0xFFL) << 32 | ((long) bytes[off + 4] & 0xFFL) << 24 | ((long) bytes[off + 5] & 0xFFL) << 16 | ((long) bytes[off + 6] & 0xFFL) << 8 | ((long) bytes[off + 7] & 0xFFL);
final long lsb = ((long) bytes[off + 8] & 0xFFL) << 56 | ((long) bytes[off + 9] & 0xFFL) << 48 | ((long) bytes[off + 10] & 0xFFL) << 40 | ((long) bytes[off + 11] & 0xFFL) << 32 | ((long) bytes[off + 12] & 0xFFL) << 24 | ((long) bytes[off + 13] & 0xFFL) << 16 | ((long) bytes[off + 14] & 0xFFL) << 8 | ((long) bytes[off + 15] & 0xFFL);
return new UUID(msb, lsb);
}
public static void UUIDToBytes(final UUID uuid, final byte[] bytes, final int off) {
final long msb = uuid.getMostSignificantBits();
final long lsb = uuid.getLeastSignificantBits();
bytes[off] = (byte) (msb >> 56);
bytes[off + 1] = (byte) (msb >> 48);
bytes[off + 2] = (byte) (msb >> 40);
bytes[off + 3] = (byte) (msb >> 32);
bytes[off + 4] = (byte) (msb >> 24);
bytes[off + 5] = (byte) (msb >> 16);
bytes[off + 6] = (byte) (msb >> 8);
bytes[off + 7] = (byte) (msb & 0xFFL);
bytes[off + 8] = (byte) (lsb >> 56);
bytes[off + 9] = (byte) (lsb >> 48);
bytes[off + 10] = (byte) (lsb >> 40);
bytes[off + 11] = (byte) (lsb >> 32);
bytes[off + 12] = (byte) (lsb >> 24);
bytes[off + 13] = (byte) (lsb >> 16);
bytes[off + 14] = (byte) (lsb >> 8);
bytes[off + 15] = (byte) (lsb & 0xFFL);
}
}
@@ -0,0 +1,249 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import com.google.common.primitives.Ints;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import net.raphimc.netminecraft.constants.MCPackets;
import net.raphimc.netminecraft.packet.PacketTypes;
import javax.imageio.ImageIO;
import java.awt.image.DataBufferByte;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class SkinService {
private final ConcurrentHashMap<UUID, CachedSkin> skinCache;
public SkinService() {
this.skinCache = new ConcurrentHashMap<>();
}
private static void sendData(final ChannelHandlerContext ctx, final byte[] data) {
final ByteBuf bb = ctx.alloc().buffer();
PacketTypes.writeVarInt(bb, MCPackets.S2C_CUSTOM_PAYLOAD.getId((((EaglercraftHandler) ctx.pipeline().get("eaglercraft-handler")).version).getVersion()));
PacketTypes.writeString(bb, "EAG|Skins-1.8");
bb.writeBytes(data);
ctx.writeAndFlush(new BinaryWebSocketFrame(bb));
}
public void processGetOtherSkin(final UUID searchUUID, final ChannelHandlerContext sender) {
final CachedSkin cached = this.skinCache.get(searchUUID);
if (cached != null) {
sendData(sender, cached.packet);
} else if (EaglerSkinHandler.skinCollection.containsKey(searchUUID)) {
final byte[] src = EaglerSkinHandler.skinCollection.get(searchUUID);
byte[] res = new byte[src.length - 1];
System.arraycopy(src, 1, res, 0, res.length);
if (res.length <= 16) {
int presetId = res[0] & 0xFF;
InputStream stream = Main.class.getResourceAsStream("/n" + presetId + ".png");
if (stream != null) {
try {
res = ((DataBufferByte) ImageIO.read(stream).getRaster().getDataBuffer()).getData();
for (int i = 0; i < res.length; i += 4) {
final byte tmp = res[i];
res[i] = res[i + 1];
res[i + 1] = res[i + 2];
res[i + 2] = res[i + 3];
res[i + 3] = tmp;
}
} catch (IOException ignored) {}
}
}
if (res.length == 8192) {
final int[] tmp1 = new int[2048];
final int[] tmp2 = new int[4096];
for (int i = 0; i < tmp1.length; ++i) {
tmp1[i] = Ints.fromBytes(res[i * 4 + 3], res[i * 4], res[i * 4 + 1], res[i * 4 + 2]);
}
SkinConverter.convert64x32to64x64(tmp1, tmp2);
res = new byte[16384];
for (int i = 0; i < tmp2.length; ++i) {
System.arraycopy(Ints.toByteArray(tmp2[i]), 0, res, i * 4, 4);
}
} else if (res.length == 16384) {
for (int j = 0; j < res.length; j += 4) {
final byte tmp3 = res[j + 3];
res[j + 3] = res[j + 2];
res[j + 2] = res[j + 1];
res[j + 1] = res[j];
res[j] = tmp3;
}
} else {
sendData(sender, SkinPackets.makePresetResponse(searchUUID));
return;
}
sendData(sender, SkinPackets.makeCustomResponse(searchUUID, 0, res));
} else {
processGetOtherSkin(searchUUID, "https://crafatar.com/skins/" + searchUUID.toString(), sender);
}
}
public byte[] fetchSkinPacket(final UUID searchUUID, final String skinURL) {
// no rate-limit or size limit. it is assumed that this feature is used privately anyway.
final CachedSkin cached = this.skinCache.get(searchUUID);
if (cached != null) {
return cached.packet;
} else {
try {
byte[] res = ((DataBufferByte) ImageIO.read(new URL(skinURL)).getRaster().getDataBuffer()).getData();
if (res.length == 8192) {
final int[] tmp1 = new int[2048];
final int[] tmp2 = new int[4096];
for (int i = 0; i < tmp1.length; ++i) {
tmp1[i] = Ints.fromBytes(res[i * 4 + 3], res[i * 4], res[i * 4 + 1], res[i * 4 + 2]);
}
SkinConverter.convert64x32to64x64(tmp1, tmp2);
res = new byte[16384];
for (int i = 0; i < tmp2.length; ++i) {
System.arraycopy(Ints.toByteArray(tmp2[i]), 0, res, i * 4, 4);
}
for (int j = 0; j < res.length; j += 4) {
final byte tmp3 = res[j];
res[j] = res[j + 1];
res[j + 1] = res[j + 2];
res[j + 2] = res[j + 3];
res[j + 3] = tmp3;
}
}
byte[] pkt = SkinPackets.makeCustomResponse(searchUUID, 0, res);
registerEaglercraftPlayer(searchUUID, pkt);
return pkt;
} catch (IOException ignored) {
return null;
}
}
}
public void processGetOtherSkin(final UUID searchUUID, final String skinURL, final ChannelHandlerContext sender) {
final byte[] skin = fetchSkinPacket(searchUUID, skinURL);
if (skin != null) {
sendData(sender, skin);
} else {
sendData(sender, SkinPackets.makePresetResponse(searchUUID));
}
}
public void registerEaglercraftPlayer(final UUID clientUUID, final byte[] generatedPacket) throws IOException {
this.skinCache.put(clientUUID, new CachedSkin(clientUUID, generatedPacket));
EaglerSkinHandler.skinCollection.put(clientUUID, newToOldSkin(generatedPacket));
}
public static byte[] newToOldSkin(final byte[] packet) throws IOException {
final byte type = packet[0];
byte[] res;
switch (type) {
case 1:
case 4: {
res = new byte[16385];
res[0] = 1;
final int o = type == 1 ? 16 : 0;
final int presetId = packet[17 - o] << 24 | packet[18 - o] << 16 | packet[19 - o] << 8 | packet[20 - o];
final InputStream stream = Main.class.getResourceAsStream("/" + presetId + ".png");
if (stream == null) {
throw new IOException("Invalid skin preset: " + presetId);
}
System.arraycopy(((DataBufferByte) ImageIO.read(stream).getRaster().getDataBuffer()).getData(), 0, res, 1, 16384);
for (int i = 1; i < 16385; i += 4) {
final byte tmp = res[i];
res[i] = res[i + 1];
res[i + 1] = res[i + 2];
res[i + 2] = res[i + 3];
res[i + 3] = tmp;
}
break;
}
case 2:
case 5: {
res = new byte[16385];
res[0] = 1;
final int o = type == 2 ? 16 : 0;
System.arraycopy(packet, 18 - o, res, 1, 16384);
for (int i = 1; i < 16385; i += 4) {
final byte tmp = res[i];
res[i] = res[i + 1];
res[i + 1] = res[i + 2];
res[i + 2] = res[i + 3];
res[i + 3] = tmp;
}
break;
}
default: {
throw new IOException("Invalid skin packet type: " + type);
}
}
return res;
}
public void unregisterPlayer(final UUID clientUUID) {
this.skinCache.remove(clientUUID);
EaglerSkinHandler.skinCollection.remove(clientUUID);
}
private static class CachedSkin {
protected final UUID uuid;
protected final byte[] packet;
protected CachedSkin(final UUID uuid, final byte[] packet) {
this.uuid = uuid;
this.packet = packet;
}
}
public static String sanitizeTextureURL(String url) {
try {
URI uri = URI.create(url);
StringBuilder builder = new StringBuilder();
String scheme = uri.getScheme();
if(scheme == null) {
return null;
}
String host = uri.getHost();
if(host == null) {
return null;
}
scheme = scheme.toLowerCase();
builder.append(scheme).append("://");
builder.append(host);
int port = uri.getPort();
if(port != -1) {
switch(scheme) {
case "http":
if(port == 80) {
port = -1;
}
break;
case "https":
if(port == 443) {
port = -1;
}
break;
default:
return null;
}
if(port != -1) {
builder.append(":").append(port);
}
}
String path = uri.getRawPath();
if(path != null) {
if(path.contains("//")) {
path = String.join("/", path.split("[\\/]+"));
}
int len = path.length();
if(len > 1 && path.charAt(len - 1) == '/') {
path = path.substring(0, len - 1);
}
builder.append(path);
}
return builder.toString();
}catch(Throwable t) {
return null;
}
}
}
@@ -0,0 +1,400 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import net.raphimc.netminecraft.constants.MCPackets;
import net.raphimc.netminecraft.packet.PacketTypes;
import net.raphimc.vialegacy.protocol.release.r1_6_4tor1_7_2_5.types.Types1_6_4;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved.
*
* 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.
*
*/
public class VoiceServerImpl {
public static final Map<UUID, String> uuidToUsernameMap = new HashMap<>();
private static void fuckFuckFuck(ByteBuf out, String str) {
int strlen = str.length();
int utflen = 0;
int c, count = 0;
/* use charAt instead of copying String to char array */
for (int i = 0; i < strlen; i++) {
c = str.charAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
utflen++;
} else if (c > 0x07FF) {
utflen += 3;
} else {
utflen += 2;
}
}
if (utflen > 65535)
throw new RuntimeException(
"encoded string too long: " + utflen + " bytes");
byte[] bytearr = new byte[utflen+2];
bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF);
bytearr[count++] = (byte) ((utflen >>> 0) & 0xFF);
int i=0;
for (i=0; i<strlen; i++) {
c = str.charAt(i);
if (!((c >= 0x0001) && (c <= 0x007F))) break;
bytearr[count++] = (byte) c;
}
for (;i < strlen; i++){
c = str.charAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
bytearr[count++] = (byte) c;
} else if (c > 0x07FF) {
bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
bytearr[count++] = (byte) (0x80 | ((c >> 6) & 0x3F));
bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
} else {
bytearr[count++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
}
}
out.writeBytes(bytearr, 0, utflen+2);
}
private int pluginMessageId = -1;
private void sendData(final ChannelHandlerContext ctx, final byte[] data) {
final ByteBuf bb = ctx.alloc().buffer();
if (((EaglerVoiceHandler) ctx.pipeline().get("ayun-eag-voice")).old) {
bb.writeByte(250);
try {
Types1_6_4.STRING.write(bb, "EAG|Voice");
} catch (Exception e) {
e.printStackTrace();
return;
}
bb.writeShort(data.length);
bb.writeBytes(data);
bb.readerIndex(23);
switch (bb.readByte()) {
case 0:
if (bb.readableBytes() == 1) break;
bb.skipBytes(1);
int vi = PacketTypes.readVarInt(bb);
String[] fard = new String[vi];
for (int i = 0; i < vi; i++) {
int xd = PacketTypes.readVarInt(bb);
byte[] arr = new byte[xd];
bb.readBytes(arr);
fard[i] = new String(arr, StandardCharsets.UTF_8);
}
bb.readerIndex(0);
bb.writerIndex(25);
bb.writeByte(vi);
for (String s : fard) {
fuckFuckFuck(bb, s);
}
break;
case 1:
UUID uuid = PacketTypes.readUuid(bb);
boolean o = bb.readBoolean();
bb.readerIndex(0);
bb.writerIndex(24);
fuckFuckFuck(bb, uuidToUsernameMap.get(uuid));
bb.writeBoolean(o);
break;
case 2:
if (bb.readableBytes() == 0) break;
uuid = PacketTypes.readUuid(bb);
bb.readerIndex(0);
bb.writerIndex(24);
fuckFuckFuck(bb, uuidToUsernameMap.get(uuid));
break;
case 3:
case 4:
uuid = PacketTypes.readUuid(bb);
vi = PacketTypes.readVarInt(bb);
byte[] arr = new byte[vi];
bb.readBytes(arr);
bb.readerIndex(0);
bb.writerIndex(24);
fuckFuckFuck(bb, uuidToUsernameMap.get(uuid));
fuckFuckFuck(bb, new String(arr, StandardCharsets.UTF_8));
break;
case 5:
vi = PacketTypes.readVarInt(bb);
bb.skipBytes(vi * 16);
fard = new String[vi];
for (int i = 0; i < vi; i++) {
int xd = PacketTypes.readVarInt(bb);
arr = new byte[xd];
bb.readBytes(arr);
fard[i] = new String(arr, StandardCharsets.UTF_8);
}
bb.readerIndex(0);
bb.writerIndex(24);
bb.writeInt(vi);
for (String s : fard) {
fuckFuckFuck(bb, s);
}
break;
}
bb.readerIndex(0);
bb.setShort(21, bb.writerIndex() - 23);
} else {
if (pluginMessageId <= 0) {
pluginMessageId = MCPackets.S2C_CUSTOM_PAYLOAD.getId((((EaglercraftHandler) ctx.pipeline().get("eaglercraft-handler")).version).getVersion());
}
PacketTypes.writeVarInt(bb, pluginMessageId);
PacketTypes.writeString(bb, "EAG|Voice-1.8");
bb.writeBytes(data);
}
ctx.writeAndFlush(new BinaryWebSocketFrame(bb));
}
private final byte[] iceServersPacket;
private final Map<UUID, ChannelHandlerContext> voicePlayers = new HashMap<>();
private final Map<UUID, ExpiringSet<UUID>> voiceRequests = new HashMap<>();
private final Set<VoicePair> voicePairs = new HashSet<>();
private static class VoicePair {
private final UUID uuid1;
private final UUID uuid2;
@Override
public int hashCode() {
return uuid1.hashCode() ^ uuid2.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VoicePair other = (VoicePair) obj;
return (uuid1.equals(other.uuid1) && uuid2.equals(other.uuid2))
|| (uuid1.equals(other.uuid2) && uuid2.equals(other.uuid1));
}
private VoicePair(UUID uuid1, UUID uuid2) {
this.uuid1 = uuid1;
this.uuid2 = uuid2;
}
private boolean anyEquals(UUID uuid) {
return uuid1.equals(uuid) || uuid2.equals(uuid);
}
}
VoiceServerImpl() {
if (FunnyConfig.eaglerVoice) {
Set<String> list = new HashSet<>();
list.add("stun:stun.l.google.com:19302");
list.add("stun:stun1.l.google.com:19302");
list.add("stun:stun2.l.google.com:19302");
list.add("stun:stun3.l.google.com:19302");
list.add("stun:stun4.l.google.com:19302");
list.add("turn:relay1.expressturn.com:3478;ef2KWF55ZPQWCLBMIG;MGn8T66L0GhgDodf");
this.iceServersPacket = VoiceSignalPackets.makeVoiceSignalPacketAllowed(true, list.toArray(new String[0]));
} else {
this.iceServersPacket = VoiceSignalPackets.makeVoiceSignalPacketAllowed(false, null);
}
}
public void handlePlayerLoggedIn(ChannelHandlerContext player) {
EaglerVoiceHandler evh = (EaglerVoiceHandler) player.pipeline().get("ayun-eag-voice");
uuidToUsernameMap.put(evh.uuid, evh.user);
sendData(player, iceServersPacket);
}
public void handlePlayerLoggedOut(UUID playerUUID) {
removeUser(playerUUID);
uuidToUsernameMap.remove(playerUUID);
}
void handleVoiceSignalPacketTypeRequest(UUID player, ChannelHandlerContext sender) {
UUID senderUUID = ((EaglerVoiceHandler) sender.pipeline().get("ayun-eag-voice")).uuid;
synchronized (voicePlayers) {
if (senderUUID.equals(player))
return; // prevent duplicates
if (!voicePlayers.containsKey(senderUUID))
return;
ChannelHandlerContext targetPlayerCon = voicePlayers.get(player);
if (targetPlayerCon == null)
return;
VoicePair newPair = new VoicePair(player, senderUUID);
if (voicePairs.contains(newPair))
return; // already paired
ExpiringSet<UUID> senderRequestSet = voiceRequests.get(senderUUID);
if (senderRequestSet == null) {
voiceRequests.put(senderUUID, senderRequestSet = new ExpiringSet<>(2000));
}
if (!senderRequestSet.add(player)) {
return;
}
// check if other has requested earlier
ExpiringSet<UUID> theSet;
if ((theSet = voiceRequests.get(player)) != null && theSet.contains(senderUUID)) {
theSet.remove(senderUUID);
if (theSet.isEmpty())
voiceRequests.remove(player);
senderRequestSet.remove(player);
if (senderRequestSet.isEmpty())
voiceRequests.remove(senderUUID);
// send each other add data
voicePairs.add(newPair);
sendData(targetPlayerCon,
VoiceSignalPackets.makeVoiceSignalPacketConnect(senderUUID, false));
sendData(sender, VoiceSignalPackets.makeVoiceSignalPacketConnect(player, true));
}
}
}
void handleVoiceSignalPacketTypeConnect(ChannelHandlerContext sender) {
UUID senderUUID = ((EaglerVoiceHandler) sender.pipeline().get("ayun-eag-voice")).uuid;
synchronized (voicePlayers) {
if (voicePlayers.containsKey(senderUUID)) {
return;
}
boolean hasNoOtherPlayers = voicePlayers.isEmpty();
voicePlayers.put(senderUUID, sender);
if (hasNoOtherPlayers) {
return;
}
byte[] packetToBroadcast = VoiceSignalPackets.makeVoiceSignalPacketGlobal(voicePlayers.values());
for (ChannelHandlerContext userCon : voicePlayers.values()) {
sendData(userCon, packetToBroadcast);
}
}
}
void handleVoiceSignalPacketTypeICE(UUID player, String str, ChannelHandlerContext sender) {
UUID senderUUID = ((EaglerVoiceHandler) sender.pipeline().get("ayun-eag-voice")).uuid;
ChannelHandlerContext pass;
VoicePair pair = new VoicePair(player, senderUUID);
synchronized (voicePlayers) {
pass = voicePairs.contains(pair) ? voicePlayers.get(player) : null;
}
if (pass != null) {
sendData(pass, VoiceSignalPackets.makeVoiceSignalPacketICE(senderUUID, str));
}
}
void handleVoiceSignalPacketTypeDesc(UUID player, String str, ChannelHandlerContext sender) {
UUID senderUUID = ((EaglerVoiceHandler) sender.pipeline().get("ayun-eag-voice")).uuid;
ChannelHandlerContext pass;
VoicePair pair = new VoicePair(player, senderUUID);
synchronized (voicePlayers) {
pass = voicePairs.contains(pair) ? voicePlayers.get(player) : null;
}
if (pass != null) {
sendData(pass,
VoiceSignalPackets.makeVoiceSignalPacketDesc(senderUUID, str));
}
}
void handleVoiceSignalPacketTypeDisconnect(UUID player, ChannelHandlerContext sender) {
UUID senderUUID = ((EaglerVoiceHandler) sender.pipeline().get("ayun-eag-voice")).uuid;
if (player != null) {
synchronized (voicePlayers) {
if (!voicePlayers.containsKey(player)) {
return;
}
byte[] userDisconnectPacket = null;
Iterator<VoicePair> pairsItr = voicePairs.iterator();
while (pairsItr.hasNext()) {
VoicePair voicePair = pairsItr.next();
UUID target = null;
if (voicePair.uuid1.equals(player)) {
target = voicePair.uuid2;
} else if (voicePair.uuid2.equals(player)) {
target = voicePair.uuid1;
}
if (target != null) {
pairsItr.remove();
ChannelHandlerContext conn = voicePlayers.get(target);
if (conn != null) {
if (userDisconnectPacket == null) {
userDisconnectPacket = VoiceSignalPackets.makeVoiceSignalPacketDisconnect(player);
}
sendData(conn, userDisconnectPacket);
}
sendData(sender,
VoiceSignalPackets.makeVoiceSignalPacketDisconnect(target));
}
}
}
} else {
removeUser(senderUUID);
}
}
public void removeUser(UUID user) {
synchronized (voicePlayers) {
if (voicePlayers.remove(user) == null) {
return;
}
voiceRequests.remove(user);
if (voicePlayers.size() > 0) {
byte[] voicePlayersPkt = VoiceSignalPackets.makeVoiceSignalPacketGlobal(voicePlayers.values());
for (Map.Entry<UUID, ChannelHandlerContext> userCon : voicePlayers.entrySet()) {
if (!user.equals(userCon.getKey())) {
sendData(userCon.getValue(), voicePlayersPkt);
}
}
}
byte[] userDisconnectPacket = null;
Iterator<VoicePair> pairsItr = voicePairs.iterator();
while (pairsItr.hasNext()) {
VoicePair voicePair = pairsItr.next();
UUID target = null;
if (voicePair.uuid1.equals(user)) {
target = voicePair.uuid2;
} else if (voicePair.uuid2.equals(user)) {
target = voicePair.uuid1;
}
if (target != null) {
pairsItr.remove();
if (voicePlayers.size() > 0) {
ChannelHandlerContext conn = voicePlayers.get(target);
if (conn != null) {
if (userDisconnectPacket == null) {
userDisconnectPacket = VoiceSignalPackets.makeVoiceSignalPacketDisconnect(user);
}
sendData(conn, userDisconnectPacket);
}
}
}
}
}
}
}
@@ -0,0 +1,186 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.UUID;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import net.raphimc.netminecraft.packet.PacketTypes;
/**
* Copyright (c) 2024 lax1dude. All Rights Reserved.
*
* 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.
*
*/
public class VoiceSignalPackets {
static final int VOICE_SIGNAL_ALLOWED = 0;
static final int VOICE_SIGNAL_REQUEST = 0;
static final int VOICE_SIGNAL_CONNECT = 1;
static final int VOICE_SIGNAL_DISCONNECT = 2;
static final int VOICE_SIGNAL_ICE = 3;
static final int VOICE_SIGNAL_DESC = 4;
static final int VOICE_SIGNAL_GLOBAL = 5;
public static void processPacket(byte[] data, ChannelHandlerContext sender) throws IOException {
int packetId = -1;
if(data.length == 0) {
throw new IOException("Zero-length packet recieved");
}
try {
ByteBuf buffer = Unpooled.wrappedBuffer(data).writerIndex(data.length);
packetId = buffer.readUnsignedByte();
switch(packetId) {
case VOICE_SIGNAL_REQUEST: {
EaglerVoiceHandler.voiceService.handleVoiceSignalPacketTypeRequest(PacketTypes.readUuid(buffer), sender);
break;
}
case VOICE_SIGNAL_CONNECT: {
EaglerVoiceHandler.voiceService.handleVoiceSignalPacketTypeConnect(sender);
break;
}
case VOICE_SIGNAL_ICE: {
EaglerVoiceHandler.voiceService.handleVoiceSignalPacketTypeICE(PacketTypes.readUuid(buffer), PacketTypes.readString(buffer, 32767), sender);
break;
}
case VOICE_SIGNAL_DESC: {
EaglerVoiceHandler.voiceService.handleVoiceSignalPacketTypeDesc(PacketTypes.readUuid(buffer), PacketTypes.readString(buffer, 32767), sender);
break;
}
case VOICE_SIGNAL_DISCONNECT: {
EaglerVoiceHandler.voiceService.handleVoiceSignalPacketTypeDisconnect(buffer.readableBytes() > 0 ? PacketTypes.readUuid(buffer) : null, sender);
break;
}
default: {
throw new IOException("Unknown packet type " + packetId);
}
}
if(buffer.readableBytes() > 0) {
throw new IOException("Voice packet is too long!");
}
}catch(IOException ex) {
throw ex;
}catch(Throwable t) {
throw new IOException("Unhandled exception handling voice packet type " + packetId, t);
}
}
static byte[] makeVoiceSignalPacketAllowed(boolean allowed, String[] iceServers) {
if (iceServers == null) {
byte[] ret = new byte[2];
ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(ret).writerIndex(0);
wrappedBuffer.writeByte(VOICE_SIGNAL_ALLOWED);
wrappedBuffer.writeBoolean(allowed);
return ret;
}
byte[][] iceServersBytes = new byte[iceServers.length][];
int totalLen = 2 + getVarIntSize(iceServers.length);
for(int i = 0; i < iceServers.length; ++i) {
byte[] b = iceServersBytes[i] = iceServers[i].getBytes(StandardCharsets.UTF_8);
totalLen += getVarIntSize(b.length) + b.length;
}
byte[] ret = new byte[totalLen];
ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(ret).writerIndex(0);
wrappedBuffer.writeByte(VOICE_SIGNAL_ALLOWED);
wrappedBuffer.writeBoolean(allowed);
PacketTypes.writeVarInt(wrappedBuffer, iceServersBytes.length);
for(int i = 0; i < iceServersBytes.length; ++i) {
byte[] b = iceServersBytes[i];
PacketTypes.writeVarInt(wrappedBuffer, b.length);
wrappedBuffer.writeBytes(b);
}
return ret;
}
static byte[] makeVoiceSignalPacketGlobal(Collection<ChannelHandlerContext> users) {
int cnt = users.size();
byte[][] displayNames = new byte[cnt][];
int i = 0;
for(ChannelHandlerContext user : users) {
String name = ((EaglerVoiceHandler) user.pipeline().get("ayun-eag-voice")).user;
if(name.length() > 16) name = name.substring(0, 16);
displayNames[i++] = name.getBytes(StandardCharsets.UTF_8);
}
int totalLength = 1 + getVarIntSize(cnt) + (cnt << 4);
for(i = 0; i < cnt; ++i) {
totalLength += getVarIntSize(displayNames[i].length) + displayNames[i].length;
}
byte[] ret = new byte[totalLength];
ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(ret).writerIndex(0);
wrappedBuffer.writeByte(VOICE_SIGNAL_GLOBAL);
PacketTypes.writeVarInt(wrappedBuffer, cnt);
for(ChannelHandlerContext user : users) {
PacketTypes.writeUuid(wrappedBuffer, ((EaglerVoiceHandler) user.pipeline().get("ayun-eag-voice")).uuid);
}
for(i = 0; i < cnt; ++i) {
PacketTypes.writeVarInt(wrappedBuffer, displayNames[i].length);
wrappedBuffer.writeBytes(displayNames[i]);
}
return ret;
}
static byte[] makeVoiceSignalPacketConnect(UUID player, boolean offer) {
byte[] ret = new byte[18];
ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(ret).writerIndex(0);
wrappedBuffer.writeByte(VOICE_SIGNAL_CONNECT);
PacketTypes.writeUuid(wrappedBuffer, player);
wrappedBuffer.writeBoolean(offer);
return ret;
}
static byte[] makeVoiceSignalPacketDisconnect(UUID player) {
if(player == null) {
return new byte[] { (byte)VOICE_SIGNAL_DISCONNECT };
}
byte[] ret = new byte[17];
ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(ret).writerIndex(0);
wrappedBuffer.writeByte(VOICE_SIGNAL_DISCONNECT);
PacketTypes.writeUuid(wrappedBuffer, player);
return ret;
}
static byte[] makeVoiceSignalPacketICE(UUID player, String str) {
byte[] strBytes = str.getBytes(StandardCharsets.UTF_8);
byte[] ret = new byte[17 + getVarIntSize(strBytes.length) + strBytes.length];
ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(ret).writerIndex(0);
wrappedBuffer.writeByte(VOICE_SIGNAL_ICE);
PacketTypes.writeUuid(wrappedBuffer, player);
PacketTypes.writeVarInt(wrappedBuffer, strBytes.length);
wrappedBuffer.writeBytes(strBytes);
return ret;
}
static byte[] makeVoiceSignalPacketDesc(UUID player, String str) {
byte[] strBytes = str.getBytes(StandardCharsets.UTF_8);
byte[] ret = new byte[17 + getVarIntSize(strBytes.length) + strBytes.length];
ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(ret).writerIndex(0);
wrappedBuffer.writeByte(VOICE_SIGNAL_DESC);
PacketTypes.writeUuid(wrappedBuffer, player);
PacketTypes.writeVarInt(wrappedBuffer, strBytes.length);
wrappedBuffer.writeBytes(strBytes);
return ret;
}
public static int getVarIntSize(int input) {
for (int i = 1; i < 5; ++i) {
if ((input & -1 << i * 7) == 0) {
return i;
}
}
return 5;
}
}
@@ -0,0 +1,26 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import net.raphimc.viaproxy.proxy.util.ExceptionUtil;
public class WebSocketActiveNotifier extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(final ChannelHandlerContext ctx) {
}
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
ctx.fireChannelActive();
ctx.pipeline().remove(this);
}
super.userEventTriggered(ctx, evt);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ExceptionUtil.handleNettyException(ctx, cause, null, true);
}
}
@@ -0,0 +1,61 @@
package me.ayunami2000.ayunViaProxyEagUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.ssl.SslCompletionEvent;
import java.util.ArrayList;
import java.util.List;
public class WebSocketConnectedNotifier extends ChannelDuplexHandler {
private final List<Object> msgsRead = new ArrayList<>();
private final List<MsgPromise> msgsWrite = new ArrayList<>();
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) {
if (evt == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) {
ctx.fireChannelActive();
ctx.fireUserEventTriggered(evt);
ctx.pipeline().remove(this);
for (final Object msg : msgsRead)
ctx.fireChannelRead(msg);
msgsRead.clear();
for (final MsgPromise msg : msgsWrite)
ctx.write(msg.msg, msg.promise);
ctx.flush();
msgsWrite.clear();
} else if (evt == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_TIMEOUT) {
ctx.fireUserEventTriggered(evt);
ctx.close();
} else {
if (evt instanceof SslCompletionEvent && !((SslCompletionEvent) evt).isSuccess()) {
((SslCompletionEvent) evt).cause().printStackTrace();
}
ctx.fireUserEventTriggered(evt);
}
}
@Override
public void channelActive(final ChannelHandlerContext ctx) {
//
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
if (msg instanceof ByteBuf) {
msgsRead.add(msg);
} else {
ctx.fireChannelRead(msg);
}
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof WebSocketFrame || msg instanceof ByteBuf) {
msgsWrite.add(new MsgPromise(msg, promise));
} else {
ctx.write(msg, promise);
}
}
}
@@ -0,0 +1,4 @@
name: ViaProxyEagUtils
version: 1.0
author: ayunami2000
main: me.ayunami2000.ayunViaProxyEagUtils.Main
@@ -0,0 +1,11 @@
# Use premium skins
premium-skins: false
# Sync Eagler skins
eagler-skins: true
# Enable Eagler voice chat
eagler-voice: true
# Eaglercraft server mode
# 0 - Default (non-Eaglercraft)
# 1 - Force non-secure (ws)
# 2 - Force secure (wss)
eagler-server-mode: 0