1 package org
.asamk
.signal
.commands
;
3 import net
.sourceforge
.argparse4j
.impl
.Arguments
;
4 import net
.sourceforge
.argparse4j
.inf
.Namespace
;
5 import net
.sourceforge
.argparse4j
.inf
.Subparser
;
7 import org
.asamk
.signal
.DbusConfig
;
8 import org
.asamk
.signal
.OutputType
;
9 import org
.asamk
.signal
.ReceiveMessageHandler
;
10 import org
.asamk
.signal
.commands
.exceptions
.CommandException
;
11 import org
.asamk
.signal
.commands
.exceptions
.IOErrorException
;
12 import org
.asamk
.signal
.commands
.exceptions
.UnexpectedErrorException
;
13 import org
.asamk
.signal
.commands
.exceptions
.UserErrorException
;
14 import org
.asamk
.signal
.dbus
.DbusSignalControlImpl
;
15 import org
.asamk
.signal
.dbus
.DbusSignalImpl
;
16 import org
.asamk
.signal
.json
.JsonReceiveMessageHandler
;
17 import org
.asamk
.signal
.jsonrpc
.SignalJsonRpcDispatcherHandler
;
18 import org
.asamk
.signal
.manager
.Manager
;
19 import org
.asamk
.signal
.manager
.MultiAccountManager
;
20 import org
.asamk
.signal
.manager
.api
.ReceiveConfig
;
21 import org
.asamk
.signal
.output
.JsonWriter
;
22 import org
.asamk
.signal
.output
.JsonWriterImpl
;
23 import org
.asamk
.signal
.output
.OutputWriter
;
24 import org
.asamk
.signal
.output
.PlainTextWriter
;
25 import org
.asamk
.signal
.util
.IOUtils
;
26 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnection
;
27 import org
.freedesktop
.dbus
.connections
.impl
.DBusConnectionBuilder
;
28 import org
.freedesktop
.dbus
.exceptions
.DBusException
;
29 import org
.slf4j
.Logger
;
30 import org
.slf4j
.LoggerFactory
;
33 import java
.io
.IOException
;
34 import java
.net
.UnixDomainSocketAddress
;
35 import java
.nio
.channels
.Channel
;
36 import java
.nio
.channels
.Channels
;
37 import java
.nio
.channels
.ServerSocketChannel
;
38 import java
.nio
.channels
.SocketChannel
;
39 import java
.nio
.charset
.StandardCharsets
;
40 import java
.util
.List
;
41 import java
.util
.concurrent
.atomic
.AtomicInteger
;
42 import java
.util
.function
.Consumer
;
44 public class DaemonCommand
implements MultiLocalCommand
, LocalCommand
{
46 private final static Logger logger
= LoggerFactory
.getLogger(DaemonCommand
.class);
49 public String
getName() {
54 public void attachToSubparser(final Subparser subparser
) {
55 final var defaultSocketPath
= new File(new File(IOUtils
.getRuntimeDir(), "signal-cli"), "socket");
56 subparser
.help("Run in daemon mode and provide an experimental dbus or JSON-RPC interface.");
57 subparser
.addArgument("--dbus")
58 .action(Arguments
.storeTrue())
59 .help("Expose a DBus interface on the user bus (the default, if no other options are given).");
60 subparser
.addArgument("--dbus-system", "--system")
61 .action(Arguments
.storeTrue())
62 .help("Expose a DBus interface on the system bus.");
63 subparser
.addArgument("--socket")
66 .setConst(defaultSocketPath
)
67 .help("Expose a JSON-RPC interface on a UNIX socket (default $XDG_RUNTIME_DIR/signal-cli/socket).");
68 subparser
.addArgument("--tcp")
70 .setConst("localhost:7583")
71 .help("Expose a JSON-RPC interface on a TCP socket (default localhost:7583).");
72 subparser
.addArgument("--no-receive-stdout")
73 .help("Don’t print received messages to stdout.")
74 .action(Arguments
.storeTrue());
75 subparser
.addArgument("--receive-mode")
76 .help("Specify when to start receiving messages.")
77 .type(Arguments
.enumStringType(ReceiveMode
.class))
78 .setDefault(ReceiveMode
.ON_START
);
79 subparser
.addArgument("--ignore-attachments")
80 .help("Don’t download attachments of received messages.")
81 .action(Arguments
.storeTrue());
85 public List
<OutputType
> getSupportedOutputTypes() {
86 return List
.of(OutputType
.PLAIN_TEXT
, OutputType
.JSON
);
90 public void handleCommand(
91 final Namespace ns
, final Manager m
, final OutputWriter outputWriter
92 ) throws CommandException
{
93 logger
.info("Starting daemon in single-account mode for " + m
.getSelfNumber());
94 final var noReceiveStdOut
= Boolean
.TRUE
.equals(ns
.getBoolean("no-receive-stdout"));
95 final var receiveMode
= ns
.<ReceiveMode
>get("receive-mode");
96 final var ignoreAttachments
= Boolean
.TRUE
.equals(ns
.getBoolean("ignore-attachments"));
98 m
.setReceiveConfig(new ReceiveConfig(ignoreAttachments
));
99 addDefaultReceiveHandler(m
, noReceiveStdOut ?
null : outputWriter
, receiveMode
!= ReceiveMode
.ON_START
);
101 final Channel inheritedChannel
;
103 inheritedChannel
= System
.inheritedChannel();
104 if (inheritedChannel
instanceof ServerSocketChannel serverChannel
) {
105 logger
.info("Using inherited socket: " + serverChannel
.getLocalAddress());
106 runSocketSingleAccount(m
, serverChannel
, receiveMode
== ReceiveMode
.MANUAL
);
108 } catch (IOException e
) {
109 throw new IOErrorException("Failed to use inherited socket", e
);
111 final var socketFile
= ns
.<File
>get("socket");
112 if (socketFile
!= null) {
113 final var address
= UnixDomainSocketAddress
.of(socketFile
.toPath());
114 final var serverChannel
= IOUtils
.bindSocket(address
);
115 runSocketSingleAccount(m
, serverChannel
, receiveMode
== ReceiveMode
.MANUAL
);
117 final var tcpAddress
= ns
.getString("tcp");
118 if (tcpAddress
!= null) {
119 final var address
= IOUtils
.parseInetSocketAddress(tcpAddress
);
120 final var serverChannel
= IOUtils
.bindSocket(address
);
121 runSocketSingleAccount(m
, serverChannel
, receiveMode
== ReceiveMode
.MANUAL
);
123 final var isDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("dbus-system"));
125 runDbusSingleAccount(m
, true, receiveMode
!= ReceiveMode
.ON_START
);
127 final var isDbusSession
= Boolean
.TRUE
.equals(ns
.getBoolean("dbus"));
128 if (isDbusSession
|| (
130 && socketFile
== null
131 && tcpAddress
== null
132 && !(inheritedChannel
instanceof ServerSocketChannel
)
134 runDbusSingleAccount(m
, false, receiveMode
!= ReceiveMode
.ON_START
);
137 m
.addClosedListener(() -> {
138 synchronized (this) {
143 synchronized (this) {
146 } catch (InterruptedException ignored
) {
152 public void handleCommand(
153 final Namespace ns
, final MultiAccountManager c
, final OutputWriter outputWriter
154 ) throws CommandException
{
155 logger
.info("Starting daemon in multi-account mode");
156 final var noReceiveStdOut
= Boolean
.TRUE
.equals(ns
.getBoolean("no-receive-stdout"));
157 final var receiveMode
= ns
.<ReceiveMode
>get("receive-mode");
158 final var ignoreAttachments
= Boolean
.TRUE
.equals(ns
.getBoolean("ignore-attachments"));
160 final var receiveConfig
= new ReceiveConfig(ignoreAttachments
);
161 c
.getManagers().forEach(m
-> {
162 m
.setReceiveConfig(receiveConfig
);
163 addDefaultReceiveHandler(m
, noReceiveStdOut ?
null : outputWriter
, receiveMode
!= ReceiveMode
.ON_START
);
165 c
.addOnManagerAddedHandler(m
-> {
166 m
.setReceiveConfig(receiveConfig
);
167 addDefaultReceiveHandler(m
, noReceiveStdOut ?
null : outputWriter
, receiveMode
!= ReceiveMode
.ON_START
);
170 final Channel inheritedChannel
;
172 inheritedChannel
= System
.inheritedChannel();
173 if (inheritedChannel
instanceof ServerSocketChannel serverChannel
) {
174 logger
.info("Using inherited socket: " + serverChannel
.getLocalAddress());
175 runSocketMultiAccount(c
, serverChannel
, receiveMode
== ReceiveMode
.MANUAL
);
177 } catch (IOException e
) {
178 throw new IOErrorException("Failed to use inherited socket", e
);
180 final var socketFile
= ns
.<File
>get("socket");
181 if (socketFile
!= null) {
182 final var address
= UnixDomainSocketAddress
.of(socketFile
.toPath());
183 final var serverChannel
= IOUtils
.bindSocket(address
);
184 runSocketMultiAccount(c
, serverChannel
, receiveMode
== ReceiveMode
.MANUAL
);
186 final var tcpAddress
= ns
.getString("tcp");
187 if (tcpAddress
!= null) {
188 final var address
= IOUtils
.parseInetSocketAddress(tcpAddress
);
189 final var serverChannel
= IOUtils
.bindSocket(address
);
190 runSocketMultiAccount(c
, serverChannel
, receiveMode
== ReceiveMode
.MANUAL
);
192 final var isDbusSystem
= Boolean
.TRUE
.equals(ns
.getBoolean("dbus-system"));
194 runDbusMultiAccount(c
, receiveMode
!= ReceiveMode
.ON_START
, true);
196 final var isDbusSession
= Boolean
.TRUE
.equals(ns
.getBoolean("dbus"));
197 if (isDbusSession
|| (
199 && socketFile
== null
200 && tcpAddress
== null
201 && !(inheritedChannel
instanceof ServerSocketChannel
)
203 runDbusMultiAccount(c
, receiveMode
!= ReceiveMode
.ON_START
, false);
206 synchronized (this) {
209 } catch (InterruptedException ignored
) {
214 private void addDefaultReceiveHandler(Manager m
, OutputWriter outputWriter
, final boolean isWeakListener
) {
215 final var handler
= outputWriter
instanceof JsonWriter o
216 ?
new JsonReceiveMessageHandler(m
, o
)
217 : outputWriter
instanceof PlainTextWriter o
218 ?
new ReceiveMessageHandler(m
, o
)
219 : Manager
.ReceiveMessageHandler
.EMPTY
;
220 m
.addReceiveHandler(handler
, isWeakListener
);
223 private void runSocketSingleAccount(
224 final Manager m
, final ServerSocketChannel serverChannel
, final boolean noReceiveOnStart
226 runSocket(serverChannel
, channel
-> {
227 final var handler
= getSignalJsonRpcDispatcherHandler(channel
, noReceiveOnStart
);
228 handler
.handleConnection(m
);
232 private void runSocketMultiAccount(
233 final MultiAccountManager c
, final ServerSocketChannel serverChannel
, final boolean noReceiveOnStart
235 runSocket(serverChannel
, channel
-> {
236 final var handler
= getSignalJsonRpcDispatcherHandler(channel
, noReceiveOnStart
);
237 handler
.handleConnection(c
);
241 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
243 private void runSocket(final ServerSocketChannel serverChannel
, Consumer
<SocketChannel
> socketHandler
) {
244 final var thread
= new Thread(() -> {
246 final var connectionId
= threadNumber
.getAndIncrement();
247 final SocketChannel channel
;
248 final String clientString
;
250 channel
= serverChannel
.accept();
251 clientString
= channel
.getRemoteAddress() + " " + IOUtils
.getUnixDomainPrincipal(channel
);
252 logger
.info("Accepted new client connection {}: {}", connectionId
, clientString
);
253 } catch (IOException e
) {
254 logger
.error("Failed to accept new socket connection", e
);
255 synchronized (this) {
260 final var connectionThread
= new Thread(() -> {
261 try (final var c
= channel
) {
262 socketHandler
.accept(c
);
263 } catch (IOException e
) {
264 logger
.warn("Failed to close channel", e
);
265 } catch (Throwable e
) {
266 logger
.warn("Connection handler failed, closing connection", e
);
268 logger
.info("Connection {} closed: {}", connectionId
, clientString
);
270 connectionThread
.setName("daemon-connection-" + connectionId
);
271 connectionThread
.start();
274 thread
.setName("daemon-listener");
278 private SignalJsonRpcDispatcherHandler
getSignalJsonRpcDispatcherHandler(
279 final SocketChannel c
, final boolean noReceiveOnStart
281 final var lineSupplier
= IOUtils
.getLineSupplier(Channels
.newReader(c
, StandardCharsets
.UTF_8
));
282 final var jsonOutputWriter
= new JsonWriterImpl(Channels
.newWriter(c
, StandardCharsets
.UTF_8
));
284 return new SignalJsonRpcDispatcherHandler(jsonOutputWriter
, lineSupplier
, noReceiveOnStart
);
287 private void runDbusSingleAccount(
288 final Manager m
, final boolean isDbusSystem
, final boolean noReceiveOnStart
289 ) throws CommandException
{
290 runDbus(isDbusSystem
, (conn
, objectPath
) -> {
292 exportDbusObject(conn
, objectPath
, m
, noReceiveOnStart
).join();
293 } catch (InterruptedException ignored
) {
298 private void runDbusMultiAccount(
299 final MultiAccountManager c
, final boolean noReceiveOnStart
, final boolean isDbusSystem
300 ) throws CommandException
{
301 runDbus(isDbusSystem
, (connection
, objectPath
) -> {
302 final var signalControl
= new DbusSignalControlImpl(c
, objectPath
);
303 connection
.exportObject(signalControl
);
305 c
.addOnManagerAddedHandler(m
-> {
306 final var thread
= exportMultiAccountManager(connection
, m
, noReceiveOnStart
);
309 } catch (InterruptedException ignored
) {
312 c
.addOnManagerRemovedHandler(m
-> {
313 final var path
= DbusConfig
.getObjectPath(m
.getSelfNumber());
315 final var object
= connection
.getExportedObject(null, path
);
316 if (object
instanceof DbusSignalImpl dbusSignal
) {
319 } catch (DBusException ignored
) {
323 final var initThreads
= c
.getManagers()
325 .map(m
-> exportMultiAccountManager(connection
, m
, noReceiveOnStart
))
328 for (var t
: initThreads
) {
331 } catch (InterruptedException ignored
) {
337 private void runDbus(
338 final boolean isDbusSystem
, DbusRunner dbusRunner
339 ) throws CommandException
{
340 DBusConnection
.DBusBusType busType
;
342 busType
= DBusConnection
.DBusBusType
.SYSTEM
;
344 busType
= DBusConnection
.DBusBusType
.SESSION
;
348 conn
= DBusConnectionBuilder
.forType(busType
).build();
349 dbusRunner
.run(conn
, DbusConfig
.getObjectPath());
350 } catch (DBusException e
) {
351 throw new UnexpectedErrorException("Dbus command failed: " + e
.getMessage(), e
);
352 } catch (UnsupportedOperationException e
) {
353 throw new UserErrorException("Failed to connect to Dbus: " + e
.getMessage(), e
);
357 conn
.requestBusName(DbusConfig
.getBusname());
358 } catch (DBusException e
) {
359 throw new UnexpectedErrorException("Dbus command failed, maybe signal-cli dbus daemon is already running: "
360 + e
.getMessage(), e
);
363 logger
.info("DBus daemon running on {} bus: {}", busType
, DbusConfig
.getBusname());
366 private Thread
exportMultiAccountManager(
367 final DBusConnection conn
, final Manager m
, final boolean noReceiveOnStart
369 final var objectPath
= DbusConfig
.getObjectPath(m
.getSelfNumber());
370 return exportDbusObject(conn
, objectPath
, m
, noReceiveOnStart
);
373 private Thread
exportDbusObject(
374 final DBusConnection conn
, final String objectPath
, final Manager m
, final boolean noReceiveOnStart
376 final var signal
= new DbusSignalImpl(m
, conn
, objectPath
, noReceiveOnStart
);
377 final var initThread
= new Thread(signal
::initObjects
);
378 initThread
.setName("dbus-init");
384 interface DbusRunner
{
386 void run(DBusConnection connection
, String objectPath
) throws DBusException
;