labelsequence.cc 13 KB

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