1 package org
.asamk
.signal
.jsonrpc
;
3 import com
.fasterxml
.jackson
.core
.TreeNode
;
4 import com
.fasterxml
.jackson
.core
.type
.TypeReference
;
5 import com
.fasterxml
.jackson
.databind
.JsonMappingException
;
6 import com
.fasterxml
.jackson
.databind
.JsonNode
;
7 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
8 import com
.fasterxml
.jackson
.databind
.node
.ArrayNode
;
9 import com
.fasterxml
.jackson
.databind
.node
.ContainerNode
;
10 import com
.fasterxml
.jackson
.databind
.node
.IntNode
;
11 import com
.fasterxml
.jackson
.databind
.node
.ObjectNode
;
13 import org
.asamk
.signal
.commands
.Command
;
14 import org
.asamk
.signal
.commands
.Commands
;
15 import org
.asamk
.signal
.commands
.JsonRpcMultiCommand
;
16 import org
.asamk
.signal
.commands
.JsonRpcRegistrationCommand
;
17 import org
.asamk
.signal
.commands
.JsonRpcSingleCommand
;
18 import org
.asamk
.signal
.commands
.exceptions
.CommandException
;
19 import org
.asamk
.signal
.commands
.exceptions
.IOErrorException
;
20 import org
.asamk
.signal
.commands
.exceptions
.UntrustedKeyErrorException
;
21 import org
.asamk
.signal
.commands
.exceptions
.UserErrorException
;
22 import org
.asamk
.signal
.json
.JsonReceiveMessageHandler
;
23 import org
.asamk
.signal
.manager
.Manager
;
24 import org
.asamk
.signal
.manager
.MultiAccountManager
;
25 import org
.asamk
.signal
.manager
.RegistrationManager
;
26 import org
.asamk
.signal
.manager
.api
.Pair
;
27 import org
.asamk
.signal
.output
.JsonWriter
;
28 import org
.asamk
.signal
.util
.Util
;
29 import org
.slf4j
.Logger
;
30 import org
.slf4j
.LoggerFactory
;
32 import java
.io
.IOException
;
33 import java
.nio
.channels
.OverlappingFileLockException
;
34 import java
.util
.HashMap
;
35 import java
.util
.List
;
37 import java
.util
.concurrent
.atomic
.AtomicInteger
;
38 import java
.util
.function
.Supplier
;
40 public class SignalJsonRpcDispatcherHandler
{
42 private final static Logger logger
= LoggerFactory
.getLogger(SignalJsonRpcDispatcherHandler
.class);
44 private static final int USER_ERROR
= -1;
45 private static final int IO_ERROR
= -3;
46 private static final int UNTRUSTED_KEY_ERROR
= -4;
48 private final ObjectMapper objectMapper
;
49 private final JsonRpcSender jsonRpcSender
;
50 private final JsonRpcReader jsonRpcReader
;
51 private final boolean noReceiveOnStart
;
53 private MultiAccountManager c
;
54 private final Map
<Integer
, List
<Pair
<Manager
, Manager
.ReceiveMessageHandler
>>> receiveHandlers
= new HashMap
<>();
58 public SignalJsonRpcDispatcherHandler(
59 final JsonWriter jsonWriter
, final Supplier
<String
> lineSupplier
, final boolean noReceiveOnStart
61 this.noReceiveOnStart
= noReceiveOnStart
;
62 this.objectMapper
= Util
.createJsonObjectMapper();
63 this.jsonRpcSender
= new JsonRpcSender(jsonWriter
);
64 this.jsonRpcReader
= new JsonRpcReader(jsonRpcSender
, lineSupplier
);
67 public void handleConnection(final MultiAccountManager c
) {
70 if (!noReceiveOnStart
) {
71 this.subscribeReceive(c
.getManagers());
72 c
.addOnManagerAddedHandler(this::subscribeReceive
);
73 c
.addOnManagerRemovedHandler(this::unsubscribeReceive
);
79 public void handleConnection(final Manager m
) {
82 if (!noReceiveOnStart
) {
86 final var currentThread
= Thread
.currentThread();
87 m
.addClosedListener(currentThread
::interrupt
);
92 private static final AtomicInteger nextSubscriptionId
= new AtomicInteger(0);
94 private int subscribeReceive(final Manager manager
) {
95 return subscribeReceive(List
.of(manager
));
98 private int subscribeReceive(final List
<Manager
> managers
) {
99 final var subscriptionId
= nextSubscriptionId
.getAndIncrement();
100 final var handlers
= managers
.stream().map(m
-> {
101 final var receiveMessageHandler
= new JsonReceiveMessageHandler(m
, s
-> {
102 final ContainerNode
<?
> params
= objectMapper
.valueToTree(s
);
103 ((ObjectNode
) params
).set("subscription", IntNode
.valueOf(subscriptionId
));
104 jsonRpcSender
.sendRequest(JsonRpcRequest
.forNotification("receive", params
, null));
106 m
.addReceiveHandler(receiveMessageHandler
);
107 return new Pair
<>(m
, (Manager
.ReceiveMessageHandler
) receiveMessageHandler
);
109 receiveHandlers
.put(subscriptionId
, handlers
);
111 return subscriptionId
;
114 private boolean unsubscribeReceive(final int subscriptionId
) {
115 final var handlers
= receiveHandlers
.remove(subscriptionId
);
116 if (handlers
== null) {
119 for (final var pair
: handlers
) {
120 unsubscribeReceiveHandler(pair
);
125 private void unsubscribeReceive(final Manager m
) {
126 final var subscriptionId
= receiveHandlers
.entrySet()
128 .filter(e
-> e
.getValue().size() == 1 && e
.getValue().get(0).first().equals(m
))
129 .map(Map
.Entry
::getKey
)
131 subscriptionId
.ifPresent(this::unsubscribeReceive
);
134 private void handleConnection() {
136 jsonRpcReader
.readMessages((method
, params
) -> handleRequest(objectMapper
, method
, params
),
137 response
-> logger
.debug("Received unexpected response for id {}", response
.getId()));
139 receiveHandlers
.forEach((_subscriptionId
, handlers
) -> handlers
.forEach(this::unsubscribeReceiveHandler
));
140 receiveHandlers
.clear();
144 private void unsubscribeReceiveHandler(final Pair
<Manager
, Manager
.ReceiveMessageHandler
> pair
) {
145 final var m
= pair
.first();
146 final var handler
= pair
.second();
147 m
.removeReceiveHandler(handler
);
150 private JsonNode
handleRequest(
151 final ObjectMapper objectMapper
, final String method
, ContainerNode
<?
> params
152 ) throws JsonRpcException
{
153 var command
= getCommand(method
);
155 if (command
instanceof JsonRpcSingleCommand
<?
> jsonRpcCommand
) {
156 final var manager
= getManagerFromParams(params
);
157 if (manager
!= null) {
158 return runCommand(objectMapper
, params
, new CommandRunnerImpl
<>(manager
, jsonRpcCommand
));
161 if (command
instanceof JsonRpcMultiCommand
<?
> jsonRpcCommand
) {
162 return runCommand(objectMapper
, params
, new MultiCommandRunnerImpl
<>(c
, jsonRpcCommand
));
164 if (command
instanceof JsonRpcRegistrationCommand
<?
> jsonRpcCommand
) {
165 try (var manager
= getRegistrationManagerFromParams(params
)) {
166 if (manager
!= null) {
167 return runCommand(objectMapper
,
169 new RegistrationCommandRunnerImpl
<>(manager
, c
, jsonRpcCommand
));
171 throw new JsonRpcException(new JsonRpcResponse
.Error(JsonRpcResponse
.Error
.INVALID_PARAMS
,
172 "Method requires valid account parameter",
175 } catch (IOException e
) {
176 logger
.warn("Failed to close registration manager", e
);
180 if (command
instanceof JsonRpcSingleCommand
<?
> jsonRpcCommand
) {
182 return runCommand(objectMapper
, params
, new CommandRunnerImpl
<>(m
, jsonRpcCommand
));
185 final var manager
= getManagerFromParams(params
);
186 if (manager
!= null) {
187 return runCommand(objectMapper
, params
, new CommandRunnerImpl
<>(manager
, jsonRpcCommand
));
189 throw new JsonRpcException(new JsonRpcResponse
.Error(JsonRpcResponse
.Error
.INVALID_PARAMS
,
190 "Method requires valid account parameter",
195 throw new JsonRpcException(new JsonRpcResponse
.Error(JsonRpcResponse
.Error
.METHOD_NOT_FOUND
,
196 "Method not implemented",
200 private Manager
getManagerFromParams(final ContainerNode
<?
> params
) throws JsonRpcException
{
201 if (params
!= null && params
.hasNonNull("account")) {
202 final var manager
= c
.getManager(params
.get("account").asText());
203 ((ObjectNode
) params
).remove("account");
204 if (manager
== null) {
205 throw new JsonRpcException(new JsonRpcResponse
.Error(JsonRpcResponse
.Error
.INVALID_PARAMS
,
206 "Specified account does not exist",
214 private RegistrationManager
getRegistrationManagerFromParams(final ContainerNode
<?
> params
) {
215 if (params
!= null && params
.has("account")) {
217 final var registrationManager
= c
.getNewRegistrationManager(params
.get("account").asText());
218 ((ObjectNode
) params
).remove("account");
219 return registrationManager
;
220 } catch (OverlappingFileLockException e
) {
221 logger
.warn("Account is already in use");
223 } catch (IOException
| IllegalStateException e
) {
224 logger
.warn("Failed to load registration manager", e
);
231 private Command
getCommand(final String method
) {
232 if ("subscribeReceive".equals(method
)) {
233 return new SubscribeReceiveCommand();
235 if ("unsubscribeReceive".equals(method
)) {
236 return new UnsubscribeReceiveCommand();
238 return Commands
.getCommand(method
);
241 private record CommandRunnerImpl
<T
>(Manager m
, JsonRpcSingleCommand
<T
> command
) implements CommandRunner
<T
> {
244 public void handleCommand(final T request
, final JsonWriter jsonWriter
) throws CommandException
{
245 command
.handleCommand(request
, m
, jsonWriter
);
249 public TypeReference
<T
> getRequestType() {
250 return command
.getRequestType();
254 private record RegistrationCommandRunnerImpl
<T
>(
255 RegistrationManager m
, MultiAccountManager c
, JsonRpcRegistrationCommand
<T
> command
256 ) implements CommandRunner
<T
> {
259 public void handleCommand(final T request
, final JsonWriter jsonWriter
) throws CommandException
{
260 command
.handleCommand(request
, m
, jsonWriter
);
264 public TypeReference
<T
> getRequestType() {
265 return command
.getRequestType();
269 private record MultiCommandRunnerImpl
<T
>(
270 MultiAccountManager c
, JsonRpcMultiCommand
<T
> command
271 ) implements CommandRunner
<T
> {
274 public void handleCommand(final T request
, final JsonWriter jsonWriter
) throws CommandException
{
275 command
.handleCommand(request
, c
, jsonWriter
);
279 public TypeReference
<T
> getRequestType() {
280 return command
.getRequestType();
284 interface CommandRunner
<T
> {
286 void handleCommand(T request
, JsonWriter jsonWriter
) throws CommandException
;
288 TypeReference
<T
> getRequestType();
291 private JsonNode
runCommand(
292 final ObjectMapper objectMapper
, final ContainerNode
<?
> params
, final CommandRunner
<?
> command
293 ) throws JsonRpcException
{
294 final Object
[] result
= {null};
295 final JsonWriter commandJsonWriter
= s
-> {
296 if (result
[0] != null) {
297 throw new AssertionError("Command may only write one json result");
304 parseParamsAndRunCommand(objectMapper
, params
, commandJsonWriter
, command
);
305 } catch (JsonMappingException e
) {
306 throw new JsonRpcException(new JsonRpcResponse
.Error(JsonRpcResponse
.Error
.INVALID_REQUEST
,
309 } catch (UserErrorException e
) {
310 throw new JsonRpcException(new JsonRpcResponse
.Error(USER_ERROR
,
312 getErrorDataNode(objectMapper
, result
)));
313 } catch (IOErrorException e
) {
314 throw new JsonRpcException(new JsonRpcResponse
.Error(IO_ERROR
,
316 getErrorDataNode(objectMapper
, result
)));
317 } catch (UntrustedKeyErrorException e
) {
318 throw new JsonRpcException(new JsonRpcResponse
.Error(UNTRUSTED_KEY_ERROR
,
320 getErrorDataNode(objectMapper
, result
)));
321 } catch (Throwable e
) {
322 logger
.error("Command execution failed", e
);
323 throw new JsonRpcException(new JsonRpcResponse
.Error(JsonRpcResponse
.Error
.INTERNAL_ERROR
,
325 getErrorDataNode(objectMapper
, result
)));
328 Object output
= result
[0] == null ? Map
.of() : result
[0];
329 return objectMapper
.valueToTree(output
);
332 private JsonNode
getErrorDataNode(final ObjectMapper objectMapper
, final Object
[] result
) {
333 if (result
[0] == null) {
336 return objectMapper
.valueToTree(Map
.of("response", result
[0]));
339 private <T
> void parseParamsAndRunCommand(
340 final ObjectMapper objectMapper
,
341 final TreeNode params
,
342 final JsonWriter jsonWriter
,
343 final CommandRunner
<T
> command
344 ) throws CommandException
, JsonMappingException
{
345 T requestParams
= null;
346 final var requestType
= command
.getRequestType();
347 if (params
!= null && requestType
!= null) {
349 requestParams
= objectMapper
.readValue(objectMapper
.treeAsTokens(params
), requestType
);
350 } catch (JsonMappingException e
) {
352 } catch (IOException e
) {
353 throw new AssertionError(e
);
356 command
.handleCommand(requestParams
, jsonWriter
);
359 private class SubscribeReceiveCommand
implements JsonRpcSingleCommand
<Void
>, JsonRpcMultiCommand
<Void
> {
362 public String
getName() {
363 return "subscribeReceive";
367 public void handleCommand(
368 final Void request
, final Manager m
, final JsonWriter jsonWriter
369 ) throws CommandException
{
370 final var subscriptionId
= subscribeReceive(m
);
371 jsonWriter
.write(subscriptionId
);
375 public void handleCommand(
376 final Void request
, final MultiAccountManager c
, final JsonWriter jsonWriter
377 ) throws CommandException
{
378 final var subscriptionId
= subscribeReceive(c
.getManagers());
379 jsonWriter
.write(subscriptionId
);
383 private class UnsubscribeReceiveCommand
implements JsonRpcSingleCommand
<JsonNode
>, JsonRpcMultiCommand
<JsonNode
> {
386 public String
getName() {
387 return "unsubscribeReceive";
391 public TypeReference
<JsonNode
> getRequestType() {
392 return new TypeReference
<>() {};
396 public void handleCommand(
397 final JsonNode request
, final Manager m
, final JsonWriter jsonWriter
398 ) throws CommandException
{
399 final var subscriptionId
= getSubscriptionId(request
);
400 if (subscriptionId
== null) {
401 unsubscribeReceive(m
);
403 if (!unsubscribeReceive(subscriptionId
)) {
404 throw new UserErrorException("Unknown subscription id");
410 public void handleCommand(
411 final JsonNode request
, final MultiAccountManager c
, final JsonWriter jsonWriter
412 ) throws CommandException
{
413 final var subscriptionId
= getSubscriptionId(request
);
414 if (subscriptionId
== null) {
415 throw new UserErrorException("Missing subscription parameter with subscription id");
417 if (!unsubscribeReceive(subscriptionId
)) {
418 throw new UserErrorException("Unknown subscription id");
423 private Integer
getSubscriptionId(final JsonNode request
) {
424 if (request
instanceof ArrayNode req
) {
425 return req
.get(0).asInt();
426 } else if (request
instanceof ObjectNode req
) {
427 return req
.get("subscription").asInt();