]> git.ipfire.org Git - thirdparty/systemd.git/blob - docs/WRITING_RESOLVER_CLIENTS.md
Revert "docs: use collections to structure the data"
[thirdparty/systemd.git] / docs / WRITING_RESOLVER_CLIENTS.md
1 ---
2 title: Writing Resolver Clients
3 category: Documentation for Developers
4 layout: default
5 SPDX-License-Identifier: LGPL-2.1-or-later
6 ---
7
8 # Writing Resolver Clients
9
10 _Or: How to look up hostnames and arbitrary DNS Resource Records via \_systemd-resolved_'s bus APIs\_
11
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.)\_
13
14 _systemd-resolved_ provides a set of APIs on the bus for resolving DNS resource records. These are:
15
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.
20
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:
22
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.
27
28 Of course, by using _systemd-resolved_ you lose some portability, but this could be handled via an automatic fallback to the glibc counterparts.
29
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.
31
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.
33
34 ## Resolving a Hostname
35
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/).
37
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.
39
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.
41
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.
43
44 ```
45 #include <arpa/inet.h>
46 #include <netinet/in.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <sys/socket.h>
50 #include <systemd/sd-bus.h>
51
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;
56 sd_bus *bus = NULL;
57 uint64_t flags;
58 int r;
59
60 r = sd_bus_open_system(&bus);
61 if (r < 0) {
62 fprintf(stderr, "Failed to open system bus: %s\n", strerror(-r));
63 goto finish;
64 }
65
66 r = sd_bus_call_method(bus,
67 "org.freedesktop.resolve1",
68 "/org/freedesktop/resolve1",
69 "org.freedesktop.resolve1.Manager",
70 "ResolveHostname",
71 &error,
72 &reply,
73 "isit",
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 */
78 if (r < 0) {
79 fprintf(stderr, "Failed to resolve hostnme: %s\n", error.message);
80 sd_bus_error_free(&error);
81 goto finish;
82 }
83
84 r = sd_bus_message_enter_container(reply, 'a', "(iiay)");
85 if (r < 0)
86 goto parse_failure;
87
88 for (;;) {
89 char buf[INET6_ADDRSTRLEN];
90 int ifindex, family;
91 const void *data;
92 size_t length;
93
94 r = sd_bus_message_enter_container(reply, 'r', "iiay");
95 if (r < 0)
96 goto parse_failure;
97 if (r == 0) /* Reached end of array */
98 break;
99 r = sd_bus_message_read(reply, "ii", &ifindex, &family);
100 if (r < 0)
101 goto parse_failure;
102 r = sd_bus_message_read_array(reply, 'y', &data, &length);
103 if (r < 0)
104 goto parse_failure;
105 r = sd_bus_message_exit_container(reply);
106 if (r < 0)
107 goto parse_failure;
108
109 printf("Found IP address %s on interface %i.\n", inet_ntop(family, data, buf, sizeof(buf)), ifindex);
110 }
111
112 r = sd_bus_message_exit_container(reply);
113 if (r < 0)
114 goto parse_failure;
115 r = sd_bus_message_read(reply, "st", &canonical, &flags);
116 if (r < 0)
117 goto parse_failure;
118
119 printf("Canonical name is %s\n", canonical);
120 goto finish;
121
122 parse_failure:
123 fprintf(stderr, "Parse failure: %s\n", strerror(-r));
124
125 finish:
126 sd_bus_message_unref(reply);
127 sd_bus_flush_close_unref(bus);
128 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
129 }
130 ```
131
132 Compile this with a command line like the following (under the assumption you save the sources above as `addrtest.c`):
133
134 ```
135 gcc addrtest.c -o addrtest -Wall `pkg-config --cflags --libs libsystemd`
136 ```
137
138 ## Resolving an Abitrary DNS Resource Record
139
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.
141
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.
144
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).
146
147 For details on the function parameters see the [bus API documentation](https://wiki.freedesktop.org/www/Software/systemd/resolved/).
148
149 ```
150 #include <assert.h>
151 #include <endian.h>
152 #include <stdbool.h>
153 #include <stdio.h>
154 #include <stdlib.h>
155 #include <string.h>
156 #include <systemd/sd-bus.h>
157
158 #define DNS_CLASS_IN 1U
159 #define DNS_TYPE_MX 15U
160
161 #define SD_RESOLVED_AUTHENTICATED (UINT64_C(1) << 9)
162
163 static const uint8_t* print_name(const uint8_t* p) {
164 bool dot = false;
165 for (;;) {
166 if (*p == 0)
167 return p + 1;
168 if (dot)
169 putchar('.');
170 else
171 dot = true;
172 printf("%.*s", (int) *p, (const char*) p + 1);
173 p += *p + 1;
174 }
175 }
176
177 static void process_mx(const void *rr, size_t sz) {
178 uint16_t class, type, rdlength, preference;
179 const uint8_t *p = rr;
180 uint32_t ttl;
181
182 fputs("Found MX: ", stdout);
183 p = print_name(p);
184
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);
195
196 assert(be16toh(type) == DNS_TYPE_MX);
197 assert(be16toh(class) == DNS_CLASS_IN);
198 printf(" preference=%u ", be16toh(preference));
199
200 p = print_name(p);
201 putchar('\n');
202
203 assert(p == (const uint8_t*) rr + sz);
204 }
205
206 int main(int argc, char*argv[]) {
207 sd_bus_error error = SD_BUS_ERROR_NULL;
208 sd_bus_message *reply = NULL;
209 sd_bus *bus = NULL;
210 uint64_t flags;
211 int r;
212
213 r = sd_bus_open_system(&bus);
214 if (r < 0) {
215 fprintf(stderr, "Failed to open system bus: %s\n", strerror(-r));
216 goto finish;
217 }
218
219 r = sd_bus_call_method(bus,
220 "org.freedesktop.resolve1",
221 "/org/freedesktop/resolve1",
222 "org.freedesktop.resolve1.Manager",
223 "ResolveRecord",
224 &error,
225 &reply,
226 "isqqt",
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 */
232 if (r < 0) {
233 fprintf(stderr, "Failed to resolve record: %s\n", error.message);
234 sd_bus_error_free(&error);
235 goto finish;
236 }
237
238 r = sd_bus_message_enter_container(reply, 'a', "(iqqay)");
239 if (r < 0)
240 goto parse_failure;
241
242 for (;;) {
243 uint16_t class, type;
244 const void *data;
245 size_t length;
246 int ifindex;
247
248 r = sd_bus_message_enter_container(reply, 'r', "iqqay");
249 if (r < 0)
250 goto parse_failure;
251 if (r == 0) /* Reached end of array */
252 break;
253 r = sd_bus_message_read(reply, "iqq", &ifindex, &class, &type);
254 if (r < 0)
255 goto parse_failure;
256 r = sd_bus_message_read_array(reply, 'y', &data, &length);
257 if (r < 0)
258 goto parse_failure;
259 r = sd_bus_message_exit_container(reply);
260 if (r < 0)
261 goto parse_failure;
262
263 process_mx(data, length);
264 }
265
266 r = sd_bus_message_exit_container(reply);
267 if (r < 0)
268 goto parse_failure;
269 r = sd_bus_message_read(reply, "t", &flags);
270 if (r < 0)
271 goto parse_failure;
272
273 printf("Response is authenticated: %s\n", flags & SD_RESOLVED_AUTHENTICATED ? "yes" : "no");
274 goto finish;
275
276 parse_failure:
277 fprintf(stderr, "Parse failure: %s\n", strerror(-r));
278
279 finish:
280 sd_bus_message_unref(reply);
281 sd_bus_flush_close_unref(bus);
282 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
283 }
284 ```
285
286 Compile this with a command line like the following (under the assumption you save the sources above as `rrtest.c`):
287
288 ```
289 gcc rrtest.c -o rrtest -Wall `pkg-config --cflags --libs libsystemd`
290 ```