+
+ public static File getRuntimeDir() {
+ var runtimeDir = System.getenv("XDG_RUNTIME_DIR");
+ if (runtimeDir != null) {
+ return new File(runtimeDir);
+ }
+
+ logger.debug("XDG_RUNTIME_DIR not set, falling back to temp dir");
+ return new File(System.getProperty("java.io.tmpdir"));
+ }
+
+ public static Supplier<String> getLineSupplier(final Reader reader) {
+ final var bufferedReader = new BufferedReader(reader);
+ return () -> {
+ try {
+ return bufferedReader.readLine();
+ } catch (IOException e) {
+ logger.error("Error occurred while reading line", e);
+ return null;
+ }
+ };
+ }
+
+ public static InetSocketAddress parseInetSocketAddress(final String tcpAddress) throws UserErrorException {
+ final var colonIndex = tcpAddress.lastIndexOf(':');
+ if (colonIndex < 0) {
+ throw new UserErrorException("Invalid tcp bind address: " + tcpAddress);
+ }
+ final String host = tcpAddress.substring(0, colonIndex);
+ final int port;
+ try {
+ port = Integer.parseInt(tcpAddress.substring(colonIndex + 1));
+ } catch (NumberFormatException e) {
+ throw new UserErrorException("Invalid tcp bind address: " + tcpAddress, e);
+ }
+ return new InetSocketAddress(host, port);
+ }
+
+ public static UnixDomainPrincipal getUnixDomainPrincipal(final SocketChannel channel) throws IOException {
+ UnixDomainPrincipal principal = null;
+ try {
+ principal = channel.getOption(ExtendedSocketOptions.SO_PEERCRED);
+ } catch (UnsupportedOperationException ignored) {
+ }
+ return principal;
+ }
+
+ public static ServerSocketChannel bindSocket(final SocketAddress address) throws IOErrorException {
+ final ServerSocketChannel serverChannel;
+ try {
+ preBind(address);
+ serverChannel = address instanceof UnixDomainSocketAddress
+ ? ServerSocketChannel.open(StandardProtocolFamily.UNIX)
+ : ServerSocketChannel.open();
+ serverChannel.bind(address);
+ logger.info("Listening on socket: " + address);
+ postBind(address);
+ } catch (IOException e) {
+ throw new IOErrorException("Failed to bind socket: " + e.getMessage(), e);
+ }
+ return serverChannel;
+ }
+
+ private static void preBind(SocketAddress address) throws IOException {
+ if (address instanceof UnixDomainSocketAddress usa) {
+ createPrivateDirectories(usa.getPath().toFile().getParentFile());
+ }
+ }
+
+ private static void postBind(SocketAddress address) {
+ if (address instanceof UnixDomainSocketAddress usa) {
+ usa.getPath().toFile().deleteOnExit();
+ }
+ }