+ }
+ }
+
+ private static void setup(final Namespace ns, final DaemonHandler daemonHandler) throws CommandException {
+ final Channel inheritedChannel;
+ try {
+ if (System.inheritedChannel() instanceof ServerSocketChannel serverChannel) {
+ inheritedChannel = serverChannel;
+ logger.info("Using inherited socket: " + serverChannel.getLocalAddress());
+ daemonHandler.runSocket(serverChannel);
+ } else {
+ inheritedChannel = null;
+ }
+ } 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 == null
+ )) {
+ 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<>();
+
+ protected 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 final void runSocket(final SocketHandler socketHandler) {
+ socketHandler.init();
+ this.closeables.add(socketHandler);
+ }
+
+ protected final void runDbus(
+ DbusHandler dbusHandler
+ ) throws CommandException {
+ dbusHandler.init();
+ this.closeables.add(dbusHandler);
+ }
+
+ protected final void runHttp(final HttpServerHandler handler) throws CommandException {