4cbb9723e21f69a1247215327cc114a766b6eb69
[thirdparty/systemd.git] / src / resolve / resolved-dns-rr.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <math.h>
4
5 #include "alloc-util.h"
6 #include "dns-domain.h"
7 #include "dns-type.h"
8 #include "escape.h"
9 #include "hexdecoct.h"
10 #include "resolved-dns-dnssec.h"
11 #include "resolved-dns-packet.h"
12 #include "resolved-dns-rr.h"
13 #include "string-table.h"
14 #include "string-util.h"
15 #include "strv.h"
16 #include "terminal-util.h"
17
18 DnsResourceKey* dns_resource_key_new(uint16_t class, uint16_t type, const char *name) {
19         DnsResourceKey *k;
20         size_t l;
21
22         assert(name);
23
24         l = strlen(name);
25         k = malloc0(sizeof(DnsResourceKey) + l + 1);
26         if (!k)
27                 return NULL;
28
29         k->n_ref = 1;
30         k->class = class;
31         k->type = type;
32
33         strcpy((char*) k + sizeof(DnsResourceKey), name);
34
35         return k;
36 }
37
38 DnsResourceKey* dns_resource_key_new_redirect(const DnsResourceKey *key, const DnsResourceRecord *cname) {
39         int r;
40
41         assert(key);
42         assert(cname);
43
44         assert(IN_SET(cname->key->type, DNS_TYPE_CNAME, DNS_TYPE_DNAME));
45
46         if (cname->key->type == DNS_TYPE_CNAME)
47                 return dns_resource_key_new(key->class, key->type, cname->cname.name);
48         else {
49                 DnsResourceKey *k;
50                 char *destination = NULL;
51
52                 r = dns_name_change_suffix(dns_resource_key_name(key), dns_resource_key_name(cname->key), cname->dname.name, &destination);
53                 if (r < 0)
54                         return NULL;
55                 if (r == 0)
56                         return dns_resource_key_ref((DnsResourceKey*) key);
57
58                 k = dns_resource_key_new_consume(key->class, key->type, destination);
59                 if (!k)
60                         return mfree(destination);
61
62                 return k;
63         }
64 }
65
66 int dns_resource_key_new_append_suffix(DnsResourceKey **ret, DnsResourceKey *key, char *name) {
67         DnsResourceKey *new_key;
68         char *joined;
69         int r;
70
71         assert(ret);
72         assert(key);
73         assert(name);
74
75         if (dns_name_is_root(name)) {
76                 *ret = dns_resource_key_ref(key);
77                 return 0;
78         }
79
80         r = dns_name_concat(dns_resource_key_name(key), name, 0, &joined);
81         if (r < 0)
82                 return r;
83
84         new_key = dns_resource_key_new_consume(key->class, key->type, joined);
85         if (!new_key) {
86                 free(joined);
87                 return -ENOMEM;
88         }
89
90         *ret = new_key;
91         return 0;
92 }
93
94 DnsResourceKey* dns_resource_key_new_consume(uint16_t class, uint16_t type, char *name) {
95         DnsResourceKey *k;
96
97         assert(name);
98
99         k = new0(DnsResourceKey, 1);
100         if (!k)
101                 return NULL;
102
103         k->n_ref = 1;
104         k->class = class;
105         k->type = type;
106         k->_name = name;
107
108         return k;
109 }
110
111 DnsResourceKey* dns_resource_key_ref(DnsResourceKey *k) {
112
113         if (!k)
114                 return NULL;
115
116         /* Static/const keys created with DNS_RESOURCE_KEY_CONST will
117          * set this to -1, they should not be reffed/unreffed */
118         assert(k->n_ref != (unsigned) -1);
119
120         assert(k->n_ref > 0);
121         k->n_ref++;
122
123         return k;
124 }
125
126 DnsResourceKey* dns_resource_key_unref(DnsResourceKey *k) {
127         if (!k)
128                 return NULL;
129
130         assert(k->n_ref != (unsigned) -1);
131         assert(k->n_ref > 0);
132
133         if (k->n_ref == 1) {
134                 free(k->_name);
135                 free(k);
136         } else
137                 k->n_ref--;
138
139         return NULL;
140 }
141
142 const char* dns_resource_key_name(const DnsResourceKey *key) {
143         const char *name;
144
145         if (!key)
146                 return NULL;
147
148         if (key->_name)
149                 name = key->_name;
150         else
151                 name = (char*) key + sizeof(DnsResourceKey);
152
153         if (dns_name_is_root(name))
154                 return ".";
155         else
156                 return name;
157 }
158
159 bool dns_resource_key_is_address(const DnsResourceKey *key) {
160         assert(key);
161
162         /* Check if this is an A or AAAA resource key */
163
164         return key->class == DNS_CLASS_IN && IN_SET(key->type, DNS_TYPE_A, DNS_TYPE_AAAA);
165 }
166
167 bool dns_resource_key_is_dnssd_ptr(const DnsResourceKey *key) {
168         assert(key);
169
170         /* Check if this is a PTR resource key used in
171            Service Instance Enumeration as described in RFC6763 p4.1. */
172
173         if (key->type != DNS_TYPE_PTR)
174                 return false;
175
176         return dns_name_endswith(dns_resource_key_name(key), "_tcp.local") ||
177                 dns_name_endswith(dns_resource_key_name(key), "_udp.local");
178 }
179
180 int dns_resource_key_equal(const DnsResourceKey *a, const DnsResourceKey *b) {
181         int r;
182
183         if (a == b)
184                 return 1;
185
186         r = dns_name_equal(dns_resource_key_name(a), dns_resource_key_name(b));
187         if (r <= 0)
188                 return r;
189
190         if (a->class != b->class)
191                 return 0;
192
193         if (a->type != b->type)
194                 return 0;
195
196         return 1;
197 }
198
199 int dns_resource_key_match_rr(const DnsResourceKey *key, DnsResourceRecord *rr, const char *search_domain) {
200         int r;
201
202         assert(key);
203         assert(rr);
204
205         if (key == rr->key)
206                 return 1;
207
208         /* Checks if an rr matches the specified key. If a search
209          * domain is specified, it will also be checked if the key
210          * with the search domain suffixed might match the RR. */
211
212         if (rr->key->class != key->class && key->class != DNS_CLASS_ANY)
213                 return 0;
214
215         if (rr->key->type != key->type && key->type != DNS_TYPE_ANY)
216                 return 0;
217
218         r = dns_name_equal(dns_resource_key_name(rr->key), dns_resource_key_name(key));
219         if (r != 0)
220                 return r;
221
222         if (search_domain) {
223                 _cleanup_free_ char *joined = NULL;
224
225                 r = dns_name_concat(dns_resource_key_name(key), search_domain, 0, &joined);
226                 if (r < 0)
227                         return r;
228
229                 return dns_name_equal(dns_resource_key_name(rr->key), joined);
230         }
231
232         return 0;
233 }
234
235 int dns_resource_key_match_cname_or_dname(const DnsResourceKey *key, const DnsResourceKey *cname, const char *search_domain) {
236         int r;
237
238         assert(key);
239         assert(cname);
240
241         if (cname->class != key->class && key->class != DNS_CLASS_ANY)
242                 return 0;
243
244         if (cname->type == DNS_TYPE_CNAME)
245                 r = dns_name_equal(dns_resource_key_name(key), dns_resource_key_name(cname));
246         else if (cname->type == DNS_TYPE_DNAME)
247                 r = dns_name_endswith(dns_resource_key_name(key), dns_resource_key_name(cname));
248         else
249                 return 0;
250
251         if (r != 0)
252                 return r;
253
254         if (search_domain) {
255                 _cleanup_free_ char *joined = NULL;
256
257                 r = dns_name_concat(dns_resource_key_name(key), search_domain, 0, &joined);
258                 if (r < 0)
259                         return r;
260
261                 if (cname->type == DNS_TYPE_CNAME)
262                         return dns_name_equal(joined, dns_resource_key_name(cname));
263                 else if (cname->type == DNS_TYPE_DNAME)
264                         return dns_name_endswith(joined, dns_resource_key_name(cname));
265         }
266
267         return 0;
268 }
269
270 int dns_resource_key_match_soa(const DnsResourceKey *key, const DnsResourceKey *soa) {
271         assert(soa);
272         assert(key);
273
274         /* Checks whether 'soa' is a SOA record for the specified key. */
275
276         if (soa->class != key->class)
277                 return 0;
278
279         if (soa->type != DNS_TYPE_SOA)
280                 return 0;
281
282         return dns_name_endswith(dns_resource_key_name(key), dns_resource_key_name(soa));
283 }
284
285 static void dns_resource_key_hash_func(const DnsResourceKey *k, struct siphash *state) {
286         assert(k);
287
288         dns_name_hash_func(dns_resource_key_name(k), state);
289         siphash24_compress(&k->class, sizeof(k->class), state);
290         siphash24_compress(&k->type, sizeof(k->type), state);
291 }
292
293 static int dns_resource_key_compare_func(const DnsResourceKey *x, const DnsResourceKey *y) {
294         int ret;
295
296         ret = dns_name_compare_func(dns_resource_key_name(x), dns_resource_key_name(y));
297         if (ret != 0)
298                 return ret;
299
300         ret = CMP(x->type, y->type);
301         if (ret != 0)
302                 return ret;
303
304         ret = CMP(x->class, y->class);
305         if (ret != 0)
306                 return ret;
307
308         return 0;
309 }
310
311 DEFINE_HASH_OPS(dns_resource_key_hash_ops, DnsResourceKey, dns_resource_key_hash_func, dns_resource_key_compare_func);
312
313 char* dns_resource_key_to_string(const DnsResourceKey *key, char *buf, size_t buf_size) {
314         const char *c, *t;
315         char *ans = buf;
316
317         /* If we cannot convert the CLASS/TYPE into a known string,
318            use the format recommended by RFC 3597, Section 5. */
319
320         c = dns_class_to_string(key->class);
321         t = dns_type_to_string(key->type);
322
323         snprintf(buf, buf_size, "%s %s%s%.0u %s%s%.0u",
324                  dns_resource_key_name(key),
325                  strempty(c), c ? "" : "CLASS", c ? 0 : key->class,
326                  strempty(t), t ? "" : "TYPE", t ? 0 : key->type);
327
328         return ans;
329 }
330
331 bool dns_resource_key_reduce(DnsResourceKey **a, DnsResourceKey **b) {
332         assert(a);
333         assert(b);
334
335         /* Try to replace one RR key by another if they are identical, thus saving a bit of memory. Note that we do
336          * this only for RR keys, not for RRs themselves, as they carry a lot of additional metadata (where they come
337          * from, validity data, and suchlike), and cannot be replaced so easily by other RRs that have the same
338          * superficial data. */
339
340         if (!*a)
341                 return false;
342         if (!*b)
343                 return false;
344
345         /* We refuse merging const keys */
346         if ((*a)->n_ref == (unsigned) -1)
347                 return false;
348         if ((*b)->n_ref == (unsigned) -1)
349                 return false;
350
351         /* Already the same? */
352         if (*a == *b)
353                 return true;
354
355         /* Are they really identical? */
356         if (dns_resource_key_equal(*a, *b) <= 0)
357                 return false;
358
359         /* Keep the one which already has more references. */
360         if ((*a)->n_ref > (*b)->n_ref) {
361                 dns_resource_key_unref(*b);
362                 *b = dns_resource_key_ref(*a);
363         } else {
364                 dns_resource_key_unref(*a);
365                 *a = dns_resource_key_ref(*b);
366         }
367
368         return true;
369 }
370
371 DnsResourceRecord* dns_resource_record_new(DnsResourceKey *key) {
372         DnsResourceRecord *rr;
373
374         rr = new0(DnsResourceRecord, 1);
375         if (!rr)
376                 return NULL;
377
378         rr->n_ref = 1;
379         rr->key = dns_resource_key_ref(key);
380         rr->expiry = USEC_INFINITY;
381         rr->n_skip_labels_signer = rr->n_skip_labels_source = (unsigned) -1;
382
383         return rr;
384 }
385
386 DnsResourceRecord* dns_resource_record_new_full(uint16_t class, uint16_t type, const char *name) {
387         _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
388
389         key = dns_resource_key_new(class, type, name);
390         if (!key)
391                 return NULL;
392
393         return dns_resource_record_new(key);
394 }
395
396 static DnsResourceRecord* dns_resource_record_free(DnsResourceRecord *rr) {
397         assert(rr);
398
399         if (rr->key) {
400                 switch(rr->key->type) {
401
402                 case DNS_TYPE_SRV:
403                         free(rr->srv.name);
404                         break;
405
406                 case DNS_TYPE_PTR:
407                 case DNS_TYPE_NS:
408                 case DNS_TYPE_CNAME:
409                 case DNS_TYPE_DNAME:
410                         free(rr->ptr.name);
411                         break;
412
413                 case DNS_TYPE_HINFO:
414                         free(rr->hinfo.cpu);
415                         free(rr->hinfo.os);
416                         break;
417
418                 case DNS_TYPE_TXT:
419                 case DNS_TYPE_SPF:
420                         dns_txt_item_free_all(rr->txt.items);
421                         break;
422
423                 case DNS_TYPE_SOA:
424                         free(rr->soa.mname);
425                         free(rr->soa.rname);
426                         break;
427
428                 case DNS_TYPE_MX:
429                         free(rr->mx.exchange);
430                         break;
431
432                 case DNS_TYPE_DS:
433                         free(rr->ds.digest);
434                         break;
435
436                 case DNS_TYPE_SSHFP:
437                         free(rr->sshfp.fingerprint);
438                         break;
439
440                 case DNS_TYPE_DNSKEY:
441                         free(rr->dnskey.key);
442                         break;
443
444                 case DNS_TYPE_RRSIG:
445                         free(rr->rrsig.signer);
446                         free(rr->rrsig.signature);
447                         break;
448
449                 case DNS_TYPE_NSEC:
450                         free(rr->nsec.next_domain_name);
451                         bitmap_free(rr->nsec.types);
452                         break;
453
454                 case DNS_TYPE_NSEC3:
455                         free(rr->nsec3.next_hashed_name);
456                         free(rr->nsec3.salt);
457                         bitmap_free(rr->nsec3.types);
458                         break;
459
460                 case DNS_TYPE_LOC:
461                 case DNS_TYPE_A:
462                 case DNS_TYPE_AAAA:
463                         break;
464
465                 case DNS_TYPE_TLSA:
466                         free(rr->tlsa.data);
467                         break;
468
469                 case DNS_TYPE_CAA:
470                         free(rr->caa.tag);
471                         free(rr->caa.value);
472                         break;
473
474                 case DNS_TYPE_OPENPGPKEY:
475                 default:
476                         if (!rr->unparseable)
477                                 free(rr->generic.data);
478                 }
479
480                 if (rr->unparseable)
481                         free(rr->generic.data);
482
483                 free(rr->wire_format);
484                 dns_resource_key_unref(rr->key);
485         }
486
487         free(rr->to_string);
488         return mfree(rr);
489 }
490
491 DEFINE_TRIVIAL_REF_UNREF_FUNC(DnsResourceRecord, dns_resource_record, dns_resource_record_free);
492
493 int dns_resource_record_new_reverse(DnsResourceRecord **ret, int family, const union in_addr_union *address, const char *hostname) {
494         _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
495         _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
496         _cleanup_free_ char *ptr = NULL;
497         int r;
498
499         assert(ret);
500         assert(address);
501         assert(hostname);
502
503         r = dns_name_reverse(family, address, &ptr);
504         if (r < 0)
505                 return r;
506
507         key = dns_resource_key_new_consume(DNS_CLASS_IN, DNS_TYPE_PTR, ptr);
508         if (!key)
509                 return -ENOMEM;
510
511         ptr = NULL;
512
513         rr = dns_resource_record_new(key);
514         if (!rr)
515                 return -ENOMEM;
516
517         rr->ptr.name = strdup(hostname);
518         if (!rr->ptr.name)
519                 return -ENOMEM;
520
521         *ret = TAKE_PTR(rr);
522
523         return 0;
524 }
525
526 int dns_resource_record_new_address(DnsResourceRecord **ret, int family, const union in_addr_union *address, const char *name) {
527         DnsResourceRecord *rr;
528
529         assert(ret);
530         assert(address);
531         assert(family);
532
533         if (family == AF_INET) {
534
535                 rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_A, name);
536                 if (!rr)
537                         return -ENOMEM;
538
539                 rr->a.in_addr = address->in;
540
541         } else if (family == AF_INET6) {
542
543                 rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_AAAA, name);
544                 if (!rr)
545                         return -ENOMEM;
546
547                 rr->aaaa.in6_addr = address->in6;
548         } else
549                 return -EAFNOSUPPORT;
550
551         *ret = rr;
552
553         return 0;
554 }
555
556 #define FIELD_EQUAL(a, b, field) \
557         ((a).field ## _size == (b).field ## _size &&  \
558          memcmp((a).field, (b).field, (a).field ## _size) == 0)
559
560 int dns_resource_record_payload_equal(const DnsResourceRecord *a, const DnsResourceRecord *b) {
561         int r;
562
563         /* Check if a and b are the same, but don't look at their keys */
564
565         if (a->unparseable != b->unparseable)
566                 return 0;
567
568         switch (a->unparseable ? _DNS_TYPE_INVALID : a->key->type) {
569
570         case DNS_TYPE_SRV:
571                 r = dns_name_equal(a->srv.name, b->srv.name);
572                 if (r <= 0)
573                         return r;
574
575                 return a->srv.priority == b->srv.priority &&
576                        a->srv.weight == b->srv.weight &&
577                        a->srv.port == b->srv.port;
578
579         case DNS_TYPE_PTR:
580         case DNS_TYPE_NS:
581         case DNS_TYPE_CNAME:
582         case DNS_TYPE_DNAME:
583                 return dns_name_equal(a->ptr.name, b->ptr.name);
584
585         case DNS_TYPE_HINFO:
586                 return strcaseeq(a->hinfo.cpu, b->hinfo.cpu) &&
587                        strcaseeq(a->hinfo.os, b->hinfo.os);
588
589         case DNS_TYPE_SPF: /* exactly the same as TXT */
590         case DNS_TYPE_TXT:
591                 return dns_txt_item_equal(a->txt.items, b->txt.items);
592
593         case DNS_TYPE_A:
594                 return memcmp(&a->a.in_addr, &b->a.in_addr, sizeof(struct in_addr)) == 0;
595
596         case DNS_TYPE_AAAA:
597                 return memcmp(&a->aaaa.in6_addr, &b->aaaa.in6_addr, sizeof(struct in6_addr)) == 0;
598
599         case DNS_TYPE_SOA:
600                 r = dns_name_equal(a->soa.mname, b->soa.mname);
601                 if (r <= 0)
602                         return r;
603                 r = dns_name_equal(a->soa.rname, b->soa.rname);
604                 if (r <= 0)
605                         return r;
606
607                 return a->soa.serial  == b->soa.serial &&
608                        a->soa.refresh == b->soa.refresh &&
609                        a->soa.retry   == b->soa.retry &&
610                        a->soa.expire  == b->soa.expire &&
611                        a->soa.minimum == b->soa.minimum;
612
613         case DNS_TYPE_MX:
614                 if (a->mx.priority != b->mx.priority)
615                         return 0;
616
617                 return dns_name_equal(a->mx.exchange, b->mx.exchange);
618
619         case DNS_TYPE_LOC:
620                 assert(a->loc.version == b->loc.version);
621
622                 return a->loc.size == b->loc.size &&
623                        a->loc.horiz_pre == b->loc.horiz_pre &&
624                        a->loc.vert_pre == b->loc.vert_pre &&
625                        a->loc.latitude == b->loc.latitude &&
626                        a->loc.longitude == b->loc.longitude &&
627                        a->loc.altitude == b->loc.altitude;
628
629         case DNS_TYPE_DS:
630                 return a->ds.key_tag == b->ds.key_tag &&
631                        a->ds.algorithm == b->ds.algorithm &&
632                        a->ds.digest_type == b->ds.digest_type &&
633                        FIELD_EQUAL(a->ds, b->ds, digest);
634
635         case DNS_TYPE_SSHFP:
636                 return a->sshfp.algorithm == b->sshfp.algorithm &&
637                        a->sshfp.fptype == b->sshfp.fptype &&
638                        FIELD_EQUAL(a->sshfp, b->sshfp, fingerprint);
639
640         case DNS_TYPE_DNSKEY:
641                 return a->dnskey.flags == b->dnskey.flags &&
642                        a->dnskey.protocol == b->dnskey.protocol &&
643                        a->dnskey.algorithm == b->dnskey.algorithm &&
644                        FIELD_EQUAL(a->dnskey, b->dnskey, key);
645
646         case DNS_TYPE_RRSIG:
647                 /* do the fast comparisons first */
648                 return a->rrsig.type_covered == b->rrsig.type_covered &&
649                        a->rrsig.algorithm == b->rrsig.algorithm &&
650                        a->rrsig.labels == b->rrsig.labels &&
651                        a->rrsig.original_ttl == b->rrsig.original_ttl &&
652                        a->rrsig.expiration == b->rrsig.expiration &&
653                        a->rrsig.inception == b->rrsig.inception &&
654                        a->rrsig.key_tag == b->rrsig.key_tag &&
655                        FIELD_EQUAL(a->rrsig, b->rrsig, signature) &&
656                        dns_name_equal(a->rrsig.signer, b->rrsig.signer);
657
658         case DNS_TYPE_NSEC:
659                 return dns_name_equal(a->nsec.next_domain_name, b->nsec.next_domain_name) &&
660                        bitmap_equal(a->nsec.types, b->nsec.types);
661
662         case DNS_TYPE_NSEC3:
663                 return a->nsec3.algorithm == b->nsec3.algorithm &&
664                        a->nsec3.flags == b->nsec3.flags &&
665                        a->nsec3.iterations == b->nsec3.iterations &&
666                        FIELD_EQUAL(a->nsec3, b->nsec3, salt) &&
667                        FIELD_EQUAL(a->nsec3, b->nsec3, next_hashed_name) &&
668                        bitmap_equal(a->nsec3.types, b->nsec3.types);
669
670         case DNS_TYPE_TLSA:
671                 return a->tlsa.cert_usage == b->tlsa.cert_usage &&
672                        a->tlsa.selector == b->tlsa.selector &&
673                        a->tlsa.matching_type == b->tlsa.matching_type &&
674                        FIELD_EQUAL(a->tlsa, b->tlsa, data);
675
676         case DNS_TYPE_CAA:
677                 return a->caa.flags == b->caa.flags &&
678                        streq(a->caa.tag, b->caa.tag) &&
679                        FIELD_EQUAL(a->caa, b->caa, value);
680
681         case DNS_TYPE_OPENPGPKEY:
682         default:
683                 return FIELD_EQUAL(a->generic, b->generic, data);
684         }
685 }
686
687 int dns_resource_record_equal(const DnsResourceRecord *a, const DnsResourceRecord *b) {
688         int r;
689
690         assert(a);
691         assert(b);
692
693         if (a == b)
694                 return 1;
695
696         r = dns_resource_key_equal(a->key, b->key);
697         if (r <= 0)
698                 return r;
699
700         return dns_resource_record_payload_equal(a, b);
701 }
702
703 static char* format_location(uint32_t latitude, uint32_t longitude, uint32_t altitude,
704                              uint8_t size, uint8_t horiz_pre, uint8_t vert_pre) {
705         char *s;
706         char NS = latitude >= 1U<<31 ? 'N' : 'S';
707         char EW = longitude >= 1U<<31 ? 'E' : 'W';
708
709         int lat = latitude >= 1U<<31 ? (int) (latitude - (1U<<31)) : (int) ((1U<<31) - latitude);
710         int lon = longitude >= 1U<<31 ? (int) (longitude - (1U<<31)) : (int) ((1U<<31) - longitude);
711         double alt = altitude >= 10000000u ? altitude - 10000000u : -(double)(10000000u - altitude);
712         double siz = (size >> 4) * exp10((double) (size & 0xF));
713         double hor = (horiz_pre >> 4) * exp10((double) (horiz_pre & 0xF));
714         double ver = (vert_pre >> 4) * exp10((double) (vert_pre & 0xF));
715
716         if (asprintf(&s, "%d %d %.3f %c %d %d %.3f %c %.2fm %.2fm %.2fm %.2fm",
717                      (lat / 60000 / 60),
718                      (lat / 60000) % 60,
719                      (lat % 60000) / 1000.,
720                      NS,
721                      (lon / 60000 / 60),
722                      (lon / 60000) % 60,
723                      (lon % 60000) / 1000.,
724                      EW,
725                      alt / 100.,
726                      siz / 100.,
727                      hor / 100.,
728                      ver / 100.) < 0)
729                 return NULL;
730
731         return s;
732 }
733
734 static int format_timestamp_dns(char *buf, size_t l, time_t sec) {
735         struct tm tm;
736
737         assert(buf);
738         assert(l > STRLEN("YYYYMMDDHHmmSS"));
739
740         if (!gmtime_r(&sec, &tm))
741                 return -EINVAL;
742
743         if (strftime(buf, l, "%Y%m%d%H%M%S", &tm) <= 0)
744                 return -EINVAL;
745
746         return 0;
747 }
748
749 static char *format_types(Bitmap *types) {
750         _cleanup_strv_free_ char **strv = NULL;
751         _cleanup_free_ char *str = NULL;
752         Iterator i;
753         unsigned type;
754         int r;
755
756         BITMAP_FOREACH(type, types, i) {
757                 if (dns_type_to_string(type)) {
758                         r = strv_extend(&strv, dns_type_to_string(type));
759                         if (r < 0)
760                                 return NULL;
761                 } else {
762                         char *t;
763
764                         r = asprintf(&t, "TYPE%u", type);
765                         if (r < 0)
766                                 return NULL;
767
768                         r = strv_consume(&strv, t);
769                         if (r < 0)
770                                 return NULL;
771                 }
772         }
773
774         str = strv_join(strv, " ");
775         if (!str)
776                 return NULL;
777
778         return strjoin("( ", str, " )");
779 }
780
781 static char *format_txt(DnsTxtItem *first) {
782         DnsTxtItem *i;
783         size_t c = 1;
784         char *p, *s;
785
786         LIST_FOREACH(items, i, first)
787                 c += i->length * 4 + 3;
788
789         p = s = new(char, c);
790         if (!s)
791                 return NULL;
792
793         LIST_FOREACH(items, i, first) {
794                 size_t j;
795
796                 if (i != first)
797                         *(p++) = ' ';
798
799                 *(p++) = '"';
800
801                 for (j = 0; j < i->length; j++) {
802                         if (i->data[j] < ' ' || i->data[j] == '"' || i->data[j] >= 127) {
803                                 *(p++) = '\\';
804                                 *(p++) = '0' + (i->data[j] / 100);
805                                 *(p++) = '0' + ((i->data[j] / 10) % 10);
806                                 *(p++) = '0' + (i->data[j] % 10);
807                         } else
808                                 *(p++) = i->data[j];
809                 }
810
811                 *(p++) = '"';
812         }
813
814         *p = 0;
815         return s;
816 }
817
818 const char *dns_resource_record_to_string(DnsResourceRecord *rr) {
819         _cleanup_free_ char *t = NULL;
820         char *s, k[DNS_RESOURCE_KEY_STRING_MAX];
821         int r;
822
823         assert(rr);
824
825         if (rr->to_string)
826                 return rr->to_string;
827
828         dns_resource_key_to_string(rr->key, k, sizeof(k));
829
830         switch (rr->unparseable ? _DNS_TYPE_INVALID : rr->key->type) {
831
832         case DNS_TYPE_SRV:
833                 r = asprintf(&s, "%s %u %u %u %s",
834                              k,
835                              rr->srv.priority,
836                              rr->srv.weight,
837                              rr->srv.port,
838                              strna(rr->srv.name));
839                 if (r < 0)
840                         return NULL;
841                 break;
842
843         case DNS_TYPE_PTR:
844         case DNS_TYPE_NS:
845         case DNS_TYPE_CNAME:
846         case DNS_TYPE_DNAME:
847                 s = strjoin(k, " ", rr->ptr.name);
848                 if (!s)
849                         return NULL;
850
851                 break;
852
853         case DNS_TYPE_HINFO:
854                 s = strjoin(k, " ", rr->hinfo.cpu, " ", rr->hinfo.os);
855                 if (!s)
856                         return NULL;
857                 break;
858
859         case DNS_TYPE_SPF: /* exactly the same as TXT */
860         case DNS_TYPE_TXT:
861                 t = format_txt(rr->txt.items);
862                 if (!t)
863                         return NULL;
864
865                 s = strjoin(k, " ", t);
866                 if (!s)
867                         return NULL;
868                 break;
869
870         case DNS_TYPE_A: {
871                 _cleanup_free_ char *x = NULL;
872
873                 r = in_addr_to_string(AF_INET, (const union in_addr_union*) &rr->a.in_addr, &x);
874                 if (r < 0)
875                         return NULL;
876
877                 s = strjoin(k, " ", x);
878                 if (!s)
879                         return NULL;
880                 break;
881         }
882
883         case DNS_TYPE_AAAA:
884                 r = in_addr_to_string(AF_INET6, (const union in_addr_union*) &rr->aaaa.in6_addr, &t);
885                 if (r < 0)
886                         return NULL;
887
888                 s = strjoin(k, " ", t);
889                 if (!s)
890                         return NULL;
891                 break;
892
893         case DNS_TYPE_SOA:
894                 r = asprintf(&s, "%s %s %s %u %u %u %u %u",
895                              k,
896                              strna(rr->soa.mname),
897                              strna(rr->soa.rname),
898                              rr->soa.serial,
899                              rr->soa.refresh,
900                              rr->soa.retry,
901                              rr->soa.expire,
902                              rr->soa.minimum);
903                 if (r < 0)
904                         return NULL;
905                 break;
906
907         case DNS_TYPE_MX:
908                 r = asprintf(&s, "%s %u %s",
909                              k,
910                              rr->mx.priority,
911                              rr->mx.exchange);
912                 if (r < 0)
913                         return NULL;
914                 break;
915
916         case DNS_TYPE_LOC:
917                 assert(rr->loc.version == 0);
918
919                 t = format_location(rr->loc.latitude,
920                                     rr->loc.longitude,
921                                     rr->loc.altitude,
922                                     rr->loc.size,
923                                     rr->loc.horiz_pre,
924                                     rr->loc.vert_pre);
925                 if (!t)
926                         return NULL;
927
928                 s = strjoin(k, " ", t);
929                 if (!s)
930                         return NULL;
931                 break;
932
933         case DNS_TYPE_DS:
934                 t = hexmem(rr->ds.digest, rr->ds.digest_size);
935                 if (!t)
936                         return NULL;
937
938                 r = asprintf(&s, "%s %u %u %u %s",
939                              k,
940                              rr->ds.key_tag,
941                              rr->ds.algorithm,
942                              rr->ds.digest_type,
943                              t);
944                 if (r < 0)
945                         return NULL;
946                 break;
947
948         case DNS_TYPE_SSHFP:
949                 t = hexmem(rr->sshfp.fingerprint, rr->sshfp.fingerprint_size);
950                 if (!t)
951                         return NULL;
952
953                 r = asprintf(&s, "%s %u %u %s",
954                              k,
955                              rr->sshfp.algorithm,
956                              rr->sshfp.fptype,
957                              t);
958                 if (r < 0)
959                         return NULL;
960                 break;
961
962         case DNS_TYPE_DNSKEY: {
963                 _cleanup_free_ char *alg = NULL;
964                 char *ss;
965                 uint16_t key_tag;
966
967                 key_tag = dnssec_keytag(rr, true);
968
969                 r = dnssec_algorithm_to_string_alloc(rr->dnskey.algorithm, &alg);
970                 if (r < 0)
971                         return NULL;
972
973                 r = asprintf(&s, "%s %u %u %s",
974                              k,
975                              rr->dnskey.flags,
976                              rr->dnskey.protocol,
977                              alg);
978                 if (r < 0)
979                         return NULL;
980
981                 r = base64_append(&s, r,
982                                   rr->dnskey.key, rr->dnskey.key_size,
983                                   8, columns());
984                 if (r < 0)
985                         return NULL;
986
987                 r = asprintf(&ss, "%s\n"
988                              "        -- Flags:%s%s%s\n"
989                              "        -- Key tag: %u",
990                              s,
991                              rr->dnskey.flags & DNSKEY_FLAG_SEP ? " SEP" : "",
992                              rr->dnskey.flags & DNSKEY_FLAG_REVOKE ? " REVOKE" : "",
993                              rr->dnskey.flags & DNSKEY_FLAG_ZONE_KEY ? " ZONE_KEY" : "",
994                              key_tag);
995                 if (r < 0)
996                         return NULL;
997                 free(s);
998                 s = ss;
999
1000                 break;
1001         }
1002
1003         case DNS_TYPE_RRSIG: {
1004                 _cleanup_free_ char *alg = NULL;
1005                 char expiration[STRLEN("YYYYMMDDHHmmSS") + 1], inception[STRLEN("YYYYMMDDHHmmSS") + 1];
1006                 const char *type;
1007
1008                 type = dns_type_to_string(rr->rrsig.type_covered);
1009
1010                 r = dnssec_algorithm_to_string_alloc(rr->rrsig.algorithm, &alg);
1011                 if (r < 0)
1012                         return NULL;
1013
1014                 r = format_timestamp_dns(expiration, sizeof(expiration), rr->rrsig.expiration);
1015                 if (r < 0)
1016                         return NULL;
1017
1018                 r = format_timestamp_dns(inception, sizeof(inception), rr->rrsig.inception);
1019                 if (r < 0)
1020                         return NULL;
1021
1022                 /* TYPE?? follows
1023                  * http://tools.ietf.org/html/rfc3597#section-5 */
1024
1025                 r = asprintf(&s, "%s %s%.*u %s %u %u %s %s %u %s",
1026                              k,
1027                              type ?: "TYPE",
1028                              type ? 0 : 1, type ? 0u : (unsigned) rr->rrsig.type_covered,
1029                              alg,
1030                              rr->rrsig.labels,
1031                              rr->rrsig.original_ttl,
1032                              expiration,
1033                              inception,
1034                              rr->rrsig.key_tag,
1035                              rr->rrsig.signer);
1036                 if (r < 0)
1037                         return NULL;
1038
1039                 r = base64_append(&s, r,
1040                                   rr->rrsig.signature, rr->rrsig.signature_size,
1041                                   8, columns());
1042                 if (r < 0)
1043                         return NULL;
1044
1045                 break;
1046         }
1047
1048         case DNS_TYPE_NSEC:
1049                 t = format_types(rr->nsec.types);
1050                 if (!t)
1051                         return NULL;
1052
1053                 r = asprintf(&s, "%s %s %s",
1054                              k,
1055                              rr->nsec.next_domain_name,
1056                              t);
1057                 if (r < 0)
1058                         return NULL;
1059                 break;
1060
1061         case DNS_TYPE_NSEC3: {
1062                 _cleanup_free_ char *salt = NULL, *hash = NULL;
1063
1064                 if (rr->nsec3.salt_size > 0) {
1065                         salt = hexmem(rr->nsec3.salt, rr->nsec3.salt_size);
1066                         if (!salt)
1067                                 return NULL;
1068                 }
1069
1070                 hash = base32hexmem(rr->nsec3.next_hashed_name, rr->nsec3.next_hashed_name_size, false);
1071                 if (!hash)
1072                         return NULL;
1073
1074                 t = format_types(rr->nsec3.types);
1075                 if (!t)
1076                         return NULL;
1077
1078                 r = asprintf(&s, "%s %"PRIu8" %"PRIu8" %"PRIu16" %s %s %s",
1079                              k,
1080                              rr->nsec3.algorithm,
1081                              rr->nsec3.flags,
1082                              rr->nsec3.iterations,
1083                              rr->nsec3.salt_size > 0 ? salt : "-",
1084                              hash,
1085                              t);
1086                 if (r < 0)
1087                         return NULL;
1088
1089                 break;
1090         }
1091
1092         case DNS_TYPE_TLSA: {
1093                 const char *cert_usage, *selector, *matching_type;
1094
1095                 cert_usage = tlsa_cert_usage_to_string(rr->tlsa.cert_usage);
1096                 selector = tlsa_selector_to_string(rr->tlsa.selector);
1097                 matching_type = tlsa_matching_type_to_string(rr->tlsa.matching_type);
1098
1099                 t = hexmem(rr->sshfp.fingerprint, rr->sshfp.fingerprint_size);
1100                 if (!t)
1101                         return NULL;
1102
1103                 r = asprintf(&s,
1104                              "%s %u %u %u %s\n"
1105                              "        -- Cert. usage: %s\n"
1106                              "        -- Selector: %s\n"
1107                              "        -- Matching type: %s",
1108                              k,
1109                              rr->tlsa.cert_usage,
1110                              rr->tlsa.selector,
1111                              rr->tlsa.matching_type,
1112                              t,
1113                              cert_usage,
1114                              selector,
1115                              matching_type);
1116                 if (r < 0)
1117                         return NULL;
1118
1119                 break;
1120         }
1121
1122         case DNS_TYPE_CAA: {
1123                 _cleanup_free_ char *value;
1124
1125                 value = octescape(rr->caa.value, rr->caa.value_size);
1126                 if (!value)
1127                         return NULL;
1128
1129                 r = asprintf(&s, "%s %u %s \"%s\"%s%s%s%.0u",
1130                              k,
1131                              rr->caa.flags,
1132                              rr->caa.tag,
1133                              value,
1134                              rr->caa.flags ? "\n        -- Flags:" : "",
1135                              rr->caa.flags & CAA_FLAG_CRITICAL ? " critical" : "",
1136                              rr->caa.flags & ~CAA_FLAG_CRITICAL ? " " : "",
1137                              rr->caa.flags & ~CAA_FLAG_CRITICAL);
1138                 if (r < 0)
1139                         return NULL;
1140
1141                 break;
1142         }
1143
1144         case DNS_TYPE_OPENPGPKEY: {
1145                 r = asprintf(&s, "%s", k);
1146                 if (r < 0)
1147                         return NULL;
1148
1149                 r = base64_append(&s, r,
1150                                   rr->generic.data, rr->generic.data_size,
1151                                   8, columns());
1152                 if (r < 0)
1153                         return NULL;
1154                 break;
1155         }
1156
1157         default:
1158                 t = hexmem(rr->generic.data, rr->generic.data_size);
1159                 if (!t)
1160                         return NULL;
1161
1162                 /* Format as documented in RFC 3597, Section 5 */
1163                 r = asprintf(&s, "%s \\# %zu %s", k, rr->generic.data_size, t);
1164                 if (r < 0)
1165                         return NULL;
1166                 break;
1167         }
1168
1169         rr->to_string = s;
1170         return s;
1171 }
1172
1173 ssize_t dns_resource_record_payload(DnsResourceRecord *rr, void **out) {
1174         assert(rr);
1175         assert(out);
1176
1177         switch(rr->unparseable ? _DNS_TYPE_INVALID : rr->key->type) {
1178         case DNS_TYPE_SRV:
1179         case DNS_TYPE_PTR:
1180         case DNS_TYPE_NS:
1181         case DNS_TYPE_CNAME:
1182         case DNS_TYPE_DNAME:
1183         case DNS_TYPE_HINFO:
1184         case DNS_TYPE_SPF:
1185         case DNS_TYPE_TXT:
1186         case DNS_TYPE_A:
1187         case DNS_TYPE_AAAA:
1188         case DNS_TYPE_SOA:
1189         case DNS_TYPE_MX:
1190         case DNS_TYPE_LOC:
1191         case DNS_TYPE_DS:
1192         case DNS_TYPE_DNSKEY:
1193         case DNS_TYPE_RRSIG:
1194         case DNS_TYPE_NSEC:
1195         case DNS_TYPE_NSEC3:
1196                 return -EINVAL;
1197
1198         case DNS_TYPE_SSHFP:
1199                 *out = rr->sshfp.fingerprint;
1200                 return rr->sshfp.fingerprint_size;
1201
1202         case DNS_TYPE_TLSA:
1203                 *out = rr->tlsa.data;
1204                 return rr->tlsa.data_size;
1205
1206         case DNS_TYPE_OPENPGPKEY:
1207         default:
1208                 *out = rr->generic.data;
1209                 return rr->generic.data_size;
1210         }
1211 }
1212
1213 int dns_resource_record_to_wire_format(DnsResourceRecord *rr, bool canonical) {
1214
1215         DnsPacket packet = {
1216                 .n_ref = 1,
1217                 .protocol = DNS_PROTOCOL_DNS,
1218                 .on_stack = true,
1219                 .refuse_compression = true,
1220                 .canonical_form = canonical,
1221         };
1222
1223         size_t start, rds;
1224         int r;
1225
1226         assert(rr);
1227
1228         /* Generates the RR in wire-format, optionally in the
1229          * canonical form as discussed in the DNSSEC RFC 4034, Section
1230          * 6.2. We allocate a throw-away DnsPacket object on the stack
1231          * here, because we need some book-keeping for memory
1232          * management, and can reuse the DnsPacket serializer, that
1233          * can generate the canonical form, too, but also knows label
1234          * compression and suchlike. */
1235
1236         if (rr->wire_format && rr->wire_format_canonical == canonical)
1237                 return 0;
1238
1239         r = dns_packet_append_rr(&packet, rr, 0, &start, &rds);
1240         if (r < 0)
1241                 return r;
1242
1243         assert(start == 0);
1244         assert(packet._data);
1245
1246         free(rr->wire_format);
1247         rr->wire_format = packet._data;
1248         rr->wire_format_size = packet.size;
1249         rr->wire_format_rdata_offset = rds;
1250         rr->wire_format_canonical = canonical;
1251
1252         packet._data = NULL;
1253         dns_packet_unref(&packet);
1254
1255         return 0;
1256 }
1257
1258 int dns_resource_record_signer(DnsResourceRecord *rr, const char **ret) {
1259         const char *n;
1260         int r;
1261
1262         assert(rr);
1263         assert(ret);
1264
1265         /* Returns the RRset's signer, if it is known. */
1266
1267         if (rr->n_skip_labels_signer == (unsigned) -1)
1268                 return -ENODATA;
1269
1270         n = dns_resource_key_name(rr->key);
1271         r = dns_name_skip(n, rr->n_skip_labels_signer, &n);
1272         if (r < 0)
1273                 return r;
1274         if (r == 0)
1275                 return -EINVAL;
1276
1277         *ret = n;
1278         return 0;
1279 }
1280
1281 int dns_resource_record_source(DnsResourceRecord *rr, const char **ret) {
1282         const char *n;
1283         int r;
1284
1285         assert(rr);
1286         assert(ret);
1287
1288         /* Returns the RRset's synthesizing source, if it is known. */
1289
1290         if (rr->n_skip_labels_source == (unsigned) -1)
1291                 return -ENODATA;
1292
1293         n = dns_resource_key_name(rr->key);
1294         r = dns_name_skip(n, rr->n_skip_labels_source, &n);
1295         if (r < 0)
1296                 return r;
1297         if (r == 0)
1298                 return -EINVAL;
1299
1300         *ret = n;
1301         return 0;
1302 }
1303
1304 int dns_resource_record_is_signer(DnsResourceRecord *rr, const char *zone) {
1305         const char *signer;
1306         int r;
1307
1308         assert(rr);
1309
1310         r = dns_resource_record_signer(rr, &signer);
1311         if (r < 0)
1312                 return r;
1313
1314         return dns_name_equal(zone, signer);
1315 }
1316
1317 int dns_resource_record_is_synthetic(DnsResourceRecord *rr) {
1318         int r;
1319
1320         assert(rr);
1321
1322         /* Returns > 0 if the RR is generated from a wildcard, and is not the asterisk name itself */
1323
1324         if (rr->n_skip_labels_source == (unsigned) -1)
1325                 return -ENODATA;
1326
1327         if (rr->n_skip_labels_source == 0)
1328                 return 0;
1329
1330         if (rr->n_skip_labels_source > 1)
1331                 return 1;
1332
1333         r = dns_name_startswith(dns_resource_key_name(rr->key), "*");
1334         if (r < 0)
1335                 return r;
1336
1337         return !r;
1338 }
1339
1340 void dns_resource_record_hash_func(const DnsResourceRecord *rr, struct siphash *state) {
1341         assert(rr);
1342
1343         dns_resource_key_hash_func(rr->key, state);
1344
1345         switch (rr->unparseable ? _DNS_TYPE_INVALID : rr->key->type) {
1346
1347         case DNS_TYPE_SRV:
1348                 siphash24_compress(&rr->srv.priority, sizeof(rr->srv.priority), state);
1349                 siphash24_compress(&rr->srv.weight, sizeof(rr->srv.weight), state);
1350                 siphash24_compress(&rr->srv.port, sizeof(rr->srv.port), state);
1351                 dns_name_hash_func(rr->srv.name, state);
1352                 break;
1353
1354         case DNS_TYPE_PTR:
1355         case DNS_TYPE_NS:
1356         case DNS_TYPE_CNAME:
1357         case DNS_TYPE_DNAME:
1358                 dns_name_hash_func(rr->ptr.name, state);
1359                 break;
1360
1361         case DNS_TYPE_HINFO:
1362                 string_hash_func(rr->hinfo.cpu, state);
1363                 string_hash_func(rr->hinfo.os, state);
1364                 break;
1365
1366         case DNS_TYPE_TXT:
1367         case DNS_TYPE_SPF: {
1368                 DnsTxtItem *j;
1369
1370                 LIST_FOREACH(items, j, rr->txt.items) {
1371                         siphash24_compress(j->data, j->length, state);
1372
1373                         /* Add an extra NUL byte, so that "a" followed by "b" doesn't result in the same hash as "ab"
1374                          * followed by "". */
1375                         siphash24_compress_byte(0, state);
1376                 }
1377                 break;
1378         }
1379
1380         case DNS_TYPE_A:
1381                 siphash24_compress(&rr->a.in_addr, sizeof(rr->a.in_addr), state);
1382                 break;
1383
1384         case DNS_TYPE_AAAA:
1385                 siphash24_compress(&rr->aaaa.in6_addr, sizeof(rr->aaaa.in6_addr), state);
1386                 break;
1387
1388         case DNS_TYPE_SOA:
1389                 dns_name_hash_func(rr->soa.mname, state);
1390                 dns_name_hash_func(rr->soa.rname, state);
1391                 siphash24_compress(&rr->soa.serial, sizeof(rr->soa.serial), state);
1392                 siphash24_compress(&rr->soa.refresh, sizeof(rr->soa.refresh), state);
1393                 siphash24_compress(&rr->soa.retry, sizeof(rr->soa.retry), state);
1394                 siphash24_compress(&rr->soa.expire, sizeof(rr->soa.expire), state);
1395                 siphash24_compress(&rr->soa.minimum, sizeof(rr->soa.minimum), state);
1396                 break;
1397
1398         case DNS_TYPE_MX:
1399                 siphash24_compress(&rr->mx.priority, sizeof(rr->mx.priority), state);
1400                 dns_name_hash_func(rr->mx.exchange, state);
1401                 break;
1402
1403         case DNS_TYPE_LOC:
1404                 siphash24_compress(&rr->loc.version, sizeof(rr->loc.version), state);
1405                 siphash24_compress(&rr->loc.size, sizeof(rr->loc.size), state);
1406                 siphash24_compress(&rr->loc.horiz_pre, sizeof(rr->loc.horiz_pre), state);
1407                 siphash24_compress(&rr->loc.vert_pre, sizeof(rr->loc.vert_pre), state);
1408                 siphash24_compress(&rr->loc.latitude, sizeof(rr->loc.latitude), state);
1409                 siphash24_compress(&rr->loc.longitude, sizeof(rr->loc.longitude), state);
1410                 siphash24_compress(&rr->loc.altitude, sizeof(rr->loc.altitude), state);
1411                 break;
1412
1413         case DNS_TYPE_SSHFP:
1414                 siphash24_compress(&rr->sshfp.algorithm, sizeof(rr->sshfp.algorithm), state);
1415                 siphash24_compress(&rr->sshfp.fptype, sizeof(rr->sshfp.fptype), state);
1416                 siphash24_compress(rr->sshfp.fingerprint, rr->sshfp.fingerprint_size, state);
1417                 break;
1418
1419         case DNS_TYPE_DNSKEY:
1420                 siphash24_compress(&rr->dnskey.flags, sizeof(rr->dnskey.flags), state);
1421                 siphash24_compress(&rr->dnskey.protocol, sizeof(rr->dnskey.protocol), state);
1422                 siphash24_compress(&rr->dnskey.algorithm, sizeof(rr->dnskey.algorithm), state);
1423                 siphash24_compress(rr->dnskey.key, rr->dnskey.key_size, state);
1424                 break;
1425
1426         case DNS_TYPE_RRSIG:
1427                 siphash24_compress(&rr->rrsig.type_covered, sizeof(rr->rrsig.type_covered), state);
1428                 siphash24_compress(&rr->rrsig.algorithm, sizeof(rr->rrsig.algorithm), state);
1429                 siphash24_compress(&rr->rrsig.labels, sizeof(rr->rrsig.labels), state);
1430                 siphash24_compress(&rr->rrsig.original_ttl, sizeof(rr->rrsig.original_ttl), state);
1431                 siphash24_compress(&rr->rrsig.expiration, sizeof(rr->rrsig.expiration), state);
1432                 siphash24_compress(&rr->rrsig.inception, sizeof(rr->rrsig.inception), state);
1433                 siphash24_compress(&rr->rrsig.key_tag, sizeof(rr->rrsig.key_tag), state);
1434                 dns_name_hash_func(rr->rrsig.signer, state);
1435                 siphash24_compress(rr->rrsig.signature, rr->rrsig.signature_size, state);
1436                 break;
1437
1438         case DNS_TYPE_NSEC:
1439                 dns_name_hash_func(rr->nsec.next_domain_name, state);
1440                 /* FIXME: we leave out the type bitmap here. Hash
1441                  * would be better if we'd take it into account
1442                  * too. */
1443                 break;
1444
1445         case DNS_TYPE_DS:
1446                 siphash24_compress(&rr->ds.key_tag, sizeof(rr->ds.key_tag), state);
1447                 siphash24_compress(&rr->ds.algorithm, sizeof(rr->ds.algorithm), state);
1448                 siphash24_compress(&rr->ds.digest_type, sizeof(rr->ds.digest_type), state);
1449                 siphash24_compress(rr->ds.digest, rr->ds.digest_size, state);
1450                 break;
1451
1452         case DNS_TYPE_NSEC3:
1453                 siphash24_compress(&rr->nsec3.algorithm, sizeof(rr->nsec3.algorithm), state);
1454                 siphash24_compress(&rr->nsec3.flags, sizeof(rr->nsec3.flags), state);
1455                 siphash24_compress(&rr->nsec3.iterations, sizeof(rr->nsec3.iterations), state);
1456                 siphash24_compress(rr->nsec3.salt, rr->nsec3.salt_size, state);
1457                 siphash24_compress(rr->nsec3.next_hashed_name, rr->nsec3.next_hashed_name_size, state);
1458                 /* FIXME: We leave the bitmaps out */
1459                 break;
1460
1461         case DNS_TYPE_TLSA:
1462                 siphash24_compress(&rr->tlsa.cert_usage, sizeof(rr->tlsa.cert_usage), state);
1463                 siphash24_compress(&rr->tlsa.selector, sizeof(rr->tlsa.selector), state);
1464                 siphash24_compress(&rr->tlsa.matching_type, sizeof(rr->tlsa.matching_type), state);
1465                 siphash24_compress(rr->tlsa.data, rr->tlsa.data_size, state);
1466                 break;
1467
1468         case DNS_TYPE_CAA:
1469                 siphash24_compress(&rr->caa.flags, sizeof(rr->caa.flags), state);
1470                 string_hash_func(rr->caa.tag, state);
1471                 siphash24_compress(rr->caa.value, rr->caa.value_size, state);
1472                 break;
1473
1474         case DNS_TYPE_OPENPGPKEY:
1475         default:
1476                 siphash24_compress(rr->generic.data, rr->generic.data_size, state);
1477                 break;
1478         }
1479 }
1480
1481 static int dns_resource_record_compare_func(const DnsResourceRecord *x, const DnsResourceRecord *y) {
1482         int r;
1483
1484         r = dns_resource_key_compare_func(x->key, y->key);
1485         if (r != 0)
1486                 return r;
1487
1488         if (dns_resource_record_equal(x, y))
1489                 return 0;
1490
1491         /* We still use CMP() here, even though don't implement proper
1492          * ordering, since the hashtable doesn't need ordering anyway. */
1493         return CMP(x, y);
1494 }
1495
1496 DEFINE_HASH_OPS(dns_resource_record_hash_ops, DnsResourceRecord, dns_resource_record_hash_func, dns_resource_record_compare_func);
1497
1498 DnsResourceRecord *dns_resource_record_copy(DnsResourceRecord *rr) {
1499         _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *copy = NULL;
1500         DnsResourceRecord *t;
1501
1502         assert(rr);
1503
1504         copy = dns_resource_record_new(rr->key);
1505         if (!copy)
1506                 return NULL;
1507
1508         copy->ttl = rr->ttl;
1509         copy->expiry = rr->expiry;
1510         copy->n_skip_labels_signer = rr->n_skip_labels_signer;
1511         copy->n_skip_labels_source = rr->n_skip_labels_source;
1512         copy->unparseable = rr->unparseable;
1513
1514         switch (rr->unparseable ? _DNS_TYPE_INVALID : rr->key->type) {
1515
1516         case DNS_TYPE_SRV:
1517                 copy->srv.priority = rr->srv.priority;
1518                 copy->srv.weight = rr->srv.weight;
1519                 copy->srv.port = rr->srv.port;
1520                 copy->srv.name = strdup(rr->srv.name);
1521                 if (!copy->srv.name)
1522                         return NULL;
1523                 break;
1524
1525         case DNS_TYPE_PTR:
1526         case DNS_TYPE_NS:
1527         case DNS_TYPE_CNAME:
1528         case DNS_TYPE_DNAME:
1529                 copy->ptr.name = strdup(rr->ptr.name);
1530                 if (!copy->ptr.name)
1531                         return NULL;
1532                 break;
1533
1534         case DNS_TYPE_HINFO:
1535                 copy->hinfo.cpu = strdup(rr->hinfo.cpu);
1536                 if (!copy->hinfo.cpu)
1537                         return NULL;
1538
1539                 copy->hinfo.os = strdup(rr->hinfo.os);
1540                 if (!copy->hinfo.os)
1541                         return NULL;
1542                 break;
1543
1544         case DNS_TYPE_TXT:
1545         case DNS_TYPE_SPF:
1546                 copy->txt.items = dns_txt_item_copy(rr->txt.items);
1547                 if (!copy->txt.items)
1548                         return NULL;
1549                 break;
1550
1551         case DNS_TYPE_A:
1552                 copy->a = rr->a;
1553                 break;
1554
1555         case DNS_TYPE_AAAA:
1556                 copy->aaaa = rr->aaaa;
1557                 break;
1558
1559         case DNS_TYPE_SOA:
1560                 copy->soa.mname = strdup(rr->soa.mname);
1561                 if (!copy->soa.mname)
1562                         return NULL;
1563                 copy->soa.rname = strdup(rr->soa.rname);
1564                 if (!copy->soa.rname)
1565                         return NULL;
1566                 copy->soa.serial = rr->soa.serial;
1567                 copy->soa.refresh = rr->soa.refresh;
1568                 copy->soa.retry = rr->soa.retry;
1569                 copy->soa.expire = rr->soa.expire;
1570                 copy->soa.minimum = rr->soa.minimum;
1571                 break;
1572
1573         case DNS_TYPE_MX:
1574                 copy->mx.priority = rr->mx.priority;
1575                 copy->mx.exchange = strdup(rr->mx.exchange);
1576                 if (!copy->mx.exchange)
1577                         return NULL;
1578                 break;
1579
1580         case DNS_TYPE_LOC:
1581                 copy->loc = rr->loc;
1582                 break;
1583
1584         case DNS_TYPE_SSHFP:
1585                 copy->sshfp.algorithm = rr->sshfp.algorithm;
1586                 copy->sshfp.fptype = rr->sshfp.fptype;
1587                 copy->sshfp.fingerprint = memdup(rr->sshfp.fingerprint, rr->sshfp.fingerprint_size);
1588                 if (!copy->sshfp.fingerprint)
1589                         return NULL;
1590                 copy->sshfp.fingerprint_size = rr->sshfp.fingerprint_size;
1591                 break;
1592
1593         case DNS_TYPE_DNSKEY:
1594                 copy->dnskey.flags = rr->dnskey.flags;
1595                 copy->dnskey.protocol = rr->dnskey.protocol;
1596                 copy->dnskey.algorithm = rr->dnskey.algorithm;
1597                 copy->dnskey.key = memdup(rr->dnskey.key, rr->dnskey.key_size);
1598                 if (!copy->dnskey.key)
1599                         return NULL;
1600                 copy->dnskey.key_size = rr->dnskey.key_size;
1601                 break;
1602
1603         case DNS_TYPE_RRSIG:
1604                 copy->rrsig.type_covered = rr->rrsig.type_covered;
1605                 copy->rrsig.algorithm = rr->rrsig.algorithm;
1606                 copy->rrsig.labels = rr->rrsig.labels;
1607                 copy->rrsig.original_ttl = rr->rrsig.original_ttl;
1608                 copy->rrsig.expiration = rr->rrsig.expiration;
1609                 copy->rrsig.inception = rr->rrsig.inception;
1610                 copy->rrsig.key_tag = rr->rrsig.key_tag;
1611                 copy->rrsig.signer = strdup(rr->rrsig.signer);
1612                 if (!copy->rrsig.signer)
1613                         return NULL;
1614                 copy->rrsig.signature = memdup(rr->rrsig.signature, rr->rrsig.signature_size);
1615                 if (!copy->rrsig.signature)
1616                         return NULL;
1617                 copy->rrsig.signature_size = rr->rrsig.signature_size;
1618                 break;
1619
1620         case DNS_TYPE_NSEC:
1621                 copy->nsec.next_domain_name = strdup(rr->nsec.next_domain_name);
1622                 if (!copy->nsec.next_domain_name)
1623                         return NULL;
1624                 copy->nsec.types = bitmap_copy(rr->nsec.types);
1625                 if (!copy->nsec.types)
1626                         return NULL;
1627                 break;
1628
1629         case DNS_TYPE_DS:
1630                 copy->ds.key_tag = rr->ds.key_tag;
1631                 copy->ds.algorithm = rr->ds.algorithm;
1632                 copy->ds.digest_type = rr->ds.digest_type;
1633                 copy->ds.digest = memdup(rr->ds.digest, rr->ds.digest_size);
1634                 if (!copy->ds.digest)
1635                         return NULL;
1636                 copy->ds.digest_size = rr->ds.digest_size;
1637                 break;
1638
1639         case DNS_TYPE_NSEC3:
1640                 copy->nsec3.algorithm = rr->nsec3.algorithm;
1641                 copy->nsec3.flags = rr->nsec3.flags;
1642                 copy->nsec3.iterations = rr->nsec3.iterations;
1643                 copy->nsec3.salt = memdup(rr->nsec3.salt, rr->nsec3.salt_size);
1644                 if (!copy->nsec3.salt)
1645                         return NULL;
1646                 copy->nsec3.salt_size = rr->nsec3.salt_size;
1647                 copy->nsec3.next_hashed_name = memdup(rr->nsec3.next_hashed_name, rr->nsec3.next_hashed_name_size);
1648                 if (!copy->nsec3.next_hashed_name_size)
1649                         return NULL;
1650                 copy->nsec3.next_hashed_name_size = rr->nsec3.next_hashed_name_size;
1651                 copy->nsec3.types = bitmap_copy(rr->nsec3.types);
1652                 if (!copy->nsec3.types)
1653                         return NULL;
1654                 break;
1655
1656         case DNS_TYPE_TLSA:
1657                 copy->tlsa.cert_usage = rr->tlsa.cert_usage;
1658                 copy->tlsa.selector = rr->tlsa.selector;
1659                 copy->tlsa.matching_type = rr->tlsa.matching_type;
1660                 copy->tlsa.data = memdup(rr->tlsa.data, rr->tlsa.data_size);
1661                 if (!copy->tlsa.data)
1662                         return NULL;
1663                 copy->tlsa.data_size = rr->tlsa.data_size;
1664                 break;
1665
1666         case DNS_TYPE_CAA:
1667                 copy->caa.flags = rr->caa.flags;
1668                 copy->caa.tag = strdup(rr->caa.tag);
1669                 if (!copy->caa.tag)
1670                         return NULL;
1671                 copy->caa.value = memdup(rr->caa.value, rr->caa.value_size);
1672                 if (!copy->caa.value)
1673                         return NULL;
1674                 copy->caa.value_size = rr->caa.value_size;
1675                 break;
1676
1677         case DNS_TYPE_OPT:
1678         default:
1679                 copy->generic.data = memdup(rr->generic.data, rr->generic.data_size);
1680                 if (!copy->generic.data)
1681                         return NULL;
1682                 copy->generic.data_size = rr->generic.data_size;
1683                 break;
1684         }
1685
1686         t = TAKE_PTR(copy);
1687
1688         return t;
1689 }
1690
1691 int dns_resource_record_clamp_ttl(DnsResourceRecord **rr, uint32_t max_ttl) {
1692         DnsResourceRecord *old_rr, *new_rr;
1693         uint32_t new_ttl;
1694
1695         assert(rr);
1696         old_rr = *rr;
1697
1698         if (old_rr->key->type == DNS_TYPE_OPT)
1699                 return -EINVAL;
1700
1701         new_ttl = MIN(old_rr->ttl, max_ttl);
1702         if (new_ttl == old_rr->ttl)
1703                 return 0;
1704
1705         if (old_rr->n_ref == 1) {
1706                 /* Patch in place */
1707                 old_rr->ttl = new_ttl;
1708                 return 1;
1709         }
1710
1711         new_rr = dns_resource_record_copy(old_rr);
1712         if (!new_rr)
1713                 return -ENOMEM;
1714
1715         new_rr->ttl = new_ttl;
1716
1717         dns_resource_record_unref(*rr);
1718         *rr = new_rr;
1719
1720         return 1;
1721 }
1722
1723 DnsTxtItem *dns_txt_item_free_all(DnsTxtItem *i) {
1724         DnsTxtItem *n;
1725
1726         if (!i)
1727                 return NULL;
1728
1729         n = i->items_next;
1730
1731         free(i);
1732         return dns_txt_item_free_all(n);
1733 }
1734
1735 bool dns_txt_item_equal(DnsTxtItem *a, DnsTxtItem *b) {
1736
1737         if (a == b)
1738                 return true;
1739
1740         if (!a != !b)
1741                 return false;
1742
1743         if (!a)
1744                 return true;
1745
1746         if (a->length != b->length)
1747                 return false;
1748
1749         if (memcmp(a->data, b->data, a->length) != 0)
1750                 return false;
1751
1752         return dns_txt_item_equal(a->items_next, b->items_next);
1753 }
1754
1755 DnsTxtItem *dns_txt_item_copy(DnsTxtItem *first) {
1756         DnsTxtItem *i, *copy = NULL, *end = NULL;
1757
1758         LIST_FOREACH(items, i, first) {
1759                 DnsTxtItem *j;
1760
1761                 j = memdup(i, offsetof(DnsTxtItem, data) + i->length + 1);
1762                 if (!j) {
1763                         dns_txt_item_free_all(copy);
1764                         return NULL;
1765                 }
1766
1767                 LIST_INSERT_AFTER(items, copy, end, j);
1768                 end = j;
1769         }
1770
1771         return copy;
1772 }
1773
1774 int dns_txt_item_new_empty(DnsTxtItem **ret) {
1775         DnsTxtItem *i;
1776
1777         /* RFC 6763, section 6.1 suggests to treat
1778          * empty TXT RRs as equivalent to a TXT record
1779          * with a single empty string. */
1780
1781         i = malloc0(offsetof(DnsTxtItem, data) + 1); /* for safety reasons we add an extra NUL byte */
1782         if (!i)
1783                 return -ENOMEM;
1784
1785         *ret = i;
1786
1787         return 0;
1788 }
1789
1790 static const char* const dnssec_algorithm_table[_DNSSEC_ALGORITHM_MAX_DEFINED] = {
1791         /* Mnemonics as listed on https://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml */
1792         [DNSSEC_ALGORITHM_RSAMD5]             = "RSAMD5",
1793         [DNSSEC_ALGORITHM_DH]                 = "DH",
1794         [DNSSEC_ALGORITHM_DSA]                = "DSA",
1795         [DNSSEC_ALGORITHM_ECC]                = "ECC",
1796         [DNSSEC_ALGORITHM_RSASHA1]            = "RSASHA1",
1797         [DNSSEC_ALGORITHM_DSA_NSEC3_SHA1]     = "DSA-NSEC3-SHA1",
1798         [DNSSEC_ALGORITHM_RSASHA1_NSEC3_SHA1] = "RSASHA1-NSEC3-SHA1",
1799         [DNSSEC_ALGORITHM_RSASHA256]          = "RSASHA256",
1800         [DNSSEC_ALGORITHM_RSASHA512]          = "RSASHA512",
1801         [DNSSEC_ALGORITHM_ECC_GOST]           = "ECC-GOST",
1802         [DNSSEC_ALGORITHM_ECDSAP256SHA256]    = "ECDSAP256SHA256",
1803         [DNSSEC_ALGORITHM_ECDSAP384SHA384]    = "ECDSAP384SHA384",
1804         [DNSSEC_ALGORITHM_ED25519]            = "ED25519",
1805         [DNSSEC_ALGORITHM_ED448]              = "ED448",
1806         [DNSSEC_ALGORITHM_INDIRECT]           = "INDIRECT",
1807         [DNSSEC_ALGORITHM_PRIVATEDNS]         = "PRIVATEDNS",
1808         [DNSSEC_ALGORITHM_PRIVATEOID]         = "PRIVATEOID",
1809 };
1810 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(dnssec_algorithm, int, 255);
1811
1812 static const char* const dnssec_digest_table[_DNSSEC_DIGEST_MAX_DEFINED] = {
1813         /* Names as listed on https://www.iana.org/assignments/ds-rr-types/ds-rr-types.xhtml */
1814         [DNSSEC_DIGEST_SHA1] = "SHA-1",
1815         [DNSSEC_DIGEST_SHA256] = "SHA-256",
1816         [DNSSEC_DIGEST_GOST_R_34_11_94] = "GOST_R_34.11-94",
1817         [DNSSEC_DIGEST_SHA384] = "SHA-384",
1818 };
1819 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(dnssec_digest, int, 255);