io.netty.channel.unix.DomainSocketAddress Java Examples

The following examples show how to use io.netty.channel.unix.DomainSocketAddress. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EpollSocketTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPeerCreds() throws IOException {
    LinuxSocket s1 = LinuxSocket.newSocketDomain();
    LinuxSocket s2 = LinuxSocket.newSocketDomain();

    try {
        DomainSocketAddress dsa = UnixTestUtils.newSocketAddress();
        s1.bind(dsa);
        s1.listen(1);

        assertTrue(s2.connect(dsa));
        byte [] addr = new byte[64];
        s1.accept(addr);
        PeerCredentials pc = s1.getPeerCredentials();
        assertNotEquals(pc.uid(), -1);
    } finally {
        s1.close();
        s2.close();
    }
}
 
Example #2
Source File: KMSEncryptionProvider.java    From credhub with Apache License 2.0 6 votes vote down vote up
public KMSEncryptionProvider(final EncryptionConfiguration configuration) {
  super();

  setChannelInfo();

  SslContext sslContext;
  try {
    sslContext = GrpcSslContexts.forClient()
      .trustManager(new ByteArrayInputStream(configuration.getCa().getBytes(UTF_8)))
      .build();
  } catch (SSLException e) {
    throw new RuntimeException(e);
  }

  blockingStub = KeyManagementServiceGrpc.newBlockingStub(
    NettyChannelBuilder.forAddress(new DomainSocketAddress(configuration.getEndpoint()))
      .eventLoopGroup(group)
      .channelType(channelType)
      .keepAliveTime(DEFAULT_KEEPALIVE_TIMEOUT_NANOS, TimeUnit.NANOSECONDS)
      .useTransportSecurity()
      .sslContext(sslContext)
      .overrideAuthority(configuration.getHost())
      .build());
}
 
Example #3
Source File: EpollServerDomainSocketChannel.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
protected void doClose() throws Exception {
    try {
        super.doClose();
    } finally {
        DomainSocketAddress local = this.local;
        if (local != null) {
            // Delete the socket file if possible.
            File socketFile = new File(local.path());
            boolean success = socketFile.delete();
            if (!success && logger.isDebugEnabled()) {
                logger.debug("Failed to delete a domain socket file: {}", local.path());
            }
        }
    }
}
 
Example #4
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testHttpClientWithDomainSocketsNIOTransport() {
	LoopResources loop = LoopResources.create("testHttpClientWithDomainSocketsNIOTransport");
	try {
		HttpClient.create()
		          .runOn(loop, false)
		          .remoteAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
		          .get()
		          .uri("/")
		          .responseContent()
		          .aggregate()
		          .block(Duration.ofSeconds(30));
	}
	finally {
		loop.disposeLater()
		    .block(Duration.ofSeconds(30));
	}
}
 
Example #5
Source File: KQueueServerDomainSocketChannel.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doClose() throws Exception {
    try {
        super.doClose();
    } finally {
        DomainSocketAddress local = this.local;
        if (local != null) {
            // Delete the socket file if possible.
            File socketFile = new File(local.path());
            boolean success = socketFile.delete();
            if (!success && logger.isDebugEnabled()) {
                logger.debug("Failed to delete a domain socket file: {}", local.path());
            }
        }
    }
}
 
Example #6
Source File: EpollServerDomainSocketChannel.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doClose() throws Exception {
    try {
        super.doClose();
    } finally {
        DomainSocketAddress local = this.local;
        if (local != null) {
            // Delete the socket file if possible.
            File socketFile = new File(local.path());
            boolean success = socketFile.delete();
            if (!success && logger.isDebugEnabled()) {
                logger.debug("Failed to delete a domain socket file: {}", local.path());
            }
        }
    }
}
 
Example #7
Source File: AddressUtils.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
/**
 * Update the provided address with the new host string.
 *
 * @param address the address supplier
 * @param host the new host string
 * @return the updated address
 */
public static SocketAddress updateHost(@Nullable Supplier<? extends SocketAddress> address, String host) {
	if (address == null) {
		return createUnresolved(host, 0);
	}

	SocketAddress socketAddress = address.get();
	if (socketAddress instanceof DomainSocketAddress) {
		throw new IllegalArgumentException("Cannot update DomainSocketAddress with host name [" + host + "].");
	}

	if (!(socketAddress instanceof InetSocketAddress)) {
		return createUnresolved(host, 0);
	}

	InetSocketAddress inet = (InetSocketAddress) socketAddress;

	return createUnresolved(host, inet.getPort());
}
 
Example #8
Source File: UriEndpoint.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
String toExternalForm() {
	StringBuilder sb = new StringBuilder();
	SocketAddress address = remoteAddress.get();
	if (address instanceof DomainSocketAddress) {
		sb.append(((DomainSocketAddress) address).path());
	}
	else {
		sb.append(scheme);
		sb.append("://");
		sb.append(address != null
						  ? toSocketAddressStringWithoutDefaultPort(address, isSecure())
						  : "localhost");
		sb.append(pathAndQuery);
	}
	return sb.toString();
}
 
Example #9
Source File: AddressUtils.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
/**
 * Update the provided address with the new port.
 *
 * @param address the address supplier
 * @param port the new port
 * @return the updated address
 */
public static SocketAddress updatePort(@Nullable Supplier<? extends SocketAddress> address, int port) {
	if (address == null) {
		return createUnresolved(NetUtil.LOCALHOST.getHostAddress(), port);
	}

	SocketAddress socketAddress = address.get();
	if (socketAddress instanceof DomainSocketAddress) {
		throw new IllegalArgumentException("Cannot update DomainSocketAddress with post number [" + port + "].");
	}

	if(!(address.get() instanceof InetSocketAddress)) {
		return createUnresolved(NetUtil.LOCALHOST.getHostAddress(), port);
	}

	InetSocketAddress inet = (InetSocketAddress) address.get();

	InetAddress addr = inet.getAddress();

	String host = addr == null ? inet.getHostName() : addr.getHostAddress();

	return createUnresolved(host, port);
}
 
Example #10
Source File: BuilderUtils.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
/**
 * If {@code address} if a ServiceTalk specific address it is unwrapped into a Netty address.
 *
 * @param address the address to convert.
 * @return an address that Netty understands.
 */
public static SocketAddress toNettyAddress(Object address) {
    // The order of the instance of checks is important because `DomainSocketAddress` is also of type
    // `SocketAddress`, and we want to identify the more specific types before returning the fallback
    // `SocketAddress` type.
    if (address instanceof io.servicetalk.transport.api.DomainSocketAddress) {
        return new DomainSocketAddress(((io.servicetalk.transport.api.DomainSocketAddress) address).getPath());
    }
    if (address instanceof SocketAddress) {
        return (SocketAddress) address;
    }
    if (address instanceof HostAndPort) {
        return toResolvedInetSocketAddress((HostAndPort) address);
    }
    throw new IllegalArgumentException("Unsupported address: " + address);
}
 
Example #11
Source File: KQueueSocketTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPeerCreds() throws IOException {
    BsdSocket s1 = BsdSocket.newSocketDomain();
    BsdSocket s2 = BsdSocket.newSocketDomain();

    try {
        DomainSocketAddress dsa = UnixTestUtils.newSocketAddress();
        s1.bind(dsa);
        s1.listen(1);

        assertTrue(s2.connect(dsa));
        byte [] addr = new byte[64];
        s1.accept(addr);
        PeerCredentials pc = s1.getPeerCredentials();
        assertNotEquals(pc.uid(), -1);
    } finally {
        s1.close();
        s2.close();
    }
}
 
Example #12
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = ChannelBindException.class)
public void testTcpServerWithDomainSocketsNIOTransport() {
	LoopResources loop = LoopResources.create("testTcpServerWithDomainSocketsNIOTransport");
	try {
		TcpServer.create()
		         .runOn(loop, false)
		         .bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
		         .bindNow();
	}
	finally {
		loop.disposeLater()
		    .block(Duration.ofSeconds(30));
	}
}
 
Example #13
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testTcpServerWithDomainSocketsWithPort() {
	TcpServer.create()
	         .bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
	         .port(1234)
	         .bindNow();
}
 
Example #14
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testHttpServerWithDomainSocketsWithHost() {
	HttpServer.create()
	          .bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
	          .host("localhost")
	          .bindNow();
}
 
Example #15
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testTcpClientWithDomainSocketsWithHost() {
	TcpClient.create()
	         .remoteAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
	         .host("localhost")
	         .connectNow();
}
 
Example #16
Source File: HttpRedirectTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
private void doTestHttpServerWithDomainSockets(HttpServer server, HttpClient client) {
	assumeTrue(LoopResources.hasNativeSupport());
	DisposableServer disposableServer = null;
	try {
		disposableServer =
				server.bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
				      .wiretap(true)
				      .route(r -> r.get("/redirect", (req, res) -> res.sendRedirect("/end"))
				                   .get("/end", (req, res) -> res.sendString(Mono.just("END"))))
				      .bindNow();

		String response =
				client.remoteAddress(disposableServer::address)
				      .wiretap(true)
				      .followRedirect(true)
				      .get()
				      .uri("/redirect")
				      .responseContent()
				      .aggregate()
				      .asString()
				      .block(Duration.ofSeconds(30));

		assertEquals("END", response);
	}
	finally {
		assertThat(disposableServer).isNotNull();
		disposableServer.disposeNow();
	}
}
 
Example #17
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = ChannelBindException.class)
public void testHttpServerWithDomainSocketsNIOTransport() {
	LoopResources loop = LoopResources.create("testHttpServerWithDomainSocketsNIOTransport");
	try {
		HttpServer.create()
		          .runOn(loop, false)
		          .bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
		          .bindNow();
	}
	finally {
		loop.disposeLater()
		    .block(Duration.ofSeconds(30));
	}
}
 
Example #18
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testHttpClientWithDomainSocketsWithHost() {
	HttpClient.create()
	          .remoteAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
	          .host("localhost")
	          .get()
	          .uri("/")
	          .responseContent()
	          .aggregate()
	          .block(Duration.ofSeconds(30));
}
 
Example #19
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testTcpClientWithDomainSocketsNIOTransport() {
	LoopResources loop = LoopResources.create("testTcpClientWithDomainSocketsNIOTransport");
	try {
		TcpClient.create()
		         .runOn(loop, false)
		         .remoteAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
		         .connectNow();
	}
	finally {
		loop.disposeLater()
		    .block(Duration.ofSeconds(30));
	}
}
 
Example #20
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testHttpServerWithDomainSocketsWithPort() {
	HttpServer.create()
	          .bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
	          .port(1234)
	          .bindNow();
}
 
Example #21
Source File: UdpClientTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testUdpClientWithDomainSocketsWithHost() {
	UdpClient.create()
	         .remoteAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
	         .host("localhost")
	         .connectNow();
}
 
Example #22
Source File: UdpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testUdpServerWithDomainSocketsWithPort() {
	UdpServer.create()
	         .bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
	         .port(1234)
	         .bindNow();
}
 
Example #23
Source File: UdpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testUdpServerWithDomainSocketsWithHost() {
	UdpServer.create()
	         .bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
	         .host("localhost")
	         .bindNow();
}
 
Example #24
Source File: TransportConnector.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Connect a {@link Channel} to the remote peer.
 *
 * @param config the transport configuration
 * @param remoteAddress the {@link SocketAddress} to connect to
 * @param resolverGroup the resolver which will resolve the address of the unresolved named address
 * @param channelInitializer the {@link ChannelInitializer} that will be used for initializing the channel pipeline
 * @return a {@link Mono} of {@link Channel}
 */
public static Mono<Channel> connect(TransportConfig config, SocketAddress remoteAddress,
		AddressResolverGroup<?> resolverGroup, ChannelInitializer<Channel> channelInitializer) {
	Objects.requireNonNull(config, "config");
	Objects.requireNonNull(remoteAddress, "remoteAddress");
	Objects.requireNonNull(resolverGroup, "resolverGroup");
	Objects.requireNonNull(channelInitializer, "channelInitializer");

	return doInitAndRegister(config, channelInitializer, remoteAddress instanceof DomainSocketAddress)
			.flatMap(channel -> doResolveAndConnect(channel, config, remoteAddress, resolverGroup));
}
 
Example #25
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
private void doTestHttpServerWithDomainSockets(HttpServer server, HttpClient client) {
	assumeTrue(LoopResources.hasNativeSupport());
	try {
		disposableServer =
				server.bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
				      .wiretap(true)
				      .handle((req, res) -> {
				          req.withConnection(conn -> {
				              assertThat(conn.channel().localAddress()).isNull();
				              assertThat(conn.channel().remoteAddress()).isNull();
				              assertThat(req.hostAddress()).isNull();
				              assertThat(req.remoteAddress()).isNull();
				          });
				          assertThat(req.requestHeaders().get(HttpHeaderNames.HOST)).isEqualTo("localhost");
				          return res.send(req.receive().retain());
				      })
				      .bindNow();

		String response =
				client.remoteAddress(disposableServer::address)
				      .wiretap(true)
				      .post()
				      .uri("/")
				      .send(ByteBufFlux.fromString(Flux.just("1", "2", "3")))
				      .responseContent()
				      .aggregate()
				      .asString()
				      .block(Duration.ofSeconds(30));

		assertEquals("123", response);
	}
	finally {
		assertThat(disposableServer).isNotNull();
		disposableServer.disposeNow();
	}
}
 
Example #26
Source File: EpollServerDomainSocketChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected void doBind(SocketAddress localAddress) throws Exception {
    int fd = fd().intValue();
    Native.bind(fd, localAddress);
    Native.listen(fd, config.getBacklog());
    local = (DomainSocketAddress) localAddress;
}
 
Example #27
Source File: HttpBlobStore.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
public static HttpBlobStore create(
    DomainSocketAddress domainSocketAddress,
    URI uri,
    int timeoutMillis,
    int remoteMaxConnections,
    @Nullable final Credentials creds)
    throws ConfigurationException, URISyntaxException, SSLException {

  if (KQueue.isAvailable()) {
    return new HttpBlobStore(
        KQueueEventLoopGroup::new,
        KQueueDomainSocketChannel.class,
        uri,
        timeoutMillis,
        remoteMaxConnections,
        creds,
        domainSocketAddress);
  } else if (Epoll.isAvailable()) {
    return new HttpBlobStore(
        EpollEventLoopGroup::new,
        EpollDomainSocketChannel.class,
        uri,
        timeoutMillis,
        remoteMaxConnections,
        creds,
        domainSocketAddress);
  } else {
    throw new ConfigurationException("Unix domain sockets are unsupported on this platform");
  }
}
 
Example #28
Source File: BuilderUtils.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the correct {@link Class} to use with the given {@link EventLoopGroup}.
 *
 * @param group        the {@link EventLoopGroup} for which the class is needed
 * @param addressClass The class of the address that to connect to.
 * @return the class that should be used for bootstrapping
 */
public static Class<? extends Channel> socketChannel(EventLoopGroup group,
                                                     Class<? extends SocketAddress> addressClass) {
    if (useEpoll(group)) {
        return DomainSocketAddress.class.isAssignableFrom(addressClass) ? EpollDomainSocketChannel.class :
                EpollSocketChannel.class;
    } else if (useKQueue(group)) {
        return DomainSocketAddress.class.isAssignableFrom(addressClass) ? KQueueDomainSocketChannel.class :
                KQueueSocketChannel.class;
    } else {
        return NioSocketChannel.class;
    }
}
 
Example #29
Source File: EpollSocketTestPermutation.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public static DomainSocketAddress newSocketAddress() {
    try {
        File file = File.createTempFile("netty", "dsocket");
        file.delete();
        return new DomainSocketAddress(file);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #30
Source File: UdpClientTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testUdpClientWithDomainSocketsWithPort() {
	UdpClient.create()
	         .remoteAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
	         .port(1234)
	         .connectNow();
}