LookupServer.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /*
  2. * Copyright (c) 2018-2020, 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 "DNSRequest.h"
  28. #include "DNSResponse.h"
  29. #include <AK/ByteBuffer.h>
  30. #include <AK/HashMap.h>
  31. #include <AK/String.h>
  32. #include <AK/StringBuilder.h>
  33. #include <LibCore/ConfigFile.h>
  34. #include <LibCore/File.h>
  35. #include <LibCore/LocalServer.h>
  36. #include <LibCore/LocalSocket.h>
  37. #include <LibCore/UDPSocket.h>
  38. #include <stdio.h>
  39. #include <sys/time.h>
  40. #include <unistd.h>
  41. LookupServer::LookupServer()
  42. {
  43. auto config = Core::ConfigFile::get_for_system("LookupServer");
  44. dbgln("Using network config file at {}", config->file_name());
  45. m_nameservers = config->read_entry("DNS", "Nameservers", "1.1.1.1,1.0.0.1").split(',');
  46. load_etc_hosts();
  47. m_local_server = Core::LocalServer::construct(this);
  48. m_local_server->on_ready_to_accept = [this]() {
  49. auto socket = m_local_server->accept();
  50. socket->on_ready_to_read = [this, socket]() {
  51. service_client(socket);
  52. RefPtr<Core::LocalSocket> keeper = socket;
  53. const_cast<Core::LocalSocket&>(*socket).on_ready_to_read = [] {};
  54. };
  55. };
  56. bool ok = m_local_server->take_over_from_system_server();
  57. ASSERT(ok);
  58. }
  59. void LookupServer::load_etc_hosts()
  60. {
  61. auto file = Core::File::construct("/etc/hosts");
  62. if (!file->open(Core::IODevice::ReadOnly))
  63. return;
  64. while (!file->eof()) {
  65. auto line = file->read_line(1024);
  66. if (line.is_empty())
  67. break;
  68. auto str_line = String((const char*)line.data(), line.size() - 1, Chomp);
  69. auto fields = str_line.split('\t');
  70. auto sections = fields[0].split('.');
  71. IPv4Address addr {
  72. (u8)atoi(sections[0].characters()),
  73. (u8)atoi(sections[1].characters()),
  74. (u8)atoi(sections[2].characters()),
  75. (u8)atoi(sections[3].characters()),
  76. };
  77. auto name = fields[1];
  78. m_etc_hosts.set(name, addr.to_string());
  79. IPv4Address reverse_addr {
  80. (u8)atoi(sections[3].characters()),
  81. (u8)atoi(sections[2].characters()),
  82. (u8)atoi(sections[1].characters()),
  83. (u8)atoi(sections[0].characters()),
  84. };
  85. StringBuilder builder;
  86. builder.append(reverse_addr.to_string());
  87. builder.append(".in-addr.arpa");
  88. m_etc_hosts.set(builder.to_string(), name);
  89. }
  90. }
  91. void LookupServer::service_client(RefPtr<Core::LocalSocket> socket)
  92. {
  93. u8 client_buffer[1024];
  94. int nrecv = socket->read(client_buffer, sizeof(client_buffer) - 1);
  95. if (nrecv < 0) {
  96. perror("read");
  97. return;
  98. }
  99. client_buffer[nrecv] = '\0';
  100. char lookup_type = client_buffer[0];
  101. if (lookup_type != 'L' && lookup_type != 'R') {
  102. dbgln("Invalid lookup_type '{}'", lookup_type);
  103. return;
  104. }
  105. auto hostname = String((const char*)client_buffer + 1, nrecv - 1, Chomp);
  106. dbgln("Got request for '{}'", hostname);
  107. Vector<String> responses;
  108. if (auto known_host = m_etc_hosts.get(hostname); known_host.has_value()) {
  109. responses.append(known_host.value());
  110. } else if (!hostname.is_empty()) {
  111. for (auto& nameserver : m_nameservers) {
  112. dbgln("Doing lookup using nameserver '{}'", nameserver);
  113. bool did_get_response = false;
  114. int retries = 3;
  115. do {
  116. if (lookup_type == 'L')
  117. responses = lookup(hostname, nameserver, did_get_response, T_A);
  118. else if (lookup_type == 'R')
  119. responses = lookup(hostname, nameserver, did_get_response, T_PTR);
  120. if (did_get_response)
  121. break;
  122. } while (--retries);
  123. if (!responses.is_empty()) {
  124. break;
  125. } else {
  126. if (!did_get_response)
  127. dbgln("Never got a response from '{}', trying next nameserver", nameserver);
  128. else
  129. dbgln("Received response from '{}' but no result(s), trying next nameserver", nameserver);
  130. }
  131. }
  132. if (responses.is_empty()) {
  133. fprintf(stderr, "LookupServer: Tried all nameservers but never got a response :(\n");
  134. return;
  135. }
  136. }
  137. if (responses.is_empty()) {
  138. int nsent = socket->write("Not found.\n");
  139. if (nsent < 0)
  140. perror("write");
  141. return;
  142. }
  143. for (auto& response : responses) {
  144. auto line = String::format("%s\n", response.characters());
  145. int nsent = socket->write(line);
  146. if (nsent < 0) {
  147. perror("write");
  148. break;
  149. }
  150. }
  151. }
  152. Vector<String> LookupServer::lookup(const String& hostname, const String& nameserver, bool& did_get_response, unsigned short record_type, ShouldRandomizeCase should_randomize_case)
  153. {
  154. if (auto it = m_lookup_cache.find(hostname); it != m_lookup_cache.end()) {
  155. auto& cached_lookup = it->value;
  156. if (cached_lookup.question.record_type() == record_type) {
  157. Vector<String> responses;
  158. for (auto& cached_answer : cached_lookup.answers) {
  159. dbgln("Cache hit: {} -> {}, expired: {}", hostname, cached_answer.record_data(), cached_answer.has_expired());
  160. if (!cached_answer.has_expired())
  161. responses.append(cached_answer.record_data());
  162. }
  163. if (!responses.is_empty())
  164. return responses;
  165. }
  166. m_lookup_cache.remove(it);
  167. }
  168. DNSRequest request;
  169. request.add_question(hostname, record_type, should_randomize_case);
  170. auto buffer = request.to_byte_buffer();
  171. auto udp_socket = Core::UDPSocket::construct();
  172. udp_socket->set_blocking(true);
  173. struct timeval timeout {
  174. 1, 0
  175. };
  176. int rc = setsockopt(udp_socket->fd(), SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
  177. if (rc < 0) {
  178. perror("setsockopt(SOL_SOCKET, SO_RCVTIMEO)");
  179. return {};
  180. }
  181. if (!udp_socket->connect(nameserver, 53))
  182. return {};
  183. if (!udp_socket->write(buffer))
  184. return {};
  185. u8 response_buffer[4096];
  186. int nrecv = udp_socket->read(response_buffer, sizeof(response_buffer));
  187. if (nrecv == 0)
  188. return {};
  189. did_get_response = true;
  190. auto o_response = DNSResponse::from_raw_response(response_buffer, nrecv);
  191. if (!o_response.has_value())
  192. return {};
  193. auto& response = o_response.value();
  194. if (response.id() != request.id()) {
  195. dbgln("LookupServer: ID mismatch ({} vs {}) :(", response.id(), request.id());
  196. return {};
  197. }
  198. if (response.code() == DNSResponse::Code::REFUSED) {
  199. if (should_randomize_case == ShouldRandomizeCase::Yes) {
  200. // Retry with 0x20 case randomization turned off.
  201. return lookup(hostname, nameserver, did_get_response, record_type, ShouldRandomizeCase::No);
  202. }
  203. return {};
  204. }
  205. if (response.question_count() != request.question_count()) {
  206. dbgln("LookupServer: Question count ({} vs {}) :(", response.question_count(), request.question_count());
  207. return {};
  208. }
  209. for (size_t i = 0; i < request.question_count(); ++i) {
  210. auto& request_question = request.questions()[i];
  211. auto& response_question = response.questions()[i];
  212. if (request_question != response_question) {
  213. dbgln("Request and response questions do not match");
  214. dbgln(" Request: name=_{}_, type={}, class={}", request_question.name(), response_question.record_type(), response_question.class_code());
  215. dbgln(" Response: name=_{}_, type={}, class={}", response_question.name(), response_question.record_type(), response_question.class_code());
  216. return {};
  217. }
  218. }
  219. if (response.answer_count() < 1) {
  220. dbgln("LookupServer: Not enough answers ({}) :(", response.answer_count());
  221. return {};
  222. }
  223. Vector<String, 8> responses;
  224. Vector<DNSAnswer, 8> cacheable_answers;
  225. for (auto& answer : response.answers()) {
  226. if (answer.type() != T_A)
  227. continue;
  228. responses.append(answer.record_data());
  229. if (!answer.has_expired())
  230. cacheable_answers.append(answer);
  231. }
  232. if (!cacheable_answers.is_empty()) {
  233. if (m_lookup_cache.size() >= 256)
  234. m_lookup_cache.remove(m_lookup_cache.begin());
  235. m_lookup_cache.set(hostname, { request.questions()[0], move(cacheable_answers) });
  236. }
  237. return responses;
  238. }