labelsequence.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. // Copyright (C) 2012-2014 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <config.h>
  15. #include <dns/labelsequence.h>
  16. #include <dns/name_internal.h>
  17. #include <exceptions/exceptions.h>
  18. #include <boost/functional/hash.hpp>
  19. #include <cstring>
  20. namespace isc {
  21. namespace dns {
  22. LabelSequence::LabelSequence(const void* buf) {
  23. #ifdef ENABLE_DEBUG
  24. // In non-debug mode, derefencing the NULL pointer further below
  25. // will lead to a crash, so disabling this check is not
  26. // unsafe. Except for a programming mistake, this case should not
  27. // happen.
  28. if (buf == NULL) {
  29. isc_throw(BadValue,
  30. "Null pointer passed to LabelSequence constructor");
  31. }
  32. #endif
  33. const uint8_t* bp = reinterpret_cast<const uint8_t*>(buf);
  34. first_label_ = 0;
  35. const uint8_t offsets_len = *bp++;
  36. #ifdef ENABLE_DEBUG
  37. if (offsets_len == 0 || offsets_len > Name::MAX_LABELS) {
  38. isc_throw(BadValue,
  39. "Bad offsets len in serialized LabelSequence data: "
  40. << static_cast<unsigned int>(offsets_len));
  41. }
  42. #endif
  43. last_label_ = offsets_len - 1;
  44. offsets_ = bp;
  45. data_ = bp + offsets_len;
  46. #ifdef ENABLE_DEBUG
  47. // Check the integrity on the offsets and the name data
  48. const uint8_t* dp = data_;
  49. for (size_t cur_offset = 0; cur_offset < offsets_len; ++cur_offset) {
  50. if (dp - data_ != offsets_[cur_offset] || *dp > Name::MAX_LABELLEN) {
  51. isc_throw(BadValue,
  52. "Broken offset or name data in serialized "
  53. "LabelSequence data");
  54. }
  55. dp += (1 + *dp);
  56. }
  57. #endif
  58. }
  59. LabelSequence::LabelSequence(const LabelSequence& src,
  60. uint8_t buf[MAX_SERIALIZED_LENGTH])
  61. {
  62. size_t data_len;
  63. const uint8_t *data = src.getData(&data_len);
  64. std::memcpy(buf, data, data_len);
  65. for (size_t i = 0; i < src.getLabelCount(); ++i) {
  66. buf[Name::MAX_WIRE + i] = src.offsets_[i + src.first_label_] -
  67. src.offsets_[src.first_label_];
  68. }
  69. first_label_ = 0;
  70. last_label_ = src.last_label_ - src.first_label_;
  71. data_ = buf;
  72. offsets_ = &buf[Name::MAX_WIRE];
  73. }
  74. const uint8_t*
  75. LabelSequence::getData(size_t *len) const {
  76. *len = getDataLength();
  77. return (&data_[offsets_[first_label_]]);
  78. }
  79. size_t
  80. LabelSequence::getDataLength() const {
  81. const size_t last_label_len = data_[offsets_[last_label_]] + 1;
  82. return (offsets_[last_label_] - offsets_[first_label_] + last_label_len);
  83. }
  84. size_t
  85. LabelSequence::getSerializedLength() const {
  86. return (1 + getLabelCount() + getDataLength());
  87. }
  88. namespace {
  89. // Check if buf is not in the range of [bp, ep), which means
  90. // - end of buffer is before bp, or
  91. // - beginning of buffer is on or after ep
  92. bool
  93. isOutOfRange(const uint8_t* bp, const uint8_t* ep,
  94. const uint8_t* buf, size_t buf_len)
  95. {
  96. return (bp >= buf + buf_len || // end of buffer is before bp
  97. ep <= buf); // beginning of buffer is on or after ep
  98. }
  99. }
  100. void
  101. LabelSequence::serialize(void* buf, size_t buf_len) const {
  102. const size_t expected_size = getSerializedLength();
  103. if (expected_size > buf_len) {
  104. isc_throw(BadValue, "buffer too short for LabelSequence::serialize");
  105. }
  106. const size_t offsets_len = getLabelCount();
  107. assert(offsets_len < 256); // should be in the 8-bit range
  108. // Overridden check. Buffer shouldn't overwrap the offset of name data
  109. // regions.
  110. uint8_t* bp = reinterpret_cast<uint8_t*>(buf);
  111. const size_t ndata_len = getDataLength();
  112. if (!isOutOfRange(offsets_, offsets_ + offsets_len, bp, buf_len) ||
  113. !isOutOfRange(data_, data_ + ndata_len, bp, buf_len)) {
  114. isc_throw(BadValue, "serialize would break the source sequence");
  115. }
  116. *bp++ = offsets_len;
  117. for (size_t i = 0; i < offsets_len; ++i) {
  118. *bp++ = offsets_[first_label_ + i] - offsets_[first_label_];
  119. }
  120. std::memcpy(bp, &data_[offsets_[first_label_]], ndata_len);
  121. bp += ndata_len;
  122. assert(bp - reinterpret_cast<const uint8_t*>(buf) == expected_size);
  123. }
  124. bool
  125. LabelSequence::equals(const LabelSequence& other, bool case_sensitive) const {
  126. size_t len, other_len;
  127. const uint8_t* data = getData(&len);
  128. const uint8_t* other_data = other.getData(&other_len);
  129. if (len != other_len) {
  130. return (false);
  131. }
  132. if (case_sensitive) {
  133. return (std::memcmp(data, other_data, len) == 0);
  134. }
  135. // As long as the data was originally validated as (part of) a name,
  136. // label length must never be a capital ascii character, so we can
  137. // simply compare them after converting to lower characters.
  138. for (size_t i = 0; i < len; ++i) {
  139. const uint8_t ch = data[i];
  140. const uint8_t other_ch = other_data[i];
  141. if (isc::dns::name::internal::maptolower[ch] !=
  142. isc::dns::name::internal::maptolower[other_ch]) {
  143. return (false);
  144. }
  145. }
  146. return (true);
  147. }
  148. NameComparisonResult
  149. LabelSequence::compare(const LabelSequence& other,
  150. bool case_sensitive) const
  151. {
  152. // Determine the relative ordering under the DNSSEC order relation of
  153. // 'this' and 'other', and also determine the hierarchical relationship
  154. // of the labels.
  155. unsigned int nlabels = 0;
  156. int l1 = getLabelCount();
  157. int l2 = other.getLabelCount();
  158. const int ldiff = static_cast<int>(l1) - static_cast<int>(l2);
  159. unsigned int l = (ldiff < 0) ? l1 : l2;
  160. while (l > 0) {
  161. --l;
  162. --l1;
  163. --l2;
  164. size_t pos1 = offsets_[l1 + first_label_];
  165. size_t pos2 = other.offsets_[l2 + other.first_label_];
  166. unsigned int count1 = data_[pos1++];
  167. unsigned int count2 = other.data_[pos2++];
  168. // We don't support any extended label types including now-obsolete
  169. // bitstring labels.
  170. assert(count1 <= Name::MAX_LABELLEN && count2 <= Name::MAX_LABELLEN);
  171. const int cdiff = static_cast<int>(count1) - static_cast<int>(count2);
  172. unsigned int count = (cdiff < 0) ? count1 : count2;
  173. while (count > 0) {
  174. const uint8_t label1 = data_[pos1];
  175. const uint8_t label2 = other.data_[pos2];
  176. int chdiff;
  177. if (case_sensitive) {
  178. chdiff = static_cast<int>(label1) - static_cast<int>(label2);
  179. } else {
  180. chdiff = static_cast<int>(
  181. isc::dns::name::internal::maptolower[label1]) -
  182. static_cast<int>(
  183. isc::dns::name::internal::maptolower[label2]);
  184. }
  185. if (chdiff != 0) {
  186. return (NameComparisonResult(
  187. chdiff, nlabels,
  188. nlabels == 0 ? NameComparisonResult::NONE :
  189. NameComparisonResult::COMMONANCESTOR));
  190. }
  191. --count;
  192. ++pos1;
  193. ++pos2;
  194. }
  195. if (cdiff != 0) {
  196. return (NameComparisonResult(
  197. cdiff, nlabels,
  198. nlabels == 0 ? NameComparisonResult::NONE :
  199. NameComparisonResult::COMMONANCESTOR));
  200. }
  201. ++nlabels;
  202. }
  203. if (ldiff < 0) {
  204. return (NameComparisonResult(ldiff, nlabels,
  205. NameComparisonResult::SUPERDOMAIN));
  206. } else if (ldiff > 0) {
  207. return (NameComparisonResult(ldiff, nlabels,
  208. NameComparisonResult::SUBDOMAIN));
  209. }
  210. return (NameComparisonResult(ldiff, nlabels, NameComparisonResult::EQUAL));
  211. }
  212. void
  213. LabelSequence::stripLeft(size_t i) {
  214. if (i >= getLabelCount()) {
  215. isc_throw(OutOfRange, "Cannot strip to zero or less labels; " << i <<
  216. " (labelcount: " << getLabelCount() << ")");
  217. }
  218. first_label_ += i;
  219. }
  220. void
  221. LabelSequence::stripRight(size_t i) {
  222. if (i >= getLabelCount()) {
  223. isc_throw(OutOfRange, "Cannot strip to zero or less labels; " << i <<
  224. " (labelcount: " << getLabelCount() << ")");
  225. }
  226. last_label_ -= i;
  227. }
  228. bool
  229. LabelSequence::isAbsolute() const {
  230. return (data_[offsets_[last_label_]] == 0);
  231. }
  232. size_t
  233. LabelSequence::getHash(bool case_sensitive) const {
  234. size_t length;
  235. const uint8_t* s = getData(&length);
  236. if (length > 16) {
  237. length = 16;
  238. }
  239. size_t hash_val = 0;
  240. while (length > 0) {
  241. const uint8_t c = *s++;
  242. boost::hash_combine(hash_val, case_sensitive ? c :
  243. isc::dns::name::internal::maptolower[c]);
  244. --length;
  245. }
  246. return (hash_val);
  247. }
  248. std::string
  249. LabelSequence::toText(bool omit_final_dot) const {
  250. const uint8_t* np = &data_[offsets_[first_label_]];
  251. const uint8_t* np_end = np + getDataLength();
  252. // use for integrity check
  253. unsigned int labels = getLabelCount();
  254. // init with an impossible value to catch error cases in the end:
  255. unsigned int count = Name::MAX_LABELLEN + 1;
  256. // result string: it will roughly have the same length as the wire format
  257. // label sequence data. reserve that length to minimize reallocation.
  258. std::string result;
  259. result.reserve(getDataLength());
  260. while (np != np_end) {
  261. labels--;
  262. count = *np++;
  263. if (count == 0) {
  264. // We've reached the "final dot". If we've not dumped any
  265. // character, the entire label sequence is the root name.
  266. // In that case we don't omit the final dot.
  267. if (!omit_final_dot || result.empty()) {
  268. result.push_back('.');
  269. }
  270. break;
  271. }
  272. if (count <= Name::MAX_LABELLEN) {
  273. assert(np_end - np >= count);
  274. if (!result.empty()) {
  275. // just after a non-empty label. add a separating dot.
  276. result.push_back('.');
  277. }
  278. while (count-- > 0) {
  279. const uint8_t c = *np++;
  280. switch (c) {
  281. case 0x22: // '"'
  282. case 0x28: // '('
  283. case 0x29: // ')'
  284. case 0x2E: // '.'
  285. case 0x3B: // ';'
  286. case 0x5C: // '\\'
  287. // Special modifiers in zone files.
  288. case 0x40: // '@'
  289. case 0x24: // '$'
  290. result.push_back('\\');
  291. result.push_back(c);
  292. break;
  293. default:
  294. if (c > 0x20 && c < 0x7f) {
  295. // append printable characters intact
  296. result.push_back(c);
  297. } else {
  298. // encode non-printable characters in the form of \DDD
  299. result.push_back(0x5c);
  300. result.push_back(0x30 + ((c / 100) % 10));
  301. result.push_back(0x30 + ((c / 10) % 10));
  302. result.push_back(0x30 + (c % 10));
  303. }
  304. }
  305. }
  306. } else {
  307. isc_throw(BadLabelType, "unknown label type in name data");
  308. }
  309. }
  310. // We should be at the end of the data and have consumed all labels.
  311. assert(np == np_end);
  312. assert(labels == 0);
  313. return (result);
  314. }
  315. std::string
  316. LabelSequence::toText() const {
  317. return (toText(!isAbsolute()));
  318. }
  319. void
  320. LabelSequence::extend(const LabelSequence& labels,
  321. uint8_t buf[MAX_SERIALIZED_LENGTH])
  322. {
  323. // collect data to perform steps before anything is changed
  324. size_t label_count = last_label_ + 1;
  325. // Since we may have been stripped, do not use getDataLength(), but
  326. // calculate actual data size this labelsequence currently uses
  327. size_t data_pos = offsets_[last_label_] + data_[offsets_[last_label_]] + 1;
  328. // If this labelsequence is absolute, virtually strip the root label.
  329. if (isAbsolute()) {
  330. data_pos--;
  331. label_count--;
  332. }
  333. const size_t append_label_count = labels.getLabelCount();
  334. size_t data_len;
  335. const uint8_t *data = labels.getData(&data_len);
  336. // Sanity checks
  337. if (data_ != buf || offsets_ != &buf[Name::MAX_WIRE]) {
  338. isc_throw(BadValue,
  339. "extend() called with unrelated buffer");
  340. }
  341. if (data_pos + data_len > Name::MAX_WIRE) {
  342. isc_throw(BadValue,
  343. "extend() would exceed maximum wire length");
  344. }
  345. if (label_count + append_label_count > Name::MAX_LABELS) {
  346. isc_throw(BadValue,
  347. "extend() would exceed maximum number of labels");
  348. }
  349. // All seems to be reasonably ok, let's proceed.
  350. std::memmove(&buf[data_pos], data, data_len);
  351. for (size_t i = 0; i < append_label_count; ++i) {
  352. buf[Name::MAX_WIRE + label_count + i] =
  353. data_pos +
  354. labels.offsets_[i + labels.first_label_] -
  355. labels.offsets_[labels.first_label_];
  356. }
  357. last_label_ = label_count + append_label_count - 1;
  358. }
  359. std::ostream&
  360. operator<<(std::ostream& os, const LabelSequence& label_sequence) {
  361. os << label_sequence.toText();
  362. return (os);
  363. }
  364. } // end namespace dns
  365. } // end namespace isc