1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 03:17:35 +00:00

Services: Move to Userland/Services/

This commit is contained in:
Andreas Kling 2021-01-12 12:23:01 +01:00
parent 4055b03291
commit c7ac7e6eaf
170 changed files with 4 additions and 4 deletions

View file

@ -0,0 +1,10 @@
set(SOURCES
DNSAnswer.cpp
DNSRequest.cpp
DNSResponse.cpp
LookupServer.cpp
main.cpp
)
serenity_bin(LookupServer)
target_link_libraries(LookupServer LibCore)

View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "DNSAnswer.h"
#include <time.h>
DNSAnswer::DNSAnswer(const String& name, u16 type, u16 class_code, u32 ttl, const String& record_data)
: m_name(name)
, m_type(type)
, m_class_code(class_code)
, m_ttl(ttl)
, m_record_data(record_data)
{
auto now = time(nullptr);
m_expiration_time = now + m_ttl;
if (m_expiration_time < now)
m_expiration_time = 0;
}
bool DNSAnswer::has_expired() const
{
return time(nullptr) >= m_expiration_time;
}

View file

@ -0,0 +1,51 @@
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <AK/String.h>
#include <AK/Types.h>
class DNSAnswer {
public:
DNSAnswer(const String& name, u16 type, u16 class_code, u32 ttl, const String& record_data);
const String& name() const { return m_name; }
u16 type() const { return m_type; }
u16 class_code() const { return m_class_code; }
u32 ttl() const { return m_ttl; }
const String& record_data() const { return m_record_data; }
bool has_expired() const;
private:
String m_name;
u16 m_type { 0 };
u16 m_class_code { 0 };
u32 m_ttl { 0 };
time_t m_expiration_time { 0 };
String m_record_data;
};

View file

@ -0,0 +1,115 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <AK/Endian.h>
#include <AK/Types.h>
class [[gnu::packed]] DNSPacket {
public:
DNSPacket()
: m_recursion_desired(false)
, m_truncated(false)
, m_authoritative_answer(false)
, m_opcode(0)
, m_query_or_response(false)
, m_response_code(0)
, m_checking_disabled(false)
, m_authenticated_data(false)
, m_zero(false)
, m_recursion_available(false)
{
}
u16 id() const { return m_id; }
void set_id(u16 w) { m_id = w; }
bool recursion_desired() const { return m_recursion_desired; }
void set_recursion_desired(bool b) { m_recursion_desired = b; }
bool is_truncated() const { return m_truncated; }
void set_truncated(bool b) { m_truncated = b; }
bool is_authoritative_answer() const { return m_authoritative_answer; }
void set_authoritative_answer(bool b) { m_authoritative_answer = b; }
u8 opcode() const { return m_opcode; }
void set_opcode(u8 b) { m_opcode = b; }
bool is_query() const { return !m_query_or_response; }
bool is_response() const { return m_query_or_response; }
void set_is_query() { m_query_or_response = false; }
void set_is_response() { m_query_or_response = true; }
u8 response_code() const { return m_response_code; }
void set_response_code(u8 b) { m_response_code = b; }
bool checking_disabled() const { return m_checking_disabled; }
void set_checking_disabled(bool b) { m_checking_disabled = b; }
bool is_authenticated_data() const { return m_authenticated_data; }
void set_authenticated_data(bool b) { m_authenticated_data = b; }
bool is_recursion_available() const { return m_recursion_available; }
void set_recursion_available(bool b) { m_recursion_available = b; }
u16 question_count() const { return m_question_count; }
void set_question_count(u16 w) { m_question_count = w; }
u16 answer_count() const { return m_answer_count; }
void set_answer_count(u16 w) { m_answer_count = w; }
u16 authority_count() const { return m_authority_count; }
void set_authority_count(u16 w) { m_authority_count = w; }
u16 additional_count() const { return m_additional_count; }
void set_additional_count(u16 w) { m_additional_count = w; }
void* payload() { return this + 1; }
const void* payload() const { return this + 1; }
private:
NetworkOrdered<u16> m_id;
bool m_recursion_desired : 1;
bool m_truncated : 1;
bool m_authoritative_answer : 1;
u8 m_opcode : 4;
bool m_query_or_response : 1;
u8 m_response_code : 4;
bool m_checking_disabled : 1;
bool m_authenticated_data : 1;
bool m_zero : 1;
bool m_recursion_available : 1;
NetworkOrdered<u16> m_question_count;
NetworkOrdered<u16> m_answer_count;
NetworkOrdered<u16> m_authority_count;
NetworkOrdered<u16> m_additional_count;
};
static_assert(sizeof(DNSPacket) == 12);

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <AK/String.h>
#include <AK/Types.h>
class DNSQuestion {
public:
DNSQuestion(const String& name, u16 record_type, u16 class_code)
: m_name(name)
, m_record_type(record_type)
, m_class_code(class_code)
{
}
u16 record_type() const { return m_record_type; }
u16 class_code() const { return m_class_code; }
const String& name() const { return m_name; }
bool operator==(const DNSQuestion& other) const
{
return m_name == other.m_name && m_record_type == other.m_record_type && m_class_code == other.m_class_code;
}
bool operator!=(const DNSQuestion& other) const
{
return !(*this == other);
}
private:
String m_name;
u16 m_record_type { 0 };
u16 m_class_code { 0 };
};

View file

@ -0,0 +1,96 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "DNSRequest.h"
#include "DNSPacket.h"
#include <AK/MemoryStream.h>
#include <AK/StringBuilder.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <stdlib.h>
const u16 C_IN = 1;
DNSRequest::DNSRequest()
: m_id(arc4random_uniform(UINT16_MAX))
{
}
void DNSRequest::add_question(const String& name, u16 record_type, ShouldRandomizeCase should_randomize_case)
{
ASSERT(m_questions.size() <= UINT16_MAX);
if (name.is_empty())
return;
StringBuilder builder;
for (size_t i = 0; i < name.length(); ++i) {
u8 ch = name[i];
if (should_randomize_case == ShouldRandomizeCase::Yes) {
// Randomize the 0x20 bit in every ASCII character.
if (isalpha(ch)) {
if (arc4random_uniform(2))
ch |= 0x20;
else
ch &= ~0x20;
}
}
builder.append(ch);
}
if (name[name.length() - 1] != '.')
builder.append('.');
m_questions.empend(builder.to_string(), record_type, C_IN);
}
ByteBuffer DNSRequest::to_byte_buffer() const
{
DNSPacket request_header;
request_header.set_id(m_id);
request_header.set_is_query();
request_header.set_opcode(0);
request_header.set_truncated(false);
request_header.set_recursion_desired(true);
request_header.set_question_count(m_questions.size());
DuplexMemoryStream stream;
stream << ReadonlyBytes { &request_header, sizeof(request_header) };
for (auto& question : m_questions) {
auto parts = question.name().split('.');
for (auto& part : parts) {
stream << (u8)part.length();
stream << part.bytes();
}
stream << '\0';
stream << htons(question.record_type());
stream << htons(question.class_code());
}
return stream.copy_into_contiguous_buffer();
}

View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "DNSQuestion.h"
#include <AK/Types.h>
#include <AK/Vector.h>
#define T_A 1
#define T_NS 2
#define T_CNAME 5
#define T_SOA 6
#define T_PTR 12
#define T_MX 15
enum class ShouldRandomizeCase {
No = 0,
Yes
};
class DNSRequest {
public:
DNSRequest();
void add_question(const String& name, u16 record_type, ShouldRandomizeCase);
const Vector<DNSQuestion>& questions() const { return m_questions; }
u16 question_count() const
{
ASSERT(m_questions.size() < UINT16_MAX);
return m_questions.size();
}
u16 id() const { return m_id; }
ByteBuffer to_byte_buffer() const;
private:
u16 m_id { 0 };
Vector<DNSQuestion> m_questions;
};

View file

@ -0,0 +1,152 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "DNSResponse.h"
#include "DNSPacket.h"
#include "DNSRequest.h"
#include <AK/IPv4Address.h>
#include <AK/StringBuilder.h>
static String parse_dns_name(const u8* data, size_t& offset, size_t max_offset, size_t recursion_level = 0);
class [[gnu::packed]] DNSRecordWithoutName {
public:
DNSRecordWithoutName() { }
u16 type() const { return m_type; }
u16 record_class() const { return m_class; }
u32 ttl() const { return m_ttl; }
u16 data_length() const { return m_data_length; }
void* data() { return this + 1; }
const void* data() const { return this + 1; }
private:
NetworkOrdered<u16> m_type;
NetworkOrdered<u16> m_class;
NetworkOrdered<u32> m_ttl;
NetworkOrdered<u16> m_data_length;
};
static_assert(sizeof(DNSRecordWithoutName) == 10);
Optional<DNSResponse> DNSResponse::from_raw_response(const u8* raw_data, size_t raw_size)
{
if (raw_size < sizeof(DNSPacket)) {
dbgln("DNS response not large enough ({} out of {}) to be a DNS packet.", raw_size, sizeof(DNSPacket));
return {};
}
auto& response_header = *(const DNSPacket*)(raw_data);
#ifdef LOOKUPSERVER_DEBUG
dbgln("Got response (ID: {})", response_header.id());
dbgln(" Question count: {}", response_header.question_count());
dbgln(" Answer count: {}", response_header.answer_count());
dbgln(" Authority count: {}", response_header.authority_count());
dbgln("Additional count: {}", response_header.additional_count());
#endif
DNSResponse response;
response.m_id = response_header.id();
response.m_code = response_header.response_code();
if (response.code() != DNSResponse::Code::NOERROR)
return response;
size_t offset = sizeof(DNSPacket);
for (u16 i = 0; i < response_header.question_count(); ++i) {
auto name = parse_dns_name(raw_data, offset, raw_size);
struct RawDNSAnswerQuestion {
NetworkOrdered<u16> record_type;
NetworkOrdered<u16> class_code;
};
auto& record_and_class = *(const RawDNSAnswerQuestion*)&raw_data[offset];
response.m_questions.empend(name, record_and_class.record_type, record_and_class.class_code);
offset += 4;
#ifdef LOOKUPSERVER_DEBUG
auto& question = response.m_questions.last();
dbgln("Question #{}: name=_{}_, type={}, class={}", i, question.name(), question.record_type(), question.class_code());
#endif
}
for (u16 i = 0; i < response_header.answer_count(); ++i) {
auto name = parse_dns_name(raw_data, offset, raw_size);
auto& record = *(const DNSRecordWithoutName*)(&raw_data[offset]);
String data;
offset += sizeof(DNSRecordWithoutName);
if (record.type() == T_PTR) {
size_t dummy_offset = offset;
data = parse_dns_name(raw_data, dummy_offset, raw_size);
} else if (record.type() == T_A) {
auto ipv4_address = IPv4Address((const u8*)record.data());
data = ipv4_address.to_string();
} else {
// FIXME: Parse some other record types perhaps?
dbgln("data=(unimplemented record type {})", record.type());
}
#ifdef LOOKUPSERVER_DEBUG
dbgln("Answer #{}: name=_{}_, type={}, ttl={}, length={}, data=_{}_", i, name, record.type(), record.ttl(), record.data_length(), data);
#endif
response.m_answers.empend(name, record.type(), record.record_class(), record.ttl(), data);
offset += record.data_length();
}
return response;
}
String parse_dns_name(const u8* data, size_t& offset, size_t max_offset, size_t recursion_level)
{
if (recursion_level > 4)
return {};
Vector<char, 128> buf;
while (offset < max_offset) {
u8 ch = data[offset];
if (ch == '\0') {
++offset;
break;
}
if ((ch & 0xc0) == 0xc0) {
if ((offset + 1) >= max_offset)
return {};
size_t dummy = (ch & 0x3f) << 8 | data[offset + 1];
offset += 2;
StringBuilder builder;
builder.append(buf.data(), buf.size());
auto okay = parse_dns_name(data, dummy, max_offset, recursion_level + 1);
builder.append(okay);
return builder.to_string();
}
for (size_t i = 0; i < ch; ++i)
buf.append(data[offset + i + 1]);
buf.append('.');
offset += ch + 1;
}
return String::copy(buf);
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "DNSAnswer.h"
#include "DNSQuestion.h"
#include <AK/Optional.h>
#include <AK/Types.h>
#include <AK/Vector.h>
class DNSResponse {
public:
static Optional<DNSResponse> from_raw_response(const u8*, size_t);
u16 id() const { return m_id; }
const Vector<DNSQuestion>& questions() const { return m_questions; }
const Vector<DNSAnswer>& answers() const { return m_answers; }
u16 question_count() const
{
ASSERT(m_questions.size() <= UINT16_MAX);
return m_questions.size();
}
u16 answer_count() const
{
ASSERT(m_answers.size() <= UINT16_MAX);
return m_answers.size();
}
enum class Code : u8 {
NOERROR = 0,
FORMERR = 1,
SERVFAIL = 2,
NXDOMAIN = 3,
NOTIMP = 4,
REFUSED = 5,
YXDOMAIN = 6,
XRRSET = 7,
NOTAUTH = 8,
NOTZONE = 9,
};
Code code() const { return (Code)m_code; }
private:
DNSResponse() { }
u16 m_id { 0 };
u8 m_code { 0 };
Vector<DNSQuestion> m_questions;
Vector<DNSAnswer> m_answers;
};

View file

@ -0,0 +1,278 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "LookupServer.h"
#include "DNSRequest.h"
#include "DNSResponse.h"
#include <AK/ByteBuffer.h>
#include <AK/HashMap.h>
#include <AK/String.h>
#include <AK/StringBuilder.h>
#include <LibCore/ConfigFile.h>
#include <LibCore/File.h>
#include <LibCore/LocalServer.h>
#include <LibCore/LocalSocket.h>
#include <LibCore/UDPSocket.h>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
//#define LOOKUPSERVER_DEBUG
LookupServer::LookupServer()
{
auto config = Core::ConfigFile::get_for_system("LookupServer");
dbgln("Using network config file at {}", config->file_name());
m_nameservers = config->read_entry("DNS", "Nameservers", "1.1.1.1,1.0.0.1").split(',');
load_etc_hosts();
m_local_server = Core::LocalServer::construct(this);
m_local_server->on_ready_to_accept = [this]() {
auto socket = m_local_server->accept();
socket->on_ready_to_read = [this, socket]() {
service_client(socket);
RefPtr<Core::LocalSocket> keeper = socket;
const_cast<Core::LocalSocket&>(*socket).on_ready_to_read = [] {};
};
};
bool ok = m_local_server->take_over_from_system_server();
ASSERT(ok);
}
void LookupServer::load_etc_hosts()
{
auto file = Core::File::construct("/etc/hosts");
if (!file->open(Core::IODevice::ReadOnly))
return;
while (!file->eof()) {
auto line = file->read_line(1024);
if (line.is_empty())
break;
auto fields = line.split('\t');
auto sections = fields[0].split('.');
IPv4Address addr {
(u8)atoi(sections[0].characters()),
(u8)atoi(sections[1].characters()),
(u8)atoi(sections[2].characters()),
(u8)atoi(sections[3].characters()),
};
auto name = fields[1];
m_etc_hosts.set(name, addr.to_string());
IPv4Address reverse_addr {
(u8)atoi(sections[3].characters()),
(u8)atoi(sections[2].characters()),
(u8)atoi(sections[1].characters()),
(u8)atoi(sections[0].characters()),
};
StringBuilder builder;
builder.append(reverse_addr.to_string());
builder.append(".in-addr.arpa");
m_etc_hosts.set(builder.to_string(), name);
}
}
void LookupServer::service_client(RefPtr<Core::LocalSocket> socket)
{
u8 client_buffer[1024];
int nrecv = socket->read(client_buffer, sizeof(client_buffer) - 1);
if (nrecv < 0) {
perror("read");
return;
}
client_buffer[nrecv] = '\0';
char lookup_type = client_buffer[0];
if (lookup_type != 'L' && lookup_type != 'R') {
dbgln("Invalid lookup_type '{}'", lookup_type);
return;
}
auto hostname = String((const char*)client_buffer + 1, nrecv - 1, Chomp);
#ifdef LOOKUPSERVER_DEBUG
dbgln("Got request for '{}'", hostname);
#endif
Vector<String> responses;
if (auto known_host = m_etc_hosts.get(hostname); known_host.has_value()) {
responses.append(known_host.value());
} else if (!hostname.is_empty()) {
for (auto& nameserver : m_nameservers) {
#ifdef LOOKUPSERVER_DEBUG
dbgln("Doing lookup using nameserver '{}'", nameserver);
#endif
bool did_get_response = false;
int retries = 3;
do {
if (lookup_type == 'L')
responses = lookup(hostname, nameserver, did_get_response, T_A);
else if (lookup_type == 'R')
responses = lookup(hostname, nameserver, did_get_response, T_PTR);
if (did_get_response)
break;
} while (--retries);
if (!responses.is_empty()) {
break;
} else {
if (!did_get_response)
dbgln("Never got a response from '{}', trying next nameserver", nameserver);
else
dbgln("Received response from '{}' but no result(s), trying next nameserver", nameserver);
}
}
if (responses.is_empty()) {
fprintf(stderr, "LookupServer: Tried all nameservers but never got a response :(\n");
return;
}
}
if (responses.is_empty()) {
int nsent = socket->write("Not found.\n");
if (nsent < 0)
perror("write");
return;
}
for (auto& response : responses) {
auto line = String::format("%s\n", response.characters());
int nsent = socket->write(line);
if (nsent < 0) {
perror("write");
break;
}
}
}
Vector<String> LookupServer::lookup(const String& hostname, const String& nameserver, bool& did_get_response, unsigned short record_type, ShouldRandomizeCase should_randomize_case)
{
if (auto it = m_lookup_cache.find(hostname); it != m_lookup_cache.end()) {
auto& cached_lookup = it->value;
if (cached_lookup.question.record_type() == record_type) {
Vector<String> responses;
for (auto& cached_answer : cached_lookup.answers) {
#ifdef LOOKUPSERVER_DEBUG
dbgln("Cache hit: {} -> {}, expired: {}", hostname, cached_answer.record_data(), cached_answer.has_expired());
#endif
if (!cached_answer.has_expired())
responses.append(cached_answer.record_data());
}
if (!responses.is_empty())
return responses;
}
m_lookup_cache.remove(it);
}
DNSRequest request;
request.add_question(hostname, record_type, should_randomize_case);
auto buffer = request.to_byte_buffer();
auto udp_socket = Core::UDPSocket::construct();
udp_socket->set_blocking(true);
struct timeval timeout {
1, 0
};
int rc = setsockopt(udp_socket->fd(), SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
if (rc < 0) {
perror("setsockopt(SOL_SOCKET, SO_RCVTIMEO)");
return {};
}
if (!udp_socket->connect(nameserver, 53))
return {};
if (!udp_socket->write(buffer))
return {};
u8 response_buffer[4096];
int nrecv = udp_socket->read(response_buffer, sizeof(response_buffer));
if (nrecv == 0)
return {};
did_get_response = true;
auto o_response = DNSResponse::from_raw_response(response_buffer, nrecv);
if (!o_response.has_value())
return {};
auto& response = o_response.value();
if (response.id() != request.id()) {
dbgln("LookupServer: ID mismatch ({} vs {}) :(", response.id(), request.id());
return {};
}
if (response.code() == DNSResponse::Code::REFUSED) {
if (should_randomize_case == ShouldRandomizeCase::Yes) {
// Retry with 0x20 case randomization turned off.
return lookup(hostname, nameserver, did_get_response, record_type, ShouldRandomizeCase::No);
}
return {};
}
if (response.question_count() != request.question_count()) {
dbgln("LookupServer: Question count ({} vs {}) :(", response.question_count(), request.question_count());
return {};
}
for (size_t i = 0; i < request.question_count(); ++i) {
auto& request_question = request.questions()[i];
auto& response_question = response.questions()[i];
if (request_question != response_question) {
dbgln("Request and response questions do not match");
dbgln(" Request: name=_{}_, type={}, class={}", request_question.name(), response_question.record_type(), response_question.class_code());
dbgln(" Response: name=_{}_, type={}, class={}", response_question.name(), response_question.record_type(), response_question.class_code());
return {};
}
}
if (response.answer_count() < 1) {
dbgln("LookupServer: Not enough answers ({}) :(", response.answer_count());
return {};
}
Vector<String, 8> responses;
Vector<DNSAnswer, 8> cacheable_answers;
for (auto& answer : response.answers()) {
if (answer.type() != T_A)
continue;
responses.append(answer.record_data());
if (!answer.has_expired())
cacheable_answers.append(answer);
}
if (!cacheable_answers.is_empty()) {
if (m_lookup_cache.size() >= 256)
m_lookup_cache.remove(m_lookup_cache.begin());
m_lookup_cache.set(hostname, { request.questions()[0], move(cacheable_answers) });
}
return responses;
}

View file

@ -0,0 +1,56 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "DNSRequest.h"
#include "DNSResponse.h"
#include <AK/HashMap.h>
#include <LibCore/Object.h>
class DNSAnswer;
class LookupServer final : public Core::Object {
C_OBJECT(LookupServer)
public:
LookupServer();
private:
void load_etc_hosts();
void service_client(RefPtr<Core::LocalSocket>);
Vector<String> lookup(const String& hostname, const String& nameserver, bool& did_get_response, unsigned short record_type, ShouldRandomizeCase = ShouldRandomizeCase::Yes);
struct CachedLookup {
DNSQuestion question;
Vector<DNSAnswer> answers;
};
RefPtr<Core::LocalServer> m_local_server;
Vector<String> m_nameservers;
HashMap<String, String> m_etc_hosts;
HashMap<String, CachedLookup> m_lookup_cache;
};

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "LookupServer.h"
#include <LibCore/EventLoop.h>
#include <LibCore/LocalServer.h>
#include <stdio.h>
int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv)
{
if (pledge("stdio accept unix inet cpath rpath fattr", nullptr) < 0) {
perror("pledge");
return 1;
}
Core::EventLoop event_loop;
LookupServer server;
if (pledge("stdio accept inet", nullptr) < 0) {
perror("pledge");
return 1;
}
unveil(nullptr, nullptr);
return event_loop.exec();
}