Kea 2.7.4
labelsequence.cc
Go to the documentation of this file.
1// Copyright (C) 2012-2024 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) == expected_size);
137}
138
139bool
140LabelSequence::equals(const LabelSequence& other, bool case_sensitive) const {
141 size_t len, other_len;
142 const uint8_t* data = getData(&len);
143 const uint8_t* other_data = other.getData(&other_len);
144
145 if (len != other_len) {
146 return (false);
147 }
148 if (case_sensitive) {
149 return (std::memcmp(data, other_data, len) == 0);
150 }
151
152 // As long as the data was originally validated as (part of) a name,
153 // label length must never be a capital ascii character, so we can
154 // simply compare them after converting to lower characters.
155 for (size_t i = 0; i < len; ++i) {
156 const uint8_t ch = data[i];
157 const uint8_t other_ch = other_data[i];
160 return (false);
161 }
162 }
163 return (true);
164}
165
168 bool case_sensitive) const {
169 // Determine the relative ordering under the DNSSEC order relation of
170 // 'this' and 'other', and also determine the hierarchical relationship
171 // of the labels.
172
173 unsigned int nlabels = 0;
174 int l1 = getLabelCount();
175 int l2 = other.getLabelCount();
176 const int ldiff = static_cast<int>(l1) - static_cast<int>(l2);
177 unsigned int l = (ldiff < 0) ? l1 : l2;
178
179 while (l > 0) {
180 --l;
181 --l1;
182 --l2;
183 size_t pos1 = offsets_[l1 + first_label_];
184 size_t pos2 = other.offsets_[l2 + other.first_label_];
185 unsigned int count1 = data_[pos1++];
186 unsigned int count2 = other.data_[pos2++];
187
188 // We don't support any extended label types including now-obsolete
189 // bitstring labels.
191
192 const int cdiff = static_cast<int>(count1) - static_cast<int>(count2);
193 unsigned int count = (cdiff < 0) ? count1 : count2;
194
195 while (count > 0) {
196 const uint8_t label1 = data_[pos1];
197 const uint8_t label2 = other.data_[pos2];
198 int chdiff;
199
200 if (case_sensitive) {
201 chdiff = static_cast<int>(label1) - static_cast<int>(label2);
202 } else {
203 chdiff = static_cast<int>(
205 static_cast<int>(
207 }
208
209 if (chdiff != 0) {
210 return (NameComparisonResult(
211 chdiff, nlabels,
212 nlabels == 0 ? NameComparisonResult::NONE :
214 }
215 --count;
216 ++pos1;
217 ++pos2;
218 }
219 if (cdiff != 0) {
220 return (NameComparisonResult(
221 cdiff, nlabels,
222 nlabels == 0 ? NameComparisonResult::NONE :
224 }
225 ++nlabels;
226 }
227
228 if (ldiff < 0) {
229 return (NameComparisonResult(ldiff, nlabels,
231 } else if (ldiff > 0) {
232 return (NameComparisonResult(ldiff, nlabels,
234 }
235
236 return (NameComparisonResult(ldiff, nlabels, NameComparisonResult::EQUAL));
237}
238
239void
241 if (i >= getLabelCount()) {
242 isc_throw(OutOfRange, "Cannot strip to zero or less labels; " << i <<
243 " (labelcount: " << getLabelCount() << ")");
244 }
245 first_label_ += i;
246}
247
248void
250 if (i >= getLabelCount()) {
251 isc_throw(OutOfRange, "Cannot strip to zero or less labels; " << i <<
252 " (labelcount: " << getLabelCount() << ")");
253 }
254 last_label_ -= i;
255}
256
257bool
259 return (data_[offsets_[last_label_]] == 0);
260}
261
262size_t
263LabelSequence::getHash(bool case_sensitive) const {
264 size_t length;
265 const uint8_t* s = getData(&length);
266 if (length > 16) {
267 length = 16;
268 }
269
270 size_t hash_val = 0;
271 while (length > 0) {
272 const uint8_t c = *s++;
273 boost::hash_combine(hash_val, case_sensitive ? c :
275 --length;
276 }
277 return (hash_val);
278}
279
280std::string
281LabelSequence::toRawText(bool omit_final_dot) const {
282 const uint8_t* np = &data_[offsets_[first_label_]];
283 const uint8_t* np_end = np + getDataLength();
284
285 // use for integrity check
286 unsigned int labels = getLabelCount();
287 // init with an impossible value to catch error cases in the end:
288 unsigned int count = Name::MAX_LABELLEN + 1;
289
290 // result string: it will roughly have the same length as the wire format
291 // label sequence data. reserve that length to minimize reallocation.
292 std::string result;
293 result.reserve(getDataLength());
294
295 while (np != np_end) {
296 labels--;
297 count = *np++;
298
299 if (count == 0) {
300 // We've reached the "final dot". If we've not dumped any
301 // character, the entire label sequence is the root name.
302 // In that case we don't omit the final dot.
303 if (!omit_final_dot || result.empty()) {
304 result.push_back('.');
305 }
306 break;
307 }
308
309 if (count <= Name::MAX_LABELLEN) {
310 isc_throw_assert(np_end - np >= count);
311
312 if (!result.empty()) {
313 // just after a non-empty label. add a separating dot.
314 result.push_back('.');
315 }
316
317 while (count-- > 0) {
318 const uint8_t c = *np++;
319 result.push_back(c);
320 }
321 } else {
322 isc_throw(BadLabelType, "unknown label type in name data");
323 }
324 }
325
326 // We should be at the end of the data and have consumed all labels.
327 isc_throw_assert(np == np_end);
328 isc_throw_assert(labels == 0);
329
330 return (result);
331}
332
333
334std::string
335LabelSequence::toText(bool omit_final_dot) const {
336 const uint8_t* np = &data_[offsets_[first_label_]];
337 const uint8_t* np_end = np + getDataLength();
338
339 // use for integrity check
340 unsigned int labels = getLabelCount();
341 // init with an impossible value to catch error cases in the end:
342 unsigned int count = Name::MAX_LABELLEN + 1;
343
344 // result string: it will roughly have the same length as the wire format
345 // label sequence data. reserve that length to minimize reallocation.
346 std::string result;
347 result.reserve(getDataLength());
348
349 while (np != np_end) {
350 labels--;
351 count = *np++;
352
353 if (count == 0) {
354 // We've reached the "final dot". If we've not dumped any
355 // character, the entire label sequence is the root name.
356 // In that case we don't omit the final dot.
357 if (!omit_final_dot || result.empty()) {
358 result.push_back('.');
359 }
360 break;
361 }
362
363 if (count <= Name::MAX_LABELLEN) {
364 isc_throw_assert(np_end - np >= count);
365
366 if (!result.empty()) {
367 // just after a non-empty label. add a separating dot.
368 result.push_back('.');
369 }
370
371 while (count-- > 0) {
372 const uint8_t c = *np++;
373 switch (c) {
374 case 0x22: // '"'
375 case 0x28: // '('
376 case 0x29: // ')'
377 case 0x2E: // '.'
378 case 0x3B: // ';'
379 case 0x5C: // '\\'
380 // Special modifiers in zone files.
381 case 0x40: // '@'
382 case 0x24: // '$'
383 result.push_back('\\');
384 result.push_back(c);
385 break;
386 default:
387 if (c > 0x20 && c < 0x7f) {
388 // append printable characters intact
389 result.push_back(c);
390 } else {
391 // encode non-printable characters in the form of \DDD
392 result.push_back(0x5c);
393 result.push_back(0x30 + ((c / 100) % 10));
394 result.push_back(0x30 + ((c / 10) % 10));
395 result.push_back(0x30 + (c % 10));
396 }
397 }
398 }
399 } else {
400 isc_throw(BadLabelType, "unknown label type in name data");
401 }
402 }
403
404 // We should be at the end of the data and have consumed all labels.
405 isc_throw_assert(np == np_end);
406 isc_throw_assert(labels == 0);
407
408 return (result);
409}
410
411std::string
413 return (toText(!isAbsolute()));
414}
415
416void
418 uint8_t buf[MAX_SERIALIZED_LENGTH]) {
419 // collect data to perform steps before anything is changed
420 size_t label_count = last_label_ + 1;
421 // Since we may have been stripped, do not use getDataLength(), but
422 // calculate actual data size this labelsequence currently uses
423 size_t data_pos = offsets_[last_label_] + data_[offsets_[last_label_]] + 1;
424
425 // If this labelsequence is absolute, virtually strip the root label.
426 if (isAbsolute()) {
427 data_pos--;
428 label_count--;
429 }
430 const size_t append_label_count = labels.getLabelCount();
431 size_t data_len;
432 const uint8_t *data = labels.getData(&data_len);
433
434 // Sanity checks
435 if (data_ != buf || offsets_ != &buf[Name::MAX_WIRE]) {
437 "extend() called with unrelated buffer");
438 }
439 // Check MAX_LABELS before MAX_WIRE or it will be never reached
440 if (label_count + append_label_count > Name::MAX_LABELS) {
442 "extend() would exceed maximum number of labels");
443 }
444 if (data_pos + data_len > Name::MAX_WIRE) {
446 "extend() would exceed maximum wire length");
447 }
448
449 // All seems to be reasonably ok, let's proceed.
450 std::memmove(&buf[data_pos], data, data_len);
451
452 for (size_t i = 0; i < append_label_count; ++i) {
453 buf[Name::MAX_WIRE + label_count + i] =
454 data_pos +
455 labels.offsets_[i + labels.first_label_] -
456 labels.offsets_[labels.first_label_];
457 }
458 last_label_ = label_count + append_label_count - 1;
459}
460
461std::ostream&
462operator<<(std::ostream& os, const LabelSequence& label_sequence) {
463 os << label_sequence.toText();
464 return (os);
465}
466
467} // end namespace dns
468} // 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.
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.