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://www.freedesktop.org/software/systemd/man/latest/org.freedesktop.resolve1.html) 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.
22 Note that glibc offers similar (and more portable) calls in _getaddrinfo()_, _getnameinfo()_ and _res\_query()_.
23 Of these _getaddrinfo()_ and _getnameinfo()_ are directed to the calls above via the _nss-resolve_ NSS module, but _req\_query()_ is not.
24 There are a number of reasons why it might be preferable to invoke `systemd-resolved`'s bus calls rather than the glibc APIs:
26 1. Bus APIs are naturally asynchronous, which the glibc APIs generally are not.
27 2. The bus calls above pass back substantially more information about the resolved data, including where and how the data was found
28 (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.
29 This in particular makes these APIs useful for retrieving certificate data from the DNS, in order to implement DANE, SSHFP, OPENGPGKEY and IPSECKEY clients.
30 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.
31 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.
32 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.
33 Because this relies on `systemd-resolved` the per-interface DNS zone handling is supported.
35 Of course, by using `systemd-resolved` you lose some portability, but this could be handled via an automatic fallback to the glibc counterparts.
37 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.
39 The examples below use the _sd-bus_ D-Bus client implementation, which is part of _libsystemd_.
40 Any other D-Bus library, including the original _libdbus_ or _GDBus_ may be used too.
42 ## Resolving a Hostname
44 To resolve a hostname use the _ResolveHostname()_ call. For details on the function parameters see the [bus API documentation](https://www.freedesktop.org/software/systemd/man/latest/org.freedesktop.resolve1.html).
46 This example specifies `AF_UNSPEC` as address family for the requested address.
47 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.
48 It is generally recommended to request `AF_UNSPEC` addresses for best compatibility with both protocols, in particular on dual-stack systems.
50 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.
51 Note that the interface index is primarily relevant for LLMNR and MulticastDNS lookups, which distinguish different scopes for each network interface index.
53 This examples makes no use of either the input flags parameter, nor the output flags parameter.
54 See the _ResolveRecord()_ example below for information how to make use of the _SD\_RESOLVED\_AUTHENTICATED_ bit in the returned flags parameter.
57 #include <arpa/inet.h>
58 #include <netinet/in.h>
61 #include <sys/socket.h>
62 #include <systemd/sd-bus.h>
64 int main(int argc, char*argv[]) {
65 sd_bus_error error = SD_BUS_ERROR_NULL;
66 sd_bus_message *reply = NULL;
67 const char *canonical;
72 r = sd_bus_open_system(&bus);
74 fprintf(stderr, "Failed to open system bus: %s\n", strerror(-r));
78 r = sd_bus_call_method(bus,
79 "org.freedesktop.resolve1",
80 "/org/freedesktop/resolve1",
81 "org.freedesktop.resolve1.Manager",
86 0, /* Network interface index where to look (0 means any) */
87 argc >= 2 ? argv[1] : "www.github.com", /* Hostname */
88 AF_UNSPEC, /* Which address family to look for */
89 UINT64_C(0)); /* Input flags parameter */
91 fprintf(stderr, "Failed to resolve hostnme: %s\n", error.message);
92 sd_bus_error_free(&error);
96 r = sd_bus_message_enter_container(reply, 'a', "(iiay)");
101 char buf[INET6_ADDRSTRLEN];
106 r = sd_bus_message_enter_container(reply, 'r', "iiay");
109 if (r == 0) /* Reached end of array */
111 r = sd_bus_message_read(reply, "ii", &ifindex, &family);
114 r = sd_bus_message_read_array(reply, 'y', &data, &length);
117 r = sd_bus_message_exit_container(reply);
121 printf("Found IP address %s on interface %i.\n", inet_ntop(family, data, buf, sizeof(buf)), ifindex);
124 r = sd_bus_message_exit_container(reply);
127 r = sd_bus_message_read(reply, "st", &canonical, &flags);
131 printf("Canonical name is %s\n", canonical);
135 fprintf(stderr, "Parse failure: %s\n", strerror(-r));
138 sd_bus_message_unref(reply);
139 sd_bus_flush_close_unref(bus);
140 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
144 Compile this with a command line like the following (under the assumption you save the sources above as `addrtest.c`):
147 gcc addrtest.c -o addrtest -Wall `pkg-config --cflags --libs libsystemd`
150 ## Resolving an Arbitrary DNS Resource Record
152 Use `ResolveRecord()` in order to resolve arbitrary resource records. The call will return the binary RRset data.
153 This calls is useful to acquire resource records for which no high-level calls such as ResolveHostname(), ResolveAddress() and ResolveService() exist.
154 In particular RRs such as MX, SSHFP, TLSA, CERT, OPENPGPKEY or IPSECKEY may be requested via this API.
156 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
157 returned `flags` parameter.
159 This example contains a simple MX record parser.
160 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.
161 For details on the MX RR binary format, see [RFC 1035](https://www.rfc-editor.org/rfc/rfc1035.txt).
163 For details on the function parameters see the [bus API documentation](https://www.freedesktop.org/software/systemd/man/latest/org.freedesktop.resolve1.html).
172 #include <systemd/sd-bus.h>
174 #define DNS_CLASS_IN 1U
175 #define DNS_TYPE_MX 15U
177 #define SD_RESOLVED_AUTHENTICATED (UINT64_C(1) << 9)
179 static const uint8_t* print_name(const uint8_t* p) {
188 printf("%.*s", (int) *p, (const char*) p + 1);
193 static void process_mx(const void *rr, size_t sz) {
194 uint16_t class, type, rdlength, preference;
195 const uint8_t *p = rr;
198 fputs("Found MX: ", stdout);
201 memcpy(&type, p, sizeof(uint16_t));
202 p += sizeof(uint16_t);
203 memcpy(&class, p, sizeof(uint16_t));
204 p += sizeof(uint16_t);
205 memcpy(&ttl, p, sizeof(uint32_t));
206 p += sizeof(uint32_t);
207 memcpy(&rdlength, p, sizeof(uint16_t));
208 p += sizeof(uint16_t);
209 memcpy(&preference, p, sizeof(uint16_t));
210 p += sizeof(uint16_t);
212 assert(be16toh(type) == DNS_TYPE_MX);
213 assert(be16toh(class) == DNS_CLASS_IN);
214 printf(" preference=%u ", be16toh(preference));
219 assert(p == (const uint8_t*) rr + sz);
222 int main(int argc, char*argv[]) {
223 sd_bus_error error = SD_BUS_ERROR_NULL;
224 sd_bus_message *reply = NULL;
229 r = sd_bus_open_system(&bus);
231 fprintf(stderr, "Failed to open system bus: %s\n", strerror(-r));
235 r = sd_bus_call_method(bus,
236 "org.freedesktop.resolve1",
237 "/org/freedesktop/resolve1",
238 "org.freedesktop.resolve1.Manager",
243 0, /* Network interface index where to look (0 means any) */
244 argc >= 2 ? argv[1] : "gmail.com", /* Domain name */
245 DNS_CLASS_IN, /* DNS RR class */
246 DNS_TYPE_MX, /* DNS RR type */
247 UINT64_C(0)); /* Input flags parameter */
249 fprintf(stderr, "Failed to resolve record: %s\n", error.message);
250 sd_bus_error_free(&error);
254 r = sd_bus_message_enter_container(reply, 'a', "(iqqay)");
259 uint16_t class, type;
264 r = sd_bus_message_enter_container(reply, 'r', "iqqay");
267 if (r == 0) /* Reached end of array */
269 r = sd_bus_message_read(reply, "iqq", &ifindex, &class, &type);
272 r = sd_bus_message_read_array(reply, 'y', &data, &length);
275 r = sd_bus_message_exit_container(reply);
279 process_mx(data, length);
282 r = sd_bus_message_exit_container(reply);
285 r = sd_bus_message_read(reply, "t", &flags);
289 printf("Response is authenticated: %s\n", flags & SD_RESOLVED_AUTHENTICATED ? "yes" : "no");
293 fprintf(stderr, "Parse failure: %s\n", strerror(-r));
296 sd_bus_message_unref(reply);
297 sd_bus_flush_close_unref(bus);
298 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
302 Compile this with a command line like the following (under the assumption you save the sources above as `rrtest.c`):
305 gcc rrtest.c -o rrtest -Wall `pkg-config --cflags --libs libsystemd`