]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/jsonrpc/JsonRpcReader.java
Make deviceId an int
[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.util.Objects;
17 import java.util.function.Consumer;
18 import java.util.function.Supplier;
19 import java.util.stream.StreamSupport;
20
21 public class JsonRpcReader {
22
23 private final static Logger logger = LoggerFactory.getLogger(JsonRpcReader.class);
24
25 private final JsonRpcSender jsonRpcSender;
26 private final ObjectMapper objectMapper;
27 private final Supplier<String> lineSupplier;
28
29 public JsonRpcReader(
30 final JsonRpcSender jsonRpcSender, final Supplier<String> lineSupplier
31 ) {
32 this.jsonRpcSender = jsonRpcSender;
33 this.lineSupplier = lineSupplier;
34 this.objectMapper = Util.createJsonObjectMapper();
35 }
36
37 public void readMessages(final RequestHandler requestHandler, final Consumer<JsonRpcResponse> responseHandler) {
38 while (!Thread.interrupted()) {
39 JsonRpcMessage message = readMessage();
40 if (message == null) break;
41
42 if (message instanceof final JsonRpcRequest jsonRpcRequest) {
43 logger.debug("Received json rpc request, method: " + jsonRpcRequest.getMethod());
44 final var response = handleRequest(requestHandler, jsonRpcRequest);
45 if (response != null) {
46 jsonRpcSender.sendResponse(response);
47 }
48 } else if (message instanceof JsonRpcResponse jsonRpcResponse) {
49 responseHandler.accept(jsonRpcResponse);
50 } else {
51 final var responseList = ((JsonRpcBatchMessage) message).getMessages().stream().map(jsonNode -> {
52 final JsonRpcRequest request;
53 try {
54 request = parseJsonRpcRequest(jsonNode);
55 } catch (JsonRpcException e) {
56 return JsonRpcResponse.forError(e.getError(), getId(jsonNode));
57 }
58
59 return handleRequest(requestHandler, request);
60 }).filter(Objects::nonNull).toList();
61
62 jsonRpcSender.sendBatchResponses(responseList);
63 }
64 }
65 }
66
67 private JsonRpcResponse handleRequest(final RequestHandler requestHandler, final JsonRpcRequest request) {
68 try {
69 final var result = requestHandler.apply(request.getMethod(), request.getParams());
70 if (request.getId() != null) {
71 return JsonRpcResponse.forSuccess(result, request.getId());
72 } else {
73 logger.debug("Command '{}' succeeded but client didn't specify an id, dropping response",
74 request.getMethod());
75 }
76 } catch (JsonRpcException e) {
77 if (request.getId() != null) {
78 return JsonRpcResponse.forError(e.getError(), request.getId());
79 } else {
80 logger.debug("Command '{}' failed but client didn't specify an id, dropping error: {}",
81 request.getMethod(),
82 e.getMessage());
83 }
84 }
85 return null;
86 }
87
88 private JsonRpcMessage readMessage() {
89 while (!Thread.interrupted()) {
90 String input = lineSupplier.get();
91
92 if (input == null) {
93 // Reached end of input stream
94 break;
95 }
96
97 JsonRpcMessage message = parseJsonRpcMessage(input);
98 if (message == null) continue;
99
100 return message;
101 }
102
103 return null;
104 }
105
106 private JsonRpcMessage parseJsonRpcMessage(final String input) {
107 final JsonNode jsonNode;
108 try {
109 jsonNode = objectMapper.readTree(input);
110 } catch (JsonParseException e) {
111 jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.PARSE_ERROR,
112 e.getMessage(),
113 null), null));
114 return null;
115 } catch (IOException e) {
116 throw new AssertionError(e);
117 }
118
119 if (jsonNode == null) {
120 jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
121 "invalid request",
122 null), null));
123 return null;
124 } else if (jsonNode.isArray()) {
125 if (jsonNode.size() == 0) {
126 jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
127 "invalid request",
128 null), null));
129 return null;
130 }
131 return new JsonRpcBatchMessage(StreamSupport.stream(jsonNode.spliterator(), false).toList());
132 } else if (jsonNode.isObject()) {
133 if (jsonNode.has("result") || jsonNode.has("error")) {
134 return parseJsonRpcResponse(jsonNode);
135 } else {
136 try {
137 return parseJsonRpcRequest(jsonNode);
138 } catch (JsonRpcException e) {
139 jsonRpcSender.sendResponse(JsonRpcResponse.forError(e.getError(), getId(jsonNode)));
140 return null;
141 }
142 }
143 } else {
144 jsonRpcSender.sendResponse(JsonRpcResponse.forError(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
145 "unexpected type: " + jsonNode.getNodeType().name(),
146 null), null));
147 return null;
148 }
149 }
150
151 private ValueNode getId(JsonNode jsonNode) {
152 final var id = jsonNode.get("id");
153 return id instanceof ValueNode ? (ValueNode) id : null;
154 }
155
156 private JsonRpcRequest parseJsonRpcRequest(final JsonNode input) throws JsonRpcException {
157 if (input instanceof ObjectNode i && input.has("params") && input.get("params").isNull()) {
158 // Workaround for clients that send a null params field instead of omitting it
159 i.remove("params");
160 }
161 JsonRpcRequest request;
162 try {
163 request = objectMapper.treeToValue(input, JsonRpcRequest.class);
164 } catch (JsonMappingException e) {
165 throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
166 e.getMessage(),
167 null));
168 } catch (IOException e) {
169 throw new AssertionError(e);
170 }
171
172 if (!"2.0".equals(request.getJsonrpc())) {
173 throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
174 "only jsonrpc version 2.0 is supported",
175 null));
176 }
177
178 if (request.getMethod() == null) {
179 throw new JsonRpcException(new JsonRpcResponse.Error(JsonRpcResponse.Error.INVALID_REQUEST,
180 "method field must be set",
181 null));
182 }
183
184 return request;
185 }
186
187 private JsonRpcResponse parseJsonRpcResponse(final JsonNode input) {
188 JsonRpcResponse response;
189 try {
190 response = objectMapper.treeToValue(input, JsonRpcResponse.class);
191 } catch (JsonParseException | JsonMappingException e) {
192 logger.debug("Received invalid jsonrpc response {}", e.getMessage());
193 return null;
194 } catch (IOException e) {
195 throw new AssertionError(e);
196 }
197
198 if (!"2.0".equals(response.getJsonrpc())) {
199 logger.debug("Received invalid jsonrpc response with invalid version {}", response.getJsonrpc());
200 return null;
201 }
202
203 if (response.getResult() != null && response.getError() != null) {
204 logger.debug("Received invalid jsonrpc response with both result and error");
205 return null;
206 }
207
208 if (response.getResult() == null && response.getError() == null) {
209 logger.debug("Received invalid jsonrpc response without result and error");
210 return null;
211 }
212
213 if (response.getId() == null || response.getId().isNull()) {
214 logger.debug("Received invalid jsonrpc response without id");
215 return null;
216 }
217
218 return response;
219 }
220
221 public interface RequestHandler {
222
223 JsonNode apply(String method, ContainerNode<?> params) throws JsonRpcException;
224 }
225 }