database.cc 39 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Copyright (C) 2011  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 <string>
16
17
#include <vector>

18
#include <datasrc/database.h>
19
20
#include <datasrc/data_source.h>
#include <datasrc/iterator.h>
21

22
23
#include <exceptions/exceptions.h>
#include <dns/name.h>
24
#include <dns/rrclass.h>
25
#include <dns/rrttl.h>
26
#include <dns/rrset.h>
27
#include <dns/rdata.h>
28
29
#include <dns/rdataclass.h>

30
#include <datasrc/data_source.h>
Jelte Jansen's avatar
Jelte Jansen committed
31
#include <datasrc/logger.h>
32

Jelte Jansen's avatar
Jelte Jansen committed
33
34
#include <boost/foreach.hpp>

35
using namespace isc::dns;
36
using namespace std;
37
using boost::shared_ptr;
38
using namespace isc::dns::rdata;
39

40
41
42
namespace isc {
namespace datasrc {

43
44
DatabaseClient::DatabaseClient(RRClass rrclass,
                               boost::shared_ptr<DatabaseAccessor>
45
                               accessor) :
46
    rrclass_(rrclass), accessor_(accessor)
47
{
48
    if (!accessor_) {
49
        isc_throw(isc::InvalidParameter,
50
                  "No database provided to DatabaseClient");
51
52
53
54
55
    }
}

DataSourceClient::FindResult
DatabaseClient::findZone(const Name& name) const {
56
    std::pair<bool, int> zone(accessor_->getZone(name.toText()));
57
58
59
    // Try exact first
    if (zone.first) {
        return (FindResult(result::SUCCESS,
60
                           ZoneFinderPtr(new Finder(accessor_,
61
                                                    zone.second, name))));
62
    }
Jelte Jansen's avatar
Jelte Jansen committed
63
    // Then super domains
64
65
    // Start from 1, as 0 is covered above
    for (size_t i(1); i < name.getLabelCount(); ++i) {
66
        isc::dns::Name superdomain(name.split(i));
67
        zone = accessor_->getZone(superdomain.toText());
68
69
        if (zone.first) {
            return (FindResult(result::PARTIALMATCH,
70
                               ZoneFinderPtr(new Finder(accessor_,
71
72
                                                        zone.second,
                                                        superdomain))));
73
74
75
76
77
78
        }
    }
    // No, really nothing
    return (FindResult(result::NOTFOUND, ZoneFinderPtr()));
}

79
80
81
DatabaseClient::Finder::Finder(boost::shared_ptr<DatabaseAccessor> accessor,
                               int zone_id, const isc::dns::Name& origin) :
    accessor_(accessor),
82
83
    zone_id_(zone_id),
    origin_(origin)
84
85
{ }

Jelte Jansen's avatar
Jelte Jansen committed
86
namespace {
87
88
89
90
91
92
93
94
95
96
97
// Adds the given Rdata to the given RRset
// If the rrset is an empty pointer, a new one is
// created with the given name, class, type and ttl
// The type is checked if the rrset exists, but the
// name is not.
//
// Then adds the given rdata to the set
//
// Raises a DataSourceError if the type does not
// match, or if the given rdata string does not
// parse correctly for the given type and class
98
//
99
// The DatabaseAccessor is passed to print the
100
101
// database name in the log message if the TTL is
// modified
102
103
104
105
106
void addOrCreate(isc::dns::RRsetPtr& rrset,
                    const isc::dns::Name& name,
                    const isc::dns::RRClass& cls,
                    const isc::dns::RRType& type,
                    const isc::dns::RRTTL& ttl,
107
                    const std::string& rdata_str,
108
                    const DatabaseAccessor& db
109
                )
110
111
112
113
{
    if (!rrset) {
        rrset.reset(new isc::dns::RRset(name, cls, type, ttl));
    } else {
Jelte Jansen's avatar
Jelte Jansen committed
114
115
        // This is a check to make sure find() is not messing things up
        assert(type == rrset->getType());
116
117
118
119
        if (ttl != rrset->getTTL()) {
            if (ttl < rrset->getTTL()) {
                rrset->setTTL(ttl);
            }
Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
120
            logger.warn(DATASRC_DATABASE_FIND_TTL_MISMATCH)
121
                .arg(db.getDBName()).arg(name).arg(cls)
122
                .arg(type).arg(rrset->getTTL());
123
        }
Jelte Jansen's avatar
Jelte Jansen committed
124
    }
125
126
127
128
129
130
131
132
133
134
135
    try {
        rrset->addRdata(isc::dns::rdata::createRdata(type, cls, rdata_str));
    } catch (const isc::dns::rdata::InvalidRdataText& ivrt) {
        // at this point, rrset may have been initialised for no reason,
        // and won't be used. But the caller would drop the shared_ptr
        // on such an error anyway, so we don't care.
        isc_throw(DataSourceError,
                    "bad rdata in database for " << name << " "
                    << type << ": " << ivrt.what());
    }
}
Jelte Jansen's avatar
Jelte Jansen committed
136

137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
// This class keeps a short-lived store of RRSIG records encountered
// during a call to find(). If the backend happens to return signatures
// before the actual data, we might not know which signatures we will need
// So if they may be relevant, we store the in this class.
//
// (If this class seems useful in other places, we might want to move
// it to util. That would also provide an opportunity to add unit tests)
class RRsigStore {
public:
    // Adds the given signature Rdata to the store
    // The signature rdata MUST be of the RRSIG rdata type
    // (the caller must make sure of this).
    // NOTE: if we move this class to a public namespace,
    // we should add a type_covered argument, so as not
    // to have to do this cast here.
    void addSig(isc::dns::rdata::RdataPtr sig_rdata) {
        const isc::dns::RRType& type_covered =
            static_cast<isc::dns::rdata::generic::RRSIG*>(
                sig_rdata.get())->typeCovered();
        sigs[type_covered].push_back(sig_rdata);
    }
Jelte Jansen's avatar
Jelte Jansen committed
158

159
160
161
162
163
164
165
166
167
    // If the store contains signatures for the type of the given
    // rrset, they are appended to it.
    void appendSignatures(isc::dns::RRsetPtr& rrset) const {
        std::map<isc::dns::RRType,
                 std::vector<isc::dns::rdata::RdataPtr> >::const_iterator
            found = sigs.find(rrset->getType());
        if (found != sigs.end()) {
            BOOST_FOREACH(isc::dns::rdata::RdataPtr sig, found->second) {
                rrset->addRRsig(sig);
Jelte Jansen's avatar
Jelte Jansen committed
168
169
            }
        }
170
    }
Jelte Jansen's avatar
Jelte Jansen committed
171

172
173
174
private:
    std::map<isc::dns::RRType, std::vector<isc::dns::rdata::RdataPtr> > sigs;
};
Jelte Jansen's avatar
Jelte Jansen committed
175
176
}

177
DatabaseClient::Finder::FoundRRsets
178
179
DatabaseClient::Finder::getRRsets(const string& name, const WantedTypes& types,
                                  bool check_ns, const string* construct_name)
180
181
182
{
    RRsigStore sig_store;
    bool records_found = false;
183
    std::map<RRType, RRsetPtr> result;
184

185
186
    // Request the context
    DatabaseAccessor::IteratorContextPtr
187
        context(accessor_->getRecords(name, zone_id_));
188
    // It must not return NULL, that's a bug of the implementation
189
    if (!context) {
190
        isc_throw(isc::Unexpected, "Iterator context null at " + name);
191
192
    }

193
    std::string columns[DatabaseAccessor::COLUMN_COUNT];
194
195
196
    if (construct_name == NULL) {
        construct_name = &name;
    }
197

198
199
    const Name construct_name_object(*construct_name);

200
    bool seen_cname(false);
201
    bool seen_ds(false);
202
203
204
    bool seen_other(false);
    bool seen_ns(false);

205
    while (context->getNext(columns)) {
206
207
        // The domain is not empty
        records_found = true;
208
209

        try {
210
211
212
            const RRType cur_type(columns[DatabaseAccessor::TYPE_COLUMN]);

            if (cur_type == RRType::RRSIG()) {
213
214
215
216
217
218
219
                // If we get signatures before we get the actual data, we
                // can't know which ones to keep and which to drop...
                // So we keep a separate store of any signature that may be
                // relevant and add them to the final RRset when we are
                // done.
                // A possible optimization here is to not store them for
                // types we are certain we don't need
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
                sig_store.addSig(rdata::createRdata(cur_type, getClass(),
                     columns[DatabaseAccessor::RDATA_COLUMN]));
            }

            if (types.find(cur_type) != types.end()) {
                // This type is requested, so put it into result
                const RRTTL cur_ttl(columns[DatabaseAccessor::TTL_COLUMN]);
                // Ths sigtype column was an optimization for finding the
                // relevant RRSIG RRs for a lookup. Currently this column is
                // not used in this revised datasource implementation. We
                // should either start using it again, or remove it from use
                // completely (i.e. also remove it from the schema and the
                // backend implementation).
                // Note that because we don't use it now, we also won't notice
                // it if the value is wrong (i.e. if the sigtype column
                // contains an rrtype that is different from the actual value
                // of the 'type covered' field in the RRSIG Rdata).
                //cur_sigtype(columns[SIGTYPE_COLUMN]);
238
239
                addOrCreate(result[cur_type], construct_name_object,
                            getClass(), cur_type, cur_ttl,
240
241
242
243
244
245
246
247
                            columns[DatabaseAccessor::RDATA_COLUMN],
                            *accessor_);
            }

            if (cur_type == RRType::CNAME()) {
                seen_cname = true;
            } else if (cur_type == RRType::NS()) {
                seen_ns = true;
248
249
250
251
252
253
254
255
            } else if (cur_type == RRType::DS()) {
                seen_ds = true;
            } else if (cur_type != RRType::RRSIG() &&
                       cur_type != RRType::NSEC3() &&
                       cur_type != RRType::NSEC()) {
                // NSEC and RRSIG can coexist with anything, otherwise
                // we've seen something that can't live together with potential
                // CNAME or NS
256
257
258
                //
                // NSEC3 lives in separate namespace from everything, therefore
                // we just ignore it here for these checks as well.
259
                seen_other = true;
260
            }
261
        } catch (const InvalidRRType&) {
262
263
264
            isc_throw(DataSourceError, "Invalid RRType in database for " <<
                      name << ": " << columns[DatabaseAccessor::
                      TYPE_COLUMN]);
265
        } catch (const InvalidRRTTL&) {
266
267
268
            isc_throw(DataSourceError, "Invalid TTL in database for " <<
                      name << ": " << columns[DatabaseAccessor::
                      TTL_COLUMN]);
269
        } catch (const rdata::InvalidRdataText&) {
270
271
272
273
274
            isc_throw(DataSourceError, "Invalid rdata in database for " <<
                      name << ": " << columns[DatabaseAccessor::
                      RDATA_COLUMN]);
        }
    }
275
    if (seen_cname && (seen_other || seen_ns || seen_ds)) {
276
277
278
279
280
281
        isc_throw(DataSourceError, "CNAME shares domain " << name <<
                  " with something else");
    }
    if (check_ns && seen_ns && seen_other) {
        isc_throw(DataSourceError, "NS shares domain " << name <<
                  " with something else");
282
    }
283
284
285
286
287
288
289
    // Add signatures to all found RRsets
    for (std::map<RRType, RRsetPtr>::iterator i(result.begin());
         i != result.end(); ++ i) {
        sig_store.appendSignatures(i->second);
    }

    return (FoundRRsets(records_found, result));
290
291
}

292
293
bool
DatabaseClient::Finder::hasSubdomains(const std::string& name) {
294
295
    // Request the context
    DatabaseAccessor::IteratorContextPtr
296
        context(accessor_->getRecords(name, zone_id_, true));
297
298
299
    // It must not return NULL, that's a bug of the implementation
    if (!context) {
        isc_throw(isc::Unexpected, "Iterator context null at " + name);
300
    }
301
302
303

    std::string columns[DatabaseAccessor::COLUMN_COUNT];
    return (context->getNext(columns));
304
}
Jelte Jansen's avatar
Jelte Jansen committed
305

306
307
308
// Some manipulation with RRType sets
namespace {

309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// Bunch of functions to construct specific sets of RRTypes we will
// ask from it.
typedef std::set<RRType> WantedTypes;

const WantedTypes&
NSEC_TYPES() {
    static bool initialized(false);
    static WantedTypes result;

    if (!initialized) {
        result.insert(RRType::NSEC());
        initialized = true;
    }
    return (result);
}

const WantedTypes&
DELEGATION_TYPES() {
    static bool initialized(false);
    static WantedTypes result;

    if (!initialized) {
        result.insert(RRType::DNAME());
        result.insert(RRType::NS());
        initialized = true;
    }
    return (result);
}

const WantedTypes&
FINAL_TYPES() {
    static bool initialized(false);
    static WantedTypes result;

    if (!initialized) {
        result.insert(RRType::CNAME());
        result.insert(RRType::NS());
        result.insert(RRType::NSEC());
        initialized = true;
    }
    return (result);
350
351
352
353
}

}

354
355
356
357
358
359
RRsetPtr
DatabaseClient::Finder::findNSECCover(const Name& name) {
    try {
        // Which one should contain the NSEC record?
        const Name coverName(findPreviousName(name));
        // Get the record and copy it out
JINMEI Tatuya's avatar
JINMEI Tatuya committed
360
361
        const FoundRRsets found = getRRsets(coverName.toText(), NSEC_TYPES(),
                                            coverName != getOrigin());
362
363
364
365
366
367
368
        const FoundIterator
            nci(found.second.find(RRType::NSEC()));
        if (nci != found.second.end()) {
            return (nci->second);
        } else {
            // The previous doesn't contain NSEC.
            // Badly signed zone or a bug?
369
370
371
372
373
374

            // FIXME: Currently, if the zone is not signed, we could get
            // here. In that case we can't really throw, but for now, we can't
            // recognize it. So we don't throw at all, enable it once
            // we have a is_signed flag or something.
#if 0
375
376
377
378
            isc_throw(DataSourceError, "No NSEC in " +
                      coverName.toText() + ", but it was "
                      "returned as previous - "
                      "accessor error? Badly signed zone?");
379
#endif
380
381
382
383
384
385
386
387
388
389
390
391
        }
    }
    catch (const isc::NotImplemented&) {
        // Well, they want DNSSEC, but there is no available.
        // So we don't provide anything.
        LOG_INFO(logger, DATASRC_DATABASE_COVER_NSEC_UNSUPPORTED).
            arg(accessor_->getDBName()).arg(name);
    }
    // We didn't find it, return nothing
    return (RRsetPtr());
}

392
ZoneFinder::FindResult
393
394
DatabaseClient::Finder::find(const isc::dns::Name& name,
                             const isc::dns::RRType& type,
395
                             isc::dns::RRsetList*,
396
                             const FindOptions options)
397
{
Jelte Jansen's avatar
Jelte Jansen committed
398
399
    // This variable is used to determine the difference between
    // NXDOMAIN and NXRRSET
400
    bool records_found = false;
401
402
    bool glue_ok((options & FIND_GLUE_OK) != 0);
    const bool dnssec_data((options & FIND_DNSSEC) != 0);
403
    bool get_cover(false);
404
    isc::dns::RRsetPtr result_rrset;
Jelte Jansen's avatar
Jelte Jansen committed
405
    ZoneFinder::Result result_status = SUCCESS;
406
    FoundRRsets found;
407
    logger.debug(DBG_TRACE_DETAILED, DATASRC_DATABASE_FIND_RECORDS)
408
        .arg(accessor_->getDBName()).arg(name).arg(type);
409
410
411
    // In case we are in GLUE_OK mode and start matching wildcards,
    // we can't do it under NS, so we store it here to check
    isc::dns::RRsetPtr first_ns;
412

413
    // First, do we have any kind of delegation (NS/DNAME) here?
JINMEI Tatuya's avatar
JINMEI Tatuya committed
414
415
    const Name origin(getOrigin());
    const size_t origin_label_count(origin.getLabelCount());
416
417
    // Number of labels in the last known non-empty domain
    size_t last_known(origin_label_count);
JINMEI Tatuya's avatar
JINMEI Tatuya committed
418
    const size_t current_label_count(name.getLabelCount());
419
    // This is how many labels we remove to get origin
420
    const size_t remove_labels(current_label_count - origin_label_count);
Jelte Jansen's avatar
Jelte Jansen committed
421

422
423
    // Now go trough all superdomains from origin down
    for (int i(remove_labels); i > 0; --i) {
424
        Name superdomain(name.split(i));
425
        // Look if there's NS or DNAME (but ignore the NS in origin)
426
        found = getRRsets(superdomain.toText(), DELEGATION_TYPES(),
427
                          i != remove_labels);
428
429
430
        if (found.first) {
            // It contains some RRs, so it exists.
            last_known = superdomain.getLabelCount();
431
432
433
434
435
436
437
438
439
440
441
442

            const FoundIterator nsi(found.second.find(RRType::NS()));
            const FoundIterator dni(found.second.find(RRType::DNAME()));
            // In case we are in GLUE_OK mode, we want to store the
            // highest encountered NS (but not apex)
            if (glue_ok && !first_ns && i != remove_labels &&
                nsi != found.second.end()) {
                first_ns = nsi->second;
            } else if (!glue_ok && i != remove_labels &&
                       nsi != found.second.end()) {
                // Do a NS delegation, but ignore NS in glue_ok mode. Ignore
                // delegation in apex
443
                LOG_DEBUG(logger, DBG_TRACE_DETAILED,
444
                          DATASRC_DATABASE_FOUND_DELEGATION).
445
                    arg(accessor_->getDBName()).arg(superdomain);
446
                result_rrset = nsi->second;
447
                result_status = DELEGATION;
448
449
450
451
                // No need to go lower, found
                break;
            } else if (dni != found.second.end()) {
                // Very similar with DNAME
452
                LOG_DEBUG(logger, DBG_TRACE_DETAILED,
453
                          DATASRC_DATABASE_FOUND_DNAME).
454
                    arg(accessor_->getDBName()).arg(superdomain);
455
                result_rrset = dni->second;
456
                result_status = DNAME;
457
458
459
460
461
462
                if (result_rrset->getRdataCount() != 1) {
                    isc_throw(DataSourceError, "DNAME at " << superdomain <<
                              " has " << result_rrset->getRdataCount() <<
                              " rdata, 1 expected");
                }
                break;
463
            }
464
465
466
467
468
469
470
        }
    }

    if (!result_rrset) { // Only if we didn't find a redirect already
        // Try getting the final result and extract it
        // It is special if there's a CNAME or NS, DNAME is ignored here
        // And we don't consider the NS in origin
471

472
473
474
        WantedTypes final_types(FINAL_TYPES());
        final_types.insert(type);
        found = getRRsets(name.toText(), final_types, name != origin);
475
        records_found = found.first;
476
477
478
479
480
481
482

        // NS records, CNAME record and Wanted Type records
        const FoundIterator nsi(found.second.find(RRType::NS()));
        const FoundIterator cni(found.second.find(RRType::CNAME()));
        const FoundIterator wti(found.second.find(type));
        if (name != origin && !glue_ok && nsi != found.second.end()) {
            // There's a delegation at the exact node.
483
            LOG_DEBUG(logger, DBG_TRACE_DETAILED,
484
                      DATASRC_DATABASE_FOUND_DELEGATION_EXACT).
485
                arg(accessor_->getDBName()).arg(name);
486
            result_status = DELEGATION;
487
488
489
490
            result_rrset = nsi->second;
        } else if (type != isc::dns::RRType::CNAME() &&
                   cni != found.second.end()) {
            // A CNAME here
491
            result_status = CNAME;
492
493
494
495
496
497
498
499
500
501
            result_rrset = cni->second;
            if (result_rrset->getRdataCount() != 1) {
                isc_throw(DataSourceError, "CNAME with " <<
                          result_rrset->getRdataCount() <<
                          " rdata at " << name << ", expected 1");
            }
        } else if (wti != found.second.end()) {
            // Just get the answer
            result_rrset = wti->second;
        } else if (!records_found) {
502
503
            // Nothing lives here.
            // But check if something lives below this
504
            // domain and if so, pretend something is here as well.
505
            if (hasSubdomains(name.toText())) {
506
507
                LOG_DEBUG(logger, DBG_TRACE_DETAILED,
                          DATASRC_DATABASE_FOUND_EMPTY_NONTERMINAL).
508
                    arg(accessor_->getDBName()).arg(name);
509
                records_found = true;
510
                get_cover = dnssec_data;
511
            } else if ((options & NO_WILDCARD) != 0) {
512
513
514
                // If wildcard check is disabled, the search will ultimately
                // terminate with NXDOMAIN. If DNSSEC is enabled, flag that
                // we need to get the NSEC records to prove this.
515
                if (dnssec_data) {
516
517
                    get_cover = true;
                }
518
519
520
521
            } else {
                // It's not empty non-terminal. So check for wildcards.
                // We remove labels one by one and look for the wildcard there.
                // Go up to first non-empty domain.
522
                for (size_t i(1); i <= current_label_count - last_known; ++i) {
523
                    // Construct the name with *
JINMEI Tatuya's avatar
JINMEI Tatuya committed
524
                    const Name superdomain(name.split(i));
525
526
                    const string wildcard("*." + superdomain.toText());
                    const string construct_name(name.toText());
527
                    // TODO What do we do about DNAME here?
528
529
                    // The types are the same as with original query
                    found = getRRsets(wildcard, final_types, true,
530
                                      &construct_name);
531
                    if (found.first) {
532
533
534
535
536
537
538
539
                        if (first_ns) {
                            // In case we are under NS, we don't
                            // wildcard-match, but return delegation
                            result_rrset = first_ns;
                            result_status = DELEGATION;
                            records_found = true;
                            // We pretend to switch to non-glue_ok mode
                            glue_ok = false;
540
541
                            LOG_DEBUG(logger, DBG_TRACE_DETAILED,
                                      DATASRC_DATABASE_WILDCARD_CANCEL_NS).
542
                                arg(accessor_->getDBName()).arg(wildcard).
543
                                arg(first_ns->getName());
544
545
546
547
548
549
                        } else if (!hasSubdomains(name.split(i - 1).toText()))
                        {
                            // Nothing we added as part of the * can exist
                            // directly, as we go up only to first existing
                            // domain, but it could be empty non-terminal. In
                            // that case, we need to cancel the match.
550
                            records_found = true;
551
552
553
554
                            const FoundIterator
                                cni(found.second.find(RRType::CNAME()));
                            const FoundIterator
                                nsi(found.second.find(RRType::NS()));
555
556
                            const FoundIterator
                                nci(found.second.find(RRType::NSEC()));
557
558
559
560
                            const FoundIterator wti(found.second.find(type));
                            if (cni != found.second.end() &&
                                type != RRType::CNAME()) {
                                result_rrset = cni->second;
561
                                result_status = WILDCARD_CNAME;
562
563
564
565
566
                            } else if (nsi != found.second.end()) {
                                result_rrset = nsi->second;
                                result_status = DELEGATION;
                            } else if (wti != found.second.end()) {
                                result_rrset = wti->second;
567
568
569
570
571
572
573
574
575
576
577
578
                                result_status = WILDCARD;
                            } else {
                                // NXRRSET case in the wildcard
                                result_status = WILDCARD_NXRRSET;
                                if (dnssec_data &&
                                    nci != found.second.end()) {
                                    // User wants a proof the wildcard doesn't
                                    // contain it
                                    //
                                    // However, we need to get the RRset in the
                                    // name of the wildcard, not the constructed
                                    // one, so we walk it again
579
                                    found = getRRsets(wildcard, NSEC_TYPES(),
580
                                                      true);
581
582
583
584
                                    result_rrset =
                                        found.second.find(RRType::NSEC())->
                                        second;
                                }
585
586
                            }

587
588
                            LOG_DEBUG(logger, DBG_TRACE_DETAILED,
                                      DATASRC_DATABASE_WILDCARD).
589
                                arg(accessor_->getDBName()).arg(wildcard).
590
591
592
593
                                arg(name);
                        } else {
                            LOG_DEBUG(logger, DBG_TRACE_DETAILED,
                                      DATASRC_DATABASE_WILDCARD_CANCEL_SUB).
594
                                arg(accessor_->getDBName()).arg(wildcard).
595
                                arg(name).arg(superdomain);
596
                        }
597
                        break;
598
                    } else if (hasSubdomains(wildcard)) {
599
600
                        // Empty non-terminal asterisk
                        records_found = true;
601
602
                        LOG_DEBUG(logger, DBG_TRACE_DETAILED,
                                  DATASRC_DATABASE_WILDCARD_EMPTY).
603
                            arg(accessor_->getDBName()).arg(wildcard).
604
                            arg(name);
605
                        if (dnssec_data) {
606
607
                            result_rrset = findNSECCover(Name(wildcard));
                            if (result_rrset) {
608
609
610
                                result_status = WILDCARD_NXRRSET;
                            }
                        }
611
                        break;
612
613
                    }
                }
614
                // This is the NXDOMAIN case (nothing found anywhere). If
615
                // they want DNSSEC data, try getting the NSEC record
616
                if (dnssec_data && !records_found) {
617
                    get_cover = true;
618
                }
619
            }
620
621
622
623
624
625
626
627
628
        } else if (dnssec_data) {
            // This is the "usual" NXRRSET case
            // So in case they want DNSSEC, provide the NSEC
            // (which should be available already here)
            result_status = NXRRSET;
            const FoundIterator nci(found.second.find(RRType::NSEC()));
            if (nci != found.second.end()) {
                result_rrset = nci->second;
            }
629
        }
630
631
    }

Jelte Jansen's avatar
Jelte Jansen committed
632
    if (!result_rrset) {
633
        if (result_status == SUCCESS) {
634
635
            // Should we look for NSEC covering the name?
            if (get_cover) {
636
637
638
                result_rrset = findNSECCover(name);
                if (result_rrset) {
                    result_status = NXDOMAIN;
639
640
                }
            }
641
642
643
644
645
646
647
648
649
650
651
652
653
654
            // Something is not here and we didn't decide yet what
            if (records_found) {
                logger.debug(DBG_TRACE_DETAILED,
                             DATASRC_DATABASE_FOUND_NXRRSET)
                    .arg(accessor_->getDBName()).arg(name)
                    .arg(getClass()).arg(type);
                result_status = NXRRSET;
            } else {
                logger.debug(DBG_TRACE_DETAILED,
                             DATASRC_DATABASE_FOUND_NXDOMAIN)
                    .arg(accessor_->getDBName()).arg(name)
                    .arg(getClass()).arg(type);
                result_status = NXDOMAIN;
            }
Jelte Jansen's avatar
Jelte Jansen committed
655
        }
656
    } else {
Jelte Jansen's avatar
Jelte Jansen committed
657
        logger.debug(DBG_TRACE_DETAILED,
658
                     DATASRC_DATABASE_FOUND_RRSET)
659
                    .arg(accessor_->getDBName()).arg(*result_rrset);
660
    }
Jelte Jansen's avatar
Jelte Jansen committed
661
    return (FindResult(result_status, result_rrset));
662
663
}

664
Name
665
DatabaseClient::Finder::findPreviousName(const Name& name) const {
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
    const string str(accessor_->findPreviousName(zone_id_,
                                                 name.reverse().toText()));
    try {
        return (Name(str));
    }
    /*
     * To avoid having the same code many times, we just catch all the
     * exceptions and handle them in a common code below
     */
    catch (const isc::dns::EmptyLabel&) {}
    catch (const isc::dns::TooLongLabel&) {}
    catch (const isc::dns::BadLabelType&) {}
    catch (const isc::dns::BadEscape&) {}
    catch (const isc::dns::TooLongName&) {}
    catch (const isc::dns::IncompleteName&) {}
    isc_throw(DataSourceError, "Bad name " + str + " from findPreviousName");
682
683
}

684
685
Name
DatabaseClient::Finder::getOrigin() const {
686
    return (origin_);
687
688
689
690
691
692
693
694
}

isc::dns::RRClass
DatabaseClient::Finder::getClass() const {
    // TODO Implement
    return isc::dns::RRClass::IN();
}

695
696
697
698
699
700
701
702
703
704
namespace {

/*
 * This needs, beside of converting all data from textual representation, group
 * together rdata of the same RRsets. To do this, we hold one row of data ahead
 * of iteration. When we get a request to provide data, we create it from this
 * data and load a new one. If it is to be put to the same rrset, we add it.
 * Otherwise we just return what we have and keep the row as the one ahead
 * for next time.
 */
705
class DatabaseIterator : public ZoneIterator {
706
public:
707
    DatabaseIterator(shared_ptr<DatabaseAccessor> accessor,
708
                     const Name& zone_name,
709
                     const RRClass& rrclass) :
710
        accessor_(accessor),
711
712
713
        class_(rrclass),
        ready_(true)
    {
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
        // Get the zone
        const pair<bool, int> zone(accessor_->getZone(zone_name.toText()));
        if (!zone.first) {
            // No such zone, can't continue
            isc_throw(DataSourceError, "Zone " + zone_name.toText() +
                      " can not be iterated, because it doesn't exist "
                      "in this data source");
        }

        // Start a separate transaction.
        accessor_->startTransaction();

        // Find the SOA of the zone (may or may not succeed).  Note that
        // this must be done before starting the iteration context.
        soa_ = DatabaseClient::Finder(accessor_, zone.second, zone_name).
            find(zone_name, RRType::SOA(), NULL).rrset;

        // Request the context
        context_ = accessor_->getAllRecords(zone.second);
        // It must not return NULL, that's a bug of the implementation
        if (!context_) {
            isc_throw(isc::Unexpected, "Iterator context null at " +
                      zone_name.toText());
        }

739
740
741
        // Prepare data for the next time
        getData();
    }
Jelte Jansen's avatar
Jelte Jansen committed
742

743
744
745
746
747
748
    virtual ~DatabaseIterator() {
        if (ready_) {
            accessor_->commit();
        }
    }

749
750
751
752
    virtual ConstRRsetPtr getSOA() const {
        return (soa_);
    }

753
754
755
756
757
758
    virtual isc::dns::ConstRRsetPtr getNextRRset() {
        if (!ready_) {
            isc_throw(isc::Unexpected, "Iterating past the zone end");
        }
        if (!data_ready_) {
            // At the end of zone
759
            accessor_->commit();
760
            ready_ = false;
761
762
            LOG_DEBUG(logger, DBG_TRACE_DETAILED,
                      DATASRC_DATABASE_ITERATE_END);
763
764
            return (ConstRRsetPtr());
        }
765
766
767
        const string name_str(name_), rtype_str(rtype_), ttl(ttl_);
        const Name name(name_str);
        const RRType rtype(rtype_str);
768
        RRsetPtr rrset(new RRset(name, class_, rtype, RRTTL(ttl)));
Jelte Jansen's avatar
Jelte Jansen committed
769
        while (data_ready_ && name_ == name_str && rtype_str == rtype_) {
770
            if (ttl_ != ttl) {
771
772
773
774
                if (ttl < ttl_) {
                    ttl_ = ttl;
                    rrset->setTTL(RRTTL(ttl));
                }
775
776
                LOG_WARN(logger, DATASRC_DATABASE_ITERATE_TTL_MISMATCH).
                    arg(name_).arg(class_).arg(rtype_).arg(rrset->getTTL());
777
778
779
780
            }
            rrset->addRdata(rdata::createRdata(rtype, class_, rdata_));
            getData();
        }
781
782
        LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ITERATE_NEXT).
            arg(rrset->getName()).arg(rrset->getType());
783
784
        return (rrset);
    }
785

786
787
788
private:
    // Load next row of data
    void getData() {
789
        string data[DatabaseAccessor::COLUMN_COUNT];
790
        data_ready_ = context_->getNext(data);
791
792
793
794
        name_ = data[DatabaseAccessor::NAME_COLUMN];
        rtype_ = data[DatabaseAccessor::TYPE_COLUMN];
        ttl_ = data[DatabaseAccessor::TTL_COLUMN];
        rdata_ = data[DatabaseAccessor::RDATA_COLUMN];
795
    }
Jelte Jansen's avatar
Jelte Jansen committed
796

797
798
    // The dedicated accessor
    shared_ptr<DatabaseAccessor> accessor_;
799
    // The context
800
    DatabaseAccessor::IteratorContextPtr context_;
801
    // Class of the zone
802
    const RRClass class_;
803
804
    // SOA of the zone, if any (it should normally exist)
    ConstRRsetPtr soa_;
805
806
807
    // Status
    bool ready_, data_ready_;
    // Data of the next row
808
    string name_, rtype_, rdata_, ttl_;
809
810
811
812
813
814
};

}

ZoneIteratorPtr
DatabaseClient::getIterator(const isc::dns::Name& name) const {
815
816
    ZoneIteratorPtr iterator = ZoneIteratorPtr(new DatabaseIterator(
                                                   accessor_->clone(), name,
817
                                                   rrclass_));
818
819
    LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ITERATE).
        arg(name);
820
821

    return (iterator);
822
823
}

824
825
826
827
828
829
830
831
832
833
//
// Zone updater using some database system as the underlying data source.
//
class DatabaseUpdater : public ZoneUpdater {
public:
    DatabaseUpdater(shared_ptr<DatabaseAccessor> accessor, int zone_id,
            const Name& zone_name, const RRClass& zone_class) :
        committed_(false), accessor_(accessor), zone_id_(zone_id),
        db_name_(accessor->getDBName()), zone_name_(zone_name.toText()),
        zone_class_(zone_class),
834
        finder_(new DatabaseClient::Finder(accessor_, zone_id_, zone_name))
835
836
837
    {
        logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_CREATED)
            .arg(zone_name_).arg(zone_class_).arg(db_name_);
838
839
    }

840
841
    virtual ~DatabaseUpdater() {
        if (!committed_) {
842
            try {
843
                accessor_->rollback();
844
845
846
847
848
                logger.info(DATASRC_DATABASE_UPDATER_ROLLBACK)
                    .arg(zone_name_).arg(zone_class_).arg(db_name_);
            } catch (const DataSourceError& e) {
                // We generally expect that rollback always succeeds, and
                // it should in fact succeed in a way we execute it.  But
849
                // as the public API allows rollback() to fail and
850
851
852
853
854
855
                // throw, we should expect it.  Obviously we cannot re-throw
                // it.  The best we can do is to log it as a critical error.
                logger.error(DATASRC_DATABASE_UPDATER_ROLLBACKFAIL)
                    .arg(zone_name_).arg(zone_class_).arg(db_name_)
                    .arg(e.what());
            }
856
        }
857

858
        logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_DESTROYED)
859
            .arg(zone_name_).arg(zone_class_).arg(db_name_);
860
861
    }

862
    virtual ZoneFinder& getFinder() { return (*finder_); }
863

864
865
866
867
868
869
870
871
872
873
874
    virtual void addRRset(const RRset& rrset);
    virtual void deleteRRset(const RRset& rrset);
    virtual void commit();

private:
    bool committed_;
    shared_ptr<DatabaseAccessor> accessor_;
    const int zone_id_;
    const string db_name_;
    const string zone_name_;
    const RRClass zone_class_;
875
    boost::scoped_ptr<DatabaseClient::Finder> finder_;
876
};
877

878
void
879
DatabaseUpdater::addRRset(const RRset& rrset) {
880
881
882
883
884
885
886
887
888
    if (committed_) {
        isc_throw(DataSourceError, "Add attempt after commit to zone: "
                  << zone_name_ << "/" << zone_class_);
    }
    if (rrset.getClass() != zone_class_) {
        isc_throw(DataSourceError, "An RRset of a different class is being "
                  << "added to " << zone_name_ << "/" << zone_class_ << ": "
                  << rrset.toText());
    }
889
890
891
892
893
    if (rrset.getRRsig()) {
        isc_throw(DataSourceError, "An RRset with RRSIG is being added to "
                  << zone_name_ << "/" << zone_class_ << ": "
                  << rrset.toText());
    }
894
895
896
897
898
899
900
901

    RdataIteratorPtr it = rrset.getRdataIterator();
    if (it->isLast()) {
        isc_throw(DataSourceError, "An empty RRset is being added for "
                  << rrset.getName() << "/" << zone_class_ << "/"
                  << rrset.getType());
    }

902
903
904
    string columns[DatabaseAccessor::ADD_COLUMN_COUNT]; // initialized with ""
    columns[DatabaseAccessor::ADD_NAME] = rrset.getName().toText();
    columns[DatabaseAccessor::ADD_REV_NAME] =
905
        rrset.getName().reverse().toText();
906
907
    columns[DatabaseAccessor::ADD_TTL] = rrset.getTTL().toText();
    columns[DatabaseAccessor::ADD_TYPE] = rrset.getType().toText();
908
909
910
911
912
913
914
915
916
    for (; !it->isLast(); it->next()) {
        if (rrset.getType() == RRType::RRSIG()) {
            // XXX: the current interface (based on the current sqlite3
            // data source schema) requires a separate "sigtype" column,
            // even though it won't be used in a newer implementation.
            // We should eventually clean up the schema design and simplify
            // the interface, but until then we have to conform to the schema.
            const generic::RRSIG& rrsig_rdata =
                dynamic_cast<const generic::RRSIG&>(it->getCurrent());
917
            columns[DatabaseAccessor::ADD_SIGTYPE] =
918
919
                rrsig_rdata.typeCovered().toText();
        }
920
921
        columns[DatabaseAccessor::ADD_RDATA] = it->getCurrent().toText();
        accessor_->addRecordToZone(columns);
922
923
924
    }
}

925
void
926
DatabaseUpdater::deleteRRset(const RRset& rrset) {
927
928
929
930
931
932
933
934
935
    if (committed_) {
        isc_throw(DataSourceError, "Delete attempt after commit on zone: "
                  << zone_name_ << "/" << zone_class_);
    }
    if (rrset.getClass() != zone_class_) {
        isc_throw(DataSourceError, "An RRset of a different class is being "
                  << "deleted from " << zone_name_ << "/" << zone_class_
                  << ": " << rrset.toText());
    }
936
937
938
939
940
    if (rrset.getRRsig()) {
        isc_throw(DataSourceError, "An RRset with RRSIG is being deleted from "
                  << zone_name_ << "/" << zone_class_ << ": "
                  << rrset.toText());
    }
941
942
943
944
945
946
947
948

    RdataIteratorPtr it = rrset.getRdataIterator();
    if (it->isLast()) {
        isc_throw(DataSourceError, "An empty RRset is being deleted for "
                  << rrset.getName() << "/" << zone_class_ << "/"
                  << rrset.getType());
    }

949
950
951
    string params[DatabaseAccessor::DEL_PARAM_COUNT]; // initialized with ""
    params[DatabaseAccessor::DEL_NAME] = rrset.getName().toText();
    params[DatabaseAccessor::DEL_TYPE] = rrset.getType().toText();
952
    for (; !it->isLast(); it->next()) {
953
954
        params[DatabaseAccessor::DEL_RDATA] = it->getCurrent().toText();
        accessor_->deleteRecordInZone(params);
955
956
957
    }
}

958
void
959
DatabaseUpdater::commit() {
960
961
    if (committed_) {
        isc_throw(DataSourceError, "Duplicate commit attempt for "
962
                  << zone_name_ << "/" << zone_class_ << " on "
963
964
                  << db_name_);
    }
965
    accessor_->commit();
966
    committed_ = true; // make sure the destructor won't trigger rollback
967
968
969
970
971
972

    // We release the accessor immediately after commit is completed so that
    // we don't hold the possible internal resource any longer.
    accessor_.reset();

    logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_COMMIT)
973
        .arg(zone_name_).arg(zone_class_).arg(db_name_);
974
}
975
976
977

// The updater factory
ZoneUpdaterPtr
978
979
980
981
DatabaseClient::getUpdater(const isc::dns::Name& name, bool replace,
                           bool) const
{
    // TODO: Handle journaling (pass it to the updater)
982
983
984
985
986
987
988
    shared_ptr<DatabaseAccessor> update_accessor(accessor_->clone());
    const std::pair<bool, int> zone(update_accessor->startUpdateZone(
                                        name.toText(), replace));
    if (!zone.first) {
        return (ZoneUpdaterPtr());
    }

Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
989
990
    return (ZoneUpdaterPtr(new DatabaseUpdater(update_accessor, zone.second,
                                               name, rrclass_)));
991
}
992
993
}
}