]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/jsonrpc/JsonRpcReader.java
Replace deprecated DBusMap
[signal-cli] / src / main / java / org / asamk / signal / jsonrpc / JsonRpcReader.java
1 package org.asamk.signal.jsonrpc;
2
3 import com.fasterxml.jackson.core.JsonParseException;
4 import com.fasterxml.jackson.databind.JsonMappingException;
5 import com.fasterxml.jackson.databind.JsonNode;
6 import com.fasterxml.jackson.databind.ObjectMapper;
7 import com.fasterxml.jackson.databind.node.ContainerNode;
8 import com.fasterxml.jackson.databind.node.ObjectNode;
9 import com.fasterxml.jackson.databind.node.ValueNode;
10
11 import org.asamk.signal.util.Util;
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
14
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.util.ArrayList;
18 import java.util.concurrent.Executors;
19 import java.util.concurrent.locks.ReentrantLock;
20 import java.util.function.Consumer;
21 import java.util.function.Supplier;
22 import java.util.stream.StreamSupport;
23
24 public class JsonRpcReader {
25
26 private static final Logger logger = LoggerFactory.getLogger(JsonRpcReader.class);
27
28 private final JsonRpcSender jsonRpcSender;
29 private final ObjectMapper objectMapper;
30 private final InputStream input;
31 private final Supplier<String> lineSupplier;
32
33 public JsonRpcReader(final JsonRpcSender jsonRpcSender, final Supplier<String> lineSupplier) {
34 this.jsonRpcSender = jsonRpcSender;
35 this.input = null;
36 this.lineSupplier = lineSupplier;
37 this.objectMapper = Util.createJsonObjectMapper();
38 }
39
40 public JsonRpcReader(final JsonRpcSender jsonRpcSender, final InputStream input) {
41 this.jsonRpcSender = jsonRpcSender;
42 this.input = input;
43 this.lineSupplier = null;
44 this.objectMapper = Util.createJsonObjectMapper();
45 }
46
47 public void readMessages(final RequestHandler requestHandler, final Consumer<JsonRpcResponse> responseHandler) {
48 if (input != null) {
49 JsonRpcMessage message = parseJsonRpcMessage(input);
50 if (message == null) {
51 return;
52 }
53
54 handleMessage(message, requestHandler, responseHandler);
55 return;
56 }
57
58 try (final var executor = Executors.newCachedThreadPool()) {
59 while (!Thread.interrupted()) {
60 final var input = lineSupplier.get();
61 if (input == null) {
62 logger.trace("Reached end of JSON-RPC input stream.");
63 break;
64 }
65
66 logger.trace("Incoming JSON-RPC message: {}", input);
67 final var message = parseJsonRpcMessage(input);
68 if (message == null) {
69 continue;
70 }
71
72 executor.submit(() -> handleMessage(message, requestHandler, responseHandler));
73 }
74 }
75 }
76
77 private void handleMessage(
78 final JsonRpcMessage message,
79 final RequestHandler requestHandler,
80 final Consumer<JsonRpcResponse> responseHandler
81 ) {
82 switch (message) {
83 case JsonRpcRequest jsonRpcRequest -> {
84 logger.debug("Received json rpc request, method: " + jsonRpcRequest.getMethod());
85 final var response = handleRequest(requestHandler, jsonRpcRequest);
86 if (response != null) {
87 jsonRpcSender.sendResponse(response);
88 }
89 }
90 case JsonRpcResponse jsonRpcResponse -> responseHandler.accept(jsonRpcResponse);
91 case JsonRpcBatchMessage jsonRpcBatchMessage -> {
92 final var messages = jsonRpcBatchMessage.getMessages();
93 final var responseList = new ArrayList<JsonRpcResponse>(messages.size());
94 try (final var executor = Executors.newCachedThreadPool()) {
95 final var lock = new ReentrantLock();
96 messages.forEach(jsonNode -> {
97 final JsonRpcRequest request;
98 try {
99 request = parseJsonRpcRequest(jsonNode);
100 } catch (JsonRpcException e) {
101 final var response = JsonRpcResponse.forError(e.getError(), getId(jsonNode));
102 lock.lock();
103 try {
104 responseList.add(response);
105 } finally {
106 lock.unlock();
107 }
108 return;
109 }
110
111 executor.submit(() -> {
112 final var response = handleRequest(requestHandler, request);
113 if (response != null) {
114 lock.lock();
115 try {
116 responseList.add(response);
117 } finally {
118 lock.unlock();
119 }
120 }
121 });
122 });
123 }
124
125 if (!responseList.isEmpty()) {
126 jsonRpcSender.sendBatchResponses(responseList);
127 }
128 }
129 }
130 }
131
132 private JsonRpcResponse handleRequest(final RequestHandler requestHandler, final JsonRpcRequest request) {
133 try {
134 final var result = requestHandler.apply(request.getMethod(), request.getParams());
135 if (request.getId() != null) {
136 return JsonRpcResponse.forSuccess(result, request.getId());
137 } else {
138 logger.debug("Command '{}' succeeded but client didn't specify an id, dropping response",
139 request.getMethod());
140 }
141 } catch (JsonRpcException e) {
142 if (request.getId() != null) {
143 return JsonRpcResponse.forError(e.getError(), request.getId());
144 } else {
145 logger.debug("Command '{}' failed but client didn't specify an id, dropping error: {}",
146 request.getMethod(),
147 e.getMessage());
148 }
149 }
150 return null;
151 }
152
153 private JsonRpcMessage parseJsonRpcMessage(final String input) {
154 final JsonNode jsonNode;
155 try {
156 jsonNode = objectMapper.readTree(input);
157 } catch (JsonParseException e) {
158 jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.PARSE_ERROR,
159 e.getMessage(),
160 null), null));
161 return null;
162 } catch (IOException e) {
163 throw new AssertionError(e);
164 }
165
166 return parseJsonRpcMessage(jsonNode);
167 }
168
169 private JsonRpcMessage parseJsonRpcMessage(final InputStream input) {
170 final JsonNode jsonNode;
171 try {
172 jsonNode = objectMapper.readTree(input);
173 } catch (JsonParseException e) {
174 jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.PARSE_ERROR,
175 e.getMessage(),
176 null), null));
177 return null;
178 } catch (IOException e) {
179 throw new AssertionError(e);
180 }
181
182 return parseJsonRpcMessage(jsonNode);
183 }
184
185 private JsonRpcMessage parseJsonRpcMessage(final JsonNode jsonNode) {
186 if (jsonNode == null) {
187 jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
188 "invalid request",
189 null), null));
190 return null;
191 } else if (jsonNode.isArray()) {
192 if (jsonNode.isEmpty()) {
193 jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
194 "invalid request",
195 null), null));
196 return null;
197 }
198 return new JsonRpcBatchMessage(StreamSupport.stream(jsonNode.spliterator(), false).toList());
199 } else if (jsonNode.isObject()) {
200 if (jsonNode.has("result") || jsonNode.has("error")) {
201 return parseJsonRpcResponse(jsonNode);
202 } else {
203 try {
204 return parseJsonRpcRequest(jsonNode);
205 } catch (JsonRpcException e) {
206 jsonRpcSender.sendResponse(JsonRpcResponse.forError(e.getError(), getId(jsonNode)));
207 return null;
208 }
209 }
210 } else {
211 jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
212 "unexpected type: " + jsonNode.getNodeType().name(),
213 null), null));
214 return null;
215 }
216 }
217
218 private ValueNode getId(JsonNode jsonNode) {
219 final var id = jsonNode.get("id");
220 return id instanceof ValueNode value ? value : null;
221 }
222
223 private JsonRpcRequest parseJsonRpcRequest(final JsonNode input) throws JsonRpcException {
224 if (input instanceof ObjectNode i && input.has("params") && input.get("params").isNull()) {
225 // Workaround for clients that send a null params field instead of omitting it
226 i.remove("params");
227 }
228 JsonRpcRequest request;
229 try {
230 request = objectMapper.treeToValue(input, JsonRpcRequest.class);
231 } catch (JsonMappingException e) {
232 throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
233 e.getMessage(),
234 null));
235 } catch (IOException e) {
236 throw new AssertionError(e);
237 }
238
239 if (!"2.0".equals(request.getJsonrpc())) {
240 throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
241 "only jsonrpc version 2.0 is supported",
242 null));
243 }
244
245 if (request.getMethod() == null) {
246 throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
247 "method field must be set",
248 null));
249 }
250
251 return request;
252 }
253
254 private JsonRpcResponse parseJsonRpcResponse(final JsonNode input) {
255 JsonRpcResponse response;
256 try {
257 response = objectMapper.treeToValue(input, JsonRpcResponse.class);
258 } catch (JsonParseException | JsonMappingException e) {
259 logger.debug("Received invalid jsonrpc response {}", e.getMessage());
260 return null;
261 } catch (IOException e) {
262 throw new AssertionError(e);
263 }
264
265 if (!"2.0".equals(response.getJsonrpc())) {
266 logger.debug("Received invalid jsonrpc response with invalid version {}", response.getJsonrpc());
267 return null;
268 }
269
270 if (response.getResult() != null && response.getError() != null) {
271 logger.debug("Received invalid jsonrpc response with both result and error");
272 return null;
273 }
274
275 if (response.getResult() == null && response.getError() == null) {
276 logger.debug("Received invalid jsonrpc response without result and error");
277 return null;
278 }
279
280 if (response.getId() == null || response.getId().isNull()) {
281 logger.debug("Received invalid jsonrpc response without id");
282 return null;
283 }
284
285 return response;
286 }
287
288 public interface RequestHandler {
289
290 JsonNode apply(String method, ContainerNode<?> params) throws JsonRpcException;
291 }
292 }