io.netty.channel.AddressedEnvelope Java Examples

The following examples show how to use io.netty.channel.AddressedEnvelope. 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: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
final Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query0(
        InetSocketAddress nameServerAddr, DnsQuestion question,
        DnsRecord[] additionals,
        ChannelPromise writePromise,
        Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> promise) {
    assert !writePromise.isVoid();

    final Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> castPromise = cast(
            checkNotNull(promise, "promise"));
    try {
        new DnsQueryContext(this, nameServerAddr, question, additionals, castPromise).query(writePromise);
        return castPromise;
    } catch (Exception e) {
        return castPromise.setFailure(e);
    }
}
 
Example #2
Source File: DnsMessageUtil.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static StringBuilder appendAddresses(StringBuilder buf, DnsMessage msg) {

        if (!(msg instanceof AddressedEnvelope)) {
            return buf;
        }

        @SuppressWarnings("unchecked")
        AddressedEnvelope<?, SocketAddress> envelope = (AddressedEnvelope<?, SocketAddress>) msg;

        SocketAddress addr = envelope.sender();
        if (addr != null) {
            buf.append("from: ")
               .append(addr)
               .append(", ");
        }

        addr = envelope.recipient();
        if (addr != null) {
            buf.append("to: ")
               .append(addr)
               .append(", ");
        }

        return buf;
    }
 
Example #3
Source File: DatagramDnsResponseEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx,
                      AddressedEnvelope<DnsResponse, InetSocketAddress> in, List<Object> out) throws Exception {

    final InetSocketAddress recipient = in.recipient();
    final DnsResponse response = in.content();
    final ByteBuf buf = allocateBuffer(ctx, in);

    boolean success = false;
    try {
        encodeHeader(response, buf);
        encodeQuestions(response, buf);
        encodeRecords(response, DnsSection.ANSWER, buf);
        encodeRecords(response, DnsSection.AUTHORITY, buf);
        encodeRecords(response, DnsSection.ADDITIONAL, buf);
        success = true;
    } finally {
        if (!success) {
            buf.release();
        }
    }

    out.add(new DatagramPacket(buf, recipient, null));
}
 
Example #4
Source File: DatagramDnsQueryEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void encode(
    ChannelHandlerContext ctx,
    AddressedEnvelope<DnsQuery, InetSocketAddress> in, List<Object> out) throws Exception {

    final InetSocketAddress recipient = in.recipient();
    final DnsQuery query = in.content();
    final ByteBuf buf = allocateBuffer(ctx, in);

    boolean success = false;
    try {
        encodeHeader(query, buf);
        encodeQuestions(query, buf);
        encodeRecords(query, DnsSection.ADDITIONAL, buf);
        success = true;
    } finally {
        if (!success) {
            buf.release();
        }
    }

    out.add(new DatagramPacket(buf, recipient, null));
}
 
Example #5
Source File: OioDatagramChannel.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
protected Object filterOutboundMessage(Object msg) {
    if (msg instanceof DatagramPacket || msg instanceof ByteBuf) {
        return msg;
    }

    if (msg instanceof AddressedEnvelope) {
        @SuppressWarnings("unchecked")
        AddressedEnvelope<Object, SocketAddress> e = (AddressedEnvelope<Object, SocketAddress>) msg;
        if (e.content() instanceof ByteBuf) {
            return msg;
        }
    }

    throw new UnsupportedOperationException(
            "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
}
 
Example #6
Source File: DnsResponseTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void readResponseTest() throws Exception {
    EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder());
    for (byte[] p: packets) {
        ByteBuf packet = embedder.alloc().buffer(512).writeBytes(p);
        embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0)));
        AddressedEnvelope<DnsResponse, InetSocketAddress> envelope = embedder.readInbound();
        assertThat(envelope, is(instanceOf(DatagramDnsResponse.class)));
        DnsResponse response = envelope.content();
        assertThat(response, is(sameInstance((Object) envelope)));

        ByteBuf raw = Unpooled.wrappedBuffer(p);
        assertThat(response.id(), is(raw.getUnsignedShort(0)));
        assertThat(response.count(DnsSection.QUESTION), is(raw.getUnsignedShort(4)));
        assertThat(response.count(DnsSection.ANSWER), is(raw.getUnsignedShort(6)));
        assertThat(response.count(DnsSection.AUTHORITY), is(raw.getUnsignedShort(8)));
        assertThat(response.count(DnsSection.ADDITIONAL), is(raw.getUnsignedShort(10)));

        envelope.release();
    }
}
 
Example #7
Source File: DnsQueryContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
DnsQueryContext(DnsNameResolver parent,
                InetSocketAddress nameServerAddr,
                DnsQuestion question,
                DnsRecord[] additionals,
                Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> promise) {

    this.parent = checkNotNull(parent, "parent");
    this.nameServerAddr = checkNotNull(nameServerAddr, "nameServerAddr");
    this.question = checkNotNull(question, "question");
    this.additionals = checkNotNull(additionals, "additionals");
    this.promise = checkNotNull(promise, "promise");
    recursionDesired = parent.isRecursionDesired();
    id = parent.queryContextManager.add(this);

    if (parent.isOptResourceEnabled()) {
        optResource = new AbstractDnsOptPseudoRrRecord(parent.maxPayloadSize(), 0, 0) {
            // We may want to remove this in the future and let the user just specify the opt record in the query.
        };
    } else {
        optResource = null;
    }
}
 
Example #8
Source File: DnsQueryContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private void setSuccess(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope) {
    parent.queryContextManager.remove(nameServerAddr(), id);

    // Cancel the timeout task.
    final ScheduledFuture<?> timeoutFuture = this.timeoutFuture;
    if (timeoutFuture != null) {
        timeoutFuture.cancel(false);
    }

    Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> promise = this.promise;
    if (promise.setUncancellable()) {
        @SuppressWarnings("unchecked")
        AddressedEnvelope<DnsResponse, InetSocketAddress> castResponse =
                (AddressedEnvelope<DnsResponse, InetSocketAddress>) envelope.retain();
        if (!promise.trySuccess(castResponse)) {
            // We failed to notify the promise as it was failed before, thus we need to release the envelope
            envelope.release();
        }
    }
}
 
Example #9
Source File: OioDatagramChannel.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected Object filterOutboundMessage(Object msg) {
    if (msg instanceof DatagramPacket || msg instanceof ByteBuf) {
        return msg;
    }

    if (msg instanceof AddressedEnvelope) {
        @SuppressWarnings("unchecked")
        AddressedEnvelope<Object, SocketAddress> e = (AddressedEnvelope<Object, SocketAddress>) msg;
        if (e.content() instanceof ByteBuf) {
            return msg;
        }
    }

    throw new UnsupportedOperationException(
            "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
}
 
Example #10
Source File: DatagramPacketEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void encode(
        ChannelHandlerContext ctx, AddressedEnvelope<M, InetSocketAddress> msg, List<Object> out) throws Exception {
    assert out.isEmpty();

    encoder.encode(ctx, msg.content(), out);
    if (out.size() != 1) {
        throw new EncoderException(
                StringUtil.simpleClassName(encoder) + " must produce only one message.");
    }
    Object content = out.get(0);
    if (content instanceof ByteBuf) {
        // Replace the ByteBuf with a DatagramPacket.
        out.set(0, new DatagramPacket((ByteBuf) content, msg.recipient(), msg.sender()));
    } else {
        throw new EncoderException(
                StringUtil.simpleClassName(encoder) + " must produce only ByteBuf.");
    }
}
 
Example #11
Source File: DatagramPacketEncoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void testSharable(boolean sharable) {
    MessageToMessageEncoder<AddressedEnvelope<ByteBuf, InetSocketAddress>> wrapped =
            new TestMessageToMessageEncoder(sharable);

    DatagramPacketEncoder<AddressedEnvelope<ByteBuf, InetSocketAddress>> encoder =
            new DatagramPacketEncoder<AddressedEnvelope<ByteBuf, InetSocketAddress>>(wrapped);
    assertEquals(wrapped.isSharable(), encoder.isSharable());
}
 
Example #12
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a DNS query with the specified question with additional records using the specified name server list.
 */
public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
        InetSocketAddress nameServerAddr, DnsQuestion question,
        Iterable<DnsRecord> additionals,
        Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> promise) {

    return query0(nameServerAddr, question, toArray(additionals, false), promise);
}
 
Example #13
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a DNS query with the specified question using the specified name server list.
 */
public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
        InetSocketAddress nameServerAddr, DnsQuestion question,
        Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> promise) {

    return query0(nameServerAddr, question, EMPTY_ADDITIONALS, promise);
}
 
Example #14
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a DNS query with the specified question with additional records using the specified name server list.
 */
public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
        InetSocketAddress nameServerAddr, DnsQuestion question, Iterable<DnsRecord> additionals) {

    return query0(nameServerAddr, question, toArray(additionals, false),
            ch.eventLoop().<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>>newPromise());
}
 
Example #15
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a DNS query with the specified question using the specified name server list.
 */
public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
        InetSocketAddress nameServerAddr, DnsQuestion question) {

    return query0(nameServerAddr, question, EMPTY_ADDITIONALS,
            ch.eventLoop().<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>>newPromise());
}
 
Example #16
Source File: DnsNameResolverContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private void onResponseCNAME(
        DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> response,
        Map<String, String> cnames, final DnsQueryLifecycleObserver queryLifecycleObserver,
        Promise<T> promise) {

    // Resolve the host name in the question into the real host name.
    final String name = question.name().toLowerCase(Locale.US);
    String resolved = name;
    boolean found = false;
    while (!cnames.isEmpty()) { // Do not attempt to call Map.remove() when the Map is empty
                                // because it can be Collections.emptyMap()
                                // whose remove() throws a UnsupportedOperationException.
        final String next = cnames.remove(resolved);
        if (next != null) {
            found = true;
            resolved = next;
        } else {
            break;
        }
    }

    if (found) {
        followCname(question, resolved, queryLifecycleObserver, promise);
    } else {
        queryLifecycleObserver.queryFailed(CNAME_NOT_FOUND_QUERY_FAILED_EXCEPTION);
    }
}
 
Example #17
Source File: DatagramPacketEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean acceptOutboundMessage(Object msg) throws Exception {
    if (super.acceptOutboundMessage(msg)) {
        @SuppressWarnings("rawtypes")
        AddressedEnvelope envelope = (AddressedEnvelope) msg;
        return encoder.acceptOutboundMessage(envelope.content())
                && envelope.sender() instanceof InetSocketAddress
                && envelope.recipient() instanceof InetSocketAddress;
    }
    return false;
}
 
Example #18
Source File: DnsNameResolverContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
void onResponse(final DnsServerAddressStream nameServerAddrStream, final int nameServerAddrStreamIndex,
                final DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope,
                final DnsQueryLifecycleObserver queryLifecycleObserver,
                Promise<T> promise) {
    try {
        final DnsResponse res = envelope.content();
        final DnsResponseCode code = res.code();
        if (code == DnsResponseCode.NOERROR) {
            if (handleRedirect(question, envelope, queryLifecycleObserver, promise)) {
                // Was a redirect so return here as everything else is handled in handleRedirect(...)
                return;
            }
            final DnsRecordType type = question.type();

            if (type == DnsRecordType.A || type == DnsRecordType.AAAA) {
                onResponseAorAAAA(type, question, envelope, queryLifecycleObserver, promise);
            } else if (type == DnsRecordType.CNAME) {
                onResponseCNAME(question, envelope, queryLifecycleObserver, promise);
            } else {
                queryLifecycleObserver.queryFailed(UNRECOGNIZED_TYPE_QUERY_FAILED_EXCEPTION);
            }
            return;
        }

        // Retry with the next server if the server did not tell us that the domain does not exist.
        if (code != DnsResponseCode.NXDOMAIN) {
            query(nameServerAddrStream, nameServerAddrStreamIndex + 1, question,
                  queryLifecycleObserver.queryNoAnswer(code), promise, null);
        } else {
            queryLifecycleObserver.queryFailed(NXDOMAIN_QUERY_FAILED_EXCEPTION);
        }
    } finally {
        ReferenceCountUtil.safeRelease(envelope);
    }
}
 
Example #19
Source File: DnsQueryContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
void finish(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope) {
    final DnsResponse res = envelope.content();
    if (res.count(DnsSection.QUESTION) != 1) {
        logger.warn("Received a DNS response with invalid number of questions: {}", envelope);
        return;
    }

    if (!question().equals(res.recordAt(DnsSection.QUESTION))) {
        logger.warn("Received a mismatching DNS response: {}", envelope);
        return;
    }

    setSuccess(envelope);
}
 
Example #20
Source File: DatagramDnsQuery.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }

    if (!super.equals(obj)) {
        return false;
    }

    if (!(obj instanceof AddressedEnvelope)) {
        return false;
    }

    @SuppressWarnings("unchecked")
    final AddressedEnvelope<?, SocketAddress> that = (AddressedEnvelope<?, SocketAddress>) obj;
    if (sender() == null) {
        if (that.sender() != null) {
            return false;
        }
    } else if (!sender().equals(that.sender())) {
        return false;
    }

    if (recipient() == null) {
        if (that.recipient() != null) {
            return false;
        }
    } else if (!recipient().equals(that.recipient())) {
        return false;
    }

    return true;
}
 
Example #21
Source File: DatagramDnsResponse.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }

    if (!super.equals(obj)) {
        return false;
    }

    if (!(obj instanceof AddressedEnvelope)) {
        return false;
    }

    @SuppressWarnings("unchecked")
    final AddressedEnvelope<?, SocketAddress> that = (AddressedEnvelope<?, SocketAddress>) obj;
    if (sender() == null) {
        if (that.sender() != null) {
            return false;
        }
    } else if (!sender().equals(that.sender())) {
        return false;
    }

    if (recipient() == null) {
        if (that.recipient() != null) {
            return false;
        }
    } else if (!recipient().equals(that.recipient())) {
        return false;
    }

    return true;
}
 
Example #22
Source File: DnsNameResolverTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private static void queryMx(
        DnsNameResolver resolver,
        Map<String, Future<AddressedEnvelope<DnsResponse, InetSocketAddress>>> futures,
        String hostname) throws Exception {
    futures.put(hostname, resolver.query(new DefaultDnsQuestion(hostname, DnsRecordType.MX)));
}
 
Example #23
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> cast(Promise<?> promise) {
    return (Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>>) promise;
}
 
Example #24
Source File: TcpClientSession.java    From PacketLib with MIT License 4 votes vote down vote up
private void resolveAddress() {
    boolean debug = getFlag(BuiltinFlags.PRINT_DEBUG, false);

    String name = this.getPacketProtocol().getSRVRecordPrefix() + "._tcp." + this.getHost();
    if(debug) {
        System.out.println("[PacketLib] Attempting SRV lookup for \"" + name + "\".");
    }

    AddressedEnvelope<DnsResponse, InetSocketAddress> envelope = null;
    try(DnsNameResolver resolver = new DnsNameResolverBuilder(this.group.next())
            .channelType(NioDatagramChannel.class)
            .build()) {
        envelope = resolver.query(new DefaultDnsQuestion(name, DnsRecordType.SRV)).get();
        DnsResponse response = envelope.content();
        if(response.count(DnsSection.ANSWER) > 0) {
            DefaultDnsRawRecord record = response.recordAt(DnsSection.ANSWER, 0);
            if(record.type() == DnsRecordType.SRV) {
                ByteBuf buf = record.content();
                buf.skipBytes(4); // Skip priority and weight.

                int port = buf.readUnsignedShort();
                String host = DefaultDnsRecordDecoder.decodeName(buf);
                if(host.endsWith(".")) {
                    host = host.substring(0, host.length() - 1);
                }

                if(debug) {
                    System.out.println("[PacketLib] Found SRV record containing \"" + host + ":" + port + "\".");
                }

                this.host = host;
                this.port = port;
            } else if(debug) {
                System.out.println("[PacketLib] Received non-SRV record in response.");
            }
        } else if(debug) {
            System.out.println("[PacketLib] No SRV record found.");
        }
    } catch(Exception e) {
        if(debug) {
            System.out.println("[PacketLib] Failed to resolve SRV record.");
            e.printStackTrace();
        }
    } finally {
        if(envelope != null) {
            envelope.release();
        }
    }
}
 
Example #25
Source File: DatagramPacketEncoderTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
protected void encode(
        ChannelHandlerContext ctx, AddressedEnvelope<ByteBuf,
        InetSocketAddress> msg, List<Object> out) {
    // NOOP
}
 
Example #26
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
final Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query0(
        InetSocketAddress nameServerAddr, DnsQuestion question,
        DnsRecord[] additionals,
        Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> promise) {
    return query0(nameServerAddr, question, additionals, ch.newPromise(), promise);
}
 
Example #27
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Sends a DNS query with the specified question.
 */
public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
        DnsQuestion question, Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> promise) {
    return query(nextNameServerAddress(), question, Collections.<DnsRecord>emptyList(), promise);
}
 
Example #28
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Sends a DNS query with the specified question with additional records.
 */
public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
        DnsQuestion question, Iterable<DnsRecord> additionals) {
    return query(nextNameServerAddress(), question, additionals);
}
 
Example #29
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Sends a DNS query with the specified question.
 */
public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(DnsQuestion question) {
    return query(nextNameServerAddress(), question);
}
 
Example #30
Source File: DnsNameResolverContext.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private void onResponseCNAME(DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope,
                             final DnsQueryLifecycleObserver queryLifecycleObserver,
                             Promise<T> promise) {
    onResponseCNAME(question, envelope, buildAliasMap(envelope.content()), queryLifecycleObserver, promise);
}