summaryrefslogtreecommitdiff
path: root/src/network/kernel/qdnslookup_unix.cpp
blob: d2435064ad79281fe9ff3d634c04b15a0677a19a (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// Copyright (C) 2012 Jeremy Lainé <jeremy.laine@m4x.org>
// Copyright (C) 2023 Intel Corporation.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qdnslookup_p.h"

#include <qendian.h>
#include <qscopedpointer.h>
#include <qurl.h>
#include <qvarlengtharray.h>
#include <private/qnativesocketengine_p.h>      // for setSockAddr
#include <private/qtnetwork-config_p.h>

QT_REQUIRE_CONFIG(res_ninit);

#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/nameser.h>
#if __has_include(<arpa/nameser_compat.h>)
#  include <arpa/nameser_compat.h>
#endif
#include <resolv.h>

QT_BEGIN_NAMESPACE

using namespace Qt::StringLiterals;

#if QT_CONFIG(res_setservers)
// https://www.ibm.com/docs/en/i/7.3?topic=ssw_ibm_i_73/apis/ressetservers.html
// https://docs.oracle.com/cd/E86824_01/html/E54774/res-setservers-3resolv.html
static const char *applyNameServer(res_state state, const QHostAddress &nameserver, quint16 port)
{
    if (nameserver.isNull())
        return nullptr;
    union res_sockaddr_union u;
    setSockaddr(reinterpret_cast<sockaddr *>(&u.sin), nameserver, port);
    res_setservers(state, &u, 1);
    return nullptr;
}
#else
template <typename T> void setNsMap(T &ext, std::enable_if_t<sizeof(T::nsmap) != 0, uint16_t> v)
{
    // Set nsmap[] to indicate that nsaddrs[0] is an IPv6 address
    // See: https://sourceware.org/ml/libc-hacker/2002-05/msg00035.html
    // Unneeded since glibc 2.22 (2015), but doesn't hurt to set it
    // See: https://sourceware.org/git/?p=glibc.git;a=commit;h=2212c1420c92a33b0e0bd9a34938c9814a56c0f7
    ext.nsmap[0] = v;
}
template <typename T> void setNsMap(T &, ...)
{
    // fallback
}

template <bool Condition>
using EnableIfIPv6 = std::enable_if_t<Condition, const QHostAddress *>;

template <typename State>
bool setIpv6NameServer(State *state,
                       EnableIfIPv6<sizeof(std::declval<State>()._u._ext.nsaddrs) != 0> addr,
                       quint16 port)
{
    // glibc-like API to set IPv6 name servers
    struct sockaddr_in6 *ns = state->_u._ext.nsaddrs[0];

    // nsaddrs will be NULL if no nameserver is set in /etc/resolv.conf
    if (!ns) {
        // Memory allocated here will be free()'d in res_close() as we
        // have done res_init() above.
        ns = static_cast<struct sockaddr_in6*>(calloc(1, sizeof(struct sockaddr_in6)));
        Q_CHECK_PTR(ns);
        state->_u._ext.nsaddrs[0] = ns;
    }

    setNsMap(state->_u._ext, MAXNS + 1);
    state->_u._ext.nscount6 = 1;
    setSockaddr(ns, *addr, port);
    return true;
}

template <typename State> bool setIpv6NameServer(State *, const void *, quint16)
{
    // fallback
    return false;
}

static const char *applyNameServer(res_state state, const QHostAddress &nameserver, quint16 port)
{
    if (nameserver.isNull())
        return nullptr;

    state->nscount = 1;
    state->nsaddr_list[0].sin_family = AF_UNSPEC;
    if (nameserver.protocol() == QAbstractSocket::IPv6Protocol) {
        if (!setIpv6NameServer(state, &nameserver, port))
            return QDnsLookupPrivate::msgNoIpV6NameServerAdresses;
    } else {
        setSockaddr(&state->nsaddr_list[0], nameserver, port);
    }
    return nullptr;
}
#endif // !QT_CONFIG(res_setservers)

void QDnsLookupRunnable::query(QDnsLookupReply *reply)
{
    // Initialize state.
    std::remove_pointer_t<res_state> state = {};
    if (res_ninit(&state) < 0) {
        reply->error = QDnsLookup::ResolverError;
        reply->errorString = tr("Resolver initialization failed");
        return;
    }
    auto guard = qScopeGuard([&] { res_nclose(&state); });

    //Check if a nameserver was set. If so, use it
    if (const char *msg = applyNameServer(&state, nameserver, DnsPort)) {
        qWarning("%s", msg);
        reply->error = QDnsLookup::ResolverError;
        reply->errorString = tr(msg);
        return;
    }
#ifdef QDNSLOOKUP_DEBUG
    state.options |= RES_DEBUG;
#endif

    // Perform DNS query.
    QVarLengthArray<unsigned char, PACKETSZ> buffer(PACKETSZ);
    std::memset(buffer.data(), 0, buffer.size());
    int responseLength = res_nquery(&state, requestName, C_IN, requestType, buffer.data(), buffer.size());
    if (Q_UNLIKELY(responseLength > PACKETSZ)) {
        buffer.resize(responseLength);
        std::memset(buffer.data(), 0, buffer.size());
        responseLength = res_nquery(&state, requestName, C_IN, requestType, buffer.data(), buffer.size());
        if (Q_UNLIKELY(responseLength > buffer.size())) {
            // Ok, we give up.
            reply->error = QDnsLookup::ResolverError;
            reply->errorString.clear(); // We cannot be more specific, alas.
            return;
        }
    }

    unsigned char *response = buffer.data();
    // Check the response header. Though res_nquery returns -1 as a
    // responseLength in case of error, we still can extract the
    // exact error code from the response.
    HEADER *header = (HEADER*)response;
    switch (header->rcode) {
    case NOERROR:
        break;
    case FORMERR:
        reply->error = QDnsLookup::InvalidRequestError;
        reply->errorString = tr("Server could not process query");
        return;
    case SERVFAIL:
    case NOTIMP:
        reply->error = QDnsLookup::ServerFailureError;
        reply->errorString = tr("Server failure");
        return;
    case NXDOMAIN:
        reply->error = QDnsLookup::NotFoundError;
        reply->errorString = tr("Non existent domain");
        return;
    case REFUSED:
        reply->error = QDnsLookup::ServerRefusedError;
        reply->errorString = tr("Server refused to answer");
        return;
    default:
        reply->error = QDnsLookup::InvalidReplyError;
        reply->errorString = tr("Invalid reply received");
        return;
    }

    // Check the reply is valid.
    if (responseLength < int(sizeof(HEADER))) {
        reply->error = QDnsLookup::InvalidReplyError;
        reply->errorString = tr("Invalid reply received");
        return;
    }

    char host[PACKETSZ], answer[PACKETSZ];
    qptrdiff offset = sizeof(HEADER);
    int status;

    if (ntohs(header->qdcount) == 1) {
        // Skip the query host, type (2 bytes) and class (2 bytes).
        status = dn_expand(response, response + responseLength, response + offset, host, sizeof(host));
        if (status < 0) {
            reply->error = QDnsLookup::InvalidReplyError;
            reply->errorString = tr("Could not expand domain name");
            return;
        }
        if (offset + status + 4 >= responseLength)
            header->qdcount = 0xffff;   // invalid reply below
        else
            offset += status + 4;
    }
    if (ntohs(header->qdcount) > 1) {
        reply->error = QDnsLookup::InvalidReplyError;
        reply->errorString = tr("Invalid reply received");
        return;
    }

    // Extract results.
    const int answerCount = ntohs(header->ancount);
    int answerIndex = 0;
    while ((offset < responseLength) && (answerIndex < answerCount)) {
        status = dn_expand(response, response + responseLength, response + offset, host, sizeof(host));
        if (status < 0) {
            reply->error = QDnsLookup::InvalidReplyError;
            reply->errorString = tr("Could not expand domain name");
            return;
        }
        const QString name = QUrl::fromAce(host);

        offset += status;
        if (offset + RRFIXEDSZ > responseLength) {
            // probably just a truncated reply, return what we have
            return;
        }
        const quint16 type = qFromBigEndian<quint16>(response + offset);
        const qint16 rrclass = qFromBigEndian<quint16>(response + offset + 2);
        const quint32 ttl = qFromBigEndian<quint32>(response + offset + 4);
        const quint16 size = qFromBigEndian<quint16>(response + offset + 8);
        offset += RRFIXEDSZ;
        if (offset + size > responseLength)
            return;             // truncated
        if (rrclass != C_IN)
            continue;

        if (type == QDnsLookup::A) {
            if (size != 4) {
                reply->error = QDnsLookup::InvalidReplyError;
                reply->errorString = tr("Invalid IPv4 address record");
                return;
            }
            const quint32 addr = qFromBigEndian<quint32>(response + offset);
            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ttl;
            record.d->value = QHostAddress(addr);
            reply->hostAddressRecords.append(record);
        } else if (type == QDnsLookup::AAAA) {
            if (size != 16) {
                reply->error = QDnsLookup::InvalidReplyError;
                reply->errorString = tr("Invalid IPv6 address record");
                return;
            }
            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ttl;
            record.d->value = QHostAddress(response + offset);
            reply->hostAddressRecords.append(record);
        } else if (type == QDnsLookup::CNAME) {
            status = dn_expand(response, response + responseLength, response + offset, answer, sizeof(answer));
            if (status < 0) {
                reply->error = QDnsLookup::InvalidReplyError;
                reply->errorString = tr("Invalid canonical name record");
                return;
            }
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ttl;
            record.d->value = QUrl::fromAce(answer);
            reply->canonicalNameRecords.append(record);
        } else if (type == QDnsLookup::NS) {
            status = dn_expand(response, response + responseLength, response + offset, answer, sizeof(answer));
            if (status < 0) {
                reply->error = QDnsLookup::InvalidReplyError;
                reply->errorString = tr("Invalid name server record");
                return;
            }
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ttl;
            record.d->value = QUrl::fromAce(answer);
            reply->nameServerRecords.append(record);
        } else if (type == QDnsLookup::PTR) {
            status = dn_expand(response, response + responseLength, response + offset, answer, sizeof(answer));
            if (status < 0) {
                reply->error = QDnsLookup::InvalidReplyError;
                reply->errorString = tr("Invalid pointer record");
                return;
            }
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ttl;
            record.d->value = QUrl::fromAce(answer);
            reply->pointerRecords.append(record);
        } else if (type == QDnsLookup::MX) {
            const quint16 preference = qFromBigEndian<quint16>(response + offset);
            status = dn_expand(response, response + responseLength, response + offset + 2, answer, sizeof(answer));
            if (status < 0) {
                reply->error = QDnsLookup::InvalidReplyError;
                reply->errorString = tr("Invalid mail exchange record");
                return;
            }
            QDnsMailExchangeRecord record;
            record.d->exchange = QUrl::fromAce(answer);
            record.d->name = name;
            record.d->preference = preference;
            record.d->timeToLive = ttl;
            reply->mailExchangeRecords.append(record);
        } else if (type == QDnsLookup::SRV) {
            const quint16 priority = qFromBigEndian<quint16>(response + offset);
            const quint16 weight = qFromBigEndian<quint16>(response + offset + 2);
            const quint16 port = qFromBigEndian<quint16>(response + offset + 4);
            status = dn_expand(response, response + responseLength, response + offset + 6, answer, sizeof(answer));
            if (status < 0) {
                reply->error = QDnsLookup::InvalidReplyError;
                reply->errorString = tr("Invalid service record");
                return;
            }
            QDnsServiceRecord record;
            record.d->name = name;
            record.d->target = QUrl::fromAce(answer);
            record.d->port = port;
            record.d->priority = priority;
            record.d->timeToLive = ttl;
            record.d->weight = weight;
            reply->serviceRecords.append(record);
        } else if (type == QDnsLookup::TXT) {
            QDnsTextRecord record;
            record.d->name = name;
            record.d->timeToLive = ttl;
            qptrdiff txt = offset;
            while (txt < offset + size) {
                const unsigned char length = response[txt];
                txt++;
                if (txt + length > offset + size) {
                    reply->error = QDnsLookup::InvalidReplyError;
                    reply->errorString = tr("Invalid text record");
                    return;
                }
                record.d->values << QByteArrayView(response + txt, length).toByteArray();
                txt += length;
            }
            reply->textRecords.append(record);
        }
        offset += size;
        answerIndex++;
    }
}

QT_END_NAMESPACE