Example usage for io.netty.handler.ssl SslContextBuilder forServer

List of usage examples for io.netty.handler.ssl SslContextBuilder forServer

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslContextBuilder forServer.

Prototype

boolean forServer

To view the source code for io.netty.handler.ssl SslContextBuilder forServer.

Click Source Link

Usage

From source file:p2p_server.P2p_server.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    List<ChannelFuture> futures = new ArrayList<>();
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();

    try {/*  ww  w. ja  va2  s  .c  o m*/
        ServerBootstrap appboot = new ServerBootstrap();
        appboot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 8192).childHandler(new AppChildChannelHandler(sslCtx));

        appboot.option(ChannelOption.SO_REUSEADDR, true);
        appboot.option(ChannelOption.TCP_NODELAY, true);
        appboot.childOption(ChannelOption.SO_KEEPALIVE, true);
        appboot.childOption(ChannelOption.SO_RCVBUF, 512);
        appboot.childOption(ChannelOption.SO_SNDBUF, 512);

        ServerBootstrap devboot = new ServerBootstrap();
        devboot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 8192).childHandler(new DevChildChannelHandler(sslCtx));

        devboot.option(ChannelOption.SO_REUSEADDR, true);
        devboot.option(ChannelOption.TCP_NODELAY, true);
        devboot.childOption(ChannelOption.SO_KEEPALIVE, true);
        devboot.childOption(ChannelOption.SO_RCVBUF, 512);
        devboot.childOption(ChannelOption.SO_SNDBUF, 512);

        //ChannelFuture f = boostrap.bind(port).sync();
        futures.add(devboot.bind(5560));
        futures.add(appboot.bind(5561));
        for (ChannelFuture f : futures) {
            f.sync();
        }

        for (ChannelFuture f : futures) {
            f.channel().closeFuture().sync();
        }
        // ???
        //   f.channel().closeFuture().sync();

    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();

    }

}

From source file:ratpack.config.internal.module.NettySslContextDeserializer.java

License:Apache License

@SuppressWarnings("Duplicates")
@Override/*  w w  w .j a  v a 2s  . c  o  m*/
public SslContext deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    ObjectNode node = jp.readValueAsTree();

    try {
        String keyStoreFile = node.path("keystoreFile").asText();
        String keyStorePassword = node.path("keystorePassword").asText();
        String trustStoreFile = node.path("truststoreFile").asText();
        String trustStorePassword = node.path("truststorePassword").asText();

        if (keyStoreFile.isEmpty()) {
            throw new IllegalStateException("keystoreFile must be set if any ssl properties are set");
        } else if (keyStorePassword.isEmpty()) {
            throw new IllegalStateException("keystorePassword must be set if any ssl properties are set");
        } else if (!trustStoreFile.isEmpty() && trustStorePassword.isEmpty()) {
            throw new IllegalStateException(
                    "truststorePassword must be specified when truststoreFile is specified");
        }

        KeyManagerFactory keyManagerFactory;
        try (InputStream is = Files.newInputStream(Paths.get(keyStoreFile))) {
            keyManagerFactory = SslContexts.keyManagerFactory(is, keyStorePassword.toCharArray());
        }

        SslContextBuilder builder = SslContextBuilder.forServer(keyManagerFactory);

        if (!trustStoreFile.isEmpty()) {
            try (InputStream is = Files.newInputStream(Paths.get(trustStoreFile))) {
                builder.trustManager(SslContexts.trustManagerFactory(is, trustStorePassword.toCharArray()));
            }
        }

        return builder.build();
    } catch (GeneralSecurityException ex) {
        throw Exceptions.uncheck(ex);
    }
}

From source file:reactor.ipc.netty.http.client.HttpClientTest.java

License:Open Source License

@Test
public void sshExchangeRelativeGet() throws CertificateException, SSLException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient()
            //make the client to trust the self signed certificate
            .trustManager(ssc.cert()).build();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newHandler((req, resp) -> resp.sendString(Flux.just("hello ", req.uri()))).block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient)).get("/foo")
            .block(Duration.ofMillis(200));
    context.dispose();// w  ww.  j  a  v  a  2 s  . c  o m
    context.onClose().block();

    String responseString = response.receive().aggregate().asString(CharsetUtil.UTF_8).block();
    assertThat(responseString).isEqualTo("hello /foo");
}

From source file:reactor.ipc.netty.http.client.HttpClientTest.java

License:Open Source License

@Test
public void sshExchangeAbsoluteGet() throws CertificateException, SSLException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newHandler((req, resp) -> resp.sendString(Flux.just("hello ", req.uri()))).block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient))
            .get("https://localhost:" + context.address().getPort() + "/foo").block(Duration.ofMillis(200));
    context.dispose();/*from  w w w.  j  a v  a2 s. c  om*/
    context.onClose().block();

    String responseString = response.receive().aggregate().asString(CharsetUtil.UTF_8).block();
    assertThat(responseString).isEqualTo("hello /foo");
}

From source file:reactor.ipc.netty.http.client.HttpClientTest.java

License:Open Source License

@Test
public void secureSendFile() throws CertificateException, SSLException, InterruptedException {
    Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").getFile());
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build();
    AtomicReference<String> uploaded = new AtomicReference<>();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newRouter(//from   w  w w.  ja va 2  s .co  m
                    r -> r.post("/upload",
                            (req, resp) -> req.receive().aggregate().asString().doOnNext(uploaded::set)
                                    .then(resp.status(201).sendString(Mono.just("Received File")).then())))
            .block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient))
            .post("/upload", r -> r.sendFile(largeFile)).block(Duration.ofSeconds(120));

    context.dispose();
    context.onClose().block();

    String responseBody = response.receive().aggregate().asString().block();
    assertThat(response.status().code()).isEqualTo(201);
    assertThat(responseBody).isEqualTo("Received File");

    assertThat(uploaded.get())
            .startsWith(
                    "This is an UTF-8 file that is larger than 1024 bytes.\n" + "It contains accents like .")
            .contains("1024 mark here -><- 1024 mark here").endsWith("End of File");
}

From source file:reactor.ipc.netty.http.server.HttpServerTests.java

License:Open Source License

@Test
public void secureSendFile() throws CertificateException, SSLException, InterruptedException {
    Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").getFile());
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newHandler((req, resp) -> resp.sendFile(largeFile)).block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient)).get("/foo")
            .block(Duration.ofSeconds(120));

    context.dispose();/* www  .  j a  v  a  2s  . c  o m*/
    context.onClose().block();

    String body = response.receive().aggregate().asString().block();

    assertThat(body)
            .startsWith(
                    "This is an UTF-8 file that is larger than 1024 bytes.\n" + "It contains accents like .")
            .contains("1024 mark here -><- 1024 mark here").endsWith("End of File");
}

From source file:reactor.ipc.netty.NettyOutboundTest.java

License:Open Source License

@Test
public void sendFileWithTlsUsesChunkedFile()
        throws URISyntaxException, NoSuchAlgorithmException, SSLException, CertificateException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    final SslHandler sslHandler = sslCtx.newHandler(ByteBufAllocator.DEFAULT);

    List<Class<?>> messageWritten = new ArrayList<>(2);
    List<Object> clearMessages = new ArrayList<>(2);

    EmbeddedChannel channel = new EmbeddedChannel(
            //outbound: pipeline reads inverted
            //bytes are encrypted
            sslHandler,/*from w ww  .  j  a  v  a 2 s  .  c  o  m*/
            //capture the chunks unencrypted, transform as Strings:
            new MessageToMessageEncoder<ByteBuf>() {
                @Override
                protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
                        throws Exception {
                    clearMessages.add(msg.toString(CharsetUtil.UTF_8));
                    out.add(msg.retain()); //the encoder will release the buffer, make sure it is retained for SslHandler
                }
            },
            //transform the ChunkedFile into ByteBuf chunks:
            new ChunkedWriteHandler(),
            //helps to ensure a ChunkedFile was written outs
            new MessageToMessageEncoder<Object>() {
                @Override
                protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out)
                        throws Exception {
                    messageWritten.add(msg.getClass());
                    //passing the ChunkedFile through this method releases it, which is undesired
                    ReferenceCountUtil.retain(msg);
                    out.add(msg);
                }
            });

    NettyContext mockContext = () -> channel;
    NettyOutbound outbound = new NettyOutbound() {
        @Override
        public NettyContext context() {
            return mockContext;
        }

        @Override
        public FileChunkedStrategy getFileChunkedStrategy() {
            return FILE_CHUNKED_STRATEGY_1024_NOPIPELINE;
        }
    };
    channel.writeOneOutbound(1);

    try {
        outbound.sendFile(Paths.get(getClass().getResource("/largeFile.txt").toURI())).then()
                .block(Duration.ofSeconds(1)); //TODO investigate why this hangs
    } catch (IllegalStateException e) {
        if (!"Timeout on blocking read for 1000 MILLISECONDS".equals(e.getMessage()))
            throw e;
        System.err.println(e);
    }

    assertThat(messageWritten).containsExactly(Integer.class, ChunkedFile.class);

    assertThat(clearMessages).hasSize(2).element(0).asString().startsWith(
            "This is an UTF-8 file that is larger than 1024 bytes.\nIt contains accents like .\nGARBAGE")
            .endsWith("1024 mark here ->");
    assertThat(clearMessages).element(1).asString().startsWith("<- 1024 mark here").endsWith("End of File");
}

From source file:reactor.ipc.netty.options.ServerOptions.java

License:Open Source License

/**
 * Enable SSL service with a self-signed certificate and allows extra
 * parameterization of the self signed {@link SslContextBuilder}. The builder is
 * then used to invoke {@link #sslContext(SslContext)}.
 *
 * @param configurator the builder callback to setup the self-signed {@link SslContextBuilder}
 *
 * @return {@code this}/*  ww w .  j a  v a2  s.c om*/
 */
public ServerOptions sslSelfSigned(Consumer<? super SslContextBuilder> configurator) {
    Objects.requireNonNull(configurator, "configurator");
    SelfSignedCertificate ssc;
    try {
        ssc = new SelfSignedCertificate();
        SslContextBuilder builder = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
        configurator.accept(builder);
        return sslContext(builder.build());
    } catch (Exception sslException) {
        throw Exceptions.bubble(sslException);
    }
}

From source file:server.operation.OperationServer.java

License:Apache License

public void start() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from   w  ww .jav a 2  s  . c  o  m
        // ??   ?  ?? ? ?.
        //?, ??  ? .
        //jvm  ?? ?. (netty api )
        //SelfSignedCertificate ssc = new SelfSignedCertificate();
        //sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();

        //File cert = new File("./resource/cert/nene.crt");
        //File privateKey= new File("./resource/cert/privatekey.pem");

        //resources/cert ? ?? ? ?? .
        //? pkcs#8? .
        final File cert = ResourceUtils.getFile("classpath:/cert/nene.crt");
        final File privateKey = ResourceUtils.getFile("classpath:/cert/nene.pem");
        sslCtx = SslContextBuilder.forServer(cert, privateKey, "tkfkdgo123!").build();
        System.out.println("ssl? ??. : " + SSL + ", port : " + PORT);

    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        p.addLast(new LoggingHandler(LogLevel.DEBUG),
                                //new StringEncoder(CharsetUtil.UTF_8),
                                //new LineBasedFrameDecoder(8192),
                                //new StringDecoder(CharsetUtil.UTF_8),
                                new ChunkedWriteHandler(),
                                new OperationServerHandler(applicationContext, eventPublisher));
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        //f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        //bossGroup.shutdownGracefully();
        //workerGroup.shutdownGracefully();
    }
}

From source file:server.telnet.TelnetServer.java

License:Apache License

public Channel start() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  ww w  .ja  v a  2 s .  co m
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new TelnetServerInitializer(sslCtx));

        // b.bind(PORT).sync();// .channel().closeFuture().sync();

        Channel ch = b.bind(PORT).sync().channel();

        return ch;
    } finally {
        // bossGroup.shutdownGracefully();
        // workerGroup.shutdownGracefully();
    }
}