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