- Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE);
- Files.createFile(file, PosixFilePermissions.asFileAttribute(perms));
- } catch (UnsupportedOperationException e) {
- Files.createFile(file);
+ port = Integer.parseInt(portString);
+ } catch (NumberFormatException e) {
+ throw new UserErrorException("Invalid tcp port: " + portString, e);
+ }
+ final var socketAddress = new InetSocketAddress(host, port);
+ if (socketAddress.isUnresolved()) {
+ throw new UserErrorException("Invalid tcp bind address, invalid host: " + host);
+ }
+ return socketAddress;
+ }
+
+ 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 " + address + ": " + 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();