Refactor DaemonCommand

This commit is contained in:
AsamK 2023-11-06 18:25:36 +01:00
parent 85b0647a3e
commit 1e35ac380e

View file

@ -18,7 +18,6 @@ import org.asamk.signal.json.JsonReceiveMessageHandler;
import org.asamk.signal.jsonrpc.SignalJsonRpcDispatcherHandler; import org.asamk.signal.jsonrpc.SignalJsonRpcDispatcherHandler;
import org.asamk.signal.manager.Manager; import org.asamk.signal.manager.Manager;
import org.asamk.signal.manager.MultiAccountManager; import org.asamk.signal.manager.MultiAccountManager;
import org.asamk.signal.manager.api.ReceiveConfig;
import org.asamk.signal.output.JsonWriter; import org.asamk.signal.output.JsonWriter;
import org.asamk.signal.output.JsonWriterImpl; import org.asamk.signal.output.JsonWriterImpl;
import org.asamk.signal.output.OutputWriter; import org.asamk.signal.output.OutputWriter;
@ -32,6 +31,7 @@ import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnixDomainSocketAddress; import java.net.UnixDomainSocketAddress;
import java.nio.channels.Channel; import java.nio.channels.Channel;
import java.nio.channels.Channels; import java.nio.channels.Channels;
@ -43,6 +43,8 @@ import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer; import java.util.function.Consumer;
import static org.asamk.signal.util.CommandUtil.getReceiveConfig;
public class DaemonCommand implements MultiLocalCommand, LocalCommand { public class DaemonCommand implements MultiLocalCommand, LocalCommand {
private final static Logger logger = LoggerFactory.getLogger(DaemonCommand.class); private final static Logger logger = LoggerFactory.getLogger(DaemonCommand.class);
@ -105,70 +107,25 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
logger.info("Starting daemon in single-account mode for " + m.getSelfNumber()); logger.info("Starting daemon in single-account mode for " + m.getSelfNumber());
final var noReceiveStdOut = Boolean.TRUE.equals(ns.getBoolean("no-receive-stdout")); final var noReceiveStdOut = Boolean.TRUE.equals(ns.getBoolean("no-receive-stdout"));
final var receiveMode = ns.<ReceiveMode>get("receive-mode"); final var receiveMode = ns.<ReceiveMode>get("receive-mode");
final var ignoreAttachments = Boolean.TRUE.equals(ns.getBoolean("ignore-attachments")); final var receiveConfig = getReceiveConfig(ns);
final var ignoreStories = Boolean.TRUE.equals(ns.getBoolean("ignore-stories"));
final var sendReadReceipts = Boolean.TRUE.equals(ns.getBoolean("send-read-receipts"));
m.setReceiveConfig(new ReceiveConfig(ignoreAttachments, ignoreStories, sendReadReceipts)); m.setReceiveConfig(receiveConfig);
addDefaultReceiveHandler(m, noReceiveStdOut ? null : outputWriter, receiveMode != ReceiveMode.ON_START); addDefaultReceiveHandler(m, noReceiveStdOut ? null : outputWriter, receiveMode != ReceiveMode.ON_START);
final Channel inheritedChannel; try (final var daemonHandler = new SingleAccountDaemonHandler(m, receiveMode)) {
try { setup(ns, daemonHandler);
inheritedChannel = System.inheritedChannel();
if (inheritedChannel instanceof ServerSocketChannel serverChannel) { m.addClosedListener(() -> {
logger.info("Using inherited socket: " + serverChannel.getLocalAddress()); synchronized (this) {
runSocketSingleAccount(m, serverChannel, receiveMode == ReceiveMode.MANUAL); notifyAll();
} }
} catch (IOException e) { });
throw new IOErrorException("Failed to use inherited socket", e);
}
final var socketFile = ns.<File>get("socket");
if (socketFile != null) {
final var address = UnixDomainSocketAddress.of(socketFile.toPath());
final var serverChannel = IOUtils.bindSocket(address);
runSocketSingleAccount(m, serverChannel, receiveMode == ReceiveMode.MANUAL);
}
final var tcpAddress = ns.getString("tcp");
if (tcpAddress != null) {
final var address = IOUtils.parseInetSocketAddress(tcpAddress);
final var serverChannel = IOUtils.bindSocket(address);
runSocketSingleAccount(m, serverChannel, receiveMode == ReceiveMode.MANUAL);
}
final var httpAddress = ns.getString("http");
if (httpAddress != null) {
final var address = IOUtils.parseInetSocketAddress(httpAddress);
final var handler = new HttpServerHandler(address, m);
try {
handler.init();
} catch (IOException ex) {
throw new IOErrorException("Failed to initialize HTTP Server", ex);
}
}
final var isDbusSystem = Boolean.TRUE.equals(ns.getBoolean("dbus-system"));
if (isDbusSystem) {
runDbusSingleAccount(m, true, receiveMode != ReceiveMode.ON_START);
}
final var isDbusSession = Boolean.TRUE.equals(ns.getBoolean("dbus"));
if (isDbusSession || (
!isDbusSystem
&& socketFile == null
&& tcpAddress == null
&& httpAddress == null
&& !(inheritedChannel instanceof ServerSocketChannel)
)) {
runDbusSingleAccount(m, false, receiveMode != ReceiveMode.ON_START);
}
m.addClosedListener(() -> {
synchronized (this) { synchronized (this) {
notifyAll(); try {
} wait();
}); } catch (InterruptedException ignored) {
}
synchronized (this) {
try {
wait();
} catch (InterruptedException ignored) {
} }
} }
} }
@ -180,11 +137,7 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
logger.info("Starting daemon in multi-account mode"); logger.info("Starting daemon in multi-account mode");
final var noReceiveStdOut = Boolean.TRUE.equals(ns.getBoolean("no-receive-stdout")); final var noReceiveStdOut = Boolean.TRUE.equals(ns.getBoolean("no-receive-stdout"));
final var receiveMode = ns.<ReceiveMode>get("receive-mode"); final var receiveMode = ns.<ReceiveMode>get("receive-mode");
final var ignoreAttachments = Boolean.TRUE.equals(ns.getBoolean("ignore-attachments")); final var receiveConfig = getReceiveConfig(ns);
final var ignoreStories = Boolean.TRUE.equals(ns.getBoolean("ignore-stories"));
final var sendReadReceipts = Boolean.TRUE.equals(ns.getBoolean("send-read-receipts"));
final var receiveConfig = new ReceiveConfig(ignoreAttachments, ignoreStories, sendReadReceipts);
c.getManagers().forEach(m -> { c.getManagers().forEach(m -> {
m.setReceiveConfig(receiveConfig); m.setReceiveConfig(receiveConfig);
addDefaultReceiveHandler(m, noReceiveStdOut ? null : outputWriter, receiveMode != ReceiveMode.ON_START); addDefaultReceiveHandler(m, noReceiveStdOut ? null : outputWriter, receiveMode != ReceiveMode.ON_START);
@ -194,42 +147,55 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
addDefaultReceiveHandler(m, noReceiveStdOut ? null : outputWriter, receiveMode != ReceiveMode.ON_START); addDefaultReceiveHandler(m, noReceiveStdOut ? null : outputWriter, receiveMode != ReceiveMode.ON_START);
}); });
try (final var daemonHandler = new MultiAccountDaemonHandler(c, receiveMode)) {
setup(ns, daemonHandler);
synchronized (this) {
try {
wait();
} catch (InterruptedException ignored) {
}
}
}
}
private static void setup(final Namespace ns, final DaemonHandler daemonHandler) throws CommandException {
final Channel inheritedChannel; final Channel inheritedChannel;
try { try {
inheritedChannel = System.inheritedChannel(); inheritedChannel = System.inheritedChannel();
if (inheritedChannel instanceof ServerSocketChannel serverChannel) { if (inheritedChannel instanceof ServerSocketChannel serverChannel) {
logger.info("Using inherited socket: " + serverChannel.getLocalAddress()); logger.info("Using inherited socket: " + serverChannel.getLocalAddress());
runSocketMultiAccount(c, serverChannel, receiveMode == ReceiveMode.MANUAL); daemonHandler.runSocket(serverChannel);
} }
} catch (IOException e) { } catch (IOException e) {
throw new IOErrorException("Failed to use inherited socket", e); throw new IOErrorException("Failed to use inherited socket", e);
} }
final var socketFile = ns.<File>get("socket"); final var socketFile = ns.<File>get("socket");
if (socketFile != null) { if (socketFile != null) {
final var address = UnixDomainSocketAddress.of(socketFile.toPath()); final var address = UnixDomainSocketAddress.of(socketFile.toPath());
final var serverChannel = IOUtils.bindSocket(address); final var serverChannel = IOUtils.bindSocket(address);
runSocketMultiAccount(c, serverChannel, receiveMode == ReceiveMode.MANUAL); daemonHandler.runSocket(serverChannel);
} }
final var tcpAddress = ns.getString("tcp"); final var tcpAddress = ns.getString("tcp");
if (tcpAddress != null) { if (tcpAddress != null) {
final var address = IOUtils.parseInetSocketAddress(tcpAddress); final var address = IOUtils.parseInetSocketAddress(tcpAddress);
final var serverChannel = IOUtils.bindSocket(address); final var serverChannel = IOUtils.bindSocket(address);
runSocketMultiAccount(c, serverChannel, receiveMode == ReceiveMode.MANUAL); daemonHandler.runSocket(serverChannel);
} }
final var httpAddress = ns.getString("http"); final var httpAddress = ns.getString("http");
if (httpAddress != null) { if (httpAddress != null) {
final var address = IOUtils.parseInetSocketAddress(httpAddress); final var address = IOUtils.parseInetSocketAddress(httpAddress);
final var handler = new HttpServerHandler(address, c); daemonHandler.runHttp(address);
try {
handler.init();
} catch (IOException ex) {
throw new IOErrorException("Failed to initialize HTTP Server", ex);
}
} }
final var isDbusSystem = Boolean.TRUE.equals(ns.getBoolean("dbus-system")); final var isDbusSystem = Boolean.TRUE.equals(ns.getBoolean("dbus-system"));
if (isDbusSystem) { if (isDbusSystem) {
runDbusMultiAccount(c, receiveMode != ReceiveMode.ON_START, true); daemonHandler.runDbus(true);
} }
final var isDbusSession = Boolean.TRUE.equals(ns.getBoolean("dbus")); final var isDbusSession = Boolean.TRUE.equals(ns.getBoolean("dbus"));
if (isDbusSession || ( if (isDbusSession || (
!isDbusSystem !isDbusSystem
@ -238,14 +204,7 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
&& httpAddress == null && httpAddress == null
&& !(inheritedChannel instanceof ServerSocketChannel) && !(inheritedChannel instanceof ServerSocketChannel)
)) { )) {
runDbusMultiAccount(c, receiveMode != ReceiveMode.ON_START, false); daemonHandler.runDbus(false);
}
synchronized (this) {
try {
wait();
} catch (InterruptedException ignored) {
}
} }
} }
@ -258,164 +217,213 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
m.addReceiveHandler(handler, isWeakListener); m.addReceiveHandler(handler, isWeakListener);
} }
private Thread runSocketSingleAccount( private static abstract class DaemonHandler implements AutoCloseable {
final Manager m, final ServerSocketChannel serverChannel, final boolean noReceiveOnStart
) {
return runSocket(serverChannel, channel -> {
final var handler = getSignalJsonRpcDispatcherHandler(channel, noReceiveOnStart);
handler.handleConnection(m);
});
}
private Thread runSocketMultiAccount( protected final ReceiveMode receiveMode;
final MultiAccountManager c, final ServerSocketChannel serverChannel, final boolean noReceiveOnStart private static final AtomicInteger threadNumber = new AtomicInteger(0);
) {
return runSocket(serverChannel, channel -> {
final var handler = getSignalJsonRpcDispatcherHandler(channel, noReceiveOnStart);
handler.handleConnection(c);
});
}
private static final AtomicInteger threadNumber = new AtomicInteger(0); public DaemonHandler(final ReceiveMode receiveMode) {
this.receiveMode = receiveMode;
}
private Thread runSocket(final ServerSocketChannel serverChannel, Consumer<SocketChannel> socketHandler) { public abstract void runSocket(ServerSocketChannel serverChannel) throws CommandException;
return Thread.ofPlatform().name("daemon-listener").start(() -> {
try (final var executor = Executors.newCachedThreadPool()) { public abstract void runDbus(boolean isDbusSystem) throws CommandException;
while (true) {
final var connectionId = threadNumber.getAndIncrement(); public abstract void runHttp(InetSocketAddress address) throws CommandException;
final SocketChannel channel;
final String clientString; protected void runSocket(final ServerSocketChannel serverChannel, Consumer<SocketChannel> socketHandler) {
try { Thread.ofPlatform().name("daemon-listener").start(() -> {
channel = serverChannel.accept(); try (final var executor = Executors.newCachedThreadPool()) {
clientString = channel.getRemoteAddress() + " " + IOUtils.getUnixDomainPrincipal(channel); while (true) {
logger.info("Accepted new client connection {}: {}", connectionId, clientString); final var connectionId = threadNumber.getAndIncrement();
} catch (IOException e) { final SocketChannel channel;
logger.error("Failed to accept new socket connection", e); final String clientString;
break; try {
} channel = serverChannel.accept();
executor.submit(() -> { clientString = channel.getRemoteAddress() + " " + IOUtils.getUnixDomainPrincipal(channel);
try (final var c = channel) { logger.info("Accepted new client connection {}: {}", connectionId, clientString);
socketHandler.accept(c);
} catch (IOException e) { } catch (IOException e) {
logger.warn("Failed to close channel", e); logger.error("Failed to accept new socket connection", e);
} catch (Throwable e) { break;
logger.warn("Connection handler failed, closing connection", e);
} }
logger.info("Connection {} closed: {}", connectionId, clientString); executor.submit(() -> {
}); try (final var c = channel) {
} socketHandler.accept(c);
} } catch (IOException e) {
synchronized (this) { logger.warn("Failed to close channel", e);
notifyAll(); } catch (Throwable e) {
} logger.warn("Connection handler failed, closing connection", e);
}); }
} logger.info("Connection {} closed: {}", connectionId, clientString);
});
private SignalJsonRpcDispatcherHandler getSignalJsonRpcDispatcherHandler(
final SocketChannel c, final boolean noReceiveOnStart
) {
final var lineSupplier = IOUtils.getLineSupplier(Channels.newReader(c, StandardCharsets.UTF_8));
final var jsonOutputWriter = new JsonWriterImpl(Channels.newWriter(c, StandardCharsets.UTF_8));
return new SignalJsonRpcDispatcherHandler(jsonOutputWriter, lineSupplier, noReceiveOnStart);
}
private void runDbusSingleAccount(
final Manager m, final boolean isDbusSystem, final boolean noReceiveOnStart
) throws CommandException {
runDbus(isDbusSystem, (conn, objectPath) -> {
try {
exportDbusObject(conn, objectPath, m, noReceiveOnStart).join();
} catch (InterruptedException ignored) {
}
});
}
private void runDbusMultiAccount(
final MultiAccountManager c, final boolean noReceiveOnStart, final boolean isDbusSystem
) throws CommandException {
runDbus(isDbusSystem, (connection, objectPath) -> {
final var signalControl = new DbusSignalControlImpl(c, objectPath);
connection.exportObject(signalControl);
c.addOnManagerAddedHandler(m -> {
final var thread = exportMultiAccountManager(connection, m, noReceiveOnStart);
try {
thread.join();
} catch (InterruptedException ignored) {
}
});
c.addOnManagerRemovedHandler(m -> {
final var path = DbusConfig.getObjectPath(m.getSelfNumber());
try {
final var object = connection.getExportedObject(null, path);
if (object instanceof DbusSignalImpl dbusSignal) {
dbusSignal.close();
} }
} catch (DBusException ignored) {
} }
}); });
}
final var initThreads = c.getManagers() protected SignalJsonRpcDispatcherHandler getSignalJsonRpcDispatcherHandler(final SocketChannel c) {
.stream() final var lineSupplier = IOUtils.getLineSupplier(Channels.newReader(c, StandardCharsets.UTF_8));
.map(m -> exportMultiAccountManager(connection, m, noReceiveOnStart)) final var jsonOutputWriter = new JsonWriterImpl(Channels.newWriter(c, StandardCharsets.UTF_8));
.toList();
for (var t : initThreads) { return new SignalJsonRpcDispatcherHandler(jsonOutputWriter,
lineSupplier,
receiveMode == ReceiveMode.MANUAL);
}
protected Thread exportDbusObject(final DBusConnection conn, final String objectPath, final Manager m) {
final var signal = new DbusSignalImpl(m, conn, objectPath, receiveMode != ReceiveMode.ON_START);
return Thread.ofPlatform().name("dbus-init-" + m.getSelfNumber()).start(signal::initObjects);
}
protected void runDbus(
final boolean isDbusSystem, MultiAccountDaemonHandler.DbusRunner dbusRunner
) throws CommandException {
DBusConnection.DBusBusType busType;
if (isDbusSystem) {
busType = DBusConnection.DBusBusType.SYSTEM;
} else {
busType = DBusConnection.DBusBusType.SESSION;
}
DBusConnection conn;
try {
conn = DBusConnectionBuilder.forType(busType).build();
dbusRunner.run(conn, DbusConfig.getObjectPath());
} catch (DBusException e) {
throw new UnexpectedErrorException("Dbus command failed: " + e.getMessage(), e);
} catch (UnsupportedOperationException e) {
throw new UserErrorException("Failed to connect to Dbus: " + e.getMessage(), e);
}
try {
conn.requestBusName(DbusConfig.getBusname());
} catch (DBusException e) {
throw new UnexpectedErrorException(
"Dbus command failed, maybe signal-cli dbus daemon is already running: " + e.getMessage(),
e);
}
logger.info("DBus daemon running on {} bus: {}", busType, DbusConfig.getBusname());
}
@Override
public void close() {
// TODO
}
}
private static final class SingleAccountDaemonHandler extends DaemonHandler {
private final Manager m;
private SingleAccountDaemonHandler(final Manager m, final ReceiveMode receiveMode) {
super(receiveMode);
this.m = m;
}
@Override
public void runSocket(final ServerSocketChannel serverChannel) {
runSocket(serverChannel, channel -> {
final var handler = getSignalJsonRpcDispatcherHandler(channel);
handler.handleConnection(m);
});
}
@Override
public void runDbus(final boolean isDbusSystem) throws CommandException {
runDbus(isDbusSystem, (conn, objectPath) -> {
try { try {
t.join(); exportDbusObject(conn, objectPath, m).join();
} catch (InterruptedException ignored) { } catch (InterruptedException ignored) {
} }
});
}
@Override
public void runHttp(InetSocketAddress address) throws CommandException {
final var handler = new HttpServerHandler(address, m);
try {
handler.init();
} catch (IOException ex) {
throw new IOErrorException("Failed to initialize HTTP Server", ex);
} }
}); }
} }
private void runDbus( private static final class MultiAccountDaemonHandler extends DaemonHandler {
final boolean isDbusSystem, DbusRunner dbusRunner
) throws CommandException { private final MultiAccountManager c;
DBusConnection.DBusBusType busType;
if (isDbusSystem) { private MultiAccountDaemonHandler(final MultiAccountManager c, final ReceiveMode receiveMode) {
busType = DBusConnection.DBusBusType.SYSTEM; super(receiveMode);
} else { this.c = c;
busType = DBusConnection.DBusBusType.SESSION;
}
DBusConnection conn;
try {
conn = DBusConnectionBuilder.forType(busType).build();
dbusRunner.run(conn, DbusConfig.getObjectPath());
} catch (DBusException e) {
throw new UnexpectedErrorException("Dbus command failed: " + e.getMessage(), e);
} catch (UnsupportedOperationException e) {
throw new UserErrorException("Failed to connect to Dbus: " + e.getMessage(), e);
} }
try { public void runSocket(final ServerSocketChannel serverChannel) {
conn.requestBusName(DbusConfig.getBusname()); runSocket(serverChannel, channel -> {
} catch (DBusException e) { final var handler = getSignalJsonRpcDispatcherHandler(channel);
throw new UnexpectedErrorException("Dbus command failed, maybe signal-cli dbus daemon is already running: " handler.handleConnection(c);
+ e.getMessage(), e); });
} }
logger.info("DBus daemon running on {} bus: {}", busType, DbusConfig.getBusname()); public void runDbus(final boolean isDbusSystem) throws CommandException {
} runDbus(isDbusSystem, (connection, objectPath) -> {
final var signalControl = new DbusSignalControlImpl(c, objectPath);
connection.exportObject(signalControl);
private Thread exportMultiAccountManager( c.addOnManagerAddedHandler(m -> {
final DBusConnection conn, final Manager m, final boolean noReceiveOnStart final var thread = exportMultiAccountManager(connection, m);
) { try {
final var objectPath = DbusConfig.getObjectPath(m.getSelfNumber()); thread.join();
return exportDbusObject(conn, objectPath, m, noReceiveOnStart); } catch (InterruptedException ignored) {
} }
});
c.addOnManagerRemovedHandler(m -> {
final var path = DbusConfig.getObjectPath(m.getSelfNumber());
try {
final var object = connection.getExportedObject(null, path);
if (object instanceof DbusSignalImpl dbusSignal) {
dbusSignal.close();
}
} catch (DBusException ignored) {
}
});
private Thread exportDbusObject( final var initThreads = c.getManagers()
final DBusConnection conn, final String objectPath, final Manager m, final boolean noReceiveOnStart .stream()
) { .map(m -> exportMultiAccountManager(connection, m))
final var signal = new DbusSignalImpl(m, conn, objectPath, noReceiveOnStart); .toList();
return Thread.ofPlatform().name("dbus-init-" + m.getSelfNumber()).start(signal::initObjects); for (var t : initThreads) {
} try {
t.join();
} catch (InterruptedException ignored) {
}
}
});
}
interface DbusRunner { @Override
public void runHttp(final InetSocketAddress address) throws CommandException {
final var handler = new HttpServerHandler(address, c);
try {
handler.init();
} catch (IOException ex) {
throw new IOErrorException("Failed to initialize HTTP Server", ex);
}
}
void run(DBusConnection connection, String objectPath) throws DBusException; private Thread exportMultiAccountManager(
final DBusConnection conn, final Manager m
) {
final var objectPath = DbusConfig.getObjectPath(m.getSelfNumber());
return exportDbusObject(conn, objectPath, m);
}
interface DbusRunner {
void run(DBusConnection connection, String objectPath) throws DBusException;
}
} }
} }