Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce session server lookups #509

Merged
merged 12 commits into from
May 18, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
import io.netty.util.AttributeKey;
import java.lang.reflect.Field;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.event.LoginEvent;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
Expand All @@ -49,7 +51,10 @@
import org.geysermc.floodgate.config.ProxyFloodgateConfig;
import org.geysermc.floodgate.skin.SkinApplier;
import org.geysermc.floodgate.skin.SkinDataImpl;
import org.geysermc.floodgate.util.Constants;
import org.geysermc.floodgate.util.HttpClient;
import org.geysermc.floodgate.util.LanguageManager;
import org.geysermc.floodgate.util.MojangUtils;
import org.geysermc.floodgate.util.ReflectionUtils;

@SuppressWarnings("ConstantConditions")
Expand Down Expand Up @@ -80,6 +85,8 @@ public final class BungeeListener implements Listener {
@Named("kickMessageAttribute")
private AttributeKey<String> kickMessageAttribute;

@Inject private HttpClient httpClient;

@EventHandler(priority = EventPriority.LOWEST)
public void onPreLogin(PreLoginEvent event) {
// well, no reason to check if the player will be kicked anyway
Expand Down Expand Up @@ -130,9 +137,35 @@ public void onPostLogin(PostLoginEvent event) {
// To fix the February 2 2022 Mojang authentication changes
if (!config.isSendFloodgateData()) {
FloodgatePlayer player = api.getPlayer(event.getPlayer().getUniqueId());
if (player != null && !player.isLinked()) {
skinApplier.applySkin(player, new SkinDataImpl("", ""));

if (player == null) {
return;
}

if (!player.isLinked()) {
skinApplier.applySkin(player, new SkinDataImpl(
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_TEXTURE,
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_TEXTURE
));

return;
}

CompletableFuture.supplyAsync(() -> {
try {
return MojangUtils.getSkinCached(httpClient, player.getJavaUniqueId());
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}).thenAccept(skin -> skinApplier.applySkin(player, skin))
.exceptionally(e -> {
logger.error("Failed to get skin for player " + player.getJavaUniqueId() + ", applying default.", e);
skinApplier.applySkin(player, new SkinDataImpl(
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_TEXTURE,
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_TEXTURE
));
return null;
});
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.util.Objects;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.geysermc.floodgate.api.event.skin.SkinApplyEvent.SkinData;
import org.geysermc.floodgate.util.Constants;

public class SkinDataImpl implements SkinData {
private final String value;
Expand All @@ -55,4 +56,9 @@ public static SkinData from(JsonObject data) {
public @NonNull String signature() {
return signature;
}

public static final SkinData DEFAULT_SKIN = new SkinDataImpl(
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_TEXTURE,
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_SIGNATURE
);
}
99 changes: 99 additions & 0 deletions core/src/main/java/org/geysermc/floodgate/util/MojangUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Copyright (c) 2019-2024 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Floodgate
*/

package org.geysermc.floodgate.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import lombok.NonNull;
import org.geysermc.floodgate.api.event.skin.SkinApplyEvent.SkinData;
import org.geysermc.floodgate.skin.SkinDataImpl;
import org.geysermc.floodgate.util.HttpClient.HttpResponse;

public class MojangUtils {

private static final String SESSION_SERVER =
"https://sessionserver.mojang.com/session/minecraft/profile/%s?unsigned=false";

private static final Cache<UUID, SkinData> SKIN_CACHE = CacheBuilder.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.maximumSize(500)
.build();

public static @NonNull SkinData getSkinCached(
HttpClient httpClient,
UUID playerId
) throws ExecutionException {
return SKIN_CACHE.get(playerId, () -> getSkin(httpClient, playerId));
}

public static @NonNull SkinData getSkin(HttpClient httpClient, UUID playerId) {
final HttpResponse<JsonObject> httpResponse = httpClient.get(String.format(SESSION_SERVER, playerId.toString()));

if (httpResponse.getHttpCode() != 200) {
return SkinDataImpl.DEFAULT_SKIN;
}

JsonObject response = httpResponse.getResponse();

if (response == null) {
return SkinDataImpl.DEFAULT_SKIN;
}

JsonArray properties = response.getAsJsonArray("properties");

if (properties.size() == 0) {
return SkinDataImpl.DEFAULT_SKIN;
}

for (JsonElement property : properties) {
if (!property.isJsonObject()) {
continue;
}

JsonObject propertyObject = property.getAsJsonObject();

if (!propertyObject.has("name")
|| !propertyObject.has("value")
|| !propertyObject.has("signature")
|| !propertyObject.get("name").getAsString().equals("textures")) {
continue;
}

return new SkinDataImpl(
propertyObject.get("value").getAsString(),
propertyObject.get("signature").getAsString()
);
}

return SkinDataImpl.DEFAULT_SKIN;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,7 @@ public final class Constants {
public static final int HANDSHAKE_PACKET_ID = 0;
public static final int LOGIN_SUCCESS_PACKET_ID = 2;
public static final int SET_COMPRESSION_PACKET_ID = 3;

public static final String DEFAULT_MINECRAFT_JAVA_SKIN_TEXTURE = "ewogICJ0aW1lc3RhbXAiIDogMTcxNTMwNTM4NDQwOSwKICAicHJvZmlsZUlkIiA6ICJjZDZkODYwMzRhMWI0YTgxYjhhN2E2Y2IyM2Y5MjI4MCIsCiAgInByb2ZpbGVOYW1lIiA6ICJKdWVsbGU5MTc5IiwKICAic2lnbmF0dXJlUmVxdWlyZWQiIDogdHJ1ZSwKICAidGV4dHVyZXMiIDogewogICAgIlNLSU4iIDogewogICAgICAidXJsIiA6ICJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzMxZjQ3N2ViMWE3YmVlZTYzMWMyY2E2NGQwNmY4ZjY4ZmE5M2EzMzg2ZDA0NDUyYWIyN2Y0M2FjZGYxYjYwY2IiCiAgICB9CiAgfQp9";
public static final String DEFAULT_MINECRAFT_JAVA_SKIN_SIGNATURE = "gUiXhG+rqQRpY2LEI3V81xOKtmuvqxZUZsqm5ojgTnUnWCAPY39H3SZV/p4C3+x4Yp1pBQCR24B1WCAXT8s1Pc3PPf0ptav2TOrn0+B40XJYlabx7m1Qd5tNmbzAAuZpmQ2kdprQom/KmtYJnxXgMHAEuOy4oW3n736ZTYlvDSZtXNcwElOIbg0Zq1Dis0Qm54MazDpYdC8VPm1twrrR6DAHSJeTAx99NBcVgKDEwnFEO+4ch4ATD0AboJq2Alfa81b2BZ8ko02rB6s4WP4/qG1yyNBanO1FnSqqNPoNXQT/+og6dWOW62dcu9OXAdTIaKJ9P+ER9Yyo6Tv5eQGSB7VikZIollYN2OZ2TPMyqqEouHjKAggQEdOb/avid08YMveQr9c7yW1Ay2JAF6BH6D0tmdZ4WQWZUT6xR98o88sUAIhSGbds+h8PbJdWhGa1MDT+hNEcUmWJ0Mui8CBWIrhJAzppgDbsZlX9mWjQEwJAtlcUe9BEeZV3EhriPr9dCg867ojV5yXjrv+G6fpPUy+Zkkg/u38APnGBsWtPU8jDEpLtsGjbe6L7v7AvJuRv4Q35YuRD2j+UXZROxmkVKc4/PV/3SC15ePhU397gicQ5E41kvjikIdYYdkjQoj2G2esEZmvqCWzAm1czPeH+FiemCYgscM2QcFe+rBV0GJw=";
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import static org.geysermc.floodgate.util.ReflectionUtils.setValue;

import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import java.lang.reflect.InvocationTargetException;
Expand All @@ -38,9 +39,17 @@
import org.geysermc.floodgate.player.FloodgateHandshakeHandler;
import org.geysermc.floodgate.player.FloodgateHandshakeHandler.HandshakeResult;
import org.geysermc.floodgate.util.ClassNames;
import org.geysermc.floodgate.util.Constants;
import org.geysermc.floodgate.util.ProxyUtils;

public final class SpigotDataHandler extends CommonDataHandler {

private static final Property DEFAULT_TEXTURE_PROPERTY = new Property(
"textures",
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_TEXTURE,
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_SIGNATURE
);

private Object networkManager;
private FloodgatePlayer player;
private boolean proxyData;
Expand Down Expand Up @@ -171,6 +180,14 @@ private boolean checkAndHandleLogin(Object packet) throws Exception {
player.getCorrectUniqueId(), player.getCorrectUsername()
);

if (!player.isLinked()) {
// Otherwise game server will try to fetch the skin from Mojang
gameProfile.getProperties().put(
"textures",
DEFAULT_TEXTURE_PROPERTY
);
}

// we have to fake the offline player (login) cycle

if (ClassNames.IS_PRE_1_20_2) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import org.bukkit.event.player.PlayerJoinEvent;
import org.geysermc.floodgate.api.SimpleFloodgateApi;
import org.geysermc.floodgate.api.player.FloodgatePlayer;
import org.geysermc.floodgate.util.Constants;

public final class PaperProfileListener implements Listener {
@Inject private SimpleFloodgateApi api;
Expand All @@ -62,7 +63,14 @@ public void onFill(PreFillProfileEvent event) {
}

Set<ProfileProperty> properties = new HashSet<>(event.getPlayerProfile().getProperties());
properties.add(new ProfileProperty("textures", "", ""));
properties.add(
new ProfileProperty(
"textures",
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_TEXTURE,
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_SIGNATURE
)
);

event.setProperties(properties);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,26 @@
import io.netty.util.AttributeKey;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import net.kyori.adventure.text.Component;
import org.geysermc.floodgate.api.ProxyFloodgateApi;
import org.geysermc.floodgate.api.event.skin.SkinApplyEvent.SkinData;
import org.geysermc.floodgate.api.logger.FloodgateLogger;
import org.geysermc.floodgate.api.player.FloodgatePlayer;
import org.geysermc.floodgate.config.ProxyFloodgateConfig;
import org.geysermc.floodgate.util.Constants;
import org.geysermc.floodgate.util.HttpClient;
import org.geysermc.floodgate.util.LanguageManager;
import org.geysermc.floodgate.util.MojangUtils;

public final class VelocityListener {
private static final Field INITIAL_MINECRAFT_CONNECTION;
private static final Field INITIAL_CONNECTION_DELEGATE;
private static final Field CHANNEL;
private static final Property DEFAULT_TEXTURE_PROPERTY;

static {
Class<?> initialConnection = getPrefixedClass("connection.client.InitialInboundConnection");
Expand All @@ -82,6 +89,11 @@ public final class VelocityListener {
}

CHANNEL = getFieldOfType(minecraftConnection, Channel.class);
DEFAULT_TEXTURE_PROPERTY = new Property(
"textures",
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_TEXTURE,
Constants.DEFAULT_MINECRAFT_JAVA_SKIN_SIGNATURE
);
}

private final Cache<InboundConnection, FloodgatePlayer> playerCache =
Expand All @@ -103,6 +115,9 @@ public final class VelocityListener {
@Named("kickMessageAttribute")
private AttributeKey<String> kickMessageAttribute;

@Inject
private HttpClient httpClient;

@Subscribe(order = PostOrder.EARLY)
public void onPreLogin(PreLoginEvent event) {
FloodgatePlayer player = null;
Expand Down Expand Up @@ -147,12 +162,22 @@ public void onGameProfileRequest(GameProfileRequestEvent event) {
GameProfile profile = new GameProfile(
player.getCorrectUniqueId(),
player.getCorrectUsername(),
Collections.emptyList()
player.isLinked() ? Collections.emptyList() : List.of(DEFAULT_TEXTURE_PROPERTY) // Otherwise game server will try to fetch the skin from Mojang
);
// The texture properties addition is to fix the February 2 2022 Mojang authentication changes
if (!config.isSendFloodgateData() && !player.isLinked()) {
profile = profile.addProperty(new Property("textures", "", ""));

if (player.isLinked()) {
// Do texture lookup to session server
try {
SkinData skin = MojangUtils.getSkinCached(httpClient,
player.getJavaUniqueId());

profile.addProperty(new Property("textures", skin.value(), skin.signature()));
} catch (ExecutionException e) {
logger.error("Failed to get skin for player " + player.getJavaUniqueId() + ", applying default.", e);
profile.addProperty(DEFAULT_TEXTURE_PROPERTY);
}
}

event.setGameProfile(profile);
}
}
Expand Down