io.netty.util.NetUtil Java Examples

The following examples show how to use io.netty.util.NetUtil. 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: TestDnsServer.java    From armeria with Apache License 2.0 6 votes vote down vote up
public TestDnsServer(Map<DnsQuestion, DnsResponse> responses,
                     @Nullable ChannelInboundHandlerAdapter beforeDnsServerHandler) {
    this.responses = ImmutableMap.copyOf(responses);

    final Bootstrap b = new Bootstrap();
    b.channel(TransportType.datagramChannelType(CommonPools.workerGroup()));
    b.group(CommonPools.workerGroup());
    b.handler(new ChannelInitializer() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            final ChannelPipeline p = ch.pipeline();
            p.addLast(new DatagramDnsQueryDecoder());
            p.addLast(new DatagramDnsResponseEncoder());
            if (beforeDnsServerHandler != null) {
                p.addLast(beforeDnsServerHandler);
            }
            p.addLast(new DnsServerHandler());
        }
    });

    channel = b.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
}
 
Example #2
Source File: WebSocketClientHandshaker.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
static CharSequence websocketHostValue(URI wsURL) {
    int port = wsURL.getPort();
    if (port == -1) {
        return wsURL.getHost();
    }
    String host = wsURL.getHost();
    if (port == HttpScheme.HTTP.port()) {
        return HttpScheme.HTTP.name().contentEquals(wsURL.getScheme())
                || WebSocketScheme.WS.name().contentEquals(wsURL.getScheme()) ?
                host : NetUtil.toSocketAddressString(host, port);
    }
    if (port == HttpScheme.HTTPS.port()) {
        return HttpScheme.HTTPS.name().contentEquals(wsURL.getScheme())
                || WebSocketScheme.WSS.name().contentEquals(wsURL.getScheme()) ?
                host : NetUtil.toSocketAddressString(host, port);
    }

    // if the port is not standard (80/443) its needed to add the port to the header.
    // See http://tools.ietf.org/html/rfc6454#section-6.2
    return NetUtil.toSocketAddressString(host, port);
}
 
Example #3
Source File: TestUtils.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * Return a free port which can be used to bind to
 *
 * @return port
 */
public static int getFreePort() {
    for (int i = 0; i < NUM_CANDIDATES; i ++) {
        final int port = nextCandidatePort();
        final InetSocketAddress wildcardAddr = new InetSocketAddress(port);
        final InetSocketAddress loopbackAddr = new InetSocketAddress(NetUtil.LOCALHOST4, port);

        // Ensure it is possible to bind on wildcard/loopback and tcp/udp.
        if (isTcpPortAvailable(wildcardAddr) &&
            isTcpPortAvailable(loopbackAddr) &&
            isUdpPortAvailable(wildcardAddr) &&
            isUdpPortAvailable(loopbackAddr)) {
            return port;
        }
    }

    throw new RuntimeException("unable to find a free port");
}
 
Example #4
Source File: DatagramConnectNotExistsTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public void testConnectNotExists(Bootstrap cb) throws Throwable {
    final Promise<Throwable> promise = ImmediateEventExecutor.INSTANCE.newPromise();
    cb.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            promise.trySuccess(cause);
        }
    });
    ChannelFuture future = cb.connect(NetUtil.LOCALHOST, SocketTestPermutation.BAD_PORT);
    try {
        Channel datagramChannel = future.syncUninterruptibly().channel();
        Assert.assertTrue(datagramChannel.isActive());
        datagramChannel.writeAndFlush(
                Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII)).syncUninterruptibly();
        if (!(datagramChannel instanceof OioDatagramChannel)) {
            Assert.assertTrue(promise.syncUninterruptibly().getNow() instanceof PortUnreachableException);
        }
    } finally {
        future.channel().close();
    }
}
 
Example #5
Source File: BuilderUtils.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
/**
 * Format an address into a canonical numeric format.
 *
 * @param address socket address
 * @return formatted address
 */
public static String formatCanonicalAddress(SocketAddress address) {
    // Try to return the "raw" address (without resolved host name, etc)
    if (address instanceof InetSocketAddress) {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) address;
        InetAddress inetAddress = inetSocketAddress.getAddress();
        // inetAddress could be null if SocketAddress is in an unresolved form
        if (inetAddress == null) {
            return address.toString();
        } else if (inetAddress instanceof Inet6Address) {
            return '[' + NetUtil.toAddressString(inetAddress) + "]:" + inetSocketAddress.getPort();
        } else {
            return NetUtil.toAddressString(inetAddress) + ':' + inetSocketAddress.getPort();
        }
    }
    return address.toString();
}
 
Example #6
Source File: Socks5ProxyHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private void sendConnectCommand(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress raddr = destinationAddress();
    Socks5AddressType addrType;
    String rhost;
    if (raddr.isUnresolved()) {
        addrType = Socks5AddressType.DOMAIN;
        rhost = raddr.getHostString();
    } else {
        rhost = raddr.getAddress().getHostAddress();
        if (NetUtil.isValidIpV4Address(rhost)) {
            addrType = Socks5AddressType.IPv4;
        } else if (NetUtil.isValidIpV6Address(rhost)) {
            addrType = Socks5AddressType.IPv6;
        } else {
            throw new ProxyConnectException(
                    exceptionMessage("unknown address type: " + StringUtil.simpleClassName(rhost)));
        }
    }

    ctx.pipeline().replace(decoderName, decoderName, new Socks5CommandResponseDecoder());
    sendToProxyServer(new DefaultSocks5CommandRequest(Socks5CommandType.CONNECT, addrType, rhost, raddr.getPort()));
}
 
Example #7
Source File: HttpProxyHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected Object newInitialMessage(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress raddr = destinationAddress();
    final String host = NetUtil.toSocketAddressString(raddr);
    FullHttpRequest req = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.CONNECT,
            host,
            Unpooled.EMPTY_BUFFER, false);

    req.headers().set(HttpHeaderNames.HOST, host);

    if (authorization != null) {
        req.headers().set(HttpHeaderNames.PROXY_AUTHORIZATION, authorization);
    }

    if (headers != null) {
        req.headers().add(headers);
    }

    return req;
}
 
Example #8
Source File: ZooKeeperReplicationConfig.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static int findServerId(Map<Integer, ZooKeeperAddress> servers, int currentServerId,
                                InetAddress addr) {
    final String ip = NetUtil.toAddressString(addr, true);
    for (Entry<Integer, ZooKeeperAddress> entry : servers.entrySet()) {
        final String zkAddr;
        try {
            zkAddr = NetUtil.toAddressString(InetAddress.getByName(entry.getValue().host()), true);
        } catch (UnknownHostException uhe) {
            throw new IllegalStateException(
                    "failed to resolve the IP address of the server name: " + entry.getValue().host());
        }

        if (zkAddr.equals(ip)) {
            final int serverId = entry.getKey().intValue();
            if (currentServerId < 0) {
                currentServerId = serverId;
            } else if (currentServerId != serverId) {
                throw new IllegalStateException(
                        "cannot auto-detect server ID because there are more than one IP address match. " +
                        "Both server ID " + currentServerId + " and " + serverId +
                        " have a matching IP address. Consider specifying server ID explicitly.");
            }
        }
    }
    return currentServerId;
}
 
Example #9
Source File: Endpoint.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static Endpoint create(String host, int port) {
    requireNonNull(host, "host");

    if (NetUtil.isValidIpV4Address(host)) {
        return new Endpoint(host, host, port, DEFAULT_WEIGHT, HostType.IPv4_ONLY);
    }

    if (NetUtil.isValidIpV6Address(host)) {
        final String ipV6Addr;
        if (host.charAt(0) == '[') {
            // Strip surrounding '[' and ']'.
            ipV6Addr = host.substring(1, host.length() - 1);
        } else {
            ipV6Addr = host;
        }
        return new Endpoint(ipV6Addr, ipV6Addr, port, DEFAULT_WEIGHT, HostType.IPv6_ONLY);
    }

    return new Endpoint(InternetDomainName.from(host).toString(),
                        null, port, DEFAULT_WEIGHT, HostType.HOSTNAME_ONLY);
}
 
Example #10
Source File: DefaultSocks4CommandResponse.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance.
 *
 * @param status the status of the response
 * @param dstAddr the {@code DSTIP} field of the response
 * @param dstPort the {@code DSTPORT} field of the response
 */
public DefaultSocks4CommandResponse(Socks4CommandStatus status, String dstAddr, int dstPort) {
    if (status == null) {
        throw new NullPointerException("cmdStatus");
    }
    if (dstAddr != null) {
        if (!NetUtil.isValidIpV4Address(dstAddr)) {
            throw new IllegalArgumentException(
                    "dstAddr: " + dstAddr + " (expected: a valid IPv4 address)");
        }
    }
    if (dstPort < 0 || dstPort > 65535) {
        throw new IllegalArgumentException("dstPort: " + dstPort + " (expected: 0~65535)");
    }

    this.status = status;
    this.dstAddr = dstAddr;
    this.dstPort = dstPort;
}
 
Example #11
Source File: TestDnsServer.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws IOException {
    InetSocketAddress address = new InetSocketAddress(NetUtil.LOCALHOST4, 0);
    UdpTransport transport = new UdpTransport(address.getHostName(), address.getPort());
    setTransports(transport);

    DatagramAcceptor acceptor = transport.getAcceptor();

    acceptor.setHandler(new DnsProtocolHandler(this, store) {
        @Override
        public void sessionCreated(IoSession session) throws Exception {
            // USe our own codec to support AAAA testing
            session.getFilterChain()
                .addFirst("codec", new ProtocolCodecFilter(new TestDnsProtocolUdpCodecFactory()));
        }
    });

    ((DatagramSessionConfig) acceptor.getSessionConfig()).setReuseAddress(true);

    // Start the listener
    acceptor.bind();
}
 
Example #12
Source File: Socks4ClientEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, Socks4CommandRequest msg, ByteBuf out) throws Exception {
    out.writeByte(msg.version().byteValue());
    out.writeByte(msg.type().byteValue());
    out.writeShort(msg.dstPort());
    if (NetUtil.isValidIpV4Address(msg.dstAddr())) {
        out.writeBytes(NetUtil.createByteArrayFromIpAddressString(msg.dstAddr()));
        ByteBufUtil.writeAscii(out, msg.userId());
        out.writeByte(0);
    } else {
        out.writeBytes(IPv4_DOMAIN_MARKER);
        ByteBufUtil.writeAscii(out, msg.userId());
        out.writeByte(0);
        ByteBufUtil.writeAscii(out, msg.dstAddr());
        out.writeByte(0);
    }
}
 
Example #13
Source File: HttpServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testHeadHeadersOnly(WebClient client, SessionProtocol protocol) throws Exception {
    assumeThat(protocol).isSameAs(H1C);

    final int port = server.httpPort();
    try (Socket s = new Socket(NetUtil.LOCALHOST, port)) {
        s.setSoTimeout(10000);
        final InputStream in = s.getInputStream();
        final OutputStream out = s.getOutputStream();
        out.write("HEAD /head-headers-only HTTP/1.0\r\n\r\n".getBytes(StandardCharsets.US_ASCII));

        // Should neither be chunked nor have content.
        assertThat(new String(ByteStreams.toByteArray(in)))
                .isEqualTo("HTTP/1.1 200 OK\r\n" +
                           "content-type: text/plain; charset=utf-8\r\n" +
                           "content-length: 6\r\n\r\n");
    }
}
 
Example #14
Source File: OioEventLoopTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTooManyAcceptedChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    assertThat(s.getInputStream().read(), is(-1));
    s.close();

    g.shutdownGracefully();
}
 
Example #15
Source File: HttpHeaderUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Nullable
private static InetSocketAddress createInetSocketAddress(String address) throws UnknownHostException {
    final char firstChar = address.charAt(0);
    if (firstChar == '_' ||
        (firstChar == 'u' && "unknown".equals(address))) {
        // To early return when the address is not an IP address.
        // - an obfuscated identifier which must start with '_'
        //   - https://tools.ietf.org/html/rfc7239#section-6.3
        // - the "unknown" identifier
        return null;
    }

    // Remote quotes. e.g. "[2001:db8:cafe::17]:4711" => [2001:db8:cafe::17]:4711
    final String addr = firstChar == '"' ? QUOTED_STRING_TRIMMER.trimFrom(address) : address;
    try {
        final HostAndPort hostAndPort = HostAndPort.fromString(addr);
        final byte[] addressBytes = NetUtil.createByteArrayFromIpAddressString(hostAndPort.getHost());
        if (addressBytes == null) {
            logger.debug("Failed to parse an address: {}", address);
            return null;
        }
        return new InetSocketAddress(InetAddress.getByAddress(addressBytes),
                                     hostAndPort.getPortOrDefault(0));
    } catch (IllegalArgumentException e) {
        logger.debug("Failed to parse an address: {}", address, e);
        return null;
    }
}
 
Example #16
Source File: SSAddrRequest.java    From shadowsocks-java with MIT License 5 votes vote down vote up
public SSAddrRequest(SocksAddressType addressType, String host, int port) {
     if (addressType == null) {
        throw new NullPointerException("addressType");
    } else if (host == null) {
        throw new NullPointerException("host");
    } else {
        switch(addressType) {
            case IPv4:
                if (!NetUtil.isValidIpV4Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv4 address");
                }
                break;
            case DOMAIN:
                if (IDN.toASCII(host).length() > 255) {
                    throw new IllegalArgumentException(host + " IDN: " + IDN.toASCII(host) + " exceeds 255 char limit");
                }
                break;
            case IPv6:
                if (!NetUtil.isValidIpV6Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv6 address");
                }
            case UNKNOWN:
        }

        if (port > 0 && port < 65536) {
            this.addressType = addressType;
            this.host = IDN.toASCII(host);
            this.port = port;
        } else {
            throw new IllegalArgumentException(port + " is not in bounds 0 < x < 65536");
        }
    }
}
 
Example #17
Source File: Socks5AddressEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void encodeAddress(Socks5AddressType addrType, String addrValue, ByteBuf out) throws Exception {
    final byte typeVal = addrType.byteValue();
    if (typeVal == Socks5AddressType.IPv4.byteValue()) {
        if (addrValue != null) {
            out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue));
        } else {
            out.writeInt(0);
        }
    } else if (typeVal == Socks5AddressType.DOMAIN.byteValue()) {
        if (addrValue != null) {
            out.writeByte(addrValue.length());
            out.writeCharSequence(addrValue, CharsetUtil.US_ASCII);
        } else {
            out.writeByte(1);
            out.writeByte(0);
        }
    } else if (typeVal == Socks5AddressType.IPv6.byteValue()) {
        if (addrValue != null) {
            out.writeBytes(NetUtil.createByteArrayFromIpAddressString(addrValue));
        } else {
            out.writeLong(0);
            out.writeLong(0);
        }
    } else {
        throw new EncoderException("unsupported addrType: " + (addrType.byteValue() & 0xFF));
    }
}
 
Example #18
Source File: NioSocketChannelTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * Reproduces the issue #1679
 */
@Test
public void testFlushAfterGatheredFlush() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                // Trigger a gathering write by writing two buffers.
                ctx.write(Unpooled.wrappedBuffer(new byte[] { 'a' }));
                ChannelFuture f = ctx.write(Unpooled.wrappedBuffer(new byte[] { 'b' }));
                f.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // This message must be flushed
                        ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[]{'c'}));
                    }
                });
                ctx.flush();
            }
        });

        SocketAddress address = sb.bind(0).sync().channel().localAddress();

        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());

        DataInput in = new DataInputStream(s.getInputStream());
        byte[] buf = new byte[3];
        in.readFully(buf);

        assertThat(new String(buf, CharsetUtil.US_ASCII), is("abc"));

        s.close();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example #19
Source File: EpollSocketTcpMd5Test.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test(expected = ConnectTimeoutException.class)
public void testKeyMismatch() throws Exception {
    server.config().setOption(EpollChannelOption.TCP_MD5SIG,
            Collections.<InetAddress, byte[]>singletonMap(NetUtil.LOCALHOST4, SERVER_KEY));

    EpollSocketChannel client = (EpollSocketChannel) new Bootstrap().group(GROUP)
            .channel(EpollSocketChannel.class)
            .handler(new ChannelInboundHandlerAdapter())
            .option(EpollChannelOption.TCP_MD5SIG,
                    Collections.<InetAddress, byte[]>singletonMap(NetUtil.LOCALHOST4, BAD_KEY))
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
            .connect(server.localAddress()).syncUninterruptibly().channel();
    client.close().syncUninterruptibly();
}
 
Example #20
Source File: MailSslTest.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
@Test
public void mailTestSSLValidCertIpv6(TestContext testContext) {
  // don't run ipv6 tests when ipv4 is preferred, this should enable running the tests
  // on CI where ipv6 is not configured
  Assume.assumeFalse("no ipv6 support", NetUtil.isIpV4StackPreferred() || "true".equals(System.getProperty("test.disableIpV6")));
  this.testContext = testContext;
  startServer(SERVER_JKS);
  final MailConfig config = new MailConfig("::1", 1465, StartTLSOptions.DISABLED, LoginOption.DISABLED)
      .setSsl(true).setKeyStore(CLIENT_JKS).setKeyStorePassword("password");
  MailClient mailClient = MailClient.create(vertx, config);
  testSuccess(mailClient);
}
 
Example #21
Source File: SocksCmdResponse.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs new response and includes provided host and port as part of it.
 *
 * @param cmdStatus status of the response
 * @param addressType type of host parameter
 * @param host host (BND.ADDR field) is address that server used when connecting to the target host.
 *             When null a value of 4/8 0x00 octets will be used for IPv4/IPv6 and a single 0x00 byte will be
 *             used for domain addressType. Value is converted to ASCII using {@link IDN#toASCII(String)}.
 * @param port port (BND.PORT field) that the server assigned to connect to the target host
 * @throws NullPointerException in case cmdStatus or addressType are missing
 * @throws IllegalArgumentException in case host or port cannot be validated
 * @see IDN#toASCII(String)
 */
public SocksCmdResponse(SocksCmdStatus cmdStatus, SocksAddressType addressType, String host, int port) {
    super(SocksResponseType.CMD);
    if (cmdStatus == null) {
        throw new NullPointerException("cmdStatus");
    }
    if (addressType == null) {
        throw new NullPointerException("addressType");
    }
    if (host != null) {
        switch (addressType) {
            case IPv4:
                if (!NetUtil.isValidIpV4Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv4 address");
                }
                break;
            case DOMAIN:
                String asciiHost = IDN.toASCII(host);
                if (asciiHost.length() > 255) {
                    throw new IllegalArgumentException(host + " IDN: " + asciiHost + " exceeds 255 char limit");
                }
                host = asciiHost;
                break;
            case IPv6:
                if (!NetUtil.isValidIpV6Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv6 address");
                }
                break;
            case UNKNOWN:
                break;
        }
    }
    if (port < 0 || port > 65535) {
        throw new IllegalArgumentException(port + " is not in bounds 0 <= x <= 65535");
    }
    this.cmdStatus = cmdStatus;
    this.addressType = addressType;
    this.host = host;
    this.port = port;
}
 
Example #22
Source File: MailSslTest.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
@Test
public void mailTestSSLValidCertIpv6_2(TestContext testContext) {
  Assume.assumeFalse("no ipv6 support", NetUtil.isIpV4StackPreferred() || "true".equals(System.getProperty("test.disableIpV6")));
  this.testContext = testContext;
  startServer(SERVER_JKS);
  final MailConfig config = new MailConfig("[::1]", 1465, StartTLSOptions.DISABLED, LoginOption.DISABLED)
      .setSsl(true).setKeyStore(CLIENT_JKS).setKeyStorePassword("password");
  MailClient mailClient = MailClient.create(vertx, config);
  testSuccess(mailClient);
}
 
Example #23
Source File: SocksCmdRequest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void encodeAsByteBuf(ByteBuf byteBuf) {
    byteBuf.writeByte(protocolVersion().byteValue());
    byteBuf.writeByte(cmdType.byteValue());
    byteBuf.writeByte(0x00);
    byteBuf.writeByte(addressType.byteValue());
    switch (addressType) {
        case IPv4: {
            byteBuf.writeBytes(NetUtil.createByteArrayFromIpAddressString(host));
            byteBuf.writeShort(port);
            break;
        }

        case DOMAIN: {
            byteBuf.writeByte(host.length());
            byteBuf.writeCharSequence(host, CharsetUtil.US_ASCII);
            byteBuf.writeShort(port);
            break;
        }

        case IPv6: {
            byteBuf.writeBytes(NetUtil.createByteArrayFromIpAddressString(host));
            byteBuf.writeShort(port);
            break;
        }
    }
}
 
Example #24
Source File: HttpServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testExpect100ContinueDoesNotBreakHttp1Decoder(WebClient client, SessionProtocol protocol)
        throws Exception {
    assumeThat(protocol).isSameAs(H1C);

    final int port = server.httpPort();
    try (Socket s = new Socket(NetUtil.LOCALHOST, port)) {
        s.setSoTimeout(10000);
        final InputStream in = s.getInputStream();
        final OutputStream out = s.getOutputStream();
        // Send 4 pipelined requests with 'Expect: 100-continue' header.
        out.write((Strings.repeat("POST /head-headers-only HTTP/1.1\r\n" +
                                  "Expect: 100-continue\r\n" +
                                  "Content-Length: 0\r\n\r\n", 3) +
                   "POST /head-headers-only HTTP/1.1\r\n" +
                   "Expect: 100-continue\r\n" +
                   "Content-Length: 0\r\n" +
                   "Connection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));

        // '100 Continue' responses must appear once for each '200 OK' response.
        assertThat(new String(ByteStreams.toByteArray(in)))
                .isEqualTo(Strings.repeat("HTTP/1.1 100 Continue\r\n\r\n" +
                                          "HTTP/1.1 200 OK\r\n" +
                                          "content-type: text/plain; charset=utf-8\r\n" +
                                          "content-length: 6\r\n\r\n200 OK", 4));
    }
}
 
Example #25
Source File: NioSocketChannelTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Reproduces the issue #1679
 */
@Test
public void testFlushAfterGatheredFlush() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                // Trigger a gathering write by writing two buffers.
                ctx.write(Unpooled.wrappedBuffer(new byte[] { 'a' }));
                ChannelFuture f = ctx.write(Unpooled.wrappedBuffer(new byte[] { 'b' }));
                f.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // This message must be flushed
                        ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[]{'c'}));
                    }
                });
                ctx.flush();
            }
        });

        SocketAddress address = sb.bind(0).sync().channel().localAddress();

        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());

        DataInput in = new DataInputStream(s.getInputStream());
        byte[] buf = new byte[3];
        in.readFully(buf);

        assertThat(new String(buf, CharsetUtil.US_ASCII), is("abc"));

        s.close();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example #26
Source File: SslUtils.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link SslHandler} which will supports SNI if the {@link InetSocketAddress} was created from
 * a hostname.
 *
 * @param context the {@link SslContext} which will be used to create the {@link SslHandler}
 * @param allocator the {@link ByteBufAllocator} which will be used to allocate direct memory if required for
 * {@link SSLEngine}
 * @param hostnameVerificationAlgorithm see {@link SSLParameters#setEndpointIdentificationAlgorithm(String)}.
 * If this is {@code null} or empty then you will be vulnerable to a MITM attack.
 * @param hostnameVerificationHost the non-authoritative name of the host.
 * @param hostnameVerificationPort the non-authoritative port.
 * @return a {@link SslHandler}
 */
static SslHandler newHandler(SslContext context, ByteBufAllocator allocator,
                             @Nullable String hostnameVerificationAlgorithm,
                             @Nullable String hostnameVerificationHost,
                             int hostnameVerificationPort) {
    if (hostnameVerificationHost == null) {
        return newHandler(context, allocator);
    }

    SslHandler handler = context.newHandler(allocator, hostnameVerificationHost, hostnameVerificationPort);
    SSLEngine engine = handler.engine();
    try {
        SSLParameters parameters = engine.getSSLParameters();
        parameters.setEndpointIdentificationAlgorithm(hostnameVerificationAlgorithm);
        if (!NetUtil.isValidIpV4Address(hostnameVerificationHost) &&
                !NetUtil.isValidIpV6Address(hostnameVerificationHost)) {
            // SNI doesn't permit IP addresses!
            // https://tools.ietf.org/html/rfc6066#section-3
            // Literal IPv4 and IPv6 addresses are not permitted in "HostName".
            parameters.setServerNames(Collections.singletonList(new SNIHostName(hostnameVerificationHost)));
        }
        engine.setSSLParameters(parameters);
    } catch (Throwable cause) {
        ReferenceCountUtil.release(engine);
        throw cause;
    }
    return handler;
}
 
Example #27
Source File: NativeTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddressIpv4() throws Exception {
    InetSocketAddress inetAddress = new InetSocketAddress(NetUtil.LOCALHOST4, 9999);
    byte[] bytes = new byte[8];
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    buffer.put(inetAddress.getAddress().getAddress());
    buffer.putInt(inetAddress.getPort());
    Assert.assertEquals(inetAddress, address(buffer.array(), 0, bytes.length));
}
 
Example #28
Source File: OioEventLoopTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testTooManyClientChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Bootstrap cb = new Bootstrap();
    cb.channel(OioSocketChannel.class);
    cb.group(g);
    cb.handler(new ChannelInboundHandlerAdapter());
    ChannelFuture f2 = cb.connect(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    f2.await();

    assertThat(f2.cause(), is(instanceOf(ChannelException.class)));
    assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels"));

    final CountDownLatch notified = new CountDownLatch(1);
    f2.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            notified.countDown();
        }
    });

    notified.await();
    g.shutdownGracefully();
}
 
Example #29
Source File: HttpServerPathTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void urlPathAssertion(HttpStatus expected, String path) throws Exception {
    final String requestString = "GET " + path + " HTTP/1.0\r\n\r\n";

    try (Socket s = new Socket(NetUtil.LOCALHOST, server.httpPort())) {
        s.setSoTimeout(10000);
        s.getOutputStream().write(requestString.getBytes(StandardCharsets.US_ASCII));
        assertThat(new String(ByteStreams.toByteArray(s.getInputStream()), StandardCharsets.US_ASCII))
                .as(path)
                .startsWith("HTTP/1.1 " + expected);
    }
}
 
Example #30
Source File: NativeTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddressIpv4() throws Exception {
    InetSocketAddress inetAddress = new InetSocketAddress(NetUtil.LOCALHOST4, 9999);
    byte[] bytes = new byte[8];
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    buffer.put(inetAddress.getAddress().getAddress());
    buffer.putInt(inetAddress.getPort());
    Assert.assertEquals(inetAddress, Native.address(buffer.array(), 0, bytes.length));
}