org.xbill.DNS.Message Java Examples
The following examples show how to use
org.xbill.DNS.Message.
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: DnsUpdateWriterTest.java From nomulus with Apache License 2.0 | 7 votes |
@Test @SuppressWarnings("AssertThrowsMultipleStatements") public void testPublishDomainFails_whenDnsUpdateReturnsError() throws Exception { DomainBase domain = persistActiveDomain("example.tld") .asBuilder() .setNameservers(ImmutableSet.of(persistActiveHost("ns1.example.tld").createVKey())) .build(); persistResource(domain); when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL)); VerifyException thrown = assertThrows( VerifyException.class, () -> { writer.publishDomain("example.tld"); writer.commit(); }); assertThat(thrown).hasMessageThat().contains("SERVFAIL"); }
Example #2
Source File: IpAddressUtil.java From megatron-java with Apache License 2.0 | 6 votes |
private static String reverseDnsLookupUsingDnsJavaSimpleResolver(long ipAddress) throws IOException { String result = null; byte[] address = convertLongAddressToBuf(ipAddress); Name name = ReverseMap.fromAddress(InetAddress.getByAddress(address)); Record record = Record.newRecord(name, Type.PTR, DClass.IN); Message query = Message.newQuery(record); Message response = simpleResolver.send(query); Record[] answers = response.getSectionArray(Section.ANSWER); if (answers.length != 0) { // If PTR-record exists this will be at index 1 or above (more than one PTR-record may exist) Record answer = (answers.length > 1) ? answers[1] : answers[0]; result = answer.rdataToString(); // remove trailing "." result = result.endsWith(".") ? result.substring(0, result.length() - 1) : result; } else { throw new IOException("Empty DNS response."); } return result; }
Example #3
Source File: DnsUpdateWriterTest.java From nomulus with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("AssertThrowsMultipleStatements") public void testPublishHostFails_whenDnsUpdateReturnsError() throws Exception { HostResource host = persistActiveSubordinateHost("ns1.example.tld", persistActiveDomain("example.tld")) .asBuilder() .setInetAddresses(ImmutableSet.of(InetAddresses.forString("10.0.0.1"))) .build(); persistResource(host); when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL)); VerifyException thrown = assertThrows( VerifyException.class, () -> { writer.publishHost("ns1.example.tld"); writer.commit(); }); assertThat(thrown).hasMessageThat().contains("SERVFAIL"); }
Example #4
Source File: XBillDnsSrvResolverTest.java From dns-java with Apache License 2.0 | 6 votes |
private Message messageWithNodes(String query, String[] names) throws TextParseException { Name queryName = Name.fromString(query); Record question = Record.newRecord(queryName, Type.SRV, DClass.IN); Message queryMessage = Message.newQuery(question); Message result = new Message(); result.setHeader(queryMessage.getHeader()); result.addRecord(question, Section.QUESTION); for (String name1 : names) { result.addRecord( new SRVRecord(queryName, DClass.IN, 1, 1, 1, 8080, Name.fromString(name1)), Section.ANSWER); } return result; }
Example #5
Source File: dig.java From dnsjava with BSD 2-Clause "Simplified" License | 6 votes |
static void doAXFR(Message response) { System.out.println("; java dig 0.0 <> " + name + " axfr"); if (response.isSigned()) { System.out.print(";; TSIG "); if (response.isVerified()) { System.out.println("ok"); } else { System.out.println("failed"); } } if (response.getRcode() != Rcode.NOERROR) { System.out.println(response); return; } for (Record record : response.getSection(Section.ANSWER)) { System.out.println(record); } System.out.print(";; done ("); System.out.print(response.getHeader().getCount(Section.ANSWER)); System.out.print(" records, "); System.out.print(response.getHeader().getCount(Section.ADDITIONAL)); System.out.println(" additional)"); }
Example #6
Source File: DNSLookupService.java From openvisualtraceroute with GNU Lesser General Public License v3.0 | 6 votes |
/** * Dns lookup more efficient than the INetAddress.getHostName(ip) * * @param hostIp * @return * @throws IOException */ public String dnsLookup(final String hostIp) { try { final Name name = ReverseMap.fromAddress(hostIp); final int type = Type.PTR; final int dclass = DClass.IN; final Record rec = Record.newRecord(name, type, dclass); final Message query = Message.newQuery(rec); final Message response = _resolver.send(query); final Record[] answers = response.getSectionArray(Section.ANSWER); if (answers.length > 0) { String ret = answers[0].rdataToString(); if (ret.endsWith(".")) { ret = ret.substring(0, ret.length() - 1); } return ret; } } catch (final IOException e) { LOGGER.warn("Failed to resolve hostname for " + hostIp, e); } return UNKNOWN_HOST; }
Example #7
Source File: SimpleDoTResolver.java From androdns with Apache License 2.0 | 6 votes |
private Message sendAXFR(Message query) throws IOException { Name qname = query.getQuestion().getName(); ZoneTransferIn xfrin = ZoneTransferIn.newAXFR(qname, address, tsig); xfrin.setTimeout((int)(getTimeout() / 1000)); xfrin.setLocalAddress(localAddress); try { xfrin.run(); } catch (ZoneTransferException e) { throw new WireParseException(e.getMessage()); } List records = xfrin.getAXFR(); Message response = new Message(query.getHeader().getID()); response.getHeader().setFlag(Flags.AA); response.getHeader().setFlag(Flags.QR); response.addRecord(query.getQuestion(), Section.QUESTION); Iterator it = records.iterator(); while (it.hasNext()) response.addRecord((Record)it.next(), Section.ANSWER); return response; }
Example #8
Source File: Dig.java From open-rmbt with Apache License 2.0 | 6 votes |
static void doAXFR(Message response) throws IOException { System.out.println("; java dig 0.0 <> " + name + " axfr"); if (response.isSigned()) { System.out.print(";; TSIG "); if (response.isVerified()) System.out.println("ok"); else System.out.println("failed"); } if (response.getRcode() != Rcode.NOERROR) { System.out.println(response); return; } Record [] records = response.getSectionArray(Section.ANSWER); for (int i = 0; i < records.length; i++) System.out.println(records[i]); System.out.print(";; done ("); System.out.print(response.getHeader().getCount(Section.ANSWER)); System.out.print(" records, "); System.out.print(response.getHeader().getCount(Section.ADDITIONAL)); System.out.println(" additional)"); }
Example #9
Source File: jnamed.java From dnsjava with BSD 2-Clause "Simplified" License | 5 votes |
private void addGlue(Message response, Name name, int flags) { RRset a = findExactMatch(name, Type.A, DClass.IN, true); if (a == null) { return; } addRRset(name, response, a, Section.ADDITIONAL, flags); }
Example #10
Source File: jnamed.java From dnsjava with BSD 2-Clause "Simplified" License | 5 votes |
private void addCacheNS(Message response, Cache cache, Name name) { SetResponse sr = cache.lookupRecords(name, Type.NS, Credibility.HINT); if (!sr.isDelegation()) { return; } RRset nsRecords = sr.getNS(); for (Record r : nsRecords.rrs()) { response.addRecord(r, Section.AUTHORITY); } }
Example #11
Source File: jnamed.java From dnsjava with BSD 2-Clause "Simplified" License | 5 votes |
private void addAdditional2(Message response, int section, int flags) { for (Record r : response.getSection(section)) { Name glueName = r.getAdditionalName(); if (glueName != null) { addGlue(response, glueName, flags); } } }
Example #12
Source File: jnamed.java From dnsjava with BSD 2-Clause "Simplified" License | 5 votes |
byte[] buildErrorMessage(Header header, int rcode, Record question) { Message response = new Message(); response.setHeader(header); for (int i = 0; i < 4; i++) { response.removeAllRecords(i); } if (rcode == Rcode.SERVFAIL) { response.addRecord(question, Section.QUESTION); } header.setRcode(rcode); return response.toWire(); }
Example #13
Source File: XBillDnsSrvResolverTest.java From dns-java with Apache License 2.0 | 5 votes |
private Message messageWithRCode(String query, int rcode) throws TextParseException { Name queryName = Name.fromString(query); Record question = Record.newRecord(queryName, Type.SRV, DClass.IN); Message queryMessage = Message.newQuery(question); Message result = new Message(); result.setHeader(queryMessage.getHeader()); result.addRecord(question, Section.QUESTION); result.getHeader().setRcode(rcode); return result; }
Example #14
Source File: OpenAliasHelper.java From xmrwallet with Apache License 2.0 | 5 votes |
@Override protected Boolean doInBackground(String... args) { //main(); if (args.length != 1) return false; String name = args[0]; if ((name == null) || (name.isEmpty())) return false; //pointless trying to lookup nothing Timber.d("Resolving %s", name); try { SimpleResolver sr = new SimpleResolver(DNSSEC_SERVERS[new Random().nextInt(DNSSEC_SERVERS.length)]); ValidatingResolver vr = new ValidatingResolver(sr); vr.setTimeout(0, DNS_LOOKUP_TIMEOUT); vr.loadTrustAnchors(new ByteArrayInputStream(ROOT.getBytes("ASCII"))); Record qr = Record.newRecord(Name.fromConstantString(name + "."), Type.TXT, DClass.IN); Message response = vr.send(Message.newQuery(qr)); final int rcode = response.getRcode(); if (rcode != Rcode.NOERROR) { Timber.i("Rcode: %s", Rcode.string(rcode)); for (RRset set : response.getSectionRRsets(Section.ADDITIONAL)) { if (set.getName().equals(Name.root) && set.getType() == Type.TXT && set.getDClass() == ValidatingResolver.VALIDATION_REASON_QCLASS) { Timber.i("Reason: %s", ((TXTRecord) set.first()).getStrings().get(0)); } } return false; } else { dnssec = response.getHeader().getFlag(Flags.AD); for (Record record : response.getSectionArray(Section.ANSWER)) { if (record.getType() == Type.TXT) { txts.addAll(((TXTRecord) record).getStrings()); } } } } catch (IOException | IllegalArgumentException ex) { return false; } return true; }
Example #15
Source File: XBillDnsSrvResolverTest.java From dns-java with Apache License 2.0 | 5 votes |
@Test public void shouldReturnEmptyForHostNotFound() throws Exception { String fqdn = "thefqdn."; when(lookupFactory.forName(fqdn)).thenReturn(testLookup(fqdn)); when(xbillResolver.send(any(Message.class))).thenReturn(messageWithRCode(fqdn, Rcode.NXDOMAIN)); assertThat(resolver.resolve(fqdn).isEmpty(), is(true)); }
Example #16
Source File: DnsMessageTransportTest.java From nomulus with Apache License 2.0 | 5 votes |
private byte[] messageToBytesWithLength(Message message) { byte[] bytes = message.toWire(); ByteBuffer buffer = ByteBuffer.allocate(bytes.length + DnsMessageTransport.MESSAGE_LENGTH_FIELD_BYTES); buffer.putShort((short) bytes.length); buffer.put(bytes); return buffer.array(); }
Example #17
Source File: DnsMessageTransportTest.java From nomulus with Apache License 2.0 | 5 votes |
private Message responseMessageWithCode(Message query, int responseCode) { Message message = new Message(query.getHeader().getID()); message.getHeader().setOpcode(query.getHeader().getOpcode()); message.getHeader().setFlag(Flags.QR); message.getHeader().setRcode(responseCode); return message; }
Example #18
Source File: DnsMessageTransportTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testTimeoutReceivingResponse() throws Exception { InputStream mockInputStream = mock(InputStream.class); when(mockInputStream.read()).thenThrow(new SocketTimeoutException("testing")); when(mockSocket.getInputStream()).thenReturn(mockInputStream); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); Duration testTimeout = Duration.standardSeconds(1); DnsMessageTransport resolver = new DnsMessageTransport(mockFactory, UPDATE_HOST, testTimeout); Message expectedQuery = new Message(); assertThrows(SocketTimeoutException.class, () -> resolver.send(expectedQuery)); verify(mockSocket).setSoTimeout((int) testTimeout.getMillis()); }
Example #19
Source File: DnsUpdateWriter.java From nomulus with Apache License 2.0 | 5 votes |
@Override protected void commitUnchecked() { try { Message response = transport.send(update); verify( response.getRcode() == Rcode.NOERROR, "DNS server failed domain update for '%s' rcode: %s", zoneName, Rcode.string(response.getRcode())); } catch (IOException e) { throw new RuntimeException("publishDomain failed for zone: " + zoneName, e); } }
Example #20
Source File: SimpleDoTResolver.java From androdns with Apache License 2.0 | 5 votes |
private Message parseMessage(byte [] b) throws WireParseException { try { return (new Message(b)); } catch (IOException e) { if (Options.check("verbose")) e.printStackTrace(); if (!(e instanceof WireParseException)) e = new WireParseException("Error parsing message"); throw (WireParseException) e; } }
Example #21
Source File: SimpleDoTResolver.java From androdns with Apache License 2.0 | 5 votes |
private void verifyTSIG(Message query, Message response, byte [] b, TSIG tsig) { if (tsig == null) return; int error = tsig.verify(response, b, query.getTSIG()); if (Options.check("verbose")) System.err.println("TSIG verify: " + Rcode.TSIGstring(error)); }
Example #22
Source File: SimpleDoTResolver.java From androdns with Apache License 2.0 | 5 votes |
private int maxUDPSize(Message query) { OPTRecord opt = query.getOPT(); if (opt == null) return DEFAULT_UDPSIZE; else return opt.getPayloadSize(); }
Example #23
Source File: DnsMessageTransportTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testEofReceivingResponse() throws Exception { byte[] messageBytes = messageToBytesWithLength(expectedResponse); ByteArrayInputStream inputStream = new ByteArrayInputStream(Arrays.copyOf(messageBytes, messageBytes.length - 1)); when(mockSocket.getInputStream()).thenReturn(inputStream); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); assertThrows(EOFException.class, () -> resolver.send(new Message())); }
Example #24
Source File: DnsMessageTransport.java From nomulus with Apache License 2.0 | 5 votes |
/** * Sends a DNS "query" message (most likely an UPDATE) and returns the response. The response is * checked for matching ID and opcode. * * @param query a message to send * @return the response received from the server * @throws IOException if the Socket input/output streams throws one * @throws IllegalArgumentException if the query is too large to be sent (> 65535 bytes) */ public Message send(Message query) throws IOException { try (Socket socket = factory.createSocket(InetAddress.getByName(updateHost), DNS_PORT)) { socket.setSoTimeout(updateTimeout); writeMessage(socket.getOutputStream(), query); Message response = readMessage(socket.getInputStream()); checkValidResponse(query, response); return response; } }
Example #25
Source File: DnsMessageTransport.java From nomulus with Apache License 2.0 | 5 votes |
private void checkValidResponse(Message query, Message response) { verify( response.getHeader().getID() == query.getHeader().getID(), "response ID %s does not match query ID %s", response.getHeader().getID(), query.getHeader().getID()); verify( response.getHeader().getOpcode() == query.getHeader().getOpcode(), "response opcode '%s' does not match query opcode '%s'", Opcode.string(response.getHeader().getOpcode()), Opcode.string(query.getHeader().getOpcode())); }
Example #26
Source File: DnsMessageTransportTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testReceivedMessageWithLengthHasCorrectContent() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream(messageToBytesWithLength(expectedResponse)); when(mockSocket.getInputStream()).thenReturn(inputStream); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); Message actualResponse = resolver.send(simpleQuery); assertThat(base16().encode(actualResponse.toWire())) .isEqualTo(base16().encode(expectedResponse.toWire())); }
Example #27
Source File: DnsMessageTransport.java From nomulus with Apache License 2.0 | 5 votes |
private void writeMessage(OutputStream outputStream, Message message) throws IOException { byte[] messageData = message.toWire(); checkArgument( messageData.length <= MESSAGE_MAXIMUM_LENGTH, "DNS request message larger than maximum of %s: %s", MESSAGE_MAXIMUM_LENGTH, messageData.length); ByteBuffer buffer = ByteBuffer.allocate(messageData.length + MESSAGE_LENGTH_FIELD_BYTES); buffer.putShort((short) messageData.length); buffer.put(messageData); outputStream.write(buffer.array()); }
Example #28
Source File: DnsMessageTransport.java From nomulus with Apache License 2.0 | 5 votes |
private Message readMessage(InputStream inputStream) throws IOException { DataInputStream stream = new DataInputStream(inputStream); int length = stream.readUnsignedShort(); byte[] messageData = new byte[length]; stream.readFully(messageData); return new Message(messageData); }
Example #29
Source File: DnsMessageTransportTest.java From nomulus with Apache License 2.0 | 5 votes |
@Before public void before() throws Exception { simpleQuery = Message.newQuery(Record.newRecord(Name.fromString("example.com."), Type.A, DClass.IN)); expectedResponse = responseMessageWithCode(simpleQuery, Rcode.NOERROR); when(mockFactory.createSocket(InetAddress.getByName(UPDATE_HOST), DnsMessageTransport.DNS_PORT)) .thenReturn(mockSocket); resolver = new DnsMessageTransport(mockFactory, UPDATE_HOST, Duration.ZERO); }
Example #30
Source File: DnsUpdateWriterTest.java From nomulus with Apache License 2.0 | 5 votes |
private Message messageWithResponseCode(int responseCode) { Message message = new Message(); message.getHeader().setOpcode(Opcode.UPDATE); message.getHeader().setFlag(Flags.QR); message.getHeader().setRcode(responseCode); return message; }