blob: 625e7c041dc0ddfc0eb5c02dc650b22d58fba7d2 [file] [log] [blame]
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/dns/dns_response.h"
6
7#include "base/string_util.h"
8#include "base/sys_byteorder.h"
9#include "net/base/address_list.h"
10#include "net/base/big_endian.h"
11#include "net/base/dns_util.h"
12#include "net/base/io_buffer.h"
13#include "net/base/net_errors.h"
14#include "net/dns/dns_protocol.h"
15#include "net/dns/dns_query.h"
16
17namespace net {
18
19DnsResourceRecord::DnsResourceRecord() {
20}
21
22DnsResourceRecord::~DnsResourceRecord() {
23}
24
25DnsRecordParser::DnsRecordParser() : packet_(NULL), length_(0), cur_(0) {
26}
27
28DnsRecordParser::DnsRecordParser(const void* packet,
29 size_t length,
30 size_t offset)
31 : packet_(reinterpret_cast<const char*>(packet)),
32 length_(length),
33 cur_(packet_ + offset) {
34 DCHECK_LE(offset, length);
35}
36
37unsigned DnsRecordParser::ReadName(const void* const vpos,
38 std::string* out) const {
39 const char* const pos = reinterpret_cast<const char*>(vpos);
40 DCHECK(packet_);
41 DCHECK_LE(packet_, pos);
42 DCHECK_LE(pos, packet_ + length_);
43
44 const char* p = pos;
45 const char* end = packet_ + length_;
46 // Count number of seen bytes to detect loops.
47 unsigned seen = 0;
48 // Remember how many bytes were consumed before first jump.
49 unsigned consumed = 0;
50
51 if (pos >= end)
52 return 0;
53
54 if (out) {
55 out->clear();
56 out->reserve(dns_protocol::kMaxNameLength);
57 }
58
59 for (;;) {
60 // The first two bits of the length give the type of the length. It's
61 // either a direct length or a pointer to the remainder of the name.
62 switch (*p & dns_protocol::kLabelMask) {
63 case dns_protocol::kLabelPointer: {
64 if (p + sizeof(uint16) > end)
65 return 0;
66 if (consumed == 0) {
67 consumed = p - pos + sizeof(uint16);
68 if (!out)
69 return consumed; // If name is not stored, that's all we need.
70 }
71 seen += sizeof(uint16);
72 // If seen the whole packet, then we must be in a loop.
73 if (seen > length_)
74 return 0;
75 uint16 offset;
76 ReadBigEndian<uint16>(p, &offset);
77 offset &= dns_protocol::kOffsetMask;
78 p = packet_ + offset;
79 if (p >= end)
80 return 0;
81 break;
82 }
83 case dns_protocol::kLabelDirect: {
84 uint8 label_len = *p;
85 ++p;
86 // Note: root domain (".") is NOT included.
87 if (label_len == 0) {
88 if (consumed == 0) {
89 consumed = p - pos;
90 } // else we set |consumed| before first jump
91 return consumed;
92 }
93 if (p + label_len >= end)
94 return 0; // Truncated or missing label.
95 if (out) {
96 if (!out->empty())
97 out->append(".");
98 out->append(p, label_len);
99 }
100 p += label_len;
101 seen += 1 + label_len;
102 break;
103 }
104 default:
105 // unhandled label type
106 return 0;
107 }
108 }
109}
110
111bool DnsRecordParser::ReadRecord(DnsResourceRecord* out) {
112 DCHECK(packet_);
113 size_t consumed = ReadName(cur_, &out->name);
114 if (!consumed)
115 return false;
116 BigEndianReader reader(cur_ + consumed,
117 packet_ + length_ - (cur_ + consumed));
118 uint16 rdlen;
119 if (reader.ReadU16(&out->type) &&
120 reader.ReadU16(&out->klass) &&
121 reader.ReadU32(&out->ttl) &&
122 reader.ReadU16(&rdlen) &&
123 reader.ReadPiece(&out->rdata, rdlen)) {
124 cur_ = reader.ptr();
125 return true;
126 }
127 return false;
128}
129
130DnsResponse::DnsResponse()
131 : io_buffer_(new IOBufferWithSize(dns_protocol::kMaxUDPSize + 1)) {
132}
133
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000134DnsResponse::DnsResponse(size_t length)
135 : io_buffer_(new IOBufferWithSize(length)) {
136}
137
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000138DnsResponse::DnsResponse(const void* data,
139 size_t length,
140 size_t answer_offset)
141 : io_buffer_(new IOBufferWithSize(length)),
142 parser_(io_buffer_->data(), length, answer_offset) {
143 DCHECK(data);
144 memcpy(io_buffer_->data(), data, length);
145}
146
147DnsResponse::~DnsResponse() {
148}
149
150bool DnsResponse::InitParse(int nbytes, const DnsQuery& query) {
151 // Response includes query, it should be at least that size.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000152 if (nbytes < query.io_buffer()->size() || nbytes >= io_buffer_->size())
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000153 return false;
154
155 // Match the query id.
156 if (base::NetToHost16(header()->id) != query.id())
157 return false;
158
159 // Match question count.
160 if (base::NetToHost16(header()->qdcount) != 1)
161 return false;
162
163 // Match the question section.
164 const size_t hdr_size = sizeof(dns_protocol::Header);
165 const base::StringPiece question = query.question();
166 if (question != base::StringPiece(io_buffer_->data() + hdr_size,
167 question.size())) {
168 return false;
169 }
170
171 // Construct the parser.
172 parser_ = DnsRecordParser(io_buffer_->data(),
173 nbytes,
174 hdr_size + question.size());
175 return true;
176}
177
178bool DnsResponse::IsValid() const {
179 return parser_.IsValid();
180}
181
182uint16 DnsResponse::flags() const {
183 DCHECK(parser_.IsValid());
184 return base::NetToHost16(header()->flags) & ~(dns_protocol::kRcodeMask);
185}
186
187uint8 DnsResponse::rcode() const {
188 DCHECK(parser_.IsValid());
189 return base::NetToHost16(header()->flags) & dns_protocol::kRcodeMask;
190}
191
192unsigned DnsResponse::answer_count() const {
193 DCHECK(parser_.IsValid());
194 return base::NetToHost16(header()->ancount);
195}
196
197base::StringPiece DnsResponse::qname() const {
198 DCHECK(parser_.IsValid());
199 // The response is HEADER QNAME QTYPE QCLASS ANSWER.
200 // |parser_| is positioned at the beginning of ANSWER, so the end of QNAME is
201 // two uint16s before it.
202 const size_t hdr_size = sizeof(dns_protocol::Header);
203 const size_t qname_size = parser_.GetOffset() - 2 * sizeof(uint16) - hdr_size;
204 return base::StringPiece(io_buffer_->data() + hdr_size, qname_size);
205}
206
207uint16 DnsResponse::qtype() const {
208 DCHECK(parser_.IsValid());
209 // QTYPE starts where QNAME ends.
210 const size_t type_offset = parser_.GetOffset() - 2 * sizeof(uint16);
211 uint16 type;
212 ReadBigEndian<uint16>(io_buffer_->data() + type_offset, &type);
213 return type;
214}
215
216std::string DnsResponse::GetDottedName() const {
217 return DNSDomainToString(qname());
218}
219
220DnsRecordParser DnsResponse::Parser() const {
221 DCHECK(parser_.IsValid());
222 // Return a copy of the parser.
223 return parser_;
224}
225
226const dns_protocol::Header* DnsResponse::header() const {
227 return reinterpret_cast<const dns_protocol::Header*>(io_buffer_->data());
228}
229
230DnsResponse::Result DnsResponse::ParseToAddressList(
231 AddressList* addr_list,
232 base::TimeDelta* ttl) const {
233 DCHECK(IsValid());
234 // DnsTransaction already verified that |response| matches the issued query.
235 // We still need to determine if there is a valid chain of CNAMEs from the
236 // query name to the RR owner name.
237 // We err on the side of caution with the assumption that if we are too picky,
238 // we can always fall back to the system getaddrinfo.
239
240 // Expected owner of record. No trailing dot.
241 std::string expected_name = GetDottedName();
242
243 uint16 expected_type = qtype();
244 DCHECK(expected_type == dns_protocol::kTypeA ||
245 expected_type == dns_protocol::kTypeAAAA);
246
247 size_t expected_size = (expected_type == dns_protocol::kTypeAAAA)
248 ? kIPv6AddressSize : kIPv4AddressSize;
249
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000250 uint32 ttl_sec = kuint32max;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000251 IPAddressList ip_addresses;
252 DnsRecordParser parser = Parser();
253 DnsResourceRecord record;
254 unsigned ancount = answer_count();
255 for (unsigned i = 0; i < ancount; ++i) {
256 if (!parser.ReadRecord(&record))
257 return DNS_MALFORMED_RESPONSE;
258
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000259 if (record.type == dns_protocol::kTypeCNAME) {
260 // Following the CNAME chain, only if no addresses seen.
261 if (!ip_addresses.empty())
262 return DNS_CNAME_AFTER_ADDRESS;
263
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000264 if (base::strcasecmp(record.name.c_str(), expected_name.c_str()) != 0)
265 return DNS_NAME_MISMATCH;
266
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000267 if (record.rdata.size() !=
268 parser.ReadName(record.rdata.begin(), &expected_name))
269 return DNS_MALFORMED_CNAME;
270
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000271 ttl_sec = std::min(ttl_sec, record.ttl);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000272 } else if (record.type == expected_type) {
273 if (record.rdata.size() != expected_size)
274 return DNS_SIZE_MISMATCH;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000275
276 if (base::strcasecmp(record.name.c_str(), expected_name.c_str()) != 0)
277 return DNS_NAME_MISMATCH;
278
279 ttl_sec = std::min(ttl_sec, record.ttl);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000280 ip_addresses.push_back(IPAddressNumber(record.rdata.begin(),
281 record.rdata.end()));
282 }
283 }
284
285 // TODO(szym): Extract TTL for NODATA results. http://crbug.com/115051
286
287 // getcanonname in eglibc returns the first owner name of an A or AAAA RR.
288 // If the response passed all the checks so far, then |expected_name| is it.
289 *addr_list = AddressList::CreateFromIPAddressList(ip_addresses,
290 expected_name);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000291 *ttl = base::TimeDelta::FromSeconds(ttl_sec);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000292 return DNS_PARSE_OK;
293}
294
295} // namespace net