Example usage for io.netty.channel ChannelHandlerContext pipeline

List of usage examples for io.netty.channel ChannelHandlerContext pipeline

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext pipeline.

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline

Usage

From source file:gribbit.http.response.FileResponse.java

License:Open Source License

@Override
public void writeResponse(ChannelHandlerContext ctx) throws Exception {
    // FileRegions cannot be used with SSL, have to use chunked content.
    // TODO: Does this work with HTTP2?
    isChunked |= ctx.pipeline().get(SslHandler.class) != null;

    sendHeaders(ctx);// w  ww  .j a va  2  s.  c  om

    // TODO: Add content compression.
    if (!request.isHEADRequest()) {
        // Write file content to channel. Both methods will close file after sending, see:
        // https://github.com/netty/netty/issues/2474#issuecomment-117905496
        if (!isChunked) {
            // Use FileRegions if possible, which supports zero-copy / mmio.
            ctx.write(new DefaultFileRegion(raf.getChannel(), 0, contentLength));
            // Write the end marker
            ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        } else {
            // Can't use FileRegions / zero-copy with SSL
            // HttpChunkedInput will write the end marker (LastHttpContent) for us, see:
            // https://github.com/netty/netty/commit/4ba2ce3cbbc55391520cfc98a7d4227630fbf978
            ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, contentLength, 8192)));
        }
    }
}

From source file:gwlpr.protocol.handshake.HandshakeHandler.java

License:Open Source License

@Override
protected void decode(final ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    ByteBuf buf = in.order(ByteOrder.LITTLE_ENDIAN);

    switch (server) {
    case LoginServer: // client version:
    {//w  ww.  j a v  a  2s  .  c om
        // lengthcheck
        if (buf.readableBytes() < (P000_ClientVersion.getLength() + P000_ClientSeed.getLength())) {
            return;
        }

        // get the header
        P000_ClientVersion.Header header = P000_ClientVersion.serializeHeader(buf);

        // check the header
        if (header == null || !P000_ClientVersion.check(header)) {
            return;
        }

        // get the data
        P000_ClientVersion.Payload payload = P000_ClientVersion.serializePayload(buf);

        LOGGER.debug(String.format("Got the client version: %d", payload.ClientVersion));
    }
        break;

    case GameServer: // verify client:
    {
        // lengthcheck
        if (buf.readableBytes() < (P000_VerifyClient.getLength() + P000_ClientSeed.getLength())) {
            return;
        }

        // get the header
        P000_VerifyClient.Header header = P000_VerifyClient.serializeHeader(buf);

        // check the header
        if (header == null || !P000_VerifyClient.check(header)) {
            return;
        }

        // get the data
        verifyClient = P000_VerifyClient.serializePayload(buf);

        LOGGER.debug(String.format("Got the verify client packet."));
    }
        break;
    }

    // client seed:
    // get the header
    P000_ClientSeed.Header header = P000_ClientSeed.serializeHeader(buf);

    // check the header
    if (header == null || !P000_ClientSeed.check(header)) {
        return;
    }

    // get the data
    P000_ClientSeed.Payload payload = P000_ClientSeed.serializePayload(buf);

    LOGGER.debug("Got the client seed packet.");

    // INITIALIZE ENCRYPTION WITH THE CLIENT SEED PAYLOAD

    // generate the shared key
    byte[] sharedKeyBytes = EncryptionUtils.generateSharedKey(payload.ClientPublicKey);

    // start RC4 key generation
    byte[] randomBytes = new byte[20];
    new SecureRandom().nextBytes(randomBytes);
    final byte[] rc4Key = EncryptionUtils.hash(randomBytes);

    // encrypt the RC4 key before sending it to the client
    byte[] xoredRandomBytes = EncryptionUtils.XOR(randomBytes, sharedKeyBytes);

    // INITIALIZATION OF ENCRYPTION DONE

    // we can set the RC4 decoder now... if encryption is enabled
    if (encryption == EncryptionOptions.Enable) {
        RC4Codec.Decoder decoder = new RC4Codec.Decoder(rc4Key);
        ctx.pipeline().addFirst(decoder);
        LOGGER.debug("RC4Decoder added to pipeline.");
    }

    // now send the server seed packet
    P001_ServerSeed serverSeed = new P001_ServerSeed();
    serverSeed.setEncryptedRC4Key(xoredRandomBytes);

    buf = ctx.alloc().buffer(70).order(ByteOrder.LITTLE_ENDIAN);
    serverSeed.serializeInto(buf);

    ChannelFuture cf = ctx.writeAndFlush(buf);

    // also remove this handler
    ctx.pipeline().remove(this);

    // set the RC4 encoder only after the serverseed packet has been send!
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (encryption == EncryptionOptions.Enable) {
                // add the rc4 codec if encryption is enabled
                RC4Codec.Encoder encoder = new RC4Codec.Encoder(rc4Key);
                ctx.pipeline().addFirst(encoder);
                LOGGER.debug("RC4Encoder added to pipeline.");
            }

            // tell the channel's context that handshake has been done
            ctx.channel().attr(GameAppContextKey.KEY).get()
                    .trigger(new HandShakeDoneEvent(ctx.channel(), verifyClient));
        }
    });
}

From source file:http2.server.Http2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0
 *//*from ww w.  j a va 2 s.c  o  m*/
private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();

    p.addLast(sourceCodec);
    p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
    // ?
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)");
            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null,
                    new HelloWorldHttp1Handler("Direct. No Upgrade Attempted."));
            pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
            ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
        }
    });

    p.addLast(new UserEventLogger());
}

From source file:io.advantageous.conekt.http.impl.ConektHttpHandler.java

License:Open Source License

@Override
protected void channelRead(final C connection, final ContextImpl context, final ChannelHandlerContext chctx,
        final Object msg) throws Exception {
    if (connection != null) {
        context.executeFromIO(() -> doMessageReceived(connection, chctx, msg));
    } else {/*from ww  w .  j  ava  2  s.c  om*/
        // We execute this directly as we don't have a context yet, the context will have to be set manually
        // inside doMessageReceived();
        try {
            doMessageReceived(null, chctx, msg);
        } catch (Throwable t) {
            chctx.pipeline().fireExceptionCaught(t);
        }
    }
}

From source file:io.airlift.drift.transport.netty.server.OptionalSslHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf in, List<Object> out) {
    // minimum bytes required to detect ssl
    if (in.readableBytes() < SSL_RECORD_HEADER_LENGTH) {
        return;/*from w  w w. jav  a2s.com*/
    }

    ChannelPipeline pipeline = context.pipeline();
    if (isTls(in, in.readerIndex())) {
        pipeline.replace(this, "ssl", sslContext.newHandler(context.alloc()));
    } else {
        pipeline.remove(this);
    }
}

From source file:io.airlift.drift.transport.netty.server.ThriftProtocolDetection.java

License:Apache License

private void switchToTransport(ChannelHandlerContext context, Transport transport,
        Optional<Protocol> protocol) {
    ChannelPipeline pipeline = context.pipeline();
    transport.addFrameHandlers(pipeline, protocol, maxFrameSize, assumeClientsSupportOutOfOrderResponses);
    pipeline.addLast(new ResponseOrderingHandler());
    pipeline.addLast(thriftServerHandler);

    // remove(this) must be last because it triggers downstream processing of the current message
    pipeline.remove(this);
}

From source file:io.aos.netty5.file.FileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
    RandomAccessFile raf = null;//from w ww  . j  ava 2  s  .co  m
    long length = -1;
    try {
        raf = new RandomAccessFile(msg, "r");
        length = raf.length();
    } catch (Exception e) {
        ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n');
        return;
    } finally {
        if (length < 0 && raf != null) {
            raf.close();
        }
    }

    ctx.write("OK: " + raf.length() + '\n');
    if (ctx.pipeline().get(SslHandler.class) == null) {
        // SSL not enabled - can use zero-copy file transfer.
        ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length));
    } else {
        // SSL enabled - cannot use zero-copy file transfer.
        ctx.write(new ChunkedFile(raf));
    }
    ctx.writeAndFlush("\n");
}

From source file:io.aos.netty5.http.file.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*  w  ww  .ja v  a 2  s .  c  o m*/
        return;
    }

    if (request.method() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.uri();
    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            sendListing(ctx, file);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }

    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaderUtil.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpHeaderUtil.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
    }

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println(future.channel() + " Transfer progress: " + progress);
            } else {
                System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.err.println(future.channel() + " Transfer complete.");
        }
    });

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!HttpHeaderUtil.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:io.aos.netty5.http2.client.Http2SettingsHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, Http2Settings msg) throws Exception {
    promise.setSuccess();/*ww  w .j  a v  a  2 s  . co m*/

    // Only care about the first settings message
    ctx.pipeline().remove(this);
}

From source file:io.aos.netty5.socksproxy.SocksPortUnificationServerHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    ChannelPipeline p = ctx.pipeline();
    SocksProtocolVersion version = SocksProtocolVersion.valueOf(in.readByte());
    System.out.println(version);/*from  w  w  w  . ja v a 2 s  .c o m*/
    in.resetReaderIndex();
    switch (version) {
    case SOCKS4a:
        p.addLast(new Socks4CmdRequestDecoder());
        p.addLast(Socks4MessageEncoder.INSTANCE);

        break;
    case SOCKS5:
        p.addLast(new Socks5InitRequestDecoder());
        p.addLast(Socks5MessageEncoder.INSTANCE);

        break;
    case UNKNOWN:
        in.clear();
        ctx.close();
        return;
    }
    p.addLast(SocksServerHandler.INSTANCE);
    p.remove(this);
}