LookupServer.cpp 9.7 KB

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