data_source.cc 41.7 KB
Newer Older
JINMEI Tatuya's avatar
JINMEI Tatuya committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

15
#include <config.h>
16

17
#include <cassert>
Evan Hunt's avatar
Evan Hunt committed
18
#include <iomanip>
19 20 21
#include <iostream>
#include <vector>

JINMEI Tatuya's avatar
JINMEI Tatuya committed
22
#include <boost/shared_ptr.hpp>
23 24
#include <boost/foreach.hpp>

Evan Hunt's avatar
Evan Hunt committed
25 26 27 28
#include <datasrc/cache.h>
#include <datasrc/data_source.h>
#include <datasrc/query.h>

29
#include <dns/util/base32hex.h>
Evan Hunt's avatar
Evan Hunt committed
30
#include <dns/buffer.h>
31
#include <dns/message.h>
32
#include <dns/name.h>
33
#include <dns/rcode.h>
34
#include <dns/rdataclass.h>
35
#include <dns/rrset.h>
36
#include <dns/rrsetlist.h>
37
#include <dns/util/sha1.h>
38

39
#include <cc/data.h>
40

41 42 43 44 45 46
#define RETERR(x) do { \
                      DataSrc::Result r = (x); \
                      if (r != DataSrc::SUCCESS) \
                          return (r); \
                      } while (0)

47 48 49 50
using namespace std;
using namespace isc::dns;
using namespace isc::dns::rdata;

51
namespace isc {
Evan Hunt's avatar
Evan Hunt committed
52
namespace datasrc {
53

JINMEI Tatuya's avatar
JINMEI Tatuya committed
54 55
typedef boost::shared_ptr<const Nsec3Param> ConstNsec3ParamPtr;

Evan Hunt's avatar
Evan Hunt committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
class ZoneInfo {
public:
    ZoneInfo(DataSrc* ts,
             const isc::dns::Name& n,
             const isc::dns::RRClass& c, 
             const isc::dns::RRType& t = isc::dns::RRType::ANY()) :
        top_source_(ts),
        dsm_(((t == RRType::DS() && n.getLabelCount() != 1)
              ? n.split(1, n.getLabelCount() - 1) : n),
             c)
    {}

    const Name* getEnclosingZone() {
        if (dsm_.getEnclosingZone() == NULL) {
            top_source_->findClosestEnclosure(dsm_);
        }
        return (dsm_.getEnclosingZone());
    }

    const DataSrc* getDataSource() {
        if (dsm_.getDataSource() == NULL) {
            top_source_->findClosestEnclosure(dsm_);
        }
        return (dsm_.getDataSource());
    }

private:
    const DataSrc* top_source_;
    DataSrcMatch dsm_;
};

87 88
// Add a task to the query task queue to look up additional data
// (i.e., address records for the names included in NS or MX records)
JINMEI Tatuya's avatar
JINMEI Tatuya committed
89
void
JINMEI Tatuya's avatar
JINMEI Tatuya committed
90
getAdditional(Query& q, ConstRRsetPtr rrset) {
91 92 93 94 95
    if (!q.wantAdditional()) {
        return;
    }

    RdataIteratorPtr it = rrset->getRdataIterator();
96
    for (; !it->isLast(); it->next()) {
97 98 99
        const Rdata& rd(it->getCurrent());
        if (rrset->getType() == RRType::NS()) {
            const generic::NS& ns = dynamic_cast<const generic::NS&>(rd);
JINMEI Tatuya's avatar
JINMEI Tatuya committed
100
            q.tasks().push(QueryTaskPtr(
Evan Hunt's avatar
Evan Hunt committed
101
                               new QueryTask(q, ns.getNSName(),
102
                                             Message::SECTION_ADDITIONAL,
JINMEI Tatuya's avatar
JINMEI Tatuya committed
103
                                             QueryTask::GLUE_QUERY,
104
                                             QueryTask::GETADDITIONAL)));
105 106
        } else if (rrset->getType() == RRType::MX()) {
            const generic::MX& mx = dynamic_cast<const generic::MX&>(rd);
JINMEI Tatuya's avatar
JINMEI Tatuya committed
107
            q.tasks().push(QueryTaskPtr(
Evan Hunt's avatar
Evan Hunt committed
108
                               new QueryTask(q, mx.getMXName(),
109
                                             Message::SECTION_ADDITIONAL,
JINMEI Tatuya's avatar
JINMEI Tatuya committed
110
                                             QueryTask::NOGLUE_QUERY,
111
                                             QueryTask::GETADDITIONAL)));
112 113 114 115 116 117
        }
    }
}

// Synthesize a CNAME answer, for the benefit of clients that don't
// understand DNAME
JINMEI Tatuya's avatar
JINMEI Tatuya committed
118
void
119
synthesizeCname(QueryTaskPtr task, RRsetPtr rrset, RRsetList& target) {
120
    RdataIteratorPtr it = rrset->getRdataIterator();
121 122 123 124 125 126 127 128 129 130 131

    // More than one DNAME RR in the RRset is illegal, so we only have
    // to process the first one.
    if (it->isLast()) {
        return;
    }

    const Rdata& rd(it->getCurrent());
    const generic::DNAME& dname = dynamic_cast<const generic::DNAME&>(rd);
    const Name& dname_target(dname.getDname());

132 133 134 135 136 137 138 139 140 141
    RRsetPtr cname(new RRset(task->qname, task->qclass, RRType::CNAME(),
                             rrset->getTTL()));

    const int qnlen = task->qname.getLabelCount();
    const int dnlen = rrset->getName().getLabelCount();
    assert(qnlen > dnlen);
    const Name& prefix(task->qname.split(0, qnlen - dnlen));
    cname->addRdata(generic::CNAME(prefix.concatenate(dname_target)));

    target.addRRset(cname);
142 143 144 145
}

// Add a task to the query task queue to look up the data pointed
// to by a CNAME record
JINMEI Tatuya's avatar
JINMEI Tatuya committed
146 147
void
chaseCname(Query& q, QueryTaskPtr task, RRsetPtr rrset) {
148
    RdataIteratorPtr it = rrset->getRdataIterator();
149 150 151 152 153 154 155

    // More than one CNAME RR in the RRset is illegal, so we only have
    // to process the first one.
    if (it->isLast()) {
        return;
    }

Evan Hunt's avatar
Evan Hunt committed
156
    // Stop chasing CNAMES after 16 lookups, to prevent loops
157 158 159 160
    if (q.tooMany()) {
        return;
    }

161
    q.tasks().push(QueryTaskPtr(
Evan Hunt's avatar
Evan Hunt committed
162
                       new QueryTask(q, dynamic_cast<const generic::CNAME&>
163
                                     (it->getCurrent()).getCname(),
164
                                     task->qtype, Message::SECTION_ANSWER,
165
                                     QueryTask::FOLLOWCNAME)));
166 167
}

Evan Hunt's avatar
Evan Hunt committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
// Check the cache for data which can answer the current query task.
bool
checkCache(QueryTask& task, RRsetList& target) {
    HotCache& cache = task.q.getCache();
    RRsetList rrsets;
    RRsetPtr rrset;
    int count = 0;
    uint32_t flags = 0, cflags = 0;
    bool hit = false, found = false;

    switch (task.op) {
    case QueryTask::SIMPLE_QUERY:       // Find exact RRset
        // ANY queries must be handled by the low-level data source,
        // or the results won't be guaranteed to be complete
        if (task.qtype == RRType::ANY() || task.qclass == RRClass::ANY()) {
            break;
        }

        hit = cache.retrieve(task.qname, task.qclass, task.qtype, rrset, flags);
        if (hit) {
            if (rrset) {
                rrsets.addRRset(rrset);
                target.append(rrsets);
            }
            task.flags = flags;
            return (true);
        }
        break;

    case QueryTask::AUTH_QUERY:         // Find exact RRset or CNAME
        if (task.qtype == RRType::ANY() || task.qclass == RRClass::ANY()) {
            break;
        }

        hit = cache.retrieve(task.qname, task.qclass, task.qtype, rrset, flags);
        if (!hit || !rrset || (flags & DataSrc::CNAME_FOUND) != 0) {
            hit = cache.retrieve(task.qname, task.qclass, RRType::CNAME(),
                                 rrset, flags);
Jeremy C. Reed's avatar
Jeremy C. Reed committed
206 207 208 209 210
            if (!rrset) {
                // If we don't have a positive cache, forget it; otherwise the
                // intermediate result may confuse the subsequent processing.
                hit = false;
            }
Evan Hunt's avatar
Evan Hunt committed
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
        }

        if (hit) {
            if (rrset) {
                rrsets.addRRset(rrset);
                target.append(rrsets);
            }
            task.flags = flags;
            return (true);
        }
        break;

    case QueryTask::GLUE_QUERY:         // Find addresses
    case QueryTask::NOGLUE_QUERY:
        // (XXX: need to figure out how to deal with noglue case)
        flags = 0;

        hit = cache.retrieve(task.qname, task.qclass, RRType::A(),
                             rrset, cflags);
        if (hit) {
            flags |= cflags;
            ++count;
            if (rrset) {
                rrsets.addRRset(rrset);
                found = true;
            }
        }

        hit = cache.retrieve(task.qname, task.qclass, RRType::AAAA(),
                             rrset, flags);
        if (hit) {
            flags |= cflags;
            ++count;
            if (rrset) {
                rrsets.addRRset(rrset);
                found = true;
            }
        }

        if (count == 2) {
            if (found) {
                flags &= ~DataSrc::TYPE_NOT_FOUND;
                target.append(rrsets);
            }
            task.flags = flags;
            return (true);
        } 
        break;


    case QueryTask::REF_QUERY:          // Find NS, DS and/or DNAME
        flags = count = 0;

        hit = cache.retrieve(task.qname, task.qclass, RRType::NS(),
                             rrset, cflags);
        if (hit) {
            flags |= cflags;
            ++count;
            if (rrset) {
                rrsets.addRRset(rrset);
                found = true;
            }
        }

        hit = cache.retrieve(task.qname, task.qclass, RRType::DS(),
                             rrset, flags);
        if (hit) {
            flags |= cflags;
            ++count;
            if (rrset) {
                rrsets.addRRset(rrset);
                found = true;
            }
        }

        hit = cache.retrieve(task.qname, task.qclass, RRType::DNAME(),
                             rrset, flags);
        if (hit) {
            flags |= cflags;
            ++count;
            if (rrset) {
                rrsets.addRRset(rrset);
                found = true;
            }
        }

        if (count == 3) {
            if (found) {
                flags &= ~DataSrc::TYPE_NOT_FOUND;
                flags &= DataSrc::REFERRAL;
                target.append(rrsets);
            }
            task.flags = flags;
            return (true);
        } 
        break;
    }

    return (false);
}

// Carry out the query specified in a QueryTask object
JINMEI Tatuya's avatar
JINMEI Tatuya committed
313
DataSrc::Result
Evan Hunt's avatar
Evan Hunt committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
doQueryTask(QueryTask& task, ZoneInfo& zoneinfo, RRsetList& target) {
    HotCache& cache = task.q.getCache();
    RRsetPtr rrset;

    // First, check the cache for matching data
    if (checkCache(task, target)) {
        return (DataSrc::SUCCESS);
    }

    // Requested data weren't in the cache (or were, but had expired),
    // so now we proceed with the low-level data source lookup, and cache
    // whatever we find.
    const DataSrc* ds = zoneinfo.getDataSource();
    const Name* const zonename = zoneinfo.getEnclosingZone();

    if (ds == NULL) {
        task.flags |= DataSrc::NO_SUCH_ZONE;
        return (DataSrc::SUCCESS);
    }

    DataSrc::Result result;
335
    switch (task.op) {
Evan Hunt's avatar
Evan Hunt committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    case QueryTask::SIMPLE_QUERY:
        result = ds->findExactRRset(task.qname, task.qclass, task.qtype,
                                    target, task.flags, zonename);

        if (result != DataSrc::SUCCESS) {
            return (result);
        }

        if (task.qclass == RRClass::ANY()) {
            // XXX: Currently, RRsetList::findRRset() doesn't handle
            // ANY queries, and without that we can't cache the results,
            // so we just return in that case.
            return (result);
        }

        if (task.flags == 0) {
            rrset = target.findRRset(task.qtype, task.qclass);
            assert(rrset);
            cache.addPositive(rrset, task.flags);
        } else {
            cache.addNegative(task.qname, task.qclass, task.qtype, task.flags);
        }

        return (result);

361
    case QueryTask::AUTH_QUERY:
Evan Hunt's avatar
Evan Hunt committed
362 363
        result = ds->findRRset(task.qname, task.qclass, task.qtype,
                               target, task.flags, zonename);
364

Evan Hunt's avatar
Evan Hunt committed
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        if (result != DataSrc::SUCCESS) {
            return (result);
        }

        if (task.qclass == RRClass::ANY()) {
            return (result);
        }

        if (task.qtype == RRType::ANY()) {
            BOOST_FOREACH(RRsetPtr rr, target) {
                cache.addPositive(rr, task.flags);
            }
        } else if ((task.flags & DataSrc::CNAME_FOUND) != 0) {
            cache.addNegative(task.qname, task.qclass, task.qtype, task.flags);
            rrset = target.findRRset(RRType::CNAME(), task.qclass);
            assert(rrset);
            cache.addPositive(rrset, task.flags);
        } else if ((task.flags & DataSrc::DATA_NOT_FOUND) == 0) {
            if (task.qtype != RRType::CNAME()) {
                cache.addNegative(task.qname, task.qclass, RRType::CNAME(),
                                  task.flags);
            }
            rrset = target.findRRset(task.qtype, task.qclass);
            assert(rrset);
            cache.addPositive(rrset, task.flags);
        } else {
            cache.addNegative(task.qname, task.qclass, task.qtype, task.flags);
        }

        return (result);
395 396 397

    case QueryTask::GLUE_QUERY:
    case QueryTask::NOGLUE_QUERY:
Evan Hunt's avatar
Evan Hunt committed
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
        result = ds->findAddrs(task.qname, task.qclass, target,
                               task.flags, zonename);

        if (result != DataSrc::SUCCESS) {
            return (result);
        }

        if (task.qclass == RRClass::ANY()) {
            return (result);
        }

        rrset = target.findRRset(RRType::A(), task.qclass);
        if (rrset) {
            cache.addPositive(rrset, task.flags);
        } else {
            cache.addNegative(task.qname, task.qclass, RRType::A(), task.flags);
        }

        rrset = target.findRRset(RRType::AAAA(), task.qclass);
        if (rrset) {
            cache.addPositive(rrset, task.flags);
        } else {
            cache.addNegative(task.qname, task.qclass, RRType::AAAA(),
                              task.flags);
        }

        return (result);
425 426

    case QueryTask::REF_QUERY:
Evan Hunt's avatar
Evan Hunt committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
        result = ds->findReferral(task.qname, task.qclass, target,
                                 task.flags, zonename);

        if (result != DataSrc::SUCCESS) {
            return (result);
        }

        if (task.qclass == RRClass::ANY()) {
            return (result);
        }

        rrset = target.findRRset(RRType::NS(), task.qclass);
        if (rrset) {
            cache.addPositive(rrset, task.flags);
        } else {
            cache.addNegative(task.qname, task.qclass, RRType::NS(),
                              task.flags);
        }
        rrset = target.findRRset(RRType::DS(), task.qclass);
        if (rrset) {
            cache.addPositive(rrset, task.flags);
        } else {
            cache.addNegative(task.qname, task.qclass, RRType::DS(),
                              task.flags);
        }
        rrset = target.findRRset(RRType::DNAME(), task.qclass);
        if (rrset) {
            cache.addPositive(rrset, task.flags);
        } else {
            cache.addNegative(task.qname, task.qclass, RRType::DNAME(),
                              task.flags);
        }

        return (result);
461
    }
462

463 464 465 466
    // Not reached
    return (DataSrc::ERROR);
}

Evan Hunt's avatar
Evan Hunt committed
467

Evan Hunt's avatar
Evan Hunt committed
468 469 470 471
// Add an RRset (and its associated RRSIG) to a message section,
// checking first to ensure that there isn't already an RRset with
// the same name and type.
inline void
472
addToMessage(Query& q, const Message::Section sect, RRsetPtr rrset,
Evan Hunt's avatar
Evan Hunt committed
473 474 475 476
             bool no_dnssec = false)
{
    Message& m = q.message();
    if (no_dnssec) {
477 478 479
        if (rrset->getType() == RRType::RRSIG() ||
            !m.hasRRset(sect, rrset->getName(), rrset->getClass(),
                        rrset->getType())) {
Evan Hunt's avatar
Evan Hunt committed
480 481 482
            m.addRRset(sect, rrset, false);
        }
    } else {
483 484
        if (!m.hasRRset(sect, rrset->getName(), rrset->getClass(),
                        rrset->getType())) {
Evan Hunt's avatar
Evan Hunt committed
485 486 487 488 489
            m.addRRset(sect, rrset, q.wantDnssec());
        }
    }
}

490
// Copy referral information into the authority section of a message
JINMEI Tatuya's avatar
JINMEI Tatuya committed
491 492
inline void
copyAuth(Query& q, RRsetList& auth) {
493 494 495 496
    BOOST_FOREACH(RRsetPtr rrset, auth) {
        if (rrset->getType() == RRType::DNAME()) {
            continue;
        }
497 498 499
        if (rrset->getType() == RRType::DS() && !q.wantDnssec()) {
            continue;
        }
500
        addToMessage(q, Message::SECTION_AUTHORITY, rrset);
501 502 503
        getAdditional(q, rrset);
    }
}
504

505
// Query for referrals (i.e., NS/DS or DNAME) at a given name
JINMEI Tatuya's avatar
JINMEI Tatuya committed
506
inline bool
Evan Hunt's avatar
Evan Hunt committed
507 508
refQuery(const Query& q, const Name& name, ZoneInfo& zoneinfo,
         RRsetList& target)
509
{
Evan Hunt's avatar
Evan Hunt committed
510
    QueryTask newtask(q, name, QueryTask::REF_QUERY);
511

Evan Hunt's avatar
Evan Hunt committed
512
    if (doQueryTask(newtask, zoneinfo, target) != DataSrc::SUCCESS) {
513
        // Lookup failed
514 515
        return (false);
    }
516

517
    // Referral bit is expected, so clear it when checking flags
518
    if ((newtask.flags & ~DataSrc::REFERRAL) != 0) {
519 520 521 522 523 524 525
        return (false);
    }

    return (true);
}

// Match downward, from the zone apex to the query name, looking for
526 527
// referrals.  Note that we exclude the apex name and query name themselves;
// they'll be handled in a normal lookup in the zone.
JINMEI Tatuya's avatar
JINMEI Tatuya committed
528
inline bool
Evan Hunt's avatar
Evan Hunt committed
529 530 531 532 533 534 535 536 537
hasDelegation(Query& q, QueryTaskPtr task, ZoneInfo& zoneinfo) {
    const Name* const zonename = zoneinfo.getEnclosingZone();
    if (zonename == NULL) {
        if (task->state == QueryTask::GETANSWER) {
            q.message().setRcode(Rcode::REFUSED());
        }
        return (false);
    }

538
    const int diff = task->qname.getLabelCount() - zonename->getLabelCount();
539
    if (diff > 1) {
540
        bool found = false;
541
        RRsetList ref;
542 543
        for (int i = diff - 1; i > 0; --i) {
            const Name sub(task->qname.split(i));
Evan Hunt's avatar
Evan Hunt committed
544
            if (refQuery(q, sub, zoneinfo, ref)) {
545 546 547 548 549 550 551
                found = true;
                break;
            }
        }

        // Found a referral while getting additional data
        // for something other than NS; we skip it.
552
        if (found && task->op == QueryTask::NOGLUE_QUERY) {
553 554 555 556 557 558
            return (true);
        }

        // Found a referral while getting answer data;
        // send a delegation.
        if (found) {
559 560
            RRsetPtr r = ref.findRRset(RRType::DNAME(), q.qclass());
            if (r != NULL) {
561
                RRsetList syn;
562 563
                addToMessage(q, Message::SECTION_ANSWER, r);
                q.message().setHeaderFlag(Message::HEADERFLAG_AA);
564
                synthesizeCname(task, r, syn);
565
                if (syn.size() == 1) {
566
                    addToMessage(q, Message::SECTION_ANSWER,
Evan Hunt's avatar
Evan Hunt committed
567
                                 syn.findRRset(RRType::CNAME(), q.qclass()));
568 569
                    chaseCname(q, task, syn.findRRset(RRType::CNAME(),
                                                      q.qclass()));
570 571 572 573 574 575 576 577 578 579 580 581
                    return (true);
                }
            }

            copyAuth(q, ref);
            return (true);
        }
    }

    // We appear to have authoritative data; set the header
    // flag.  (We may clear it later if we find a referral
    // at the actual qname node.)
582 583
    if (task->op == QueryTask::AUTH_QUERY &&
        task->state == QueryTask::GETANSWER) {
584
        q.message().setHeaderFlag(Message::HEADERFLAG_AA);
585 586 587 588 589
    }

    return (false);
}

JINMEI Tatuya's avatar
JINMEI Tatuya committed
590
inline DataSrc::Result
Evan Hunt's avatar
Evan Hunt committed
591
addSOA(Query& q, ZoneInfo& zoneinfo) {
Evan Hunt's avatar
Evan Hunt committed
592 593
    RRsetList soa;

Evan Hunt's avatar
Evan Hunt committed
594 595 596
    const Name* const zonename = zoneinfo.getEnclosingZone();
    QueryTask newtask(q, *zonename, RRType::SOA(), QueryTask::SIMPLE_QUERY);
    RETERR(doQueryTask(newtask, zoneinfo, soa));
597
    if (newtask.flags != 0) {
Evan Hunt's avatar
Evan Hunt committed
598 599 600
        return (DataSrc::ERROR);
    }

601
    addToMessage(q, Message::SECTION_AUTHORITY,
Evan Hunt's avatar
Evan Hunt committed
602
                 soa.findRRset(RRType::SOA(), q.qclass()));
Evan Hunt's avatar
Evan Hunt committed
603 604 605
    return (DataSrc::SUCCESS);
}

JINMEI Tatuya's avatar
JINMEI Tatuya committed
606
inline DataSrc::Result
Evan Hunt's avatar
Evan Hunt committed
607
addNSEC(Query& q, const Name& name, ZoneInfo& zoneinfo) {
Evan Hunt's avatar
Evan Hunt committed
608 609
    RRsetList nsec;

Evan Hunt's avatar
Evan Hunt committed
610 611
    QueryTask newtask(q, name, RRType::NSEC(), QueryTask::SIMPLE_QUERY); 
    RETERR(doQueryTask(newtask, zoneinfo, nsec));
Evan Hunt's avatar
Evan Hunt committed
612
    if (newtask.flags == 0) {
613
        addToMessage(q, Message::SECTION_AUTHORITY,
Evan Hunt's avatar
Evan Hunt committed
614
                     nsec.findRRset(RRType::NSEC(), q.qclass()));
Evan Hunt's avatar
Evan Hunt committed
615 616 617 618 619
    }

    return (DataSrc::SUCCESS);
}

JINMEI Tatuya's avatar
JINMEI Tatuya committed
620
inline DataSrc::Result
Evan Hunt's avatar
Evan Hunt committed
621 622 623 624 625 626 627 628 629
getNsec3(Query& q, ZoneInfo& zoneinfo, string& hash, RRsetPtr& target) {
    const DataSrc* ds = zoneinfo.getDataSource();
    const Name* const zonename = zoneinfo.getEnclosingZone();

    if (ds == NULL) {
        q.message().setRcode(Rcode::SERVFAIL());
        return (DataSrc::ERROR);
    }

630
    RRsetList rl;
Evan Hunt's avatar
Evan Hunt committed
631 632 633
    RETERR(ds->findCoveringNSEC3(*zonename, hash, rl));
    target = rl.findRRset(RRType::NSEC3(), q.qclass());

Evan Hunt's avatar
Evan Hunt committed
634 635 636
    return (DataSrc::SUCCESS);
}

JINMEI Tatuya's avatar
JINMEI Tatuya committed
637
ConstNsec3ParamPtr
Evan Hunt's avatar
Evan Hunt committed
638
getNsec3Param(Query& q, ZoneInfo& zoneinfo) {
Evan Hunt's avatar
Evan Hunt committed
639 640 641
    DataSrc::Result result;
    RRsetList nsec3param;

Evan Hunt's avatar
Evan Hunt committed
642 643
    const Name* const zonename = zoneinfo.getEnclosingZone();
    QueryTask newtask(q, *zonename, RRType::NSEC3PARAM(),
Evan Hunt's avatar
Evan Hunt committed
644
                      QueryTask::SIMPLE_QUERY); 
Evan Hunt's avatar
Evan Hunt committed
645
    result = doQueryTask(newtask, zoneinfo, nsec3param);
Evan Hunt's avatar
Evan Hunt committed
646 647
    newtask.flags &= ~DataSrc::REFERRAL;
    if (result != DataSrc::SUCCESS || newtask.flags != 0) {
JINMEI Tatuya's avatar
JINMEI Tatuya committed
648
        return (ConstNsec3ParamPtr());
Evan Hunt's avatar
Evan Hunt committed
649 650
    }

651
    RRsetPtr rrset = nsec3param.findRRset(RRType::NSEC3PARAM(), q.qclass());
Evan Hunt's avatar
Evan Hunt committed
652
    if (!rrset) {
JINMEI Tatuya's avatar
JINMEI Tatuya committed
653
        return (ConstNsec3ParamPtr());
Evan Hunt's avatar
Evan Hunt committed
654 655 656 657 658 659
    }

    // XXX: currently only one NSEC3 chain per zone is supported;
    // we will need to revisit this.
    RdataIteratorPtr it = rrset->getRdataIterator();
    if (it->isLast()) {
JINMEI Tatuya's avatar
JINMEI Tatuya committed
660
        return (ConstNsec3ParamPtr());
Evan Hunt's avatar
Evan Hunt committed
661 662 663 664
    }

    const generic::NSEC3PARAM& np =
            dynamic_cast<const generic::NSEC3PARAM&>(it->getCurrent());
JINMEI Tatuya's avatar
JINMEI Tatuya committed
665 666 667
    return (ConstNsec3ParamPtr(new Nsec3Param(np.getHashalg(), np.getFlags(),
                                              np.getIterations(),
                                              np.getSalt())));
Evan Hunt's avatar
Evan Hunt committed
668 669
}

JINMEI Tatuya's avatar
JINMEI Tatuya committed
670
inline DataSrc::Result
Evan Hunt's avatar
Evan Hunt committed
671 672 673 674 675
proveNX(Query& q, QueryTaskPtr task, ZoneInfo& zoneinfo, const bool wildcard) {
    Message& m = q.message();
    const Name* const zonename = zoneinfo.getEnclosingZone();
    ConstNsec3ParamPtr nsec3 = getNsec3Param(q, zoneinfo);

JINMEI Tatuya's avatar
JINMEI Tatuya committed
676
    if (nsec3 != NULL) {
677 678
        // Attach the NSEC3 record covering the QNAME
        RRsetPtr rrset;
JINMEI Tatuya's avatar
JINMEI Tatuya committed
679
        string hash1(nsec3->getHash(task->qname));
Evan Hunt's avatar
Evan Hunt committed
680
        RETERR(getNsec3(q, zoneinfo, hash1, rrset));
681
        addToMessage(q, Message::SECTION_AUTHORITY, rrset);
682 683 684 685 686 687 688

        // If this is an NXRRSET or NOERROR/NODATA, we're done
        if ((task->flags & DataSrc::TYPE_NOT_FOUND) != 0) {
            return (DataSrc::SUCCESS);
        }

        // Find the closest provable enclosing name for QNAME
Evan Hunt's avatar
Evan Hunt committed
689
        Name enclosure(*zonename);
690 691
        const int diff = task->qname.getLabelCount() -
            enclosure.getLabelCount();
JINMEI Tatuya's avatar
JINMEI Tatuya committed
692
        string hash2;
693
        for (int i = 1; i <= diff; ++i) {
694
            enclosure = task->qname.split(i);
695 696 697 698 699 700
            string nodehash(nsec3->getHash(enclosure));
            if (nodehash == hash1) {
                break;
            }
            hash2 = nodehash;
            RRsetList rl;
Evan Hunt's avatar
Evan Hunt committed
701

702 703
            // hash2 will be overwritten with the actual hash found;
            // we don't want to use one until we find an exact match
Evan Hunt's avatar
Evan Hunt committed
704
            RETERR(getNsec3(q, zoneinfo, hash2, rrset));
705
            if (hash2 == nodehash) {
706
                addToMessage(q, Message::SECTION_AUTHORITY, rrset);
707
                break;
Evan Hunt's avatar
Evan Hunt committed
708 709 710
            }
        }

711 712 713 714 715 716 717
        // If we are processing a wildcard answer, we're done.
        if (wildcard) {
            return (DataSrc::SUCCESS);
        }

        // Otherwise, there is no wildcard record, so we must add a
        // covering NSEC3 to prove that it doesn't exist.
718
        string hash3(nsec3->getHash(Name("*").concatenate(enclosure)));
Evan Hunt's avatar
Evan Hunt committed
719
        RETERR(getNsec3(q, zoneinfo, hash3, rrset));
720
        if (hash3 != hash1 && hash3 != hash2) {
721
            addToMessage(q, Message::SECTION_AUTHORITY, rrset);
Evan Hunt's avatar
Evan Hunt committed
722 723 724
        }
    } else {
        Name nsecname(task->qname);
725
        if ((task->flags & DataSrc::NAME_NOT_FOUND) != 0 || wildcard) {
Evan Hunt's avatar
Evan Hunt committed
726 727 728 729 730 731
            const DataSrc* ds = zoneinfo.getDataSource();
            if (ds == NULL) {
                m.setRcode(Rcode::SERVFAIL());
                return (DataSrc::ERROR);
            }
            ds->findPreviousName(task->qname, nsecname, zonename);
Evan Hunt's avatar
Evan Hunt committed
732 733
        }

Evan Hunt's avatar
Evan Hunt committed
734
        RETERR(addNSEC(q, nsecname, zoneinfo));
Evan Hunt's avatar
Evan Hunt committed
735
        if ((task->flags & DataSrc::TYPE_NOT_FOUND) != 0 ||
Evan Hunt's avatar
Evan Hunt committed
736
            nsecname == *zonename)
Evan Hunt's avatar
Evan Hunt committed
737 738 739 740
        {
            return (DataSrc::SUCCESS);
        }

741 742 743 744 745 746 747
        // If we are processing a wildcard answer, we're done.
        if (wildcard) {
            return (DataSrc::SUCCESS);
        }

        // Otherwise, there is no wildcard record, so we must add an
        // NSEC for the zone to prove the wildcard doesn't exist.
Evan Hunt's avatar
Evan Hunt committed
748
        RETERR(addNSEC(q, *zonename, zoneinfo));
Evan Hunt's avatar
Evan Hunt committed
749 750 751 752 753
    }

    return (DataSrc::SUCCESS);
}

754
// Attempt a wildcard lookup
JINMEI Tatuya's avatar
JINMEI Tatuya committed
755
inline DataSrc::Result
Evan Hunt's avatar
Evan Hunt committed
756
tryWildcard(Query& q, QueryTaskPtr task, ZoneInfo& zoneinfo, bool& found) {
757 758 759 760
    Message& m = q.message();
    DataSrc::Result result;
    found = false;

761 762 763
    if ((task->flags & DataSrc::NAME_NOT_FOUND) == 0 || 
        (task->state != QueryTask::GETANSWER &&
         task->state != QueryTask::FOLLOWCNAME)) {
764 765 766
        return (DataSrc::SUCCESS);
    }

Evan Hunt's avatar
Evan Hunt committed
767
    const Name* const zonename = zoneinfo.getEnclosingZone();
768
    const int diff = task->qname.getLabelCount() - zonename->getLabelCount();
769 770 771 772 773
    if (diff < 1) {
        return (DataSrc::SUCCESS);
    }

    RRsetList wild;
774
    const Name star("*");
775
    bool cname = false;
776

777
    for (int i = 1; i <= diff; ++i) {
778
        const Name& wname(star.concatenate(task->qname.split(i)));
779
        QueryTask newtask(q, wname, task->qtype, Message::SECTION_ANSWER,
780
                          QueryTask::AUTH_QUERY); 
Evan Hunt's avatar
Evan Hunt committed
781
        result = doQueryTask(newtask, zoneinfo, wild);
782
        if (result == DataSrc::SUCCESS) {
783
            if (newtask.flags == 0) {
784 785
                task->flags &= ~DataSrc::NAME_NOT_FOUND;
                task->flags &= ~DataSrc::TYPE_NOT_FOUND;
786 787
                found = true;
                break;
788
            } else if ((newtask.flags & DataSrc::CNAME_FOUND) != 0) {
789 790
                task->flags &= ~DataSrc::NAME_NOT_FOUND;
                task->flags &= ~DataSrc::TYPE_NOT_FOUND;
791 792 793 794
                task->flags |= DataSrc::CNAME_FOUND;
                found = true;
                cname = true;
                break;
795
            } else if ((newtask.flags & DataSrc::TYPE_NOT_FOUND) != 0) {
796
                task->flags &= ~DataSrc::NAME_NOT_FOUND;
797 798 799
                task->flags |= DataSrc::TYPE_NOT_FOUND;
                break;
            }
800 801 802
        }
    }

803
    // A wildcard was found.
804
    if (found) {
805
        // Prove the nonexistence of the name we were looking for
806
        if (q.wantDnssec()) {
Evan Hunt's avatar
Evan Hunt committed
807
            result = proveNX(q, task, zoneinfo, true);
808 809 810 811
            if (result != DataSrc::SUCCESS) {
                m.setRcode(Rcode::SERVFAIL());
                return (DataSrc::ERROR);
            }
812 813
        }

814 815 816
        // Add the data to the answer section (but with the name changed to
        // match the qname), and then continue as if this were a normal
        // answer: if a CNAME, chase the target, otherwise add authority.
817
        if (cname) {
818 819
            RRsetPtr rrset = wild.findRRset(RRType::CNAME(), q.qclass());
            if (rrset != NULL) {
820
                rrset->setName(task->qname);
821
                addToMessage(q, Message::SECTION_ANSWER, rrset);
822 823 824 825
                chaseCname(q, task, rrset);
            }
        } else {
            BOOST_FOREACH (RRsetPtr rrset, wild) {
826
                rrset->setName(task->qname);
827
                addToMessage(q, Message::SECTION_ANSWER, rrset);
828 829 830
            }

            RRsetList auth;
Evan Hunt's avatar
Evan Hunt committed
831
            if (!refQuery(q, *zonename, zoneinfo, auth)) {
832 833 834 835 836 837 838 839 840 841 842 843 844 845
                return (DataSrc::ERROR);
            }

            copyAuth(q, auth);
        }
    }

    return (DataSrc::SUCCESS);
}

//
// doQuery: Processes a query.
// 
void
JINMEI Tatuya's avatar
JINMEI Tatuya committed
846
DataSrc::doQuery(Query& q) {
847 848 849
    Message& m = q.message();
    vector<RRsetPtr> additional;

Evan Hunt's avatar
Evan Hunt committed
850 851 852 853 854 855
    // Record the fact that the query is being processed by the
    // current data source.
    q.setDatasrc(this);

    // Process the query task queue.  (The queue is initialized
    // and the first task placed on it by the Query constructor.)
856
    m.setHeaderFlag(Message::HEADERFLAG_AA, false);
857
    while (!q.tasks().empty()) {
858
        QueryTaskPtr task = q.tasks().front();
859 860
        q.tasks().pop();

Evan Hunt's avatar
Evan Hunt committed
861 862 863 864 865 866
        // Can't query directly for RRSIG.
        if (task->qtype == RRType::RRSIG()) {
            m.setRcode(Rcode::REFUSED());
            return;
        }

867
        // These task types should never be on the task queue.
868 869
        if (task->op == QueryTask::SIMPLE_QUERY ||
            task->op == QueryTask::REF_QUERY) {
870 871 872 873
            m.setRcode(Rcode::SERVFAIL());
            return;
        }

Evan Hunt's avatar
Evan Hunt committed
874
        ZoneInfo zoneinfo(this, task->qname, task->qclass, task->qtype);
875 876 877
        RRsetList data;
        Result result = SUCCESS;

Evan Hunt's avatar
Evan Hunt committed
878 879 880 881 882 883 884 885
        // For these query task types, if there is more than
        // one level between the zone name and qname, we need to
        // check the intermediate nodes for referrals.
        if ((task->op == QueryTask::AUTH_QUERY ||
             task->op == QueryTask::NOGLUE_QUERY) &&
            hasDelegation(q, task, zoneinfo)) {
            continue;
        }
886

Evan Hunt's avatar
Evan Hunt committed
887 888 889 890 891
        result = doQueryTask(*task, zoneinfo, data);
        if (result != SUCCESS) {
            m.setRcode(Rcode::SERVFAIL());
            return;
        }
892

Evan Hunt's avatar
Evan Hunt committed
893 894 895 896
        // No such zone.  If we're chasing cnames or adding additional
        // data, that's okay, but if doing an original query, return
        // REFUSED.
        if (task->flags == NO_SUCH_ZONE) {
897 898 899 900 901
            if (task->state == QueryTask::GETANSWER) {
                m.setRcode(Rcode::REFUSED());
                return;
            }
            continue;
902 903
        }

Evan Hunt's avatar
Evan Hunt committed
904 905 906 907 908 909 910 911 912 913 914 915 916
        // Query found a referral; let's find out if that was expected--
        // i.e., if an NS was at the zone apex, or if we were querying
        // specifically for, and found, a DS, NSEC, or DNAME record.
        const Name* const zonename = zoneinfo.getEnclosingZone();
        if ((task->flags & REFERRAL) != 0 &&
            (zonename->getLabelCount() == task->qname.getLabelCount() ||
             ((task->qtype == RRType::NSEC() ||
               task->qtype == RRType::DS() ||
               task->qtype == RRType::DNAME()) &&
              data.findRRset(task->qtype, task->qclass)))) {
            task->flags &= ~REFERRAL;
        }

917
        if (result == SUCCESS && task->flags == 0) {
918
            bool have_ns = false, need_auth = false;
919
            switch (task->state) {
920 921 922
            case QueryTask::GETANSWER:
            case QueryTask::FOLLOWCNAME:
                BOOST_FOREACH(RRsetPtr rrset, data) {
Evan Hunt's avatar
Evan Hunt committed
923
                    addToMessage(q, task->section, rrset);
924 925 926 927 928 929 930
                    if (q.tasks().empty()) {
                        need_auth = true;
                    }
                    getAdditional(q, rrset);
                    if (rrset->getType() == RRType::NS()) {
                        have_ns = true;
                    }
931
                }
932 933 934 935 936 937
                q.setStatus(Query::ANSWERED);
                if (need_auth && !have_ns) {
                    // Data found, no additional processing needed.
                    // Add the NS records for the enclosing zone to
                    // the authority section.
                    RRsetList auth;
Evan Hunt's avatar
Evan Hunt committed
938 939 940
                    const DataSrc* ds = zoneinfo.getDataSource();
                    if (!refQuery(q, Name(*zonename), zoneinfo, auth)  ||
                        !auth.findRRset(RRType::NS(), ds->getClass())) {
941 942
                        isc_throw(DataSourceError,
                                  "NS RR not found in " << *zonename << "/" <<
Evan Hunt's avatar
Evan Hunt committed
943
                                  q.qclass());
944
                    }
945

946
                    copyAuth(q, auth);
947
                }
948
                continue;
949

950 951 952 953 954 955 956 957 958 959 960
            case QueryTask::GETADDITIONAL:
                // Got additional data.  Do not add it to the message
                // yet; instead store it and copy it in at the end
                // (this allow RRSIGs to be omitted if necessary).
                BOOST_FOREACH(RRsetPtr rrset, data) {
                    if (q.status() == Query::ANSWERED &&
                        rrset->getName() == q.qname() &&
                        rrset->getType() == q.qtype()) {
                        continue;
                    }
                    additional.push_back(rrset);
961 962 963
                }
                continue;

964
            default:
JINMEI Tatuya's avatar
JINMEI Tatuya committed
965
                isc_throw (Unexpected, "unexpected query state");
966 967 968 969
            }
        } else if (result == ERROR || result == NOT_IMPLEMENTED) {
            m.setRcode(Rcode::SERVFAIL());
            return;
970
        } else if ((task->flags & CNAME_FOUND) != 0) {
971 972
            // The qname node contains a CNAME.  Add a new task to the
            // queue to look up its target.
973 974
            RRsetPtr rrset = data.findRRset(RRType::CNAME(), q.qclass());
            if (rrset != NULL) {
Evan Hunt's avatar
Evan Hunt committed
975
                addToMessage(q, task->section, rrset);
976 977 978
                chaseCname(q, task, rrset);
            }
            continue;
979
        } else if ((task->flags & REFERRAL) != 0) {
980
            // The qname node contains an out-of-zone referral.
981
            if (task->state == QueryTask::GETANSWER) {
982
                RRsetList auth;
983
                m.setHeaderFlag(Message::HEADERFLAG_AA, false);
Evan Hunt's avatar
Evan Hunt committed
984
                if (!refQuery(q, task->qname, zoneinfo, auth)) {
985 986
                    m.setRcode(Rcode::SERVFAIL());
                    return;
987
                }
988
                BOOST_FOREACH (RRsetPtr rrset, auth) {
989
                    if (rrset->getType() == RRType::NS()) {
990
                        addToMessage(q, Message::SECTION_AUTHORITY, rrset);
991
                    } else if (rrset->getType() == task->qtype) {
992
                        addToMessage(q, Message::SECTION_ANSWER, rrset);
993 994
                    } else if (rrset->getType() == RRType::DS() &&
                               q.wantDnssec()) {
995
                        addToMessage(q, Message::SECTION_AUTHORITY, rrset);
996 997 998 999 1000
                    }
                    getAdditional(q, rrset);
                }
            } 
            continue;
1001
        } else if ((task->flags & (NAME_NOT_FOUND|TYPE_NOT_FOUND)) != 0) {
1002 1003 1004 1005 1006
            // No data found at this qname/qtype.
            // If we were looking for answer data, not additional,
            // and the name was not found, we need to find out whether
            // there are any relevant wildcards.
            bool wildcard_found = false;
Evan Hunt's avatar
Evan Hunt committed
1007
            result = tryWildcard(q, task, zoneinfo, wildcard_found);
1008 1009 1010 1011
            if (result != SUCCESS) {
                m.setRcode(Rcode::SERVFAIL());
                return;
            }
1012

1013
            if (wildcard_found) {
1014
                continue;
1015 1016 1017 1018 1019 1020 1021 1022 1023
            }

            // If we've reached this point, there is definitely no answer.
            // If we were chasing cnames or adding additional data, that's
            // okay, but if we were doing an original query, reply with the
            // SOA in the authority section.  For NAME_NOT_FOUND, set
            // NXDOMAIN, and also add the previous NSEC to the authority
            // section.  For TYPE_NOT_FOUND, do not set an error rcode,
            // and send the current NSEC in the authority section.
1024
            if (task->state == QueryTask::GETANSWER) {
1025
                if ((task->flags & NAME_NOT_FOUND) != 0) {
1026
                    m.setRcode(Rcode::NXDOMAIN());
1027 1028
                }

Evan Hunt's avatar
Evan Hunt committed
1029
                result = addSOA(q, zoneinfo);
Evan Hunt's avatar
Evan Hunt committed
1030
                if (result != SUCCESS) {
1031
                    isc_throw(DataSourceError,
1032
                              "SOA RR not found in " << *zonename <<
Evan Hunt's avatar
Evan Hunt committed
1033
                              "/" << q.qclass());
1034
                }
Evan Hunt's avatar
Evan Hunt committed
1035
            }
1036

Evan Hunt's avatar
Evan Hunt committed
1037 1038
            Name nsecname(task->qname);
            if ((task->flags & NAME_NOT_FOUND) != 0) {
Evan Hunt's avatar
Evan Hunt committed
1039 1040
                const DataSrc* ds = zoneinfo.getDataSource();
                ds->findPreviousName(task->qname, nsecname, zonename);
1041
            }
1042

1043
            if (q.wantDnssec()) {
Evan Hunt's avatar
Evan Hunt committed
1044
                result = proveNX(q, task, zoneinfo, false);
Evan Hunt's avatar
Evan Hunt committed
1045
                if (result != DataSrc::SUCCESS) {
1046 1047 1048 1049
                    m.setRcode(Rcode::SERVFAIL());
                    return;
                }
            }
1050

1051 1052 1053 1054 1055
            return;
        } else {
            // Should never be reached!
            m.setRcode(Rcode::SERVFAIL());
            return;
1056 1057 1058
        }
    }

1059 1060 1061 1062 1063
    // We're done, so now copy in the additional data:
    // data first, then signatures.  (If we run out of
    // space, signatures in additional section are
    // optional.)
    BOOST_FOREACH(RRsetPtr rrset, additional) {