| 1 | package net.minecraft.server.network;
|
| 2 |
|
| 3 | import com.google.common.collect.ImmutableList;
|
| 4 | import com.google.gson.JsonArray;
|
| 5 | import com.google.gson.JsonObject;
|
| 6 | import com.google.gson.internal.Streams;
|
| 7 | import com.google.gson.stream.JsonWriter;
|
| 8 | import com.mojang.authlib.GameProfile;
|
| 9 | import com.mojang.logging.LogUtils;
|
| 10 | import java.io.IOException;
|
| 11 | import java.io.InputStream;
|
| 12 | import java.io.InputStreamReader;
|
| 13 | import java.io.OutputStreamWriter;
|
| 14 | import java.net.HttpURLConnection;
|
| 15 | import java.net.MalformedURLException;
|
| 16 | import java.net.URI;
|
| 17 | import java.net.URL;
|
| 18 | import java.nio.charset.StandardCharsets;
|
| 19 | import java.util.List;
|
| 20 | import java.util.concurrent.CompletableFuture;
|
| 21 | import java.util.concurrent.Executor;
|
| 22 | import java.util.concurrent.ExecutorService;
|
| 23 | import java.util.concurrent.Executors;
|
| 24 | import java.util.concurrent.ThreadFactory;
|
| 25 | import java.util.concurrent.atomic.AtomicInteger;
|
| 26 | import net.minecraft.SharedConstants;
|
| 27 | import net.minecraft.network.chat.FilterMask;
|
| 28 | import net.minecraft.server.dedicated.DedicatedServerProperties;
|
| 29 | import net.minecraft.util.GsonHelper;
|
| 30 | import net.minecraft.util.LenientJsonParser;
|
| 31 | import net.minecraft.util.StringUtil;
|
| 32 | import net.minecraft.util.Util;
|
| 33 | import net.minecraft.util.thread.ConsecutiveExecutor;
|
| 34 | import org.jspecify.annotations.Nullable;
|
| 35 | import org.slf4j.Logger;
|
| 36 |
|
| 37 | public abstract class ServerTextFilter implements AutoCloseable {
|
| 38 | protected static final Logger LOGGER = LogUtils.getLogger();
|
| 39 | private static final AtomicInteger WORKER_COUNT = new AtomicInteger(1);
|
| 40 | private static final ThreadFactory THREAD_FACTORY = runnable -> new Thread(runnable, "Chat-Filter-Worker-" + WORKER_COUNT.getAndIncrement());
|
| 41 | private final URL chatEndpoint;
|
| 42 | private final ServerTextFilter.MessageEncoder chatEncoder;
|
| 43 | private final ServerTextFilter.IgnoreStrategy chatIgnoreStrategy;
|
| 44 | private final ExecutorService workerPool;
|
| 45 |
|
| 46 | protected static ExecutorService createWorkerPool(final int maxConcurrentRequests) {
|
| 47 | return Executors.newFixedThreadPool(maxConcurrentRequests, THREAD_FACTORY);
|
| 48 | }
|
| 49 |
|
| 50 | protected ServerTextFilter(
|
| 51 | final URL chatEndpoint,
|
| 52 | final ServerTextFilter.MessageEncoder chatEncoder,
|
| 53 | final ServerTextFilter.IgnoreStrategy chatIgnoreStrategy,
|
| 54 | final ExecutorService workerPool
|
| 55 | ) {
|
| 56 | this.chatIgnoreStrategy = chatIgnoreStrategy;
|
| 57 | this.workerPool = workerPool;
|
| 58 | this.chatEndpoint = chatEndpoint;
|
| 59 | this.chatEncoder = chatEncoder;
|
| 60 | }
|
| 61 |
|
| 62 | protected static URL getEndpoint(final URI host, final @Nullable JsonObject source, final String id, final String def) throws MalformedURLException {
|
| 63 | String endpointConfig = getEndpointFromConfig(source, id, def);
|
| 64 | return host.resolve("/" + endpointConfig).toURL();
|
| 65 | }
|
| 66 |
|
| 67 | protected static String getEndpointFromConfig(final @Nullable JsonObject source, final String id, final String def) {
|
| 68 | return source != null ? GsonHelper.getAsString(source, id, def) : def;
|
| 69 | }
|
| 70 |
|
| 71 | public static @Nullable ServerTextFilter createFromConfig(final DedicatedServerProperties config) {
|
| 72 | String textFilteringConfig = config.textFilteringConfig;
|
| 73 | if (StringUtil.isBlank(textFilteringConfig)) {
|
| 74 | return null;
|
| 75 | }
|
| 76 |
|
| 77 | return switch (config.textFilteringVersion) {
|
| 78 | case 0 -> LegacyTextFilter.createTextFilterFromConfig(textFilteringConfig);
|
| 79 | case 1 -> PlayerSafetyServiceTextFilter.createTextFilterFromConfig(textFilteringConfig);
|
| 80 | default -> {
|
| 81 | LOGGER.warn("Could not create text filter - unsupported text filtering version used");
|
| 82 | yield null;
|
| 83 | }
|
| 84 | };
|
| 85 | }
|
| 86 |
|
| 87 | protected CompletableFuture<FilteredText> requestMessageProcessing(
|
| 88 | final GameProfile sender, final String message, final ServerTextFilter.IgnoreStrategy ignoreStrategy, final Executor executor
|
| 89 | ) {
|
| 90 | return message.isEmpty() ? CompletableFuture.completedFuture(FilteredText.EMPTY) : CompletableFuture.supplyAsync(() -> {
|
| 91 | JsonObject object = this.chatEncoder.encode(sender, message);
|
| 92 |
|
| 93 | try {
|
| 94 | JsonObject result = this.processRequestResponse(object, this.chatEndpoint);
|
| 95 | return this.filterText(message, ignoreStrategy, result);
|
| 96 | } catch (Exception e) {
|
| 97 | LOGGER.warn("Failed to validate message '{}'", message, e);
|
| 98 | return FilteredText.fullyFiltered(message);
|
| 99 | }
|
| 100 | }, executor);
|
| 101 | }
|
| 102 |
|
| 103 | protected abstract FilteredText filterText(final String message, final ServerTextFilter.IgnoreStrategy ignoreStrategy, final JsonObject result);
|
| 104 |
|
| 105 | protected FilterMask parseMask(final String message, final JsonArray removedChars, final ServerTextFilter.IgnoreStrategy ignoreStrategy) {
|
| 106 | if (removedChars.isEmpty()) {
|
| 107 | return FilterMask.PASS_THROUGH;
|
| 108 | }
|
| 109 |
|
| 110 | if (ignoreStrategy.shouldIgnore(message, removedChars.size())) {
|
| 111 | return FilterMask.FULLY_FILTERED;
|
| 112 | }
|
| 113 |
|
| 114 | FilterMask mask = new FilterMask(message.length());
|
| 115 |
|
| 116 | for (int i = 0; i < removedChars.size(); i++) {
|
| 117 | mask.setFiltered(removedChars.get(i).getAsInt());
|
| 118 | }
|
| 119 |
|
| 120 | return mask;
|
| 121 | }
|
| 122 |
|
| 123 | @Override
|
| 124 | public void close() {
|
| 125 | this.workerPool.shutdownNow();
|
| 126 | }
|
| 127 |
|
| 128 | protected void drainStream(final InputStream input) throws IOException {
|
| 129 | byte[] trashcan = new byte[1024];
|
| 130 |
|
| 131 | while (input.read(trashcan) != -1) {
|
| 132 | }
|
| 133 | }
|
| 134 |
|
| 135 | private JsonObject processRequestResponse(final JsonObject payload, final URL url) throws IOException {
|
| 136 | HttpURLConnection connection = this.makeRequest(payload, url);
|
| 137 |
|
| 138 | try (InputStream is = connection.getInputStream()) {
|
| 139 | if (connection.getResponseCode() == 204) {
|
| 140 | return new JsonObject();
|
| 141 | }
|
| 142 |
|
| 143 | try {
|
| 144 | return LenientJsonParser.parse(new InputStreamReader(is, StandardCharsets.UTF_8)).getAsJsonObject();
|
| 145 | } finally {
|
| 146 | this.drainStream(is);
|
| 147 | }
|
| 148 | }
|
| 149 | }
|
| 150 |
|
| 151 | protected HttpURLConnection makeRequest(final JsonObject payload, final URL url) throws IOException {
|
| 152 | HttpURLConnection connection = this.getURLConnection(url);
|
| 153 | this.setAuthorizationProperty(connection);
|
| 154 | OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
|
| 155 |
|
| 156 | try (JsonWriter jsonWriter = new JsonWriter(writer)) {
|
| 157 | Streams.write(payload, jsonWriter);
|
| 158 | } catch (Throwable var11) {
|
| 159 | try {
|
| 160 | writer.close();
|
| 161 | } catch (Throwable var8) {
|
| 162 | var11.addSuppressed(var8);
|
| 163 | }
|
| 164 |
|
| 165 | throw var11;
|
| 166 | }
|
| 167 |
|
| 168 | writer.close();
|
| 169 | int responseCode = connection.getResponseCode();
|
| 170 | if (responseCode >= 200 && responseCode < 300) {
|
| 171 | return connection;
|
| 172 | } else {
|
| 173 | throw new ServerTextFilter.RequestFailedException(responseCode + " " + connection.getResponseMessage());
|
| 174 | }
|
| 175 | }
|
| 176 |
|
| 177 | protected abstract void setAuthorizationProperty(final HttpURLConnection connection);
|
| 178 |
|
| 179 | protected int connectionReadTimeout() {
|
| 180 | return 2000;
|
| 181 | }
|
| 182 |
|
| 183 | protected HttpURLConnection getURLConnection(final URL url) throws IOException {
|
| 184 | HttpURLConnection connection = (HttpURLConnection)url.openConnection();
|
| 185 | connection.setConnectTimeout(15000);
|
| 186 | connection.setReadTimeout(this.connectionReadTimeout());
|
| 187 | connection.setUseCaches(false);
|
| 188 | connection.setDoOutput(true);
|
| 189 | connection.setDoInput(true);
|
| 190 | connection.setRequestMethod("POST");
|
| 191 | connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
|
| 192 | connection.setRequestProperty("Accept", "application/json");
|
| 193 | connection.setRequestProperty("User-Agent", "Minecraft server" + SharedConstants.getCurrentVersion().name());
|
| 194 | return connection;
|
| 195 | }
|
| 196 |
|
| 197 | public TextFilter createContext(final GameProfile gameProfile) {
|
| 198 | return new ServerTextFilter.PlayerContext(gameProfile);
|
| 199 | }
|
| 200 |
|
| 201 | @FunctionalInterface
|
| 202 | public interface IgnoreStrategy {
|
| 203 | ServerTextFilter.IgnoreStrategy NEVER_IGNORE = (message, removedCharCount) -> false;
|
| 204 | ServerTextFilter.IgnoreStrategy IGNORE_FULLY_FILTERED = (message, removedCharCount) -> message.length() == removedCharCount;
|
| 205 |
|
| 206 | static ServerTextFilter.IgnoreStrategy ignoreOverThreshold(final int threshold) {
|
| 207 | return (message, removedCharCount) -> removedCharCount >= threshold;
|
| 208 | }
|
| 209 |
|
| 210 | static ServerTextFilter.IgnoreStrategy select(final int hashesToDrop) {
|
| 211 | return switch (hashesToDrop) {
|
| 212 | case -1 -> NEVER_IGNORE;
|
| 213 | case 0 -> IGNORE_FULLY_FILTERED;
|
| 214 | default -> ignoreOverThreshold(hashesToDrop);
|
| 215 | };
|
| 216 | }
|
| 217 |
|
| 218 | boolean shouldIgnore(final String message, final int removedCharCount);
|
| 219 | }
|
| 220 |
|
| 221 | @FunctionalInterface
|
| 222 | protected interface MessageEncoder {
|
| 223 | JsonObject encode(GameProfile profile, String message);
|
| 224 | }
|
| 225 |
|
| 226 | protected class PlayerContext implements TextFilter {
|
| 227 | protected final GameProfile profile;
|
| 228 | protected final Executor streamExecutor;
|
| 229 |
|
| 230 | protected PlayerContext(final GameProfile profile) {
|
| 231 | this.profile = profile;
|
| 232 | ConsecutiveExecutor streamProcessor = new ConsecutiveExecutor(ServerTextFilter.this.workerPool, "chat stream for " + profile.name());
|
| 233 | this.streamExecutor = streamProcessor::schedule;
|
| 234 | }
|
| 235 |
|
| 236 | @Override
|
| 237 | public CompletableFuture<List<FilteredText>> processMessageBundle(final List<String> messages) {
|
| 238 | List<CompletableFuture<FilteredText>> requests = messages.stream()
|
| 239 | .map(message -> ServerTextFilter.this.requestMessageProcessing(this.profile, message, ServerTextFilter.this.chatIgnoreStrategy, this.streamExecutor))
|
| 240 | .collect(ImmutableList.toImmutableList());
|
| 241 | return Util.sequenceFailFast(requests).exceptionally(e -> ImmutableList.of());
|
| 242 | }
|
| 243 |
|
| 244 | @Override
|
| 245 | public CompletableFuture<FilteredText> processStreamMessage(final String message) {
|
| 246 | return ServerTextFilter.this.requestMessageProcessing(this.profile, message, ServerTextFilter.this.chatIgnoreStrategy, this.streamExecutor);
|
| 247 | }
|
| 248 | }
|
| 249 |
|
| 250 | protected static class RequestFailedException extends RuntimeException {
|
| 251 | protected RequestFailedException(final String message) {
|
| 252 | super(message);
|
| 253 | }
|
| 254 | }
|
| 255 | }
|
| 256 |
|