Search in sources :

Example 16 with DatagramChannel

use of io.netty.channel.socket.DatagramChannel in project traccar by tananaev.

the class NetworkMessageHandler method write.

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    if (msg instanceof NetworkMessage) {
        NetworkMessage message = (NetworkMessage) msg;
        if (ctx.channel() instanceof DatagramChannel) {
            InetSocketAddress recipient = (InetSocketAddress) message.getRemoteAddress();
            InetSocketAddress sender = (InetSocketAddress) ctx.channel().localAddress();
            ctx.write(new DatagramPacket((ByteBuf) message.getMessage(), recipient, sender), promise);
        } else {
            ctx.write(message.getMessage(), promise);
        }
    } else {
        ctx.write(msg, promise);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) DatagramChannel(io.netty.channel.socket.DatagramChannel) NetworkMessage(org.traccar.NetworkMessage) ByteBuf(io.netty.buffer.ByteBuf)

Example 17 with DatagramChannel

use of io.netty.channel.socket.DatagramChannel in project netty by netty.

the class DnsNameResolverTest method testMultipleAdditionalRecordsForSameNSRecord.

private static void testMultipleAdditionalRecordsForSameNSRecord(final boolean reversed) throws Exception {
    final String domain = "netty.io";
    final String hostname = "test.netty.io";
    final String ns1Name = "ns1." + domain;
    final InetSocketAddress ns1Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 1 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns2Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 2 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns3Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 3 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns4Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 4 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    TestDnsServer redirectServer = new TestDnsServer(new HashSet<String>(asList(hostname, ns1Name))) {

        @Override
        protected DnsMessage filterMessage(DnsMessage message) {
            for (QuestionRecord record : message.getQuestionRecords()) {
                if (record.getDomainName().equals(hostname)) {
                    message.getAdditionalRecords().clear();
                    message.getAnswerRecords().clear();
                    message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns1Name));
                    message.getAdditionalRecords().add(newARecord(ns1Address));
                    message.getAdditionalRecords().add(newARecord(ns2Address));
                    message.getAdditionalRecords().add(newARecord(ns3Address));
                    message.getAdditionalRecords().add(newARecord(ns4Address));
                    return message;
                }
            }
            return message;
        }

        private ResourceRecord newARecord(InetSocketAddress address) {
            return newARecord(address.getHostName(), address.getAddress().getHostAddress());
        }
    };
    redirectServer.start();
    EventLoopGroup group = new NioEventLoopGroup(1);
    final List<InetSocketAddress> cached = new CopyOnWriteArrayList<InetSocketAddress>();
    final AuthoritativeDnsServerCache authoritativeDnsServerCache = new AuthoritativeDnsServerCache() {

        @Override
        public DnsServerAddressStream get(String hostname) {
            return null;
        }

        @Override
        public void cache(String hostname, InetSocketAddress address, long originalTtl, EventLoop loop) {
            cached.add(address);
        }

        @Override
        public void clear() {
        // NOOP
        }

        @Override
        public boolean clear(String hostname) {
            return false;
        }
    };
    final AtomicReference<DnsServerAddressStream> redirectedRef = new AtomicReference<DnsServerAddressStream>();
    final DnsNameResolver resolver = new DnsNameResolver(group.next(), new ReflectiveChannelFactory<DatagramChannel>(NioDatagramChannel.class), NoopDnsCache.INSTANCE, authoritativeDnsServerCache, NoopDnsQueryLifecycleObserverFactory.INSTANCE, 2000, ResolvedAddressTypes.IPV4_ONLY, true, 10, true, 4096, false, HostsFileEntriesResolver.DEFAULT, new SingletonDnsServerAddressStreamProvider(redirectServer.localAddress()), DnsNameResolver.DEFAULT_SEARCH_DOMAINS, 0, true) {

        @Override
        protected DnsServerAddressStream newRedirectDnsServerStream(String hostname, List<InetSocketAddress> nameservers) {
            if (reversed) {
                Collections.reverse(nameservers);
            }
            DnsServerAddressStream stream = new SequentialDnsServerAddressStream(nameservers, 0);
            redirectedRef.set(stream);
            return stream;
        }
    };
    try {
        Throwable cause = resolver.resolveAll(hostname).await().cause();
        assertTrue(cause instanceof UnknownHostException);
        DnsServerAddressStream redirected = redirectedRef.get();
        assertNotNull(redirected);
        assertEquals(4, redirected.size());
        assertEquals(4, cached.size());
        if (reversed) {
            assertEquals(ns4Address, redirected.next());
            assertEquals(ns3Address, redirected.next());
            assertEquals(ns2Address, redirected.next());
            assertEquals(ns1Address, redirected.next());
        } else {
            assertEquals(ns1Address, redirected.next());
            assertEquals(ns2Address, redirected.next());
            assertEquals(ns3Address, redirected.next());
            assertEquals(ns4Address, redirected.next());
        }
        // We should always have the same order in the cache.
        assertEquals(ns1Address, cached.get(0));
        assertEquals(ns2Address, cached.get(1));
        assertEquals(ns3Address, cached.get(2));
        assertEquals(ns4Address, cached.get(3));
    } finally {
        resolver.close();
        group.shutdownGracefully(0, 0, TimeUnit.SECONDS);
        redirectServer.stop();
    }
}
Also used : QuestionRecord(org.apache.directory.server.dns.messages.QuestionRecord) UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DnsMessage(org.apache.directory.server.dns.messages.DnsMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) EventLoop(io.netty.channel.EventLoop) Collections.singletonList(java.util.Collections.singletonList) Arrays.asList(java.util.Arrays.asList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 18 with DatagramChannel

use of io.netty.channel.socket.DatagramChannel 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 19 with DatagramChannel

use of io.netty.channel.socket.DatagramChannel in project netty by netty.

the class PcapWriteHandler method handleUDP.

/**
 * Handle UDP l4
 *
 * @param ctx {@link ChannelHandlerContext} for {@code localAddress} / {@code remoteAddress},
 *            {@link ByteBuf} allocation and {@code fireExceptionCaught}
 * @param msg {@link DatagramPacket} or {@link DatagramChannel}
 */
private void handleUDP(ChannelHandlerContext ctx, Object msg) {
    ByteBuf udpBuf = ctx.alloc().buffer();
    try {
        if (msg instanceof DatagramPacket) {
            // If bytes are 0 and `captureZeroByte` is false, we won't capture this.
            if (((DatagramPacket) msg).content().readableBytes() == 0 && !captureZeroByte) {
                logger.debug("Discarding Zero Byte UDP Packet");
                return;
            }
            DatagramPacket datagramPacket = ((DatagramPacket) msg).duplicate();
            InetSocketAddress srcAddr = datagramPacket.sender();
            InetSocketAddress dstAddr = datagramPacket.recipient();
            // `sender` (local) address. In this case, we'll get source address from Channel.
            if (srcAddr == null) {
                srcAddr = (InetSocketAddress) ctx.channel().localAddress();
            }
            logger.debug("Writing UDP Data of {} Bytes, Src Addr {}, Dst Addr {}", datagramPacket.content().readableBytes(), srcAddr, dstAddr);
            UDPPacket.writePacket(udpBuf, datagramPacket.content(), srcAddr.getPort(), dstAddr.getPort());
            completeUDPWrite(srcAddr, dstAddr, udpBuf, ctx.alloc(), ctx);
        } else if (msg instanceof ByteBuf && ((DatagramChannel) ctx.channel()).isConnected()) {
            // If bytes are 0 and `captureZeroByte` is false, we won't capture this.
            if (((ByteBuf) msg).readableBytes() == 0 && !captureZeroByte) {
                logger.debug("Discarding Zero Byte UDP Packet");
                return;
            }
            ByteBuf byteBuf = ((ByteBuf) msg).duplicate();
            logger.debug("Writing UDP Data of {} Bytes, Src Addr {}, Dst Addr {}", byteBuf.readableBytes(), initiatiorAddr, handlerAddr);
            UDPPacket.writePacket(udpBuf, byteBuf, initiatiorAddr.getPort(), handlerAddr.getPort());
            completeUDPWrite(initiatiorAddr, handlerAddr, udpBuf, ctx.alloc(), ctx);
        } else {
            logger.debug("Discarding Pcap Write for UDP Object: {}", msg);
        }
    } finally {
        udpBuf.release();
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) DatagramChannel(io.netty.channel.socket.DatagramChannel) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

DatagramChannel (io.netty.channel.socket.DatagramChannel)19 InetSocketAddress (java.net.InetSocketAddress)12 NioDatagramChannel (io.netty.channel.socket.nio.NioDatagramChannel)9 Bootstrap (io.netty.bootstrap.Bootstrap)8 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)8 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)6 EventLoopGroup (io.netty.channel.EventLoopGroup)6 DatagramPacket (io.netty.channel.socket.DatagramPacket)6 ByteBuf (io.netty.buffer.ByteBuf)5 UnknownHostException (java.net.UnknownHostException)4 NetworkMessage (org.traccar.NetworkMessage)4 List (java.util.List)3 DnsMessage (org.apache.directory.server.dns.messages.DnsMessage)3 QuestionRecord (org.apache.directory.server.dns.messages.QuestionRecord)3 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2 ChannelPipeline (io.netty.channel.ChannelPipeline)2 EventLoop (io.netty.channel.EventLoop)2 FixedRecvByteBufAllocator (io.netty.channel.FixedRecvByteBufAllocator)2 DefaultChannelGroup (io.netty.channel.group.DefaultChannelGroup)2 MessageToMessageDecoder (io.netty.handler.codec.MessageToMessageDecoder)2