Packet.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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 "Packet.h"
  8. #include "Name.h"
  9. #include "PacketHeader.h"
  10. #include <AK/Debug.h>
  11. #include <AK/MemoryStream.h>
  12. #include <AK/StringBuilder.h>
  13. #include <arpa/inet.h>
  14. namespace DNS {
  15. void Packet::add_question(Question const& question)
  16. {
  17. m_questions.empend(question);
  18. VERIFY(m_questions.size() <= UINT16_MAX);
  19. }
  20. void Packet::add_answer(Answer const& answer)
  21. {
  22. m_answers.empend(answer);
  23. VERIFY(m_answers.size() <= UINT16_MAX);
  24. }
  25. ErrorOr<ByteBuffer> Packet::to_byte_buffer() const
  26. {
  27. PacketHeader header;
  28. header.set_id(m_id);
  29. if (is_query())
  30. header.set_is_query();
  31. else
  32. header.set_is_response();
  33. header.set_authoritative_answer(m_authoritative_answer);
  34. // FIXME: What should this be?
  35. header.set_opcode(0);
  36. header.set_response_code(m_code);
  37. header.set_truncated(false); // hopefully...
  38. header.set_recursion_desired(m_recursion_desired);
  39. // FIXME: what should the be for requests?
  40. header.set_recursion_available(m_recursion_available);
  41. header.set_question_count(m_questions.size());
  42. header.set_answer_count(m_answers.size());
  43. AllocatingMemoryStream stream;
  44. TRY(stream.write_value(header));
  45. for (auto& question : m_questions) {
  46. TRY(stream.write_value(question.name()));
  47. TRY(stream.write_value(htons((u16)question.record_type())));
  48. TRY(stream.write_value(htons(question.raw_class_code())));
  49. }
  50. for (auto& answer : m_answers) {
  51. TRY(stream.write_value(answer.name()));
  52. TRY(stream.write_value(htons((u16)answer.type())));
  53. TRY(stream.write_value(htons(answer.raw_class_code())));
  54. TRY(stream.write_value(htonl(answer.ttl())));
  55. if (answer.type() == RecordType::PTR) {
  56. Name name { answer.record_data() };
  57. TRY(stream.write_value(htons(name.serialized_size())));
  58. TRY(stream.write_value(name));
  59. } else {
  60. TRY(stream.write_value(htons(answer.record_data().length())));
  61. TRY(stream.write_until_depleted(answer.record_data().bytes()));
  62. }
  63. }
  64. auto buffer = TRY(ByteBuffer::create_uninitialized(stream.used_buffer_size()));
  65. TRY(stream.read_until_filled(buffer));
  66. return buffer;
  67. }
  68. class [[gnu::packed]] DNSRecordWithoutName {
  69. public:
  70. DNSRecordWithoutName() = default;
  71. u16 type() const { return m_type; }
  72. u16 record_class() const { return m_class; }
  73. u32 ttl() const { return m_ttl; }
  74. u16 data_length() const { return m_data_length; }
  75. void* data() { return this + 1; }
  76. void const* data() const { return this + 1; }
  77. private:
  78. NetworkOrdered<u16> m_type;
  79. NetworkOrdered<u16> m_class;
  80. NetworkOrdered<u32> m_ttl;
  81. NetworkOrdered<u16> m_data_length;
  82. };
  83. static_assert(sizeof(DNSRecordWithoutName) == 10);
  84. ErrorOr<Packet> Packet::from_raw_packet(ReadonlyBytes bytes)
  85. {
  86. if (bytes.size() < sizeof(PacketHeader)) {
  87. dbgln_if(LOOKUPSERVER_DEBUG, "DNS response not large enough ({} out of {}) to be a DNS packet", bytes.size(), sizeof(PacketHeader));
  88. return Error::from_string_literal("DNS response not large enough to be a DNS packet");
  89. }
  90. auto const& header = *bit_cast<PacketHeader const*>(bytes.data());
  91. dbgln_if(LOOKUPSERVER_DEBUG, "Got packet (ID: {})", header.id());
  92. dbgln_if(LOOKUPSERVER_DEBUG, " Question count: {}", header.question_count());
  93. dbgln_if(LOOKUPSERVER_DEBUG, " Answer count: {}", header.answer_count());
  94. dbgln_if(LOOKUPSERVER_DEBUG, " Authority count: {}", header.authority_count());
  95. dbgln_if(LOOKUPSERVER_DEBUG, "Additional count: {}", header.additional_count());
  96. Packet packet;
  97. packet.m_id = header.id();
  98. packet.m_query_or_response = header.is_response();
  99. packet.m_code = header.response_code();
  100. // FIXME: Should we parse further in this case?
  101. if (packet.code() != Code::NOERROR)
  102. return packet;
  103. size_t offset = sizeof(PacketHeader);
  104. for (u16 i = 0; i < header.question_count(); i++) {
  105. auto name = TRY(Name::parse(bytes, offset));
  106. struct RawDNSAnswerQuestion {
  107. NetworkOrdered<u16> record_type;
  108. NetworkOrdered<u16> class_code;
  109. };
  110. if (offset >= bytes.size() || bytes.size() - offset < sizeof(RawDNSAnswerQuestion))
  111. return Error::from_string_literal("Unexpected EOF when parsing DNS packet");
  112. auto const& record_and_class = *bit_cast<RawDNSAnswerQuestion const*>(bytes.offset_pointer(offset));
  113. u16 class_code = record_and_class.class_code & ~MDNS_WANTS_UNICAST_RESPONSE;
  114. bool mdns_wants_unicast_response = record_and_class.class_code & MDNS_WANTS_UNICAST_RESPONSE;
  115. packet.m_questions.empend(name, (RecordType)(u16)record_and_class.record_type, (RecordClass)class_code, mdns_wants_unicast_response);
  116. offset += 4;
  117. auto& question = packet.m_questions.last();
  118. dbgln_if(LOOKUPSERVER_DEBUG, "Question #{}: name=_{}_, type={}, class={}", i, question.name(), question.record_type(), question.class_code());
  119. }
  120. for (u16 i = 0; i < header.answer_count(); ++i) {
  121. auto name = TRY(Name::parse(bytes, offset));
  122. if (offset >= bytes.size() || bytes.size() - offset < sizeof(DNSRecordWithoutName))
  123. return Error::from_string_literal("Unexpected EOF when parsing DNS packet");
  124. auto const& record = *bit_cast<DNSRecordWithoutName const*>(bytes.offset_pointer(offset));
  125. offset += sizeof(DNSRecordWithoutName);
  126. if (record.data_length() > bytes.size() - offset)
  127. return Error::from_string_literal("Unexpected EOF when parsing DNS packet");
  128. ByteString data;
  129. switch ((RecordType)record.type()) {
  130. case RecordType::PTR: {
  131. size_t dummy_offset = offset;
  132. data = TRY(Name::parse(bytes, dummy_offset)).as_string();
  133. break;
  134. }
  135. case RecordType::CNAME:
  136. // Fall through
  137. case RecordType::A:
  138. // Fall through
  139. case RecordType::TXT:
  140. // Fall through
  141. case RecordType::AAAA:
  142. // Fall through
  143. case RecordType::SRV:
  144. data = ReadonlyBytes { record.data(), record.data_length() };
  145. break;
  146. default:
  147. // FIXME: Parse some other record types perhaps?
  148. dbgln("data=(unimplemented record type {})", (u16)record.type());
  149. }
  150. dbgln_if(LOOKUPSERVER_DEBUG, "Answer #{}: name=_{}_, type={}, ttl={}, length={}, data=_{}_", i, name, record.type(), record.ttl(), record.data_length(), data);
  151. u16 class_code = record.record_class() & ~MDNS_CACHE_FLUSH;
  152. bool mdns_cache_flush = record.record_class() & MDNS_CACHE_FLUSH;
  153. packet.m_answers.empend(name, (RecordType)record.type(), (RecordClass)class_code, record.ttl(), data, mdns_cache_flush);
  154. offset += record.data_length();
  155. }
  156. return packet;
  157. }
  158. }