Kea 2.7.9
labelsequence.cc
Go to the documentation of this file.
1// Copyright (C) 2012-2025 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#include <config.h>
8
9#include <dns/labelsequence.h>
10#include <dns/name_internal.h>
13
14#include <boost/functional/hash.hpp>
15
16#include <cstring>
17
18namespace isc {
19namespace dns {
20
22#ifdef ENABLE_DEBUG
23 // In non-debug mode, dereferencing the null pointer further below
24 // will lead to a crash, so disabling this check is not
25 // unsafe. Except for a programming mistake, this case should not
26 // happen.
27 if (!buf) {
29 "Null pointer passed to LabelSequence constructor");
30 }
31#endif
32
33 const uint8_t* bp = reinterpret_cast<const uint8_t*>(buf);
34 first_label_ = 0;
35 const uint8_t offsets_len = *bp++;
36
37#ifdef ENABLE_DEBUG
38 if (offsets_len == 0 || offsets_len > Name::MAX_LABELS) {
40 "Bad offsets len in serialized LabelSequence data: "
41 << static_cast<unsigned int>(offsets_len));
42 }
43#endif
44
45 last_label_ = offsets_len - 1;
46 offsets_ = bp;
47 data_ = bp + offsets_len;
48
49#ifdef ENABLE_DEBUG
50 // Check the integrity on the offsets and the name data
51 const uint8_t* dp = data_;
52 for (size_t cur_offset = 0; cur_offset < offsets_len; ++cur_offset) {
53 if (dp - data_ != offsets_[cur_offset] || *dp > Name::MAX_LABELLEN) {
55 "Broken offset or name data in serialized "
56 "LabelSequence data");
57 }
58 dp += (1 + *dp);
59 }
60#endif
61}
62
64 uint8_t buf[MAX_SERIALIZED_LENGTH]) {
65 size_t data_len;
66 const uint8_t *data = src.getData(&data_len);
67 std::memcpy(buf, data, data_len);
68
69 for (size_t i = 0; i < src.getLabelCount(); ++i) {
70 buf[Name::MAX_WIRE + i] = src.offsets_[i + src.first_label_] -
71 src.offsets_[src.first_label_];
72 }
73
74 first_label_ = 0;
75 last_label_ = src.last_label_ - src.first_label_;
76 data_ = buf;
77 offsets_ = &buf[Name::MAX_WIRE];
78}
79
80
81const uint8_t*
82LabelSequence::getData(size_t *len) const {
83 *len = getDataLength();
84 return (&data_[offsets_[first_label_]]);
85}
86
87size_t
89 const size_t last_label_len = data_[offsets_[last_label_]] + 1;
90 return (offsets_[last_label_] - offsets_[first_label_] + last_label_len);
91}
92
93size_t
97
98namespace {
99// Check if buf is not in the range of [bp, ep), which means
100// - end of buffer is before bp, or
101// - beginning of buffer is on or after ep
102bool
103isOutOfRange(const uint8_t* bp, const uint8_t* ep,
104 const uint8_t* buf, size_t buf_len) {
105 return (bp >= buf + buf_len || // end of buffer is before bp
106 ep <= buf); // beginning of buffer is on or after ep
107}
108}
109
110void
111LabelSequence::serialize(void* buf, size_t buf_len) const {
112 const size_t expected_size = getSerializedLength();
113 if (expected_size > buf_len) {
114 isc_throw(BadValue, "buffer too short for LabelSequence::serialize");
115 }
116
117 const size_t offsets_len = getLabelCount();
118 isc_throw_assert(offsets_len < 256); // should be in the 8-bit range
119
120 // Overridden check. Buffer shouldn't overwrap the offset of name data
121 // regions.
122 uint8_t* bp = reinterpret_cast<uint8_t*>(buf);
123 const size_t ndata_len = getDataLength();
124 if (!isOutOfRange(offsets_, offsets_ + offsets_len, bp, buf_len) ||
125 !isOutOfRange(data_, data_ + ndata_len, bp, buf_len)) {
126 isc_throw(BadValue, "serialize would break the source sequence");
127 }
128
129 *bp++ = offsets_len;
130 for (size_t i = 0; i < offsets_len; ++i) {
131 *bp++ = offsets_[first_label_ + i] - offsets_[first_label_];
132 }
133 std::memcpy(bp, &data_[offsets_[first_label_]], ndata_len);
134 bp += ndata_len;
135
136 isc_throw_assert(bp - reinterpret_cast<const uint8_t*>(buf) ==
137 static_cast<ssize_t>(expected_size));
138}
139
140bool
141LabelSequence::equals(const LabelSequence& other, bool case_sensitive) const {
142 size_t len, other_len;
143 const uint8_t* data = getData(&len);
144 const uint8_t* other_data = other.getData(&other_len);
145
146 if (len != other_len) {
147 return (false);
148 }
149 if (case_sensitive) {
150 return (std::memcmp(data, other_data, len) == 0);
151 }
152
153 // As long as the data was originally validated as (part of) a name,
154 // label length must never be a capital ascii character, so we can
155 // simply compare them after converting to lower characters.
156 for (size_t i = 0; i < len; ++i) {
157 const uint8_t ch = data[i];
158 const uint8_t other_ch = other_data[i];
161 return (false);
162 }
163 }
164 return (true);
165}
166
169 bool case_sensitive) const {
170 // Determine the relative ordering under the DNSSEC order relation of
171 // 'this' and 'other', and also determine the hierarchical relationship
172 // of the labels.
173
174 unsigned int nlabels = 0;
175 int l1 = getLabelCount();
176 int l2 = other.getLabelCount();
177 const int ldiff = static_cast<int>(l1) - static_cast<int>(l2);
178 unsigned int l = (ldiff < 0) ? l1 : l2;
179
180 while (l > 0) {
181 --l;
182 --l1;
183 --l2;
184 size_t pos1 = offsets_[l1 + first_label_];
185 size_t pos2 = other.offsets_[l2 + other.first_label_];
186 unsigned int count1 = data_[pos1++];
187 unsigned int count2 = other.data_[pos2++];
188
189 // We don't support any extended label types including now-obsolete
190 // bitstring labels.
192
193 const int cdiff = static_cast<int>(count1) - static_cast<int>(count2);
194 unsigned int count = (cdiff < 0) ? count1 : count2;
195
196 while (count > 0) {
197 const uint8_t label1 = data_[pos1];
198 const uint8_t label2 = other.data_[pos2];
199 int chdiff;
200
201 if (case_sensitive) {
202 chdiff = static_cast<int>(label1) - static_cast<int>(label2);
203 } else {
204 chdiff = static_cast<int>(
206 static_cast<int>(
208 }
209
210 if (chdiff != 0) {
211 return (NameComparisonResult(
212 chdiff, nlabels,
213 nlabels == 0 ? NameComparisonResult::NONE :
215 }
216 --count;
217 ++pos1;
218 ++pos2;
219 }
220 if (cdiff != 0) {
221 return (NameComparisonResult(
222 cdiff, nlabels,
223 nlabels == 0 ? NameComparisonResult::NONE :
225 }
226 ++nlabels;
227 }
228
229 if (ldiff < 0) {
230 return (NameComparisonResult(ldiff, nlabels,
232 } else if (ldiff > 0) {
233 return (NameComparisonResult(ldiff, nlabels,
235 }
236
237 return (NameComparisonResult(ldiff, nlabels, NameComparisonResult::EQUAL));
238}
239
240void
242 if (i >= getLabelCount()) {
243 isc_throw(OutOfRange, "Cannot strip to zero or less labels; " << i <<
244 " (labelcount: " << getLabelCount() << ")");
245 }
246 first_label_ += i;
247}
248
249void
251 if (i >= getLabelCount()) {
252 isc_throw(OutOfRange, "Cannot strip to zero or less labels; " << i <<
253 " (labelcount: " << getLabelCount() << ")");
254 }
255 last_label_ -= i;
256}
257
258bool
260 return (data_[offsets_[last_label_]] == 0);
261}
262
263size_t
264LabelSequence::getHash(bool case_sensitive) const {
265 size_t length;
266 const uint8_t* s = getData(&length);
267 if (length > 16) {
268 length = 16;
269 }
270
271 size_t hash_val = 0;
272 while (length > 0) {
273 const uint8_t c = *s++;
274 boost::hash_combine(hash_val, case_sensitive ? c :
276 --length;
277 }
278 return (hash_val);
279}
280
281std::string
282LabelSequence::toRawText(bool omit_final_dot) const {
283 const uint8_t* np = &data_[offsets_[first_label_]];
284 const uint8_t* np_end = np + getDataLength();
285
286 // use for integrity check
287 unsigned int labels = getLabelCount();
288 // init with an impossible value to catch error cases in the end:
289 unsigned int count = Name::MAX_LABELLEN + 1;
290
291 // result string: it will roughly have the same length as the wire format
292 // label sequence data. reserve that length to minimize reallocation.
293 std::string result;
294 result.reserve(getDataLength());
295
296 while (np != np_end) {
297 labels--;
298 count = *np++;
299
300 if (count == 0) {
301 // We've reached the "final dot". If we've not dumped any
302 // character, the entire label sequence is the root name.
303 // In that case we don't omit the final dot.
304 if (!omit_final_dot || result.empty()) {
305 result.push_back('.');
306 }
307 break;
308 }
309
310 if (count <= Name::MAX_LABELLEN) {
311 isc_throw_assert(np_end - np >= count);
312
313 if (!result.empty()) {
314 // just after a non-empty label. add a separating dot.
315 result.push_back('.');
316 }
317
318 while (count-- > 0) {
319 const uint8_t c = *np++;
320 result.push_back(c);
321 }
322 } else {
323 isc_throw(BadLabelType, "unknown label type in name data");
324 }
325 }
326
327 // We should be at the end of the data and have consumed all labels.
328 isc_throw_assert(np == np_end);
329 isc_throw_assert(labels == 0);
330
331 return (result);
332}
333
334
335std::string
336LabelSequence::toText(bool omit_final_dot) const {
337 const uint8_t* np = &data_[offsets_[first_label_]];
338 const uint8_t* np_end = np + getDataLength();
339
340 // use for integrity check
341 unsigned int labels = getLabelCount();
342 // init with an impossible value to catch error cases in the end:
343 unsigned int count = Name::MAX_LABELLEN + 1;
344
345 // result string: it will roughly have the same length as the wire format
346 // label sequence data. reserve that length to minimize reallocation.
347 std::string result;
348 result.reserve(getDataLength());
349
350 while (np != np_end) {
351 labels--;
352 count = *np++;
353
354 if (count == 0) {
355 // We've reached the "final dot". If we've not dumped any
356 // character, the entire label sequence is the root name.
357 // In that case we don't omit the final dot.
358 if (!omit_final_dot || result.empty()) {
359 result.push_back('.');
360 }
361 break;
362 }
363
364 if (count <= Name::MAX_LABELLEN) {
365 isc_throw_assert(np_end - np >= count);
366
367 if (!result.empty()) {
368 // just after a non-empty label. add a separating dot.
369 result.push_back('.');
370 }
371
372 while (count-- > 0) {
373 const uint8_t c = *np++;
374 switch (c) {
375 case 0x22: // '"'
376 case 0x28: // '('
377 case 0x29: // ')'
378 case 0x2E: // '.'
379 case 0x3B: // ';'
380 case 0x5C: // '\\'
381 // Special modifiers in zone files.
382 case 0x40: // '@'
383 case 0x24: // '$'
384 result.push_back('\\');
385 result.push_back(c);
386 break;
387 default:
388 if (c > 0x20 && c < 0x7f) {
389 // append printable characters intact
390 result.push_back(c);
391 } else {
392 // encode non-printable characters in the form of \DDD
393 result.push_back(0x5c);
394 result.push_back(0x30 + ((c / 100) % 10));
395 result.push_back(0x30 + ((c / 10) % 10));
396 result.push_back(0x30 + (c % 10));
397 }
398 }
399 }
400 } else {
401 isc_throw(BadLabelType, "unknown label type in name data");
402 }
403 }
404
405 // We should be at the end of the data and have consumed all labels.
406 isc_throw_assert(np == np_end);
407 isc_throw_assert(labels == 0);
408
409 return (result);
410}
411
412std::string
414 return (toText(!isAbsolute()));
415}
416
417void
419 uint8_t buf[MAX_SERIALIZED_LENGTH]) {
420 // collect data to perform steps before anything is changed
421 size_t label_count = last_label_ + 1;
422 // Since we may have been stripped, do not use getDataLength(), but
423 // calculate actual data size this labelsequence currently uses
424 size_t data_pos = offsets_[last_label_] + data_[offsets_[last_label_]] + 1;
425
426 // If this labelsequence is absolute, virtually strip the root label.
427 if (isAbsolute()) {
428 data_pos--;
429 label_count--;
430 }
431 const size_t append_label_count = labels.getLabelCount();
432 size_t data_len;
433 const uint8_t *data = labels.getData(&data_len);
434
435 // Sanity checks
436 if (data_ != buf || offsets_ != &buf[Name::MAX_WIRE]) {
438 "extend() called with unrelated buffer");
439 }
440 // Check MAX_LABELS before MAX_WIRE or it will be never reached
441 if (label_count + append_label_count > Name::MAX_LABELS) {
443 "extend() would exceed maximum number of labels");
444 }
445 if (data_pos + data_len > Name::MAX_WIRE) {
447 "extend() would exceed maximum wire length");
448 }
449
450 // All seems to be reasonably ok, let's proceed.
451 std::memmove(&buf[data_pos], data, data_len);
452
453 for (size_t i = 0; i < append_label_count; ++i) {
454 buf[Name::MAX_WIRE + label_count + i] =
455 data_pos +
456 labels.offsets_[i + labels.first_label_] -
457 labels.offsets_[labels.first_label_];
458 }
459 last_label_ = label_count + append_label_count - 1;
460}
461
462std::ostream&
463operator<<(std::ostream& os, const LabelSequence& label_sequence) {
464 os << label_sequence.toText();
465 return (os);
466}
467
468} // end namespace dns
469} // end namespace isc
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
A generic exception that is thrown if a parameter given to a method would refer to or modify out-of-r...
A standard DNS module exception that is thrown if the name parser encounters an obsolete or incomplet...
Definition name.h:58
Light-weight Accessor to Name data.
std::string toRawText(bool omit_final_dot) const
Convert the LabelSequence to a string without escape sequences.
size_t getHash(bool case_sensitive) const
Calculate a simple hash for the label sequence.
void serialize(void *buf, size_t buf_len) const
Serialize the LabelSequence object in to a buffer.
NameComparisonResult compare(const LabelSequence &other, bool case_sensitive=false) const
Compares two label sequences.
bool isAbsolute() const
Checks whether the label sequence is absolute.
std::string toText() const
Convert the LabelSequence to a string.
LabelSequence(const Name &name)
Constructs a LabelSequence for the given name.
bool equals(const LabelSequence &other, bool case_sensitive=false) const
Compares two label sequences for equality.
size_t getLabelCount() const
Returns the current number of labels for this LabelSequence.
size_t getSerializedLength() const
Return the size of serialized image of the LabelSequence.
void stripLeft(size_t i)
Remove labels from the front of this LabelSequence.
const uint8_t * getData(size_t *len) const
Return the wire-format data for this LabelSequence.
friend std::string Name::toText(bool) const
void stripRight(size_t i)
Remove labels from the end of this LabelSequence.
size_t getDataLength() const
Return the length of the wire-format data of this LabelSequence.
void extend(const LabelSequence &labels, uint8_t buf[MAX_SERIALIZED_LENGTH])
Extend this LabelSequence with the given labelsequence.
This is a supplemental class used only as a return value of Name::compare() and LabelSequence::compar...
Definition name.h:113
static const size_t MAX_LABELLEN
Max allowable length of labels of a domain name.
Definition name.h:704
static const size_t MAX_WIRE
Max allowable length of domain names.
Definition name.h:695
static const size_t MAX_LABELS
Max allowable labels of domain names.
Definition name.h:701
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
#define isc_throw_assert(expr)
Replacement for assert() that throws if the expression is false.
Definition isc_assert.h:18
const uint8_t maptolower[]
Definition name.cc:71
ostream & operator<<(std::ostream &os, const EDNS &edns)
Insert the EDNS as a string into stream.
Definition edns.cc:163
Defines the logger used by the top-level component of kea-lfc.