2 title: Writing Resolver Clients
3 category: Documentation for Developers
5 SPDX-License-Identifier: LGPL-2.1-or-later
8 # Writing Resolver Clients
10 _Or: How to look up hostnames and arbitrary DNS Resource Records via \_systemd-resolved_'s bus APIs\_
12 _(This is a longer explanation how to use some parts of \_systemd-resolved_ bus API. If you are just looking for an API reference, consult the [bus API documentation](https://wiki.freedesktop.org/www/Software/systemd/resolved/) instead.)\_
14 _systemd-resolved_ provides a set of APIs on the bus for resolving DNS resource records. These are:
16 1. _ResolveHostname()_ for resolving hostnames to acquire their IP addresses
17 2. _ResolveAddress()_ for the reverse operation: acquire the hostname for an IP address
18 3. _ResolveService()_ for resolving a DNS-SD or SRV service
19 4. _ResolveRecord()_ for resolving arbitrary resource records.
21 Below you'll find examples for two of these calls, to show how to use them. Note that glibc offers similar (and more portable) calls in _getaddrinfo()_, _getnameinfo()_ and _res_query()_. Of these _getaddrinfo()_ and _getnameinfo()_ are directed to the calls above via the _nss-resolve_ NSS module, but _req_query()_ is not. There are a number of reasons why it might be preferable to invoke _systemd-resolved_'s bus calls rather than the glibc APIs:
23 1. Bus APIs are naturally asynchronous, which the glibc APIs generally are not.
24 2. The bus calls above pass back substantially more information about the resolved data, including where and how the data was found (i.e. which protocol was used: DNS, LLMNR, MulticastDNS, and on which network interface), and most importantly, whether the data could be authenticated via DNSSEC. This in particular makes these APIs useful for retrieving certificate data from the DNS, in order to implement DANE, SSHFP, OPENGPGKEY and IPSECKEY clients.
25 3. _ResolveService()_ knows no counterpart in glibc, and has the benefit of being a single call that collects all data necessary to connect to a DNS-SD or pure SRV service in one step.
26 4. _ResolveRecord()_ in contrast to _res_query()_ supports LLMNR and MulticastDNS as protocols on top of DNS, and makes use of _systemd-resolved_'s local DNS record cache. The processing of the request is done in the sandboxed _systemd-resolved_ process rather than in the local process, and all packets are pre-validated. Because this relies on _systemd-resolved_ the per-interface DNS zone handling is supported.
28 Of course, by using _systemd-resolved_ you lose some portability, but this could be handled via an automatic fallback to the glibc counterparts.
30 Note that the various resolver calls provided by _systemd-resolved_ will consult _/etc/hosts_ and synthesize resource records for these entries in order to ensure that this file is honoured fully.
32 The examples below use the _sd-bus_ D-Bus client implementation, which is part of _libsystemd_. Any other D-Bus library, including the original _libdbus_ or _GDBus_ may be used too.
34 ## Resolving a Hostname
36 To resolve a hostname use the _ResolveHostname()_ call. For details on the function parameters see the [bus API documentation](https://wiki.freedesktop.org/www/Software/systemd/resolved/).
38 This example specifies _AF_UNSPEC_ as address family for the requested address. This means both an _AF_INET_ (A) and an _AF_INET6_ (AAAA) record is looked for, depending on whether the local system has configured IPv4 and/or IPv6 connectivity. It is generally recommended to request _AF_UNSPEC_ addresses for best compatibility with both protocols, in particular on dual-stack systems.
40 The example specifies a network interface index of "0", i.e. does not specify any at all, so that the request may be done on any. Note that the interface index is primarily relevant for LLMNR and MulticastDNS lookups, which distinguish different scopes for each network interface index.
42 This examples makes no use of either the input flags parameter, nor the output flags parameter. See the _ResolveRecord()_ example below for information how to make use of the _SD_RESOLVED_AUTHENTICATED_ bit in the returned flags paramter.
45 #include <arpa/inet.h>
46 #include <netinet/in.h>
49 #include <sys/socket.h>
50 #include <systemd/sd-bus.h>
52 int main(int argc, char*argv[]) {
53 sd_bus_error error = SD_BUS_ERROR_NULL;
54 sd_bus_message *reply = NULL;
55 const char *canonical;
60 r = sd_bus_open_system(&bus);
62 fprintf(stderr, "Failed to open system bus: %s\n", strerror(-r));
66 r = sd_bus_call_method(bus,
67 "org.freedesktop.resolve1",
68 "/org/freedesktop/resolve1",
69 "org.freedesktop.resolve1.Manager",
74 0, /* Network interface index where to look (0 means any) */
75 argc >= 2 ? argv[1] : "www.github.com", /* Hostname */
76 AF_UNSPEC, /* Which address family to look for */
77 UINT64_C(0)); /* Input flags parameter */
79 fprintf(stderr, "Failed to resolve hostnme: %s\n", error.message);
80 sd_bus_error_free(&error);
84 r = sd_bus_message_enter_container(reply, 'a', "(iiay)");
89 char buf[INET6_ADDRSTRLEN];
94 r = sd_bus_message_enter_container(reply, 'r', "iiay");
97 if (r == 0) /* Reached end of array */
99 r = sd_bus_message_read(reply, "ii", &ifindex, &family);
102 r = sd_bus_message_read_array(reply, 'y', &data, &length);
105 r = sd_bus_message_exit_container(reply);
109 printf("Found IP address %s on interface %i.\n", inet_ntop(family, data, buf, sizeof(buf)), ifindex);
112 r = sd_bus_message_exit_container(reply);
115 r = sd_bus_message_read(reply, "st", &canonical, &flags);
119 printf("Canonical name is %s\n", canonical);
123 fprintf(stderr, "Parse failure: %s\n", strerror(-r));
126 sd_bus_message_unref(reply);
127 sd_bus_flush_close_unref(bus);
128 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
132 Compile this with a command line like the following (under the assumption you save the sources above as `addrtest.c`):
135 gcc addrtest.c -o addrtest -Wall `pkg-config --cflags --libs libsystemd`
138 ## Resolving an Abitrary DNS Resource Record
140 Use `ResolveRecord()` in order to resolve arbitrary resource records. The call will return the binary RRset data. This calls is useful to acquire resource records for which no high-level calls such as ResolveHostname(), ResolveAddress() and ResolveService() exist. In particular RRs such as MX, SSHFP, TLSA, CERT, OPENPGPKEY or IPSECKEY may be requested via this API.
142 This example also shows how to determine whether the acquired data has been authenticated via DNSSEC (or another means) by checking the `SD_RESOLVED_AUTHENTICATED` bit in the
143 returned `flags` parameter.
145 This example contains a simple MX record parser. Note that the data comes pre-validated from `systemd-resolved`, hence we allow the example to parse the record slightly sloppily, to keep the example brief. For details on the MX RR binary format, see [RFC 1035](https://www.rfc-editor.org/rfc/rfc1035.txt).
147 For details on the function parameters see the [bus API documentation](https://wiki.freedesktop.org/www/Software/systemd/resolved/).
156 #include <systemd/sd-bus.h>
158 #define DNS_CLASS_IN 1U
159 #define DNS_TYPE_MX 15U
161 #define SD_RESOLVED_AUTHENTICATED (UINT64_C(1) << 9)
163 static const uint8_t* print_name(const uint8_t* p) {
172 printf("%.*s", (int) *p, (const char*) p + 1);
177 static void process_mx(const void *rr, size_t sz) {
178 uint16_t class, type, rdlength, preference;
179 const uint8_t *p = rr;
182 fputs("Found MX: ", stdout);
185 memcpy(&type, p, sizeof(uint16_t));
186 p += sizeof(uint16_t);
187 memcpy(&class, p, sizeof(uint16_t));
188 p += sizeof(uint16_t);
189 memcpy(&ttl, p, sizeof(uint32_t));
190 p += sizeof(uint32_t);
191 memcpy(&rdlength, p, sizeof(uint16_t));
192 p += sizeof(uint16_t);
193 memcpy(&preference, p, sizeof(uint16_t));
194 p += sizeof(uint16_t);
196 assert(be16toh(type) == DNS_TYPE_MX);
197 assert(be16toh(class) == DNS_CLASS_IN);
198 printf(" preference=%u ", be16toh(preference));
203 assert(p == (const uint8_t*) rr + sz);
206 int main(int argc, char*argv[]) {
207 sd_bus_error error = SD_BUS_ERROR_NULL;
208 sd_bus_message *reply = NULL;
213 r = sd_bus_open_system(&bus);
215 fprintf(stderr, "Failed to open system bus: %s\n", strerror(-r));
219 r = sd_bus_call_method(bus,
220 "org.freedesktop.resolve1",
221 "/org/freedesktop/resolve1",
222 "org.freedesktop.resolve1.Manager",
227 0, /* Network interface index where to look (0 means any) */
228 argc >= 2 ? argv[1] : "gmail.com", /* Domain name */
229 DNS_CLASS_IN, /* DNS RR class */
230 DNS_TYPE_MX, /* DNS RR type */
231 UINT64_C(0)); /* Input flags parameter */
233 fprintf(stderr, "Failed to resolve record: %s\n", error.message);
234 sd_bus_error_free(&error);
238 r = sd_bus_message_enter_container(reply, 'a', "(iqqay)");
243 uint16_t class, type;
248 r = sd_bus_message_enter_container(reply, 'r', "iqqay");
251 if (r == 0) /* Reached end of array */
253 r = sd_bus_message_read(reply, "iqq", &ifindex, &class, &type);
256 r = sd_bus_message_read_array(reply, 'y', &data, &length);
259 r = sd_bus_message_exit_container(reply);
263 process_mx(data, length);
266 r = sd_bus_message_exit_container(reply);
269 r = sd_bus_message_read(reply, "t", &flags);
273 printf("Response is authenticated: %s\n", flags & SD_RESOLVED_AUTHENTICATED ? "yes" : "no");
277 fprintf(stderr, "Parse failure: %s\n", strerror(-r));
280 sd_bus_message_unref(reply);
281 sd_bus_flush_close_unref(bus);
282 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
286 Compile this with a command line like the following (under the assumption you save the sources above as `rrtest.c`):
289 gcc rrtest.c -o rrtest -Wall `pkg-config --cflags --libs libsystemd`