1:255.16-alt1
[systemd_ALT.git] / docs / WRITING_RESOLVER_CLIENTS.md
blob93c51c538803c8d88442db94858eb6f48eba57d2
1 ---
2 title: Writing Resolver Clients
3 category: Documentation for Developers
4 layout: default
5 SPDX-License-Identifier: LGPL-2.1-or-later
6 ---
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.
56 ```c
57 #include <arpa/inet.h>
58 #include <netinet/in.h>
59 #include <stdio.h>
60 #include <stdlib.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;
68         sd_bus *bus = NULL;
69         uint64_t flags;
70         int r;
72         r = sd_bus_open_system(&bus);
73         if (r < 0) {
74                 fprintf(stderr, "Failed to open system bus: %s\n", strerror(-r));
75                 goto finish;
76         }
78         r = sd_bus_call_method(bus,
79                                "org.freedesktop.resolve1",
80                                "/org/freedesktop/resolve1",
81                                "org.freedesktop.resolve1.Manager",
82                                "ResolveHostname",
83                                &error,
84                                &reply,
85                                "isit",
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 */
90         if (r < 0) {
91                fprintf(stderr, "Failed to resolve hostnme: %s\n", error.message);
92                 sd_bus_error_free(&error);
93                 goto finish;
94         }
96         r = sd_bus_message_enter_container(reply, 'a', "(iiay)");
97         if (r < 0)
98                 goto parse_failure;
100         for (;;) {
101                 char buf[INET6_ADDRSTRLEN];
102                 int ifindex, family;
103                 const void *data;
104                 size_t length;
106                 r = sd_bus_message_enter_container(reply, 'r', "iiay");
107                 if (r < 0)
108                         goto parse_failure;
109                 if (r == 0)  /* Reached end of array */
110                         break;
111                 r = sd_bus_message_read(reply, "ii", &ifindex, &family);
112                 if (r < 0)
113                         goto parse_failure;
114                 r = sd_bus_message_read_array(reply, 'y', &data, &length);
115                 if (r < 0)
116                         goto parse_failure;
117                 r = sd_bus_message_exit_container(reply);
118                 if (r < 0)
119                         goto parse_failure;
121                 printf("Found IP address %s on interface %i.\n", inet_ntop(family, data, buf, sizeof(buf)), ifindex);
122         }
124         r = sd_bus_message_exit_container(reply);
125         if (r < 0)
126                 goto parse_failure;
127         r = sd_bus_message_read(reply, "st", &canonical, &flags);
128         if (r < 0)
129                 goto parse_failure;
131         printf("Canonical name is %s\n", canonical);
132         goto finish;
134 parse_failure:
135         fprintf(stderr, "Parse failure: %s\n", strerror(-r));
137 finish:
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).
165 ```c
166 #include <assert.h>
167 #include <endian.h>
168 #include <stdbool.h>
169 #include <stdio.h>
170 #include <stdlib.h>
171 #include <string.h>
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) {
180         bool dot = false;
181         for (;;) {
182                 if (*p == 0)
183                         return p + 1;
184                 if (dot)
185                         putchar('.');
186                 else
187                         dot = true;
188                 printf("%.*s", (int) *p, (const char*) p + 1);
189                 p += *p + 1;
190         }
193 static void process_mx(const void *rr, size_t sz) {
194         uint16_t class, type, rdlength, preference;
195         const uint8_t *p = rr;
196         uint32_t ttl;
198         fputs("Found MX: ", stdout);
199         p = print_name(p);
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));
216         p = print_name(p);
217         putchar('\n');
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;
225         sd_bus *bus = NULL;
226         uint64_t flags;
227         int r;
229         r = sd_bus_open_system(&bus);
230         if (r < 0) {
231                 fprintf(stderr, "Failed to open system bus: %s\n", strerror(-r));
232                 goto finish;
233         }
235         r = sd_bus_call_method(bus,
236                                "org.freedesktop.resolve1",
237                                "/org/freedesktop/resolve1",
238                                "org.freedesktop.resolve1.Manager",
239                                "ResolveRecord",
240                                &error,
241                                &reply,
242                                "isqqt",
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 */
248         if (r < 0) {
249                 fprintf(stderr, "Failed to resolve record: %s\n", error.message);
250                 sd_bus_error_free(&error);
251                 goto finish;
252         }
254         r = sd_bus_message_enter_container(reply, 'a', "(iqqay)");
255         if (r < 0)
256                 goto parse_failure;
258         for (;;) {
259                 uint16_t class, type;
260                 const void *data;
261                 size_t length;
262                 int ifindex;
264                 r = sd_bus_message_enter_container(reply, 'r', "iqqay");
265                 if (r < 0)
266                         goto parse_failure;
267                 if (r == 0)  /* Reached end of array */
268                         break;
269                 r = sd_bus_message_read(reply, "iqq", &ifindex, &class, &type);
270                 if (r < 0)
271                         goto parse_failure;
272                 r = sd_bus_message_read_array(reply, 'y', &data, &length);
273                 if (r < 0)
274                         goto parse_failure;
275                 r = sd_bus_message_exit_container(reply);
276                 if (r < 0)
277                         goto parse_failure;
279                 process_mx(data, length);
280         }
282         r = sd_bus_message_exit_container(reply);
283         if (r < 0)
284                 goto parse_failure;
285         r = sd_bus_message_read(reply, "t", &flags);
286         if (r < 0)
287                 goto parse_failure;
289         printf("Response is authenticated: %s\n", flags & SD_RESOLVED_AUTHENTICATED ? "yes" : "no");
290         goto finish;
292 parse_failure:
293         fprintf(stderr, "Parse failure: %s\n", strerror(-r));
295 finish:
296         sd_bus_message_unref(reply);
297         sd_bus_flush_close_unref(bus);
298         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
299    }
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`