1 package org
.asamk
.signal
.http
;
3 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
4 import com
.sun
.net
.httpserver
.HttpExchange
;
5 import com
.sun
.net
.httpserver
.HttpServer
;
7 import org
.asamk
.signal
.commands
.Commands
;
8 import org
.asamk
.signal
.json
.JsonReceiveMessageHandler
;
9 import org
.asamk
.signal
.jsonrpc
.JsonRpcReader
;
10 import org
.asamk
.signal
.jsonrpc
.JsonRpcResponse
;
11 import org
.asamk
.signal
.jsonrpc
.JsonRpcSender
;
12 import org
.asamk
.signal
.jsonrpc
.SignalJsonRpcCommandHandler
;
13 import org
.asamk
.signal
.manager
.Manager
;
14 import org
.asamk
.signal
.manager
.MultiAccountManager
;
15 import org
.asamk
.signal
.manager
.api
.Pair
;
16 import org
.asamk
.signal
.manager
.util
.Utils
;
17 import org
.asamk
.signal
.util
.Util
;
18 import org
.slf4j
.Logger
;
19 import org
.slf4j
.LoggerFactory
;
21 import java
.io
.IOException
;
22 import java
.net
.InetSocketAddress
;
23 import java
.util
.List
;
25 import java
.util
.concurrent
.Executors
;
26 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
28 public class HttpServerHandler
{
30 private final static Logger logger
= LoggerFactory
.getLogger(HttpServerHandler
.class);
32 private final ObjectMapper objectMapper
= Util
.createJsonObjectMapper();
34 private final InetSocketAddress address
;
36 private final SignalJsonRpcCommandHandler commandHandler
;
37 private final MultiAccountManager c
;
38 private final Manager m
;
40 public HttpServerHandler(final InetSocketAddress address
, final Manager m
) {
41 this.address
= address
;
42 commandHandler
= new SignalJsonRpcCommandHandler(m
, Commands
::getCommand
);
47 public HttpServerHandler(final InetSocketAddress address
, final MultiAccountManager c
) {
48 this.address
= address
;
49 commandHandler
= new SignalJsonRpcCommandHandler(c
, Commands
::getCommand
);
54 public void init() throws IOException
{
55 logger
.info("Starting server on " + address
.toString());
57 final var server
= HttpServer
.create(address
, 0);
58 server
.setExecutor(Executors
.newFixedThreadPool(10));
60 server
.createContext("/api/v1/rpc", this::handleRpcEndpoint
);
61 server
.createContext("/api/v1/events", this::handleEventsEndpoint
);
62 server
.createContext("/api/v1/check", this::handleCheckEndpoint
);
67 private void sendResponse(int status
, Object response
, HttpExchange httpExchange
) throws IOException
{
68 if (response
!= null) {
69 final var byteResponse
= objectMapper
.writeValueAsBytes(response
);
71 httpExchange
.getResponseHeaders().add("Content-Type", "application/json");
72 httpExchange
.sendResponseHeaders(status
, byteResponse
.length
);
74 httpExchange
.getResponseBody().write(byteResponse
);
76 httpExchange
.sendResponseHeaders(status
, -1);
79 httpExchange
.getResponseBody().close();
82 private void handleRpcEndpoint(HttpExchange httpExchange
) throws IOException
{
83 if (!"/api/v1/rpc".equals(httpExchange
.getRequestURI().getPath())) {
84 sendResponse(404, null, httpExchange
);
87 if (!"POST".equals(httpExchange
.getRequestMethod())) {
88 sendResponse(405, null, httpExchange
);
92 final var contentType
= httpExchange
.getRequestHeaders().getFirst("Content-Type");
93 if (contentType
== null || !contentType
.startsWith("application/json")) {
94 sendResponse(415, null, httpExchange
);
100 final Object
[] result
= {null};
101 final var jsonRpcSender
= new JsonRpcSender(s
-> {
102 if (result
[0] != null) {
103 throw new AssertionError("There should only be a single JSON-RPC response");
109 final var jsonRpcReader
= new JsonRpcReader(jsonRpcSender
, httpExchange
.getRequestBody());
110 jsonRpcReader
.readMessages((method
, params
) -> commandHandler
.handleRequest(objectMapper
, method
, params
),
111 response
-> logger
.debug("Received unexpected response for id {}", response
.getId()));
113 if (result
[0] != null) {
114 sendResponse(200, result
[0], httpExchange
);
116 sendResponse(201, null, httpExchange
);
119 } catch (Throwable aEx
) {
120 logger
.error("Failed to process request.", aEx
);
122 JsonRpcResponse
.forError(new JsonRpcResponse
.Error(JsonRpcResponse
.Error
.INTERNAL_ERROR
,
123 "An internal server error has occurred.",
129 private void handleEventsEndpoint(HttpExchange httpExchange
) throws IOException
{
130 if (!"/api/v1/events".equals(httpExchange
.getRequestURI().getPath())) {
131 sendResponse(404, null, httpExchange
);
134 if (!"GET".equals(httpExchange
.getRequestMethod())) {
135 sendResponse(405, null, httpExchange
);
140 final var queryString
= httpExchange
.getRequestURI().getQuery();
141 final var query
= queryString
== null ? Map
.<String
, String
>of() : Utils
.getQueryMap(queryString
);
143 List
<Manager
> managers
= getManagerFromQuery(query
);
144 if (managers
== null) {
145 sendResponse(400, null, httpExchange
);
149 httpExchange
.getResponseHeaders().add("Content-Type", "text/event-stream");
150 httpExchange
.sendResponseHeaders(200, 0);
151 final var sender
= new ServerSentEventSender(httpExchange
.getResponseBody());
153 final var shouldStop
= new AtomicBoolean(false);
154 final var handlers
= subscribeReceiveHandlers(managers
, sender
, () -> {
155 shouldStop
.set(true);
156 synchronized (this) {
163 synchronized (this) {
166 if (shouldStop
.get()) {
171 sender
.sendKeepAlive();
172 } catch (IOException e
) {
177 for (final var pair
: handlers
) {
178 unsubscribeReceiveHandler(pair
);
181 httpExchange
.getResponseBody().close();
182 } catch (IOException ignored
) {
185 } catch (Throwable aEx
) {
186 logger
.error("Failed to process request.", aEx
);
187 sendResponse(500, null, httpExchange
);
191 private void handleCheckEndpoint(HttpExchange httpExchange
) throws IOException
{
192 if (!"/api/v1/check".equals(httpExchange
.getRequestURI().getPath())) {
193 sendResponse(404, null, httpExchange
);
196 if (!"GET".equals(httpExchange
.getRequestMethod())) {
197 sendResponse(405, null, httpExchange
);
201 sendResponse(200, null, httpExchange
);
204 private List
<Manager
> getManagerFromQuery(final Map
<String
, String
> query
) {
205 List
<Manager
> managers
;
207 managers
= List
.of(m
);
209 final var account
= query
.get("account");
210 if (account
== null || account
.isEmpty()) {
211 managers
= c
.getManagers();
213 final var manager
= c
.getManager(account
);
214 if (manager
== null) {
217 managers
= List
.of(manager
);
223 private List
<Pair
<Manager
, Manager
.ReceiveMessageHandler
>> subscribeReceiveHandlers(
224 final List
<Manager
> managers
, final ServerSentEventSender sender
, Callable unsubscribe
226 return managers
.stream().map(m1
-> {
227 final var receiveMessageHandler
= new JsonReceiveMessageHandler(m1
, s
-> {
229 sender
.sendEvent(null, "receive", List
.of(objectMapper
.writeValueAsString(s
)));
230 } catch (IOException e
) {
234 m1
.addReceiveHandler(receiveMessageHandler
);
235 return new Pair
<>(m1
, (Manager
.ReceiveMessageHandler
) receiveMessageHandler
);
239 private void unsubscribeReceiveHandler(final Pair
<Manager
, Manager
.ReceiveMessageHandler
> pair
) {
240 final var m
= pair
.first();
241 final var handler
= pair
.second();
242 m
.removeReceiveHandler(handler
);
245 private interface Callable
{