Search in sources :

Example 71 with ByteBufAllocator

use of io.netty.buffer.ByteBufAllocator in project netty by netty.

the class PcapWriteHandler method channelActive.

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ByteBufAllocator byteBufAllocator = ctx.alloc();
    /*
         * If `writePcapGlobalHeader` is `true`, we'll write Pcap Global Header.
         */
    if (writePcapGlobalHeader) {
        ByteBuf byteBuf = byteBufAllocator.buffer();
        try {
            this.pCapWriter = new PcapWriter(this.outputStream, byteBuf);
        } catch (IOException ex) {
            ctx.channel().close();
            ctx.fireExceptionCaught(ex);
            logger.error("Caught Exception While Initializing PcapWriter, Closing Channel.", ex);
        } finally {
            byteBuf.release();
        }
    } else {
        this.pCapWriter = new PcapWriter(this.outputStream);
    }
    // If Channel belongs to `SocketChannel` then we're handling TCP.
    if (ctx.channel() instanceof SocketChannel) {
        // Capture correct `localAddress` and `remoteAddress`
        if (ctx.channel().parent() instanceof ServerSocketChannel) {
            isServerPipeline = true;
            initiatiorAddr = (InetSocketAddress) ctx.channel().remoteAddress();
            handlerAddr = (InetSocketAddress) ctx.channel().localAddress();
        } else {
            isServerPipeline = false;
            initiatiorAddr = (InetSocketAddress) ctx.channel().localAddress();
            handlerAddr = (InetSocketAddress) ctx.channel().remoteAddress();
        }
        logger.debug("Initiating Fake TCP 3-Way Handshake");
        ByteBuf tcpBuf = byteBufAllocator.buffer();
        try {
            // Write SYN with Normal Source and Destination Address
            TCPPacket.writePacket(tcpBuf, null, 0, 0, initiatiorAddr.getPort(), handlerAddr.getPort(), TCPPacket.TCPFlag.SYN);
            completeTCPWrite(initiatiorAddr, handlerAddr, tcpBuf, byteBufAllocator, ctx);
            // Write SYN+ACK with Reversed Source and Destination Address
            TCPPacket.writePacket(tcpBuf, null, 0, 1, handlerAddr.getPort(), initiatiorAddr.getPort(), TCPPacket.TCPFlag.SYN, TCPPacket.TCPFlag.ACK);
            completeTCPWrite(handlerAddr, initiatiorAddr, tcpBuf, byteBufAllocator, ctx);
            // Write ACK with Normal Source and Destination Address
            TCPPacket.writePacket(tcpBuf, null, 1, 1, initiatiorAddr.getPort(), handlerAddr.getPort(), TCPPacket.TCPFlag.ACK);
            completeTCPWrite(initiatiorAddr, handlerAddr, tcpBuf, byteBufAllocator, ctx);
        } finally {
            tcpBuf.release();
        }
        logger.debug("Finished Fake TCP 3-Way Handshake");
    } else if (ctx.channel() instanceof DatagramChannel) {
        DatagramChannel datagramChannel = (DatagramChannel) ctx.channel();
        // `localAddress` and `remoteAddress` from Channel.
        if (datagramChannel.isConnected()) {
            initiatiorAddr = (InetSocketAddress) ctx.channel().localAddress();
            handlerAddr = (InetSocketAddress) ctx.channel().remoteAddress();
        }
    }
    super.channelActive(ctx);
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) ServerSocketChannel(io.netty.channel.socket.ServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(io.netty.channel.socket.DatagramChannel) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) ServerSocketChannel(io.netty.channel.socket.ServerSocketChannel)

Example 72 with ByteBufAllocator

use of io.netty.buffer.ByteBufAllocator in project netty by netty.

the class PcapWriteHandler method handlerRemoved.

@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    // If `isTCP` is true, then we'll simulate a `FIN` flow.
    if (ctx.channel() instanceof SocketChannel) {
        logger.debug("Starting Fake TCP FIN+ACK Flow to close connection");
        ByteBufAllocator byteBufAllocator = ctx.alloc();
        ByteBuf tcpBuf = byteBufAllocator.buffer();
        try {
            // Write FIN+ACK with Normal Source and Destination Address
            TCPPacket.writePacket(tcpBuf, null, sendSegmentNumber, receiveSegmentNumber, initiatiorAddr.getPort(), handlerAddr.getPort(), TCPPacket.TCPFlag.FIN, TCPPacket.TCPFlag.ACK);
            completeTCPWrite(initiatiorAddr, handlerAddr, tcpBuf, byteBufAllocator, ctx);
            // Write FIN+ACK with Reversed Source and Destination Address
            TCPPacket.writePacket(tcpBuf, null, receiveSegmentNumber, sendSegmentNumber, handlerAddr.getPort(), initiatiorAddr.getPort(), TCPPacket.TCPFlag.FIN, TCPPacket.TCPFlag.ACK);
            completeTCPWrite(handlerAddr, initiatiorAddr, tcpBuf, byteBufAllocator, ctx);
            // Write ACK with Normal Source and Destination Address
            TCPPacket.writePacket(tcpBuf, null, sendSegmentNumber + 1, receiveSegmentNumber + 1, initiatiorAddr.getPort(), handlerAddr.getPort(), TCPPacket.TCPFlag.ACK);
            completeTCPWrite(initiatiorAddr, handlerAddr, tcpBuf, byteBufAllocator, ctx);
        } finally {
            tcpBuf.release();
        }
        logger.debug("Finished Fake TCP FIN+ACK Flow to close connection");
    }
    close();
    super.handlerRemoved(ctx);
}
Also used : ServerSocketChannel(io.netty.channel.socket.ServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) ByteBuf(io.netty.buffer.ByteBuf)

Example 73 with ByteBufAllocator

use of io.netty.buffer.ByteBufAllocator in project netty by netty.

the class PcapWriteHandler method handleTCP.

/**
 * Handle TCP L4
 *
 * @param ctx              {@link ChannelHandlerContext} for {@link ByteBuf} allocation and
 *                         {@code fireExceptionCaught}
 * @param msg              {@link Object} must be {@link ByteBuf} else it'll be discarded
 * @param isWriteOperation Set {@code true} if we have to process packet when packets are being sent out
 *                         else set {@code false}
 */
private void handleTCP(ChannelHandlerContext ctx, Object msg, boolean isWriteOperation) {
    if (msg instanceof ByteBuf) {
        // If bytes are 0 and `captureZeroByte` is false, we won't capture this.
        if (((ByteBuf) msg).readableBytes() == 0 && !captureZeroByte) {
            logger.debug("Discarding Zero Byte TCP Packet. isWriteOperation {}", isWriteOperation);
            return;
        }
        ByteBufAllocator byteBufAllocator = ctx.alloc();
        ByteBuf packet = ((ByteBuf) msg).duplicate();
        ByteBuf tcpBuf = byteBufAllocator.buffer();
        int bytes = packet.readableBytes();
        try {
            if (isWriteOperation) {
                final InetSocketAddress srcAddr;
                final InetSocketAddress dstAddr;
                if (isServerPipeline) {
                    srcAddr = handlerAddr;
                    dstAddr = initiatiorAddr;
                } else {
                    srcAddr = initiatiorAddr;
                    dstAddr = handlerAddr;
                }
                TCPPacket.writePacket(tcpBuf, packet, sendSegmentNumber, receiveSegmentNumber, srcAddr.getPort(), dstAddr.getPort(), TCPPacket.TCPFlag.ACK);
                completeTCPWrite(srcAddr, dstAddr, tcpBuf, byteBufAllocator, ctx);
                logTCP(true, bytes, sendSegmentNumber, receiveSegmentNumber, srcAddr, dstAddr, false);
                sendSegmentNumber += bytes;
                TCPPacket.writePacket(tcpBuf, null, receiveSegmentNumber, sendSegmentNumber, dstAddr.getPort(), srcAddr.getPort(), TCPPacket.TCPFlag.ACK);
                completeTCPWrite(dstAddr, srcAddr, tcpBuf, byteBufAllocator, ctx);
                logTCP(true, bytes, sendSegmentNumber, receiveSegmentNumber, dstAddr, srcAddr, true);
            } else {
                final InetSocketAddress srcAddr;
                final InetSocketAddress dstAddr;
                if (isServerPipeline) {
                    srcAddr = initiatiorAddr;
                    dstAddr = handlerAddr;
                } else {
                    srcAddr = handlerAddr;
                    dstAddr = initiatiorAddr;
                }
                TCPPacket.writePacket(tcpBuf, packet, receiveSegmentNumber, sendSegmentNumber, srcAddr.getPort(), dstAddr.getPort(), TCPPacket.TCPFlag.ACK);
                completeTCPWrite(srcAddr, dstAddr, tcpBuf, byteBufAllocator, ctx);
                logTCP(false, bytes, receiveSegmentNumber, sendSegmentNumber, srcAddr, dstAddr, false);
                receiveSegmentNumber += bytes;
                TCPPacket.writePacket(tcpBuf, null, sendSegmentNumber, receiveSegmentNumber, dstAddr.getPort(), srcAddr.getPort(), TCPPacket.TCPFlag.ACK);
                completeTCPWrite(dstAddr, srcAddr, tcpBuf, byteBufAllocator, ctx);
                logTCP(false, bytes, sendSegmentNumber, receiveSegmentNumber, dstAddr, srcAddr, true);
            }
        } finally {
            tcpBuf.release();
        }
    } else {
        logger.debug("Discarding Pcap Write for TCP Object: {}", msg);
    }
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) InetSocketAddress(java.net.InetSocketAddress) ByteBuf(io.netty.buffer.ByteBuf)

Example 74 with ByteBufAllocator

use of io.netty.buffer.ByteBufAllocator in project zuul by Netflix.

the class Server method start.

public void start() {
    serverGroup = new ServerGroup("Salamander", eventLoopConfig.acceptorCount(), eventLoopConfig.eventLoopCount(), eventLoopGroupMetrics);
    serverGroup.initializeTransport();
    try {
        List<ChannelFuture> allBindFutures = new ArrayList<>(addressesToInitializers.size());
        // Setup each of the channel initializers on requested ports.
        for (Map.Entry<NamedSocketAddress, ? extends ChannelInitializer<?>> entry : addressesToInitializers.entrySet()) {
            NamedSocketAddress requestedNamedAddr = entry.getKey();
            ChannelFuture nettyServerFuture = setupServerBootstrap(requestedNamedAddr, entry.getValue());
            Channel chan = nettyServerFuture.channel();
            addressesToChannels.put(requestedNamedAddr.withNewSocket(chan.localAddress()), chan);
            allBindFutures.add(nettyServerFuture);
        }
        // Add metrics to monitor that allocator's memory usage.
        if (!allBindFutures.isEmpty()) {
            ByteBufAllocator alloc = allBindFutures.get(0).channel().alloc();
            if (alloc instanceof ByteBufAllocatorMetricProvider) {
                ByteBufAllocatorMetric metrics = ((ByteBufAllocatorMetricProvider) alloc).metric();
                PolledMeter.using(registry).withId(registry.createId("zuul.nettybuffermem.live", "type", "heap")).monitorValue(metrics, ByteBufAllocatorMetric::usedHeapMemory);
                PolledMeter.using(registry).withId(registry.createId("zuul.nettybuffermem.live", "type", "direct")).monitorValue(metrics, ByteBufAllocatorMetric::usedDirectMemory);
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ByteBufAllocatorMetric(io.netty.buffer.ByteBufAllocatorMetric) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) ByteBufAllocatorMetricProvider(io.netty.buffer.ByteBufAllocatorMetricProvider) IOUringServerSocketChannel(io.netty.incubator.channel.uring.IOUringServerSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) KQueueServerSocketChannel(io.netty.channel.kqueue.KQueueServerSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) KQueueSocketChannel(io.netty.channel.kqueue.KQueueSocketChannel) IOUringSocketChannel(io.netty.incubator.channel.uring.IOUringSocketChannel) Channel(io.netty.channel.Channel) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 75 with ByteBufAllocator

use of io.netty.buffer.ByteBufAllocator in project zipkin by openzipkin.

the class BulkCallBuilder method build.

/**
 * Creates a bulk request when there is more than one object to store
 */
public HttpCall<Void> build() {
    QueryStringEncoder urlBuilder = new QueryStringEncoder("/_bulk");
    if (pipeline != null)
        urlBuilder.addParam("pipeline", pipeline);
    if (waitForRefresh)
        urlBuilder.addParam("refresh", "wait_for");
    ByteBufAllocator alloc = RequestContext.mapCurrent(RequestContext::alloc, () -> PooledByteBufAllocator.DEFAULT);
    HttpCall.RequestSupplier request = new BulkRequestSupplier(entries, shouldAddType, RequestHeaders.of(HttpMethod.POST, urlBuilder.toString(), HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8), alloc);
    return http.newCall(request, CHECK_FOR_ERRORS, tag);
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) HttpCall(zipkin2.elasticsearch.internal.client.HttpCall) RequestContext(com.linecorp.armeria.common.RequestContext) QueryStringEncoder(io.netty.handler.codec.http.QueryStringEncoder)

Aggregations

ByteBufAllocator (io.netty.buffer.ByteBufAllocator)79 ByteBuf (io.netty.buffer.ByteBuf)48 ArrayList (java.util.ArrayList)17 Test (org.junit.Test)17 Test (org.junit.jupiter.api.Test)11 PooledByteBufAllocator (io.netty.buffer.PooledByteBufAllocator)10 Channel (io.netty.channel.Channel)9 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)8 IOException (java.io.IOException)8 UnpooledByteBufAllocator (io.netty.buffer.UnpooledByteBufAllocator)7 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 ChannelFuture (io.netty.channel.ChannelFuture)6 Mono (reactor.core.publisher.Mono)6 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)4 InetSocketAddress (java.net.InetSocketAddress)4 StandardCharsets (java.nio.charset.StandardCharsets)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 NettyDataBufferFactory (org.springframework.core.io.buffer.NettyDataBufferFactory)4 RecvByteBufAllocator (io.netty.channel.RecvByteBufAllocator)3 ByteBuffer (java.nio.ByteBuffer)3