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
.util
.Util
;
17 import org
.slf4j
.Logger
;
18 import org
.slf4j
.LoggerFactory
;
20 import java
.io
.IOException
;
21 import java
.net
.InetSocketAddress
;
22 import java
.util
.List
;
24 import java
.util
.concurrent
.Executors
;
25 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
27 public class HttpServerHandler
implements AutoCloseable
{
29 private final static Logger logger
= LoggerFactory
.getLogger(HttpServerHandler
.class);
31 private final ObjectMapper objectMapper
= Util
.createJsonObjectMapper();
33 private final InetSocketAddress address
;
35 private final SignalJsonRpcCommandHandler commandHandler
;
36 private final MultiAccountManager c
;
37 private final Manager m
;
38 private HttpServer server
;
39 private final AtomicBoolean shutdown
= new AtomicBoolean(false);
41 public HttpServerHandler(final InetSocketAddress address
, final Manager m
) {
42 this.address
= address
;
43 commandHandler
= new SignalJsonRpcCommandHandler(m
, Commands
::getCommand
);
48 public HttpServerHandler(final InetSocketAddress address
, final MultiAccountManager c
) {
49 this.address
= address
;
50 commandHandler
= new SignalJsonRpcCommandHandler(c
, Commands
::getCommand
);
55 public void init() throws IOException
{
57 throw new AssertionError("HttpServerHandler already initialized");
59 logger
.info("Starting server on " + address
.toString());
61 server
= HttpServer
.create(address
, 0);
62 server
.setExecutor(Executors
.newCachedThreadPool());
64 server
.createContext("/api/v1/rpc", this::handleRpcEndpoint
);
65 server
.createContext("/api/v1/events", this::handleEventsEndpoint
);
66 server
.createContext("/api/v1/check", this::handleCheckEndpoint
);
71 private void sendResponse(int status
, Object response
, HttpExchange httpExchange
) throws IOException
{
72 if (response
!= null) {
73 final var byteResponse
= objectMapper
.writeValueAsBytes(response
);
75 httpExchange
.getResponseHeaders().add("Content-Type", "application/json");
76 httpExchange
.sendResponseHeaders(status
, byteResponse
.length
);
78 httpExchange
.getResponseBody().write(byteResponse
);
80 httpExchange
.sendResponseHeaders(status
, -1);
83 httpExchange
.getResponseBody().close();
86 private void handleRpcEndpoint(HttpExchange httpExchange
) throws IOException
{
87 if (!"/api/v1/rpc".equals(httpExchange
.getRequestURI().getPath())) {
88 sendResponse(404, null, httpExchange
);
91 if (!"POST".equals(httpExchange
.getRequestMethod())) {
92 sendResponse(405, null, httpExchange
);
96 final var contentType
= httpExchange
.getRequestHeaders().getFirst("Content-Type");
97 if (contentType
== null || !contentType
.startsWith("application/json")) {
98 sendResponse(415, null, httpExchange
);
104 final Object
[] result
= {null};
105 final var jsonRpcSender
= new JsonRpcSender(s
-> {
106 if (result
[0] != null) {
107 throw new AssertionError("There should only be a single JSON-RPC response");
113 final var jsonRpcReader
= new JsonRpcReader(jsonRpcSender
, httpExchange
.getRequestBody());
114 jsonRpcReader
.readMessages((method
, params
) -> commandHandler
.handleRequest(objectMapper
, method
, params
),
115 response
-> logger
.debug("Received unexpected response for id {}", response
.getId()));
117 if (result
[0] != null) {
118 sendResponse(200, result
[0], httpExchange
);
120 sendResponse(201, null, httpExchange
);
123 } catch (Throwable aEx
) {
124 logger
.error("Failed to process request.", aEx
);
126 JsonRpcResponse
.forError(new JsonRpcResponse
.Error(JsonRpcResponse
.Error
.INTERNAL_ERROR
,
127 "An internal server error has occurred.",
133 private void handleEventsEndpoint(HttpExchange httpExchange
) throws IOException
{
134 if (!"/api/v1/events".equals(httpExchange
.getRequestURI().getPath())) {
135 sendResponse(404, null, httpExchange
);
138 if (!"GET".equals(httpExchange
.getRequestMethod())) {
139 sendResponse(405, null, httpExchange
);
144 final var queryString
= httpExchange
.getRequestURI().getQuery();
145 final var query
= queryString
== null ? Map
.<String
, String
>of() : Util
.getQueryMap(queryString
);
147 List
<Manager
> managers
= getManagerFromQuery(query
);
148 if (managers
== null) {
149 sendResponse(400, null, httpExchange
);
153 httpExchange
.getResponseHeaders().add("Content-Type", "text/event-stream");
154 httpExchange
.sendResponseHeaders(200, 0);
155 final var sender
= new ServerSentEventSender(httpExchange
.getResponseBody());
157 final var shouldStop
= new AtomicBoolean(false);
158 final var handlers
= subscribeReceiveHandlers(managers
, sender
, () -> {
159 shouldStop
.set(true);
160 synchronized (this) {
167 synchronized (this) {
170 if (shouldStop
.get() || shutdown
.get()) {
175 sender
.sendKeepAlive();
176 } catch (IOException e
) {
181 for (final var pair
: handlers
) {
182 unsubscribeReceiveHandler(pair
);
185 httpExchange
.getResponseBody().close();
186 } catch (IOException ignored
) {
189 } catch (Throwable aEx
) {
190 logger
.error("Failed to process request.", aEx
);
191 sendResponse(500, null, httpExchange
);
195 private void handleCheckEndpoint(HttpExchange httpExchange
) throws IOException
{
196 if (!"/api/v1/check".equals(httpExchange
.getRequestURI().getPath())) {
197 sendResponse(404, null, httpExchange
);
200 if (!"GET".equals(httpExchange
.getRequestMethod())) {
201 sendResponse(405, null, httpExchange
);
205 sendResponse(200, null, httpExchange
);
208 private List
<Manager
> getManagerFromQuery(final Map
<String
, String
> query
) {
213 final var account
= query
.get("account");
214 if (account
== null || account
.isEmpty()) {
215 return c
.getManagers();
217 final var manager
= c
.getManager(account
);
218 if (manager
== null) {
221 return List
.of(manager
);
227 private List
<Pair
<Manager
, Manager
.ReceiveMessageHandler
>> subscribeReceiveHandlers(
228 final List
<Manager
> managers
, final ServerSentEventSender sender
, Callable unsubscribe
230 return managers
.stream().map(m1
-> {
231 final var receiveMessageHandler
= new JsonReceiveMessageHandler(m1
, s
-> {
233 sender
.sendEvent(null, "receive", List
.of(objectMapper
.writeValueAsString(s
)));
234 } catch (IOException e
) {
238 m1
.addReceiveHandler(receiveMessageHandler
);
239 return new Pair
<>(m1
, (Manager
.ReceiveMessageHandler
) receiveMessageHandler
);
243 private void unsubscribeReceiveHandler(final Pair
<Manager
, Manager
.ReceiveMessageHandler
> pair
) {
244 final var m
= pair
.first();
245 final var handler
= pair
.second();
246 m
.removeReceiveHandler(handler
);
250 public void close() {
251 if (server
!= null) {
253 synchronized (this) {
256 // Increase this delay when https://bugs.openjdk.org/browse/JDK-8304065 is fixed
263 private interface Callable
{