master_loader.cc 24.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (C) 2012  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.

#include <dns/master_loader.h>
16 17
#include <dns/master_lexer.h>
#include <dns/name.h>
18
#include <dns/rdataclass.h>
19 20 21
#include <dns/rrttl.h>
#include <dns/rrclass.h>
#include <dns/rrtype.h>
Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
22
#include <dns/rdata.h>
23

24 25
#include <boost/scoped_ptr.hpp>

26
#include <string>
27
#include <memory>
28
#include <vector>
29
#include <boost/algorithm/string/predicate.hpp> // for iequals
30
#include <boost/shared_ptr.hpp>
31

32
using std::string;
33
using std::auto_ptr;
34 35
using std::vector;
using std::pair;
36
using boost::algorithm::iequals;
37
using boost::shared_ptr;
38 39 40 41

namespace isc {
namespace dns {

42 43
namespace {

44 45 46 47 48 49 50 51 52 53
// An internal exception, used to control the code flow in case of errors.
// It is thrown during the loading and caught later, not to be propagated
// outside of the file.
class InternalException : public isc::Exception {
public:
    InternalException(const char* filename, size_t line, const char* what) :
        Exception(filename, line, what)
    {}
};

Jelte Jansen's avatar
Jelte Jansen committed
54
} // end unnamed namespace
55

56 57 58 59
class MasterLoader::MasterLoaderImpl {
public:
    MasterLoaderImpl(const char* master_file,
                     const Name& zone_origin,
60 61
                     const RRClass& zone_class,
                     const MasterLoaderCallbacks& callbacks,
62
                     const AddRRCallback& add_callback,
63
                     MasterLoader::Options options) :
64
        MAX_TTL(0x7fffffff),
65 66
        lexer_(),
        zone_origin_(zone_origin),
67
        active_origin_(zone_origin),
68 69
        zone_class_(zone_class),
        callbacks_(callbacks),
70
        add_callback_(add_callback),
71 72 73
        options_(options),
        master_file_(master_file),
        initialized_(false),
74
        ok_(true),
75
        many_errors_((options & MANY_ERRORS) != 0),
76
        previous_name_(false),
77
        complete_(false),
78 79
        seen_error_(false),
        warn_rfc1035_ttl_(true)
80 81 82 83 84
    {}

    void pushSource(const std::string& filename) {
        std::string error;
        if (!lexer_.pushSource(filename.c_str(), &error)) {
85
            if (initialized_) {
86
                isc_throw(InternalException, error.c_str());
87 88 89 90 91
            } else {
                // Top-level file
                reportError("", 0, error);
                ok_ = false;
            }
92
        }
93 94
        // Store the current status, so we can recover it upon popSource
        include_info_.push_back(IncludeInfo(active_origin_, last_name_));
95
        initialized_ = true;
96
        previous_name_ = false;
97 98
    }

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    void pushStreamSource(std::istream& stream) {
        lexer_.pushSource(stream);
        initialized_ = true;
    }

    bool loadIncremental(size_t count_limit);

private:
    void reportError(const std::string& filename, size_t line,
                     const std::string& reason)
    {
        seen_error_ = true;
        callbacks_.error(filename, line, reason);
        if (!many_errors_) {
            // In case we don't have the lenient mode, every error is fatal
            // and we throw
            ok_ = false;
            complete_ = true;
            isc_throw(MasterLoaderError, reason.c_str());
        }
    }

121
    bool popSource() {
122
        if (lexer_.getSourceCount() == 1) {
123 124
            return (false);
        }
125
        lexer_.popSource();
126 127 128 129 130 131 132 133 134
        // Restore original origin and last seen name

        // We move in tandem, there's an extra item included during the
        // initialization, so we can never run out of them
        assert(!include_info_.empty());
        const IncludeInfo& info(include_info_.back());
        active_origin_ = info.first;
        last_name_ = info.second;
        include_info_.pop_back();
135
        previous_name_ = false;
136
        return (true);
137 138
    }

139 140
    // Get a string token. Handle it as error if it is not string.
    const string getString() {
141
        lexer_.getNextToken(MasterToken::STRING).getString(string_token_);
142
        return (string_token_);
143 144
    }

145 146
    MasterToken handleInitialToken();

147 148 149 150 151
    void doOrigin(bool is_optional) {
        // Parse and create the new origin. It is relative to the previous
        // one.
        const MasterToken&
            name_tok(lexer_.getNextToken(MasterToken::QSTRING, is_optional));
152 153 154

        if (name_tok.getType() == MasterToken::QSTRING ||
            name_tok.getType() == MasterToken::STRING) {
155

156 157 158 159
            const MasterToken::StringRegion&
                name_string(name_tok.getStringRegion());
            active_origin_ = Name(name_string.beg, name_string.len,
                                  &active_origin_);
160 161 162 163 164 165 166
            if (name_string.len > 0 &&
                name_string.beg[name_string.len - 1] != '.') {
                callbacks_.warning(lexer_.getSourceName(),
                                   lexer_.getSourceLine(),
                                   "The new origin is relative, did you really"
                                   " mean " + active_origin_.toText() + "?");
            }
167
        } else {
168 169 170 171 172 173 174
            // If it is not optional, we must not get anything but
            // a string token.
            assert(is_optional);

            // We return the newline there. This is because we want to
            // behave the same if there is or isn't the name, leaving the
            // newline there.
175 176
            lexer_.ungetToken();
        }
177 178
    }

179 180 181 182 183 184 185 186 187
    void doInclude() {
        // First, get the filename to include
        const string
            filename(lexer_.getNextToken(MasterToken::QSTRING).getString());

        // There optionally can be an origin, that applies before the include.
        doOrigin(true);

        pushSource(filename);
188 189
    }

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    // Upper limit check when recognizing a specific TTL value from the
    // zone file ($TTL, the RR's TTL field, or the SOA minimum).  RFC2181
    // Section 8 limits the range of TTL values to unsigned 32-bit integers,
    // and prohibits transmitting a TTL field exceeding this range.  We
    // guarantee that by limiting the value at the time of zone
    // parsing/loading, following what BIND 9 does.  Resetting it to 0
    // at this point may not be exactly what the RFC states, but the end
    // result would be the same.  Again, we follow the BIND 9's behavior here.
    //
    // post_parsing is true iff this method is called after parsing the entire
    // RR and the lexer is positioned at the next line.  It's just for
    // calculating the accurate source line when callback is necessary.
    void limitTTL(RRTTL& ttl, bool post_parsing) {
        if (ttl > MAX_TTL) {
            const size_t src_line = lexer_.getSourceLine() -
                (post_parsing ? 1 : 0);
            callbacks_.warning(lexer_.getSourceName(), src_line,
                               "TTL " + ttl.toText() + " > MAXTTL, "
                               "setting to 0 per RFC2181");
            ttl = RRTTL(0);
        }
    }

213
    // Set/reset the default TTL.  Either from $TTL or SOA minimum TTL.
214 215
    // see LimitTTL() for parameter post_parsing.
    void setDefaultTTL(const RRTTL& ttl, bool post_parsing) {
216
        if (!default_ttl_) {
217
            default_ttl_.reset(new RRTTL(ttl));
218
        } else {
219
            *default_ttl_ = ttl;
220
        }
221
        limitTTL(*default_ttl_, post_parsing);
222 223
    }

224 225
    // Set/reset the TTL currently being used.  This can be used the last
    // resort TTL when no other TTL is known for an RR.
226 227 228 229 230 231 232 233
    void setCurrentTTL(const RRTTL& ttl) {
        if (!current_ttl_) {
            current_ttl_.reset(new RRTTL(ttl));
        } else {
            *current_ttl_ = ttl;
        }
    }

234
    // Try to set/reset the current TTL from candidate TTL text.  It's possible
235 236 237
    // it does not actually represent a TTL (which is not immediately
    // considered an error).  Return true iff it's recognized as a valid TTL
    // (and only in which case the current TTL is set).
238
    bool setCurrentTTL(const string& ttl_txt) {
239 240 241 242 243 244 245 246
        // We use the factory version instead of RRTTL constructor as we
        // need to expect cases where ttl_txt does not actually represent a TTL
        // but an RR class or type.
        RRTTL* ttl = RRTTL::createFromText(ttl_txt, current_ttl_.get());
        if (ttl != NULL) {
            if (!current_ttl_) {
                current_ttl_.reset(ttl);
            }
247
            limitTTL(*current_ttl_, false);
248 249
            return (true);
        }
250
        return (false);
251 252
    }

253 254 255 256 257 258 259 260 261 262
    // Determine the TTL of the current RR based on the given parsing context.
    //
    // explicit_ttl is true iff the TTL is explicitly specified for that RR
    // (in which case current_ttl_ is set to that TTL).
    // rrtype is the type of the current RR, and rdata is its RDATA.  They
    // only matter if the type is SOA and no available TTL is known.  In this
    // case the minimum TTL of the SOA will be used as the TTL of that SOA
    // and the default TTL for subsequent RRs.
    const RRTTL& getCurrentTTL(bool explicit_ttl, const RRType& rrtype,
                               const rdata::ConstRdataPtr& rdata) {
263 264 265 266 267
        // We've completed parsing the full of RR, and the lexer is already
        // positioned at the next line.  If we need to call callback,
        // we need to adjust the line number.
        const size_t current_line = lexer_.getSourceLine() - 1;

268 269
        if (!current_ttl_ && !default_ttl_) {
            if (rrtype == RRType::SOA()) {
270
                callbacks_.warning(lexer_.getSourceName(), current_line,
271 272 273 274 275
                                   "no TTL specified; "
                                   "using SOA MINTTL instead");
                const uint32_t ttl_val =
                    dynamic_cast<const rdata::generic::SOA&>(*rdata).
                    getMinimum();
276
                setDefaultTTL(RRTTL(ttl_val), true);
277
                setCurrentTTL(*default_ttl_);
278 279 280 281 282 283
            } else {
                // On catching the exception we'll try to reach EOL again,
                // so we need to unget it now.
                lexer_.ungetToken();
                throw InternalException(__FILE__, __LINE__,
                                        "no TTL specified; load rejected");
284 285 286 287 288 289
            }
        } else if (!explicit_ttl && default_ttl_) {
            setCurrentTTL(*default_ttl_);
        } else if (!explicit_ttl && warn_rfc1035_ttl_) {
            // Omitted (class and) TTL values are default to the last
            // explicitly stated values (RFC 1035, Sec. 5.1).
290
            callbacks_.warning(lexer_.getSourceName(), current_line,
291 292 293 294 295 296 297
                               "using RFC1035 TTL semantics");
            warn_rfc1035_ttl_ = false; // we only warn about this once
        }
        assert(current_ttl_);
        return (*current_ttl_);
    }

298
    void handleDirective(const char* directive, size_t length) {
299
        if (iequals(directive, "INCLUDE")) {
300
            doInclude();
301
        } else if (iequals(directive, "ORIGIN")) {
302 303
            doOrigin(false);
            eatUntilEOL(true);
304
        } else if (iequals(directive, "TTL")) {
305
            setDefaultTTL(RRTTL(getString()), false);
306
            eatUntilEOL(true);
307 308 309 310 311 312
        } else {
            isc_throw(InternalException, "Unknown directive '" <<
                      string(directive, directive + length) << "'");
        }
    }

313 314 315 316 317 318 319 320
    void eatUntilEOL(bool reportExtra) {
        // We want to continue. Try to read until the end of line
        for (;;) {
            const MasterToken& token(lexer_.getNextToken());
            switch (token.getType()) {
                case MasterToken::END_OF_FILE:
                    callbacks_.warning(lexer_.getSourceName(),
                                       lexer_.getSourceLine(),
Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
321
                                       "File does not end with newline");
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
                    // We don't pop here. The End of file will stay there,
                    // and we'll handle it in the next iteration of
                    // loadIncremental properly.
                    return;
                case MasterToken::END_OF_LINE:
                    // Found the end of the line. Good.
                    return;
                default:
                    // Some other type of token.
                    if (reportExtra) {
                        reportExtra = false;
                        reportError(lexer_.getSourceName(),
                                    lexer_.getSourceLine(),
                                    "Extra tokens at the end of line");
                    }
                    break;
            }
        }
    }

342
private:
343 344 345 346 347
    // RFC2181 Section 8 specifies TTLs are unsigned 32-bit integer,
    // effectively limiting the maximum value to 2^32-1.  This constant
    // represent a TTL of the max value.
    const RRTTL MAX_TTL;

348
    MasterLexer lexer_;
349
    const Name zone_origin_;
350 351
    Name active_origin_; // The origin used during parsing
                         // (modifiable by $ORIGIN)
352
    shared_ptr<Name> last_name_; // Last seen name (for INITAL_WS handling)
353 354
    const RRClass zone_class_;
    MasterLoaderCallbacks callbacks_;
355
    AddRRCallback add_callback_;
356 357 358 359 360 361
    boost::scoped_ptr<RRTTL> default_ttl_; // Default TTL of RRs used when
                                           // unspecified.  If NULL no default
                                           // is known.
    boost::scoped_ptr<RRTTL> current_ttl_; // The TTL used most recently.
                                           // Initially set to NULL.  Once set
                                           // always non NULL.
JINMEI Tatuya's avatar
JINMEI Tatuya committed
362
    const MasterLoader::Options options_;
363
    const std::string master_file_;
364
    std::string string_token_;
365
    bool initialized_;
366 367 368
    bool ok_;                   // Is it OK to continue loading?
    const bool many_errors_;    // Are many errors allowed (or should we abort
                                // on the first)
369 370 371 372 373
    // Some info about the outer files from which we include.
    // The first one is current origin, the second is the last seen name
    // in that file.
    typedef pair<Name, shared_ptr<Name> > IncludeInfo;
    vector<IncludeInfo> include_info_;
374 375
    bool previous_name_; // True if there was a previous name in this file
                         // (false at the beginning or after an $INCLUDE line)
376
public:
377 378 379
    bool complete_;             // All work done.
    bool seen_error_;           // Was there at least one error during the
                                // load?
380 381
    bool warn_rfc1035_ttl_;     // should warn if implicit TTL determination
                                // from the previous RR is used.
382 383
};

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
// A helper method of loadIncremental, parsing the first token of a new line.
// If it looks like an RR, detect its owner name and return a string token for
// the next field of the RR.
// Otherwise, return either END_OF_LINE or END_OF_FILE token depending on
// whether the loader continues to the next line or completes the load,
// respectively.  Other corner cases including $-directive handling is done
// here.
// For unexpected errors, it throws an exception, which will be handled in
// loadIncremental.
MasterToken
MasterLoader::MasterLoaderImpl::handleInitialToken() {
    const MasterToken& initial_token =
        lexer_.getNextToken(MasterLexer::QSTRING | MasterLexer::INITIAL_WS);

    // The most likely case is INITIAL_WS, and then string/qstring.  We
    // handle them first.
    if (initial_token.getType() == MasterToken::INITIAL_WS) {
        const MasterToken& next_token = lexer_.getNextToken();
        if (next_token.getType() == MasterToken::END_OF_LINE) {
            return (next_token); // blank line
        } else if (next_token.getType() == MasterToken::END_OF_FILE) {
            lexer_.ungetToken(); // handle it in the next iteration.
            eatUntilEOL(true);  // effectively warn about the unexpected EOF.
            return (MasterToken(MasterToken::END_OF_LINE));
        }

        // This means the same name as previous.
        if (last_name_.get() == NULL) {
            isc_throw(InternalException, "No previous name to use in "
                      "place of initial whitespace");
        } else if (!previous_name_) {
415
            callbacks_.warning(lexer_.getSourceName(), lexer_.getSourceLine(),
416 417
                               "Owner name omitted around $INCLUDE, the result "
                               "might not be as expected");
418 419 420 421 422 423 424 425 426 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
        }
        return (next_token);
    } else if (initial_token.getType() == MasterToken::STRING ||
               initial_token.getType() == MasterToken::QSTRING) {
        // If it is name (or directive), handle it.
        const MasterToken::StringRegion&
            name_string(initial_token.getStringRegion());

        if (name_string.len > 0 && name_string.beg[0] == '$') {
            // This should have either thrown (and the error handler
            // will read up until the end of line) or read until the
            // end of line.

            // Exclude the $ from the string on this point.
            handleDirective(name_string.beg + 1, name_string.len - 1);
            // So, get to the next line, there's nothing more interesting
            // in this one.
            return (MasterToken(MasterToken::END_OF_LINE));
        }

        // This should be an RR, starting with an owner name.  Construct the
        // name, and some string token should follow.
        last_name_.reset(new Name(name_string.beg, name_string.len,
                                  &active_origin_));
        previous_name_ = true;
        return (lexer_.getNextToken(MasterToken::STRING));
    }

    switch (initial_token.getType()) { // handle less common cases
    case MasterToken::END_OF_FILE:
        if (!popSource()) {
            return (initial_token);
        } else {
            // We try to read a token from the popped source
452 453
            // So continue to the next line of that source, but first, make
            // sure the source is at EOL
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
            eatUntilEOL(true);
            return (MasterToken(MasterToken::END_OF_LINE));
        }
    case MasterToken::END_OF_LINE:
        return (initial_token); // empty line
    case MasterToken::ERROR:
        // Error token here.
        isc_throw(InternalException, initial_token.getErrorText());
    default:
        // Some other token (what could that be?)
        isc_throw(InternalException, "Parser got confused (unexpected "
                  "token " << initial_token.getType() << ")");
    }
}

469 470
bool
MasterLoader::MasterLoaderImpl::loadIncremental(size_t count_limit) {
471 472 473
    if (count_limit == 0) {
        isc_throw(isc::InvalidParameter, "Count limit set to 0");
    }
474 475 476 477 478 479 480 481 482 483
    if (complete_) {
        isc_throw(isc::InvalidOperation,
                  "Trying to load when already loaded");
    }
    if (!initialized_) {
        pushSource(master_file_);
    }
    size_t count = 0;
    while (ok_ && count < count_limit) {
        try {
484 485 486 487 488
            const MasterToken next_token = handleInitialToken();
            if (next_token.getType() == MasterToken::END_OF_FILE) {
                return (true);  // we are done
            } else if (next_token.getType() == MasterToken::END_OF_LINE) {
                continue;       // nothing more to do in this line
489
            }
490 491 492
            // We are going to parse an RR, have known the owner name,
            // and are now seeing the next string token in the rest of the RR.
            assert(next_token.getType() == MasterToken::STRING);
493

494 495 496 497
            // TODO: Some more flexibility. We don't allow omitting
            // anything yet

            // The parameters
Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
498
            MasterToken rrparam_token = next_token;
499 500

            bool explicit_ttl = false;
501 502 503
            if (rrparam_token.getType() == MasterToken::STRING) {
                // Try TTL
                if (setCurrentTTL(rrparam_token.getString())) {
504
                    explicit_ttl = true;
505 506 507 508 509
                    rrparam_token = lexer_.getNextToken();
                }
            }

            const RRClass rrclass(rrparam_token.getString());
510 511 512 513 514 515 516 517 518
            const RRType rrtype(getString());

            // TODO: Some more validation?
            if (rrclass != zone_class_) {
                // It doesn't really matter much what type of exception
                // we throw, we catch it just below.
                isc_throw(isc::BadValue, "Class mismatch: " << rrclass <<
                          "vs. " << zone_class_);
            }
Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
519
            // TODO: Check if it is SOA, it should be at the origin.
520

521
            const rdata::RdataPtr rdata(rdata::createRdata(rrtype, rrclass,
522
                                                          lexer_,
523
                                                          &active_origin_,
524 525 526 527 528 529
                                                          options_,
                                                          callbacks_));
            // In case we get NULL, it means there was error creating
            // the Rdata. The errors should have been reported by
            // callbacks_ already. We need to decide if we want to continue
            // or not.
530
            if (rdata) {
Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
531
                add_callback_(*last_name_, rrclass, rrtype,
532 533
                              getCurrentTTL(explicit_ttl, rrtype, rdata),
                              rdata);
534 535
                // Good, we loaded another one
                ++count;
536 537 538 539 540 541 542 543 544
            } else {
                seen_error_ = true;
                if (!many_errors_) {
                    ok_ = false;
                    complete_ = true;
                    // We don't have the exact error here, but it was reported
                    // by the error callback.
                    isc_throw(MasterLoaderError, "Invalid RR data");
                }
545 546 547 548 549 550 551 552 553 554 555 556
            }
        } catch (const MasterLoaderError&) {
            // This is a hack. We exclude the MasterLoaderError from the
            // below case. Once we restrict the below to some smaller
            // exception, we should remove this.
            throw;
        } catch (const isc::Exception& e) {
            // TODO: Once we do #2518, catch only the DNSTextError here,
            // not isc::Exception. The rest should be just simply
            // propagated.
            reportError(lexer_.getSourceName(), lexer_.getSourceLine(),
                        e.what());
557
            eatUntilEOL(false);
558 559 560 561 562 563
        }
    }
    // When there was a fatal error and ok is false, we say we are done.
    return (!ok_);
}

564 565
MasterLoader::MasterLoader(const char* master_file,
                           const Name& zone_origin,
566 567
                           const RRClass& zone_class,
                           const MasterLoaderCallbacks& callbacks,
568
                           const AddRRCallback& add_callback,
569 570
                           Options options)
{
571 572 573
    if (add_callback.empty()) {
        isc_throw(isc::InvalidParameter, "Empty add RR callback");
    }
574
    impl_ = new MasterLoaderImpl(master_file, zone_origin,
575
                                 zone_class, callbacks, add_callback, options);
576 577
}

578 579 580 581 582 583 584 585 586 587
MasterLoader::MasterLoader(std::istream& stream,
                           const Name& zone_origin,
                           const RRClass& zone_class,
                           const MasterLoaderCallbacks& callbacks,
                           const AddRRCallback& add_callback,
                           Options options)
{
    if (add_callback.empty()) {
        isc_throw(isc::InvalidParameter, "Empty add RR callback");
    }
588 589 590 591 592 593
    auto_ptr<MasterLoaderImpl> impl(new MasterLoaderImpl("", zone_origin,
                                                         zone_class, callbacks,
                                                         add_callback,
                                                         options));
    impl->pushStreamSource(stream);
    impl_ = impl.release();
594 595
}

596 597 598 599 600 601
MasterLoader::~MasterLoader() {
    delete impl_;
}

bool
MasterLoader::loadIncremental(size_t count_limit) {
JINMEI Tatuya's avatar
JINMEI Tatuya committed
602
    const bool result = impl_->loadIncremental(count_limit);
603 604
    impl_->complete_ = result;
    return (result);
605 606
}

607 608 609 610 611
bool
MasterLoader::loadedSucessfully() const {
    return (impl_->complete_ && !impl_->seen_error_);
}

612 613
} // end namespace dns
} // end namespace isc