+ private static void setup(final Namespace ns, final DaemonHandler daemonHandler) throws CommandException {
+ final Channel inheritedChannel;
+ try {
+ inheritedChannel = System.inheritedChannel();
+ if (inheritedChannel instanceof ServerSocketChannel serverChannel) {
+ logger.info("Using inherited socket: " + serverChannel.getLocalAddress());
+ daemonHandler.runSocket(serverChannel);
+ }
+ } 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);
+ daemonHandler.runSocket(serverChannel);
+ }
+
+ final var tcpAddress = ns.getString("tcp");
+ if (tcpAddress != null) {
+ final var address = IOUtils.parseInetSocketAddress(tcpAddress);
+ final var serverChannel = IOUtils.bindSocket(address);
+ daemonHandler.runSocket(serverChannel);
+ }
+
+ final var httpAddress = ns.getString("http");
+ if (httpAddress != null) {
+ final var address = IOUtils.parseInetSocketAddress(httpAddress);
+ daemonHandler.runHttp(address);
+ }
+
+ final var isDbusSystem = Boolean.TRUE.equals(ns.getBoolean("dbus-system"));
+ if (isDbusSystem) {
+ daemonHandler.runDbus(true);
+ }
+
+ final var isDbusSession = Boolean.TRUE.equals(ns.getBoolean("dbus"));
+ if (isDbusSession || (
+ !isDbusSystem
+ && socketFile == null
+ && tcpAddress == null
+ && httpAddress == null
+ && !(inheritedChannel instanceof ServerSocketChannel)
+ )) {
+ daemonHandler.runDbus(false);
+ }
+ }
+
+ private void addDefaultReceiveHandler(Manager m, OutputWriter outputWriter, final boolean isWeakListener) {
+ final var handler = switch (outputWriter) {
+ case PlainTextWriter writer -> new ReceiveMessageHandler(m, writer);
+ case JsonWriter writer -> new JsonReceiveMessageHandler(m, writer);
+ case null -> Manager.ReceiveMessageHandler.EMPTY;
+ };
+ m.addReceiveHandler(handler, isWeakListener);
+ }
+
+ private static abstract class DaemonHandler implements AutoCloseable {
+
+ protected final ReceiveMode receiveMode;
+ protected final List<AutoCloseable> closeables = new ArrayList<>();
+
+ private static final AtomicInteger threadNumber = new AtomicInteger(0);
+
+ public DaemonHandler(final ReceiveMode receiveMode) {
+ this.receiveMode = receiveMode;
+ }
+
+ public abstract void runSocket(ServerSocketChannel serverChannel) throws CommandException;
+
+ public abstract void runDbus(boolean isDbusSystem) throws CommandException;
+
+ public abstract void runHttp(InetSocketAddress address) throws CommandException;
+
+ protected void runSocket(final ServerSocketChannel serverChannel, Consumer<SocketChannel> socketHandler) {
+ final List<AutoCloseable> channels = new ArrayList<>();
+ final var thread = Thread.ofPlatform().name("daemon-listener").start(() -> {
+ try (final var executor = Executors.newCachedThreadPool()) {
+ while (true) {
+ final var connectionId = threadNumber.getAndIncrement();
+ final SocketChannel channel;
+ final String clientString;
+ try {
+ channel = serverChannel.accept();
+ clientString = channel.getRemoteAddress() + " " + IOUtils.getUnixDomainPrincipal(channel);
+ logger.info("Accepted new client connection {}: {}", connectionId, clientString);
+ } catch (ClosedChannelException ignored) {
+ logger.trace("Listening socket has been closed");
+ break;
+ } catch (IOException e) {
+ logger.error("Failed to accept new socket connection", e);
+ break;
+ }
+ channels.add(channel);
+ executor.submit(() -> {
+ try (final var c = channel) {
+ socketHandler.accept(c);
+ } catch (IOException e) {
+ logger.warn("Failed to close channel", e);
+ } catch (Throwable e) {
+ logger.warn("Connection handler failed, closing connection", e);
+ }
+ logger.info("Connection {} closed: {}", connectionId, clientString);
+ channels.remove(channel);
+ });
+ }
+ }
+ });
+ closeables.add(() -> {
+ serverChannel.close();
+ for (final var c : new ArrayList<>(channels)) {
+ c.close();
+ }
+ thread.join();
+ });
+ }
+
+ protected SignalJsonRpcDispatcherHandler getSignalJsonRpcDispatcherHandler(final SocketChannel c) {
+ 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,
+ 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);
+ closeables.add(signal);
+
+ 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);
+ }
+ closeables.add(conn);
+
+ logger.info("DBus daemon running on {} bus: {}", busType, DbusConfig.getBusname());
+ }
+
+ @Override
+ public void close() {
+ for (final var closeable : new ArrayList<>(closeables)) {
+ try {
+ closeable.close();
+ } catch (Exception e) {
+ logger.warn("Failed to close daemon handler", e);
+ }
+ }
+ closeables.clear();
+ }
+ }
+
+ private static final class SingleAccountDaemonHandler extends DaemonHandler {
+
+ private final Manager m;