summaryrefslogtreecommitdiff
path: root/Userland/Services/LookupServer/ClientConnection.cpp
blob: 273ca96873fba5613f11e1de2296e27feb7486d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
 * Copyright (c) 2021, Sergey Bugaev <bugaevc@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "ClientConnection.h"
#include "DNSPacket.h"
#include "LookupServer.h"
#include <AK/IPv4Address.h>

namespace LookupServer {

static HashMap<int, RefPtr<ClientConnection>> s_connections;

ClientConnection::ClientConnection(NonnullOwnPtr<Core::Stream::LocalSocket> socket, int client_id)
    : IPC::ClientConnection<LookupClientEndpoint, LookupServerEndpoint>(*this, move(socket), client_id)
{
    s_connections.set(client_id, *this);
}

ClientConnection::~ClientConnection()
{
}

void ClientConnection::die()
{
    s_connections.remove(client_id());
}

Messages::LookupServer::LookupNameResponse ClientConnection::lookup_name(String const& name)
{
    auto maybe_answers = LookupServer::the().lookup(name, DNSRecordType::A);
    if (maybe_answers.is_error()) {
        dbgln("LookupServer: Failed to lookup PTR record: {}", maybe_answers.error());
    }

    auto answers = maybe_answers.release_value();
    Vector<String> addresses;
    for (auto& answer : answers) {
        addresses.append(answer.record_data());
    }
    return { 0, move(addresses) };
}

Messages::LookupServer::LookupAddressResponse ClientConnection::lookup_address(String const& address)
{
    if (address.length() != 4)
        return { 1, String() };
    IPv4Address ip_address { (const u8*)address.characters() };
    auto name = String::formatted("{}.{}.{}.{}.in-addr.arpa",
        ip_address[3],
        ip_address[2],
        ip_address[1],
        ip_address[0]);

    auto maybe_answers = LookupServer::the().lookup(name, DNSRecordType::PTR);
    if (maybe_answers.is_error()) {
        dbgln("LookupServer: Failed to lookup PTR record: {}", maybe_answers.error());
    }

    auto answers = maybe_answers.release_value();
    if (answers.is_empty())
        return { 1, String() };
    return { 0, answers[0].record_data() };
}
}