LookupServer.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "LookupServer.h"
  27. #include "ClientConnection.h"
  28. #include "DNSRequest.h"
  29. #include "DNSResponse.h"
  30. #include <AK/ByteBuffer.h>
  31. #include <AK/Debug.h>
  32. #include <AK/HashMap.h>
  33. #include <AK/String.h>
  34. #include <AK/StringBuilder.h>
  35. #include <LibCore/ConfigFile.h>
  36. #include <LibCore/File.h>
  37. #include <LibCore/LocalServer.h>
  38. #include <LibCore/LocalSocket.h>
  39. #include <LibCore/UDPSocket.h>
  40. #include <stdio.h>
  41. #include <sys/time.h>
  42. #include <unistd.h>
  43. namespace LookupServer {
  44. static LookupServer* s_the;
  45. LookupServer& LookupServer::the()
  46. {
  47. ASSERT(s_the);
  48. return *s_the;
  49. }
  50. LookupServer::LookupServer()
  51. {
  52. ASSERT(s_the == nullptr);
  53. s_the = this;
  54. auto config = Core::ConfigFile::get_for_system("LookupServer");
  55. dbgln("Using network config file at {}", config->file_name());
  56. m_nameservers = config->read_entry("DNS", "Nameservers", "1.1.1.1,1.0.0.1").split(',');
  57. load_etc_hosts();
  58. m_local_server = Core::LocalServer::construct(this);
  59. m_local_server->on_ready_to_accept = [this]() {
  60. auto socket = m_local_server->accept();
  61. if (!socket) {
  62. dbgln("Failed to accept a client connection");
  63. return;
  64. }
  65. static int s_next_client_id = 0;
  66. int client_id = ++s_next_client_id;
  67. IPC::new_client_connection<ClientConnection>(socket.release_nonnull(), client_id);
  68. };
  69. bool ok = m_local_server->take_over_from_system_server();
  70. ASSERT(ok);
  71. }
  72. void LookupServer::load_etc_hosts()
  73. {
  74. auto file = Core::File::construct("/etc/hosts");
  75. if (!file->open(Core::IODevice::ReadOnly))
  76. return;
  77. while (!file->eof()) {
  78. auto line = file->read_line(1024);
  79. if (line.is_empty())
  80. break;
  81. auto fields = line.split('\t');
  82. auto sections = fields[0].split('.');
  83. IPv4Address addr {
  84. (u8)atoi(sections[0].characters()),
  85. (u8)atoi(sections[1].characters()),
  86. (u8)atoi(sections[2].characters()),
  87. (u8)atoi(sections[3].characters()),
  88. };
  89. auto raw_addr = addr.to_in_addr_t();
  90. auto name = fields[1];
  91. m_etc_hosts.set(name, String { (const char*)&raw_addr, sizeof(raw_addr) });
  92. IPv4Address reverse_addr {
  93. (u8)atoi(sections[3].characters()),
  94. (u8)atoi(sections[2].characters()),
  95. (u8)atoi(sections[1].characters()),
  96. (u8)atoi(sections[0].characters()),
  97. };
  98. StringBuilder builder;
  99. builder.append(reverse_addr.to_string());
  100. builder.append(".in-addr.arpa");
  101. m_etc_hosts.set(builder.to_string(), name);
  102. }
  103. }
  104. Vector<String> LookupServer::lookup(const String& name, unsigned short record_type)
  105. {
  106. #if LOOKUPSERVER_DEBUG
  107. dbgln("Got request for '{}'", name);
  108. #endif
  109. Vector<String> responses;
  110. if (auto known_host = m_etc_hosts.get(name); known_host.has_value()) {
  111. responses.append(known_host.value());
  112. } else if (!name.is_empty()) {
  113. for (auto& nameserver : m_nameservers) {
  114. #if LOOKUPSERVER_DEBUG
  115. dbgln("Doing lookup using nameserver '{}'", nameserver);
  116. #endif
  117. bool did_get_response = false;
  118. int retries = 3;
  119. do {
  120. responses = lookup(name, nameserver, did_get_response, record_type);
  121. if (did_get_response)
  122. break;
  123. } while (--retries);
  124. if (!responses.is_empty()) {
  125. break;
  126. } else {
  127. if (!did_get_response)
  128. dbgln("Never got a response from '{}', trying next nameserver", nameserver);
  129. else
  130. dbgln("Received response from '{}' but no result(s), trying next nameserver", nameserver);
  131. }
  132. }
  133. if (responses.is_empty()) {
  134. fprintf(stderr, "LookupServer: Tried all nameservers but never got a response :(\n");
  135. return {};
  136. }
  137. }
  138. return move(responses);
  139. }
  140. Vector<String> LookupServer::lookup(const String& hostname, const String& nameserver, bool& did_get_response, unsigned short record_type, ShouldRandomizeCase should_randomize_case)
  141. {
  142. if (auto it = m_lookup_cache.find(hostname); it != m_lookup_cache.end()) {
  143. auto& cached_lookup = it->value;
  144. if (cached_lookup.question.record_type() == record_type) {
  145. Vector<String> responses;
  146. for (auto& cached_answer : cached_lookup.answers) {
  147. #if LOOKUPSERVER_DEBUG
  148. dbgln("Cache hit: {} -> {}, expired: {}", hostname, cached_answer.record_data(), cached_answer.has_expired());
  149. #endif
  150. if (!cached_answer.has_expired())
  151. responses.append(cached_answer.record_data());
  152. }
  153. if (!responses.is_empty())
  154. return responses;
  155. }
  156. m_lookup_cache.remove(it);
  157. }
  158. DNSRequest request;
  159. request.add_question(hostname, record_type, should_randomize_case);
  160. auto buffer = request.to_byte_buffer();
  161. auto udp_socket = Core::UDPSocket::construct();
  162. udp_socket->set_blocking(true);
  163. struct timeval timeout {
  164. 1, 0
  165. };
  166. int rc = setsockopt(udp_socket->fd(), SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
  167. if (rc < 0) {
  168. perror("setsockopt(SOL_SOCKET, SO_RCVTIMEO)");
  169. return {};
  170. }
  171. if (!udp_socket->connect(nameserver, 53))
  172. return {};
  173. if (!udp_socket->write(buffer))
  174. return {};
  175. u8 response_buffer[4096];
  176. int nrecv = udp_socket->read(response_buffer, sizeof(response_buffer));
  177. if (nrecv == 0)
  178. return {};
  179. did_get_response = true;
  180. auto o_response = DNSResponse::from_raw_response(response_buffer, nrecv);
  181. if (!o_response.has_value())
  182. return {};
  183. auto& response = o_response.value();
  184. if (response.id() != request.id()) {
  185. dbgln("LookupServer: ID mismatch ({} vs {}) :(", response.id(), request.id());
  186. return {};
  187. }
  188. if (response.code() == DNSResponse::Code::REFUSED) {
  189. if (should_randomize_case == ShouldRandomizeCase::Yes) {
  190. // Retry with 0x20 case randomization turned off.
  191. return lookup(hostname, nameserver, did_get_response, record_type, ShouldRandomizeCase::No);
  192. }
  193. return {};
  194. }
  195. if (response.question_count() != request.question_count()) {
  196. dbgln("LookupServer: Question count ({} vs {}) :(", response.question_count(), request.question_count());
  197. return {};
  198. }
  199. for (size_t i = 0; i < request.question_count(); ++i) {
  200. auto& request_question = request.questions()[i];
  201. auto& response_question = response.questions()[i];
  202. if (request_question != response_question) {
  203. dbgln("Request and response questions do not match");
  204. dbgln(" Request: name=_{}_, type={}, class={}", request_question.name(), response_question.record_type(), response_question.class_code());
  205. dbgln(" Response: name=_{}_, type={}, class={}", response_question.name(), response_question.record_type(), response_question.class_code());
  206. return {};
  207. }
  208. }
  209. if (response.answer_count() < 1) {
  210. dbgln("LookupServer: Not enough answers ({}) :(", response.answer_count());
  211. return {};
  212. }
  213. Vector<String, 8> responses;
  214. Vector<DNSAnswer, 8> cacheable_answers;
  215. for (auto& answer : response.answers()) {
  216. if (answer.type() != record_type)
  217. continue;
  218. responses.append(answer.record_data());
  219. if (!answer.has_expired())
  220. cacheable_answers.append(answer);
  221. }
  222. if (!cacheable_answers.is_empty()) {
  223. if (m_lookup_cache.size() >= 256)
  224. m_lookup_cache.remove(m_lookup_cache.begin());
  225. m_lookup_cache.set(hostname, { request.questions()[0], move(cacheable_answers) });
  226. }
  227. return responses;
  228. }
  229. }