Name.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Sergey Bugaev <bugaevc@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "Name.h"
  8. #include <AK/Random.h>
  9. #include <AK/Stream.h>
  10. #include <AK/Vector.h>
  11. #include <ctype.h>
  12. namespace DNS {
  13. Name::Name(DeprecatedString const& name)
  14. {
  15. if (name.ends_with('.'))
  16. m_name = name.substring(0, name.length() - 1);
  17. else
  18. m_name = name;
  19. }
  20. Name Name::parse(u8 const* data, size_t& offset, size_t max_offset, size_t recursion_level)
  21. {
  22. if (recursion_level > 4)
  23. return {};
  24. StringBuilder builder;
  25. while (true) {
  26. if (offset >= max_offset)
  27. return {};
  28. u8 b = data[offset++];
  29. if (b == '\0') {
  30. // This terminates the name.
  31. return builder.to_deprecated_string();
  32. } else if ((b & 0xc0) == 0xc0) {
  33. // The two bytes tell us the offset when to continue from.
  34. if (offset >= max_offset)
  35. return {};
  36. size_t dummy = (b & 0x3f) << 8 | data[offset++];
  37. auto rest_of_name = parse(data, dummy, max_offset, recursion_level + 1);
  38. builder.append(rest_of_name.as_string());
  39. return builder.to_deprecated_string();
  40. } else {
  41. // This is the length of a part.
  42. if (offset + b >= max_offset)
  43. return {};
  44. builder.append((char const*)&data[offset], (size_t)b);
  45. builder.append('.');
  46. offset += b;
  47. }
  48. }
  49. }
  50. size_t Name::serialized_size() const
  51. {
  52. if (m_name.is_empty())
  53. return 1;
  54. return m_name.length() + 2;
  55. }
  56. void Name::randomize_case()
  57. {
  58. StringBuilder builder;
  59. for (char c : m_name) {
  60. // Randomize the 0x20 bit in every ASCII character.
  61. if (isalpha(c)) {
  62. if (get_random_uniform(2))
  63. c |= 0x20;
  64. else
  65. c &= ~0x20;
  66. }
  67. builder.append(c);
  68. }
  69. m_name = builder.to_deprecated_string();
  70. }
  71. ErrorOr<void> Name::write_to_stream(Stream& stream) const
  72. {
  73. auto parts = as_string().split_view('.');
  74. for (auto& part : parts) {
  75. TRY(stream.write_value<u8>(part.length()));
  76. TRY(stream.write_until_depleted(part.bytes()));
  77. }
  78. TRY(stream.write_value('\0'));
  79. return {};
  80. }
  81. unsigned Name::Traits::hash(Name const& name)
  82. {
  83. return CaseInsensitiveStringTraits::hash(name.as_string());
  84. }
  85. bool Name::Traits::equals(Name const& a, Name const& b)
  86. {
  87. return CaseInsensitiveStringTraits::equals(a.as_string(), b.as_string());
  88. }
  89. }