| 1 | package net.minecraft.server.jsonrpc;
|
| 2 |
|
| 3 | import com.google.common.annotations.VisibleForTesting;
|
| 4 | import com.google.gson.JsonArray;
|
| 5 | import com.google.gson.JsonElement;
|
| 6 | import com.google.gson.JsonNull;
|
| 7 | import com.google.gson.JsonObject;
|
| 8 | import com.google.gson.JsonParseException;
|
| 9 | import com.mojang.logging.LogUtils;
|
| 10 | import io.netty.channel.Channel;
|
| 11 | import io.netty.channel.ChannelHandlerContext;
|
| 12 | import io.netty.channel.SimpleChannelInboundHandler;
|
| 13 | import io.netty.handler.timeout.ReadTimeoutException;
|
| 14 | import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
| 15 | import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
|
| 16 | import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
| 17 | import java.util.List;
|
| 18 | import java.util.Objects;
|
| 19 | import java.util.Optional;
|
| 20 | import java.util.concurrent.CompletableFuture;
|
| 21 | import java.util.concurrent.CompletionException;
|
| 22 | import java.util.concurrent.atomic.AtomicInteger;
|
| 23 | import net.minecraft.core.Holder;
|
| 24 | import net.minecraft.core.registries.BuiltInRegistries;
|
| 25 | import net.minecraft.resources.Identifier;
|
| 26 | import net.minecraft.server.jsonrpc.internalapi.MinecraftApi;
|
| 27 | import net.minecraft.server.jsonrpc.methods.ClientInfo;
|
| 28 | import net.minecraft.server.jsonrpc.methods.EncodeJsonRpcException;
|
| 29 | import net.minecraft.server.jsonrpc.methods.InvalidParameterJsonRpcException;
|
| 30 | import net.minecraft.server.jsonrpc.methods.InvalidRequestJsonRpcException;
|
| 31 | import net.minecraft.server.jsonrpc.methods.MethodNotFoundJsonRpcException;
|
| 32 | import net.minecraft.server.jsonrpc.methods.RemoteRpcErrorException;
|
| 33 | import net.minecraft.server.notifications.NotificationManager;
|
| 34 | import net.minecraft.util.GsonHelper;
|
| 35 | import net.minecraft.util.Util;
|
| 36 | import org.jetbrains.annotations.Contract;
|
| 37 | import org.jspecify.annotations.Nullable;
|
| 38 | import org.slf4j.Logger;
|
| 39 |
|
| 40 | public class Connection extends SimpleChannelInboundHandler<JsonElement> {
|
| 41 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 42 | private static final AtomicInteger CONNECTION_ID_COUNTER = new AtomicInteger(0);
|
| 43 | private final JsonRpcLogger jsonRpcLogger;
|
| 44 | private final ClientInfo clientInfo;
|
| 45 | private final ManagementServer managementServer;
|
| 46 | private final Channel channel;
|
| 47 | private final MinecraftApi minecraftApi;
|
| 48 | private final AtomicInteger transactionId = new AtomicInteger();
|
| 49 | private final Int2ObjectMap<PendingRpcRequest<?>> pendingRequests = Int2ObjectMaps.synchronize(new Int2ObjectOpenHashMap<>());
|
| 50 |
|
| 51 | public Connection(final Channel channel, final ManagementServer managementServer, final MinecraftApi minecraftApi, final JsonRpcLogger jsonrpcLogger) {
|
| 52 | this.clientInfo = ClientInfo.of(CONNECTION_ID_COUNTER.incrementAndGet());
|
| 53 | this.managementServer = managementServer;
|
| 54 | this.minecraftApi = minecraftApi;
|
| 55 | this.channel = channel;
|
| 56 | this.jsonRpcLogger = jsonrpcLogger;
|
| 57 | }
|
| 58 |
|
| 59 | public void tick() {
|
| 60 | long time = Util.getMillis();
|
| 61 | this.pendingRequests
|
| 62 | .int2ObjectEntrySet()
|
| 63 | .removeIf(
|
| 64 | entry -> {
|
| 65 | boolean timedOut = entry.getValue().timedOut(time);
|
| 66 | if (timedOut) {
|
| 67 | entry.getValue()
|
| 68 | .resultFuture()
|
| 69 | .completeExceptionally(new ReadTimeoutException("RPC method " + entry.getValue().method().key().identifier() + " timed out waiting for response"));
|
| 70 | }
|
| 71 |
|
| 72 | return timedOut;
|
| 73 | }
|
| 74 | );
|
| 75 | }
|
| 76 |
|
| 77 | @Override
|
| 78 | public void channelActive(final ChannelHandlerContext ctx) throws Exception {
|
| 79 | this.jsonRpcLogger.log(this.clientInfo, "Management connection opened for {}", this.channel.remoteAddress());
|
| 80 | super.channelActive(ctx);
|
| 81 | this.managementServer.onConnected(this);
|
| 82 | }
|
| 83 |
|
| 84 | @Override
|
| 85 | public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
|
| 86 | this.jsonRpcLogger.log(this.clientInfo, "Management connection closed for {}", this.channel.remoteAddress());
|
| 87 | super.channelInactive(ctx);
|
| 88 | this.managementServer.onDisconnected(this);
|
| 89 | }
|
| 90 |
|
| 91 | @Override
|
| 92 | public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
|
| 93 | if (cause.getCause() instanceof JsonParseException) {
|
| 94 | this.channel.writeAndFlush(JsonRPCErrors.PARSE_ERROR.createWithUnknownId(cause.getMessage()));
|
| 95 | } else {
|
| 96 | super.exceptionCaught(ctx, cause);
|
| 97 | this.channel.close().awaitUninterruptibly();
|
| 98 | }
|
| 99 | }
|
| 100 |
|
| 101 | protected void channelRead0(final ChannelHandlerContext channelHandlerContext, final JsonElement jsonElement) {
|
| 102 | if (jsonElement.isJsonObject()) {
|
| 103 | JsonObject response = this.handleJsonObject(jsonElement.getAsJsonObject());
|
| 104 | if (response != null) {
|
| 105 | this.channel.writeAndFlush(response);
|
| 106 | }
|
| 107 | } else if (jsonElement.isJsonArray()) {
|
| 108 | this.channel.writeAndFlush(this.handleBatchRequest(jsonElement.getAsJsonArray().asList()));
|
| 109 | } else {
|
| 110 | this.channel.writeAndFlush(JsonRPCErrors.INVALID_REQUEST.createWithUnknownId(null));
|
| 111 | }
|
| 112 | }
|
| 113 |
|
| 114 | private JsonArray handleBatchRequest(final List<JsonElement> batchRequests) {
|
| 115 | JsonArray batchResponses = new JsonArray();
|
| 116 | batchRequests.stream().map(batchEntry -> this.handleJsonObject(batchEntry.getAsJsonObject())).filter(Objects::nonNull).forEach(batchResponses::add);
|
| 117 | return batchResponses;
|
| 118 | }
|
| 119 |
|
| 120 | public void sendNotification(final Holder.Reference<? extends OutgoingRpcMethod<Void, ?>> method) {
|
| 121 | this.sendRequest(method, null, false);
|
| 122 | }
|
| 123 |
|
| 124 | public <Params> void sendNotification(final Holder.Reference<? extends OutgoingRpcMethod<Params, ?>> method, final Params params) {
|
| 125 | this.sendRequest(method, params, false);
|
| 126 | }
|
| 127 |
|
| 128 | public <Result> CompletableFuture<Result> sendRequest(final Holder.Reference<? extends OutgoingRpcMethod<Void, Result>> method) {
|
| 129 | return this.sendRequest(method, null, true);
|
| 130 | }
|
| 131 |
|
| 132 | public <Params, Result> CompletableFuture<Result> sendRequest(final Holder.Reference<? extends OutgoingRpcMethod<Params, Result>> method, final Params params) {
|
| 133 | return this.sendRequest(method, params, true);
|
| 134 | }
|
| 135 |
|
| 136 | @Contract("_,_,false->null;_,_,true->!null")
|
| 137 | private <Params, Result> @Nullable CompletableFuture<Result> sendRequest(
|
| 138 | final Holder.Reference<? extends OutgoingRpcMethod<Params, ? extends Result>> methodHolder, final @Nullable Params params, final boolean expectReply
|
| 139 | ) {
|
| 140 | OutgoingRpcMethod<Params, ? extends Result> method = (OutgoingRpcMethod<Params, ? extends Result>)methodHolder.value();
|
| 141 | if (this.minecraftApi.notificationManager().server() == null && !method.attributes().allowPreServerInit()) {
|
| 142 | return CompletableFuture.failedFuture(new InvalidRequestJsonRpcException("Method cannot be dispatched pre server initialization: " + method));
|
| 143 | } else {
|
| 144 | List<JsonElement> jsonParams = params != null ? List.of(Objects.requireNonNull(method.encodeParams(params))) : List.of();
|
| 145 | if (expectReply) {
|
| 146 | CompletableFuture<Result> future = new CompletableFuture<>();
|
| 147 | int id = this.transactionId.incrementAndGet();
|
| 148 | long time = Util.getMillis();
|
| 149 | this.pendingRequests.put(id, new PendingRpcRequest<>(methodHolder, future, time + 5000L));
|
| 150 | this.channel.writeAndFlush(JsonRPCUtils.createRequest(id, methodHolder.key().identifier(), jsonParams));
|
| 151 | return future;
|
| 152 | } else {
|
| 153 | this.channel.writeAndFlush(JsonRPCUtils.createRequest(null, methodHolder.key().identifier(), jsonParams));
|
| 154 | return null;
|
| 155 | }
|
| 156 | }
|
| 157 | }
|
| 158 |
|
| 159 | @VisibleForTesting
|
| 160 | @Nullable JsonObject handleJsonObject(final JsonObject jsonObject) {
|
| 161 | try {
|
| 162 | JsonElement id = JsonRPCUtils.getRequestId(jsonObject);
|
| 163 | String method = JsonRPCUtils.getMethodName(jsonObject);
|
| 164 | JsonElement result = JsonRPCUtils.getResult(jsonObject);
|
| 165 | JsonElement params = JsonRPCUtils.getParams(jsonObject);
|
| 166 | JsonObject error = JsonRPCUtils.getError(jsonObject);
|
| 167 | if (method != null && result == null && error == null) {
|
| 168 | return id != null && !isValidRequestId(id)
|
| 169 | ? JsonRPCErrors.INVALID_REQUEST.createWithUnknownId("Invalid request id - only String, Number and NULL supported")
|
| 170 | : this.handleIncomingRequest(id, method, params);
|
| 171 | }
|
| 172 |
|
| 173 | if (method == null && result != null && error == null && id != null) {
|
| 174 | if (isValidResponseId(id)) {
|
| 175 | this.handleRequestResponse(id.getAsInt(), result);
|
| 176 | } else {
|
| 177 | LOGGER.warn("Received respose {} with id {} we did not request", result, id);
|
| 178 | }
|
| 179 |
|
| 180 | return null;
|
| 181 | } else {
|
| 182 | return method == null && result == null && error != null
|
| 183 | ? this.handleError(id, error)
|
| 184 | : JsonRPCErrors.INVALID_REQUEST.createWithoutData(Objects.requireNonNullElse(id, JsonNull.INSTANCE));
|
| 185 | }
|
| 186 | } catch (Exception e) {
|
| 187 | LOGGER.error("Error while handling rpc request", e);
|
| 188 | return JsonRPCErrors.INTERNAL_ERROR.createWithUnknownId("Unknown error handling request - check server logs for stack trace");
|
| 189 | }
|
| 190 | }
|
| 191 |
|
| 192 | private static boolean isValidRequestId(final JsonElement id) {
|
| 193 | return id.isJsonNull() || GsonHelper.isNumberValue(id) || GsonHelper.isStringValue(id);
|
| 194 | }
|
| 195 |
|
| 196 | private static boolean isValidResponseId(final JsonElement id) {
|
| 197 | return GsonHelper.isNumberValue(id);
|
| 198 | }
|
| 199 |
|
| 200 | private @Nullable JsonObject handleIncomingRequest(final @Nullable JsonElement id, final String method, final @Nullable JsonElement params) {
|
| 201 | boolean sendResponse = id != null;
|
| 202 |
|
| 203 | try {
|
| 204 | JsonElement result = this.dispatchIncomingRequest(method, params);
|
| 205 | return result != null && sendResponse ? JsonRPCUtils.createSuccessResult(id, result) : null;
|
| 206 | } catch (InvalidParameterJsonRpcException e) {
|
| 207 | LOGGER.debug("Invalid parameter invocation {}: {}", method, params, e);
|
| 208 | return sendResponse ? JsonRPCErrors.INVALID_PARAMS.create(id, e.getMessage()) : null;
|
| 209 | } catch (EncodeJsonRpcException e) {
|
| 210 | LOGGER.error("Failed to encode json rpc response {}", method, e);
|
| 211 | return sendResponse ? JsonRPCErrors.INTERNAL_ERROR.create(id, e.getMessage()) : null;
|
| 212 | } catch (InvalidRequestJsonRpcException e) {
|
| 213 | return sendResponse ? JsonRPCErrors.INVALID_REQUEST.create(id, e.getMessage()) : null;
|
| 214 | } catch (MethodNotFoundJsonRpcException e) {
|
| 215 | return sendResponse ? JsonRPCErrors.METHOD_NOT_FOUND.create(id, e.getMessage()) : null;
|
| 216 | } catch (Exception e) {
|
| 217 | LOGGER.error("Error while dispatching rpc method {}", method, e);
|
| 218 | return sendResponse ? JsonRPCErrors.INTERNAL_ERROR.createWithoutData(id) : null;
|
| 219 | }
|
| 220 | }
|
| 221 |
|
| 222 | public @Nullable JsonElement dispatchIncomingRequest(final String method, final @Nullable JsonElement params) {
|
| 223 | Identifier identifier = Identifier.tryParse(method);
|
| 224 | if (identifier == null) {
|
| 225 | throw new InvalidRequestJsonRpcException("Failed to parse method value: " + method);
|
| 226 | }
|
| 227 |
|
| 228 | Optional<IncomingRpcMethod<?, ?>> incomingRpcMethod = BuiltInRegistries.INCOMING_RPC_METHOD.getOptional(identifier);
|
| 229 | if (incomingRpcMethod.isEmpty()) {
|
| 230 | throw new MethodNotFoundJsonRpcException("Method not found: " + method);
|
| 231 | }
|
| 232 |
|
| 233 | IncomingRpcMethod.Attributes attributes = incomingRpcMethod.get().attributes();
|
| 234 | NotificationManager notificationManager = this.minecraftApi.notificationManager();
|
| 235 | if (notificationManager != null && notificationManager.server() == null && !attributes.allowPreServerInit()) {
|
| 236 | throw new InvalidRequestJsonRpcException("Method cannot be dispatched pre server initialization: " + method);
|
| 237 | }
|
| 238 |
|
| 239 | if (attributes.runOnMainThread()) {
|
| 240 | try {
|
| 241 | return this.minecraftApi.<JsonElement>submit(() -> incomingRpcMethod.get().apply(this.minecraftApi, params, this.clientInfo)).join();
|
| 242 | } catch (CompletionException e) {
|
| 243 | if (e.getCause() instanceof RuntimeException re) {
|
| 244 | throw re;
|
| 245 | } else {
|
| 246 | throw e;
|
| 247 | }
|
| 248 | }
|
| 249 | } else {
|
| 250 | return incomingRpcMethod.get().apply(this.minecraftApi, params, this.clientInfo);
|
| 251 | }
|
| 252 | }
|
| 253 |
|
| 254 | private void handleRequestResponse(final int id, final JsonElement result) {
|
| 255 | PendingRpcRequest<?> request = this.pendingRequests.remove(id);
|
| 256 | if (request == null) {
|
| 257 | LOGGER.warn("Received unknown response (id: {}): {}", id, result);
|
| 258 | } else {
|
| 259 | request.accept(result);
|
| 260 | }
|
| 261 | }
|
| 262 |
|
| 263 | private @Nullable JsonObject handleError(final @Nullable JsonElement id, final JsonObject error) {
|
| 264 | if (id != null && isValidResponseId(id)) {
|
| 265 | PendingRpcRequest<?> request = this.pendingRequests.remove(id.getAsInt());
|
| 266 | if (request != null) {
|
| 267 | request.resultFuture().completeExceptionally(new RemoteRpcErrorException(id, error));
|
| 268 | }
|
| 269 | }
|
| 270 |
|
| 271 | LOGGER.error("Received error (id: {}): {}", id, error);
|
| 272 | return null;
|
| 273 | }
|
| 274 | }
|
| 275 |
|