labelsequence.cc 13.1 KB
Newer Older
1
// Copyright (C) 2012-2015,2017 Internet Systems Consortium, Inc. ("ISC")
Jelte Jansen's avatar
Jelte Jansen committed
2
//
3 4 5
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
Jelte Jansen's avatar
Jelte Jansen committed
6

7
#include <config.h>
8

Jelte Jansen's avatar
Jelte Jansen committed
9
#include <dns/labelsequence.h>
10
#include <dns/name_internal.h>
Jelte Jansen's avatar
Jelte Jansen committed
11 12
#include <exceptions/exceptions.h>

13 14
#include <boost/functional/hash.hpp>

15 16
#include <cstring>

Jelte Jansen's avatar
Jelte Jansen committed
17 18 19
namespace isc {
namespace dns {

20
LabelSequence::LabelSequence(const void* buf) {
21
#ifdef ENABLE_DEBUG
22
    // In non-debug mode, dereferencing the NULL pointer further below
23 24 25
    // will lead to a crash, so disabling this check is not
    // unsafe. Except for a programming mistake, this case should not
    // happen.
26 27 28 29
    if (buf == NULL) {
        isc_throw(BadValue,
                  "Null pointer passed to LabelSequence constructor");
    }
30
#endif
31 32 33 34

    const uint8_t* bp = reinterpret_cast<const uint8_t*>(buf);
    first_label_ = 0;
    const uint8_t offsets_len = *bp++;
35 36

#ifdef ENABLE_DEBUG
37 38 39 40 41
    if (offsets_len == 0 || offsets_len > Name::MAX_LABELS) {
        isc_throw(BadValue,
                  "Bad offsets len in serialized LabelSequence data: "
                  << static_cast<unsigned int>(offsets_len));
    }
42 43
#endif

44 45 46 47
    last_label_ = offsets_len - 1;
    offsets_ = bp;
    data_ = bp + offsets_len;

48
#ifdef ENABLE_DEBUG
49 50 51
    // Check the integrity on the offsets and the name data
    const uint8_t* dp = data_;
    for (size_t cur_offset = 0; cur_offset < offsets_len; ++cur_offset) {
52
        if (dp - data_ != offsets_[cur_offset] || *dp > Name::MAX_LABELLEN) {
53 54 55 56 57 58
            isc_throw(BadValue,
                      "Broken offset or name data in serialized "
                      "LabelSequence data");
        }
        dp += (1 + *dp);
    }
59
#endif
60
}
61

62 63 64 65 66
LabelSequence::LabelSequence(const LabelSequence& src,
                             uint8_t buf[MAX_SERIALIZED_LENGTH])
{
    size_t data_len;
    const uint8_t *data = src.getData(&data_len);
67
    std::memcpy(buf, data, data_len);
68 69 70 71 72 73 74 75 76 77 78 79 80

    for (size_t i = 0; i < src.getLabelCount(); ++i) {
        buf[Name::MAX_WIRE + i] = src.offsets_[i + src.first_label_] -
                                  src.offsets_[src.first_label_];
    }

    first_label_ = 0;
    last_label_ = src.last_label_ - src.first_label_;
    data_ = buf;
    offsets_ = &buf[Name::MAX_WIRE];
}


81
const uint8_t*
Jelte Jansen's avatar
Jelte Jansen committed
82
LabelSequence::getData(size_t *len) const {
83
    *len = getDataLength();
Jelte Jansen's avatar
Jelte Jansen committed
84
    return (&data_[offsets_[first_label_]]);
85 86 87 88
}

size_t
LabelSequence::getDataLength() const {
89 90
    const size_t last_label_len = data_[offsets_[last_label_]] + 1;
    return (offsets_[last_label_] - offsets_[first_label_] + last_label_len);
Jelte Jansen's avatar
Jelte Jansen committed
91 92
}

93 94 95 96 97
size_t
LabelSequence::getSerializedLength() const {
    return (1 + getLabelCount() + getDataLength());
}

98 99 100 101 102 103 104 105 106 107 108 109 110
namespace {
// Check if buf is not in the range of [bp, ep), which means
// - end of buffer is before bp, or
// - beginning of buffer is on or after ep
bool
isOutOfRange(const uint8_t* bp, const uint8_t* ep,
             const uint8_t* buf, size_t buf_len)
{
    return (bp >= buf + buf_len || // end of buffer is before bp
            ep <= buf);            // beginning of buffer is on or after ep
}
}

111 112 113 114 115 116 117 118 119 120
void
LabelSequence::serialize(void* buf, size_t buf_len) const {
    const size_t expected_size = getSerializedLength();
    if (expected_size > buf_len) {
        isc_throw(BadValue, "buffer too short for LabelSequence::serialize");
    }

    const size_t offsets_len = getLabelCount();
    assert(offsets_len < 256);  // should be in the 8-bit range

121 122
    // Overridden check.  Buffer shouldn't overwrap the offset of name data
    // regions.
123
    uint8_t* bp = reinterpret_cast<uint8_t*>(buf);
124 125 126 127 128 129
    const size_t ndata_len = getDataLength();
    if (!isOutOfRange(offsets_, offsets_ + offsets_len, bp, buf_len) ||
        !isOutOfRange(data_, data_ + ndata_len, bp, buf_len)) {
        isc_throw(BadValue, "serialize would break the source sequence");
    }

130 131 132 133
    *bp++ = offsets_len;
    for (size_t i = 0; i < offsets_len; ++i) {
        *bp++ = offsets_[first_label_ + i] - offsets_[first_label_];
    }
134
    std::memcpy(bp, &data_[offsets_[first_label_]], ndata_len);
135 136 137 138 139
    bp += ndata_len;

    assert(bp - reinterpret_cast<const uint8_t*>(buf) == expected_size);
}

Jelte Jansen's avatar
Jelte Jansen committed
140 141
bool
LabelSequence::equals(const LabelSequence& other, bool case_sensitive) const {
142
    size_t len, other_len;
143 144
    const uint8_t* data = getData(&len);
    const uint8_t* other_data = other.getData(&other_len);
145 146 147 148

    if (len != other_len) {
        return (false);
    }
Jelte Jansen's avatar
Jelte Jansen committed
149
    if (case_sensitive) {
150
        return (std::memcmp(data, other_data, len) == 0);
Jelte Jansen's avatar
Jelte Jansen committed
151
    }
152 153 154 155 156

    // As long as the data was originally validated as (part of) a name,
    // label length must never be a capital ascii character, so we can
    // simply compare them after converting to lower characters.
    for (size_t i = 0; i < len; ++i) {
157 158
        const uint8_t ch = data[i];
        const uint8_t other_ch = other_data[i];
159 160 161 162 163 164
        if (isc::dns::name::internal::maptolower[ch] !=
            isc::dns::name::internal::maptolower[other_ch]) {
            return (false);
        }
    }
    return (true);
Jelte Jansen's avatar
Jelte Jansen committed
165 166
}

167 168
NameComparisonResult
LabelSequence::compare(const LabelSequence& other,
169 170
                       bool case_sensitive) const
{
171 172
    // Determine the relative ordering under the DNSSEC order relation of
    // 'this' and 'other', and also determine the hierarchical relationship
173
    // of the labels.
174 175

    unsigned int nlabels = 0;
176 177
    int l1 = getLabelCount();
    int l2 = other.getLabelCount();
178
    const int ldiff = static_cast<int>(l1) - static_cast<int>(l2);
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    unsigned int l = (ldiff < 0) ? l1 : l2;

    while (l > 0) {
        --l;
        --l1;
        --l2;
        size_t pos1 = offsets_[l1 + first_label_];
        size_t pos2 = other.offsets_[l2 + other.first_label_];
        unsigned int count1 = data_[pos1++];
        unsigned int count2 = other.data_[pos2++];

        // We don't support any extended label types including now-obsolete
        // bitstring labels.
        assert(count1 <= Name::MAX_LABELLEN && count2 <= Name::MAX_LABELLEN);

194
        const int cdiff = static_cast<int>(count1) - static_cast<int>(count2);
195 196 197
        unsigned int count = (cdiff < 0) ? count1 : count2;

        while (count > 0) {
198 199
            const uint8_t label1 = data_[pos1];
            const uint8_t label2 = other.data_[pos2];
200 201 202
            int chdiff;

            if (case_sensitive) {
203
                chdiff = static_cast<int>(label1) - static_cast<int>(label2);
204
            } else {
205 206 207 208
                chdiff = static_cast<int>(
                    isc::dns::name::internal::maptolower[label1]) -
                    static_cast<int>(
                        isc::dns::name::internal::maptolower[label2]);
209 210 211
            }

            if (chdiff != 0) {
212 213 214 215
                return (NameComparisonResult(
                            chdiff, nlabels,
                            nlabels == 0 ? NameComparisonResult::NONE :
                            NameComparisonResult::COMMONANCESTOR));
216 217 218 219 220 221
            }
            --count;
            ++pos1;
            ++pos2;
        }
        if (cdiff != 0) {
222 223 224 225
            return (NameComparisonResult(
                        cdiff, nlabels,
                        nlabels == 0 ? NameComparisonResult::NONE :
                        NameComparisonResult::COMMONANCESTOR));
226 227 228 229 230 231 232 233 234 235 236 237 238
        }
        ++nlabels;
    }

    if (ldiff < 0) {
        return (NameComparisonResult(ldiff, nlabels,
                                     NameComparisonResult::SUPERDOMAIN));
    } else if (ldiff > 0) {
        return (NameComparisonResult(ldiff, nlabels,
                                     NameComparisonResult::SUBDOMAIN));
    }

    return (NameComparisonResult(ldiff, nlabels, NameComparisonResult::EQUAL));
239 240
}

Jelte Jansen's avatar
Jelte Jansen committed
241
void
Jelte Jansen's avatar
Jelte Jansen committed
242
LabelSequence::stripLeft(size_t i) {
Jelte Jansen's avatar
Jelte Jansen committed
243
    if (i >= getLabelCount()) {
Jelte Jansen's avatar
Jelte Jansen committed
244
        isc_throw(OutOfRange, "Cannot strip to zero or less labels; " << i <<
Jelte Jansen's avatar
Jelte Jansen committed
245
                              " (labelcount: " << getLabelCount() << ")");
Jelte Jansen's avatar
Jelte Jansen committed
246
    }
Jelte Jansen's avatar
Jelte Jansen committed
247 248 249 250
    first_label_ += i;
}

void
Jelte Jansen's avatar
Jelte Jansen committed
251
LabelSequence::stripRight(size_t i) {
Jelte Jansen's avatar
Jelte Jansen committed
252
    if (i >= getLabelCount()) {
Jelte Jansen's avatar
Jelte Jansen committed
253
        isc_throw(OutOfRange, "Cannot strip to zero or less labels; " << i <<
Jelte Jansen's avatar
Jelte Jansen committed
254
                              " (labelcount: " << getLabelCount() << ")");
Jelte Jansen's avatar
Jelte Jansen committed
255
    }
Jelte Jansen's avatar
Jelte Jansen committed
256
    last_label_ -= i;
Jelte Jansen's avatar
Jelte Jansen committed
257 258
}

Jelte Jansen's avatar
Jelte Jansen committed
259 260
bool
LabelSequence::isAbsolute() const {
261
    return (data_[offsets_[last_label_]] == 0);
Jelte Jansen's avatar
Jelte Jansen committed
262 263
}

264 265 266
size_t
LabelSequence::getHash(bool case_sensitive) const {
    size_t length;
267
    const uint8_t* s = getData(&length);
268 269 270 271 272 273
    if (length > 16) {
        length = 16;
    }

    size_t hash_val = 0;
    while (length > 0) {
274
        const uint8_t c = *s++;
275 276 277 278 279 280 281
        boost::hash_combine(hash_val, case_sensitive ? c :
                            isc::dns::name::internal::maptolower[c]);
        --length;
    }
    return (hash_val);
}

282 283
std::string
LabelSequence::toText(bool omit_final_dot) const {
284 285 286
    const uint8_t* np = &data_[offsets_[first_label_]];
    const uint8_t* np_end = np + getDataLength();

287
    // use for integrity check
288
    unsigned int labels = getLabelCount();
289 290 291 292
    // init with an impossible value to catch error cases in the end:
    unsigned int count = Name::MAX_LABELLEN + 1;

    // result string: it will roughly have the same length as the wire format
293
    // label sequence data.  reserve that length to minimize reallocation.
294
    std::string result;
295
    result.reserve(getDataLength());
296 297 298 299 300 301

    while (np != np_end) {
        labels--;
        count = *np++;

        if (count == 0) {
302 303 304 305
            // We've reached the "final dot".  If we've not dumped any
            // character, the entire label sequence is the root name.
            // In that case we don't omit the final dot.
            if (!omit_final_dot || result.empty()) {
306 307 308 309 310 311 312 313 314 315 316 317 318 319
                result.push_back('.');
            }
            break;
        }

        if (count <= Name::MAX_LABELLEN) {
            assert(np_end - np >= count);

            if (!result.empty()) {
                // just after a non-empty label.  add a separating dot.
                result.push_back('.');
            }

            while (count-- > 0) {
320
                const uint8_t c = *np++;
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 350 351
                switch (c) {
                case 0x22: // '"'
                case 0x28: // '('
                case 0x29: // ')'
                case 0x2E: // '.'
                case 0x3B: // ';'
                case 0x5C: // '\\'
                    // Special modifiers in zone files.
                case 0x40: // '@'
                case 0x24: // '$'
                    result.push_back('\\');
                    result.push_back(c);
                    break;
                default:
                    if (c > 0x20 && c < 0x7f) {
                        // append printable characters intact
                        result.push_back(c);
                    } else {
                        // encode non-printable characters in the form of \DDD
                        result.push_back(0x5c);
                        result.push_back(0x30 + ((c / 100) % 10));
                        result.push_back(0x30 + ((c / 10) % 10));
                        result.push_back(0x30 + (c % 10));
                    }
                }
            }
        } else {
            isc_throw(BadLabelType, "unknown label type in name data");
        }
    }

352 353
    // We should be at the end of the data and have consumed all labels.
    assert(np == np_end);
354 355 356 357 358
    assert(labels == 0);

    return (result);
}

359 360
std::string
LabelSequence::toText() const {
361
    return (toText(!isAbsolute()));
362 363
}

364 365 366 367
void
LabelSequence::extend(const LabelSequence& labels,
                      uint8_t buf[MAX_SERIALIZED_LENGTH])
{
368 369 370
    // collect data to perform steps before anything is changed
    size_t label_count = last_label_ + 1;
    // Since we may have been stripped, do not use getDataLength(), but
371
    // calculate actual data size this labelsequence currently uses
372 373 374
    size_t data_pos = offsets_[last_label_] + data_[offsets_[last_label_]] + 1;

    // If this labelsequence is absolute, virtually strip the root label.
Jelte Jansen's avatar
Jelte Jansen committed
375
    if (isAbsolute()) {
376 377 378
        data_pos--;
        label_count--;
    }
Jelte Jansen's avatar
Jelte Jansen committed
379
    const size_t append_label_count = labels.getLabelCount();
380 381 382 383
    size_t data_len;
    const uint8_t *data = labels.getData(&data_len);

    // Sanity checks
384 385 386 387
    if (data_ != buf || offsets_ != &buf[Name::MAX_WIRE]) {
        isc_throw(BadValue,
                  "extend() called with unrelated buffer");
    }
388
    // Check MAX_LABELS before MAX_WIRE or it will be never reached
389
    if (label_count + append_label_count > Name::MAX_LABELS) {
390 391 392
        isc_throw(BadValue,
                  "extend() would exceed maximum number of labels");
    }
393 394 395 396
    if (data_pos + data_len > Name::MAX_WIRE) {
        isc_throw(BadValue,
                  "extend() would exceed maximum wire length");
    }
397

398
    // All seems to be reasonably ok, let's proceed.
399
    std::memmove(&buf[data_pos], data, data_len);
400

401 402
    for (size_t i = 0; i < append_label_count; ++i) {
        buf[Name::MAX_WIRE + label_count + i] =
403
            data_pos +
404 405
            labels.offsets_[i + labels.first_label_] -
            labels.offsets_[labels.first_label_];
406
    }
407
    last_label_ = label_count + append_label_count - 1;
408 409
}

410 411 412 413 414 415
std::ostream&
operator<<(std::ostream& os, const LabelSequence& label_sequence) {
    os << label_sequence.toText();
    return (os);
}

Jelte Jansen's avatar
Jelte Jansen committed
416 417
} // end namespace dns
} // end namespace isc