Bug 1881437 - Use a thread local __res_state for HTTPS res_nquery r=necko-reviewers...
[gecko.git] / netwerk / dns / PlatformDNSUnix.cpp
blobc7f57fcddad1865f3afbe06b9968c98a97d303e7
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=4 sw=2 sts=2 et cin: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "GetAddrInfo.h"
8 #include "mozilla/net/DNSPacket.h"
9 #include "nsIDNSService.h"
10 #include "mozilla/Maybe.h"
11 #include "mozilla/StaticPrefs_network.h"
12 #include "mozilla/ThreadLocal.h"
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <netinet/in.h>
18 #include <resolv.h>
20 namespace mozilla::net {
22 #if defined(HAVE_RES_NINIT)
23 MOZ_THREAD_LOCAL(struct __res_state*) sThreadRes;
24 #endif
26 #define LOG(msg, ...) \
27 MOZ_LOG(gGetAddrInfoLog, LogLevel::Debug, ("[DNS]: " msg, ##__VA_ARGS__))
29 nsresult ResolveHTTPSRecordImpl(const nsACString& aHost, uint16_t aFlags,
30 TypeRecordResultType& aResult, uint32_t& aTTL) {
31 DNSPacket packet;
32 nsAutoCString host(aHost);
33 nsAutoCString cname;
34 nsresult rv;
36 if (xpc::IsInAutomation() &&
37 !StaticPrefs::network_dns_native_https_query_in_automation()) {
38 return NS_ERROR_UNKNOWN_HOST;
41 #if defined(HAVE_RES_NINIT)
42 if (!sThreadRes.get()) {
43 UniquePtr<struct __res_state> resState(new struct __res_state);
44 memset(resState.get(), 0, sizeof(struct __res_state));
45 if (int ret = res_ninit(resState.get())) {
46 LOG("res_ninit failed: %d", ret);
47 return NS_ERROR_UNKNOWN_HOST;
49 sThreadRes.set(resState.release());
51 #endif
53 LOG("resolving %s\n", host.get());
54 // Perform the query
55 rv = packet.FillBuffer(
56 [&](unsigned char response[DNSPacket::MAX_SIZE]) -> int {
57 int len = 0;
58 #if defined(HAVE_RES_NINIT)
59 len = res_nquery(sThreadRes.get(), host.get(), ns_c_in,
60 nsIDNSService::RESOLVE_TYPE_HTTPSSVC, response,
61 DNSPacket::MAX_SIZE);
62 #else
63 len =
64 res_query(host.get(), ns_c_in, nsIDNSService::RESOLVE_TYPE_HTTPSSVC,
65 response, DNSPacket::MAX_SIZE);
66 #endif
68 if (len < 0) {
69 LOG("DNS query failed");
71 return len;
72 });
73 if (NS_FAILED(rv)) {
74 return rv;
77 return ParseHTTPSRecord(host, packet, aResult, aTTL);
80 void DNSThreadShutdown() {
81 #if defined(HAVE_RES_NINIT)
82 auto* res = sThreadRes.get();
83 if (!res) {
84 return;
87 sThreadRes.set(nullptr);
88 res_nclose(res);
89 #endif
92 } // namespace mozilla::net