Debian Codegraph @

src/resolve/resolved-hook.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-event.h"
4 #include "sd-varlink.h"
5
6 #include "dirent-util.h"
7 #include "dns-domain.h"
8 #include "env-util.h"
9 #include "errno-util.h"
10 #include "fd-util.h"
11 #include "hash-funcs.h"
12 #include "iovec-util.h"
13 #include "json-util.h"
14 #include "ratelimit.h"
15 #include "resolved-hook.h"
16 #include "resolved-manager.h"
17 #include "set.h"
18 #include "stat-util.h"
19 #include "varlink-util.h"
20
21 /* Controls how many idle connections to keep around at max. This is purely an optimization: an established
22 * socket that has gone through connect()/accept() already is just quicker to use. Since we might get a flood
23 * of resolution requests we keep multiple connections open thus, but not too many. */
24 #define HOOK_IDLE_CONNECTIONS_MAX 4U
25
26 /* Encapsulates a specific hook, i.e. bound socket in in the /run/systemd/resolve.hook/ directory */
27 typedef struct Hook {
28 unsigned n_ref;
29
30 Manager *manager;
31 char *socket_path;
32
33 sd_varlink *filter_link;
34 Set *idle_links; /* we retry to recycle varlink connections */
35
36 /* This hook only shall be applied to names matching the following filter parameters */
37 Set *filter_domains; /* if NULL → no filtering; if empty → do not accept anything */
38 unsigned filter_labels_min; /* minimum number of labels */
39 unsigned filter_labels_max; /* maximum number of labels (this is useful to hook only into single-label lookups á la LLMNR) */
40
41 /* timestamp we last saw this in CLOCK_MONOTONIC, for GC handling */
42 uint64_t seen_usec;
43
44 /* When a hook never responds correctly, we'll eventually give up trying */
45 RateLimit reconnect_ratelimit;
46 } Hook;
47
48 static Hook* hook_free(Hook *h) {
49 if (!h)
50 return NULL;
51
52 free(h->socket_path);
53 sd_varlink_unref(h->filter_link);
54 set_free(h->idle_links);
55
56 set_free(h->filter_domains);
57
58 return mfree(h);
59 }
60
61 DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(Hook, hook, hook_free);
62 DEFINE_TRIVIAL_CLEANUP_FUNC(Hook*, hook_unref);
63
64 static Hook *hook_unlink(Hook *h) {
65 if (!h)
66 return NULL;
67
68 if (!h->manager)
69 return NULL;
70
71 if (h->socket_path)
72 hashmap_remove(h->manager->hooks, h->socket_path);
73 h->manager = NULL;
74
75 return hook_unref(h);
76 }
77
78 static int dispatch_filter_domains(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
79 Hook *h = ASSERT_PTR(userdata);
80 int r;
81
82 if (!sd_json_variant_is_array(variant))
83 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an array.", strna(name));
84
85 /* Let's explicitly allocate the set here, since we want that a NULL set means: let everything
86 * through; but an empty set shall mean: let nothing through */
87 r = set_ensure_allocated(&h->filter_domains, &dns_name_hash_ops_free);
88 if (r < 0)
89 return json_log_oom(variant, flags);
90
91 sd_json_variant *i;
92 JSON_VARIANT_ARRAY_FOREACH(i, variant) {
93 if (!sd_json_variant_is_string(i))
94 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL),
95 "Element of JSON field '%s' is not a string.", strna(name));
96
97 r = set_put_strdup_full(&h->filter_domains, &dns_name_hash_ops_free, sd_json_variant_string(i));
98 if (r < 0 && r != -EEXIST)
99 return json_log_oom(variant, flags);
100 }
101
102 return 0;
103 }
104
105 static void hook_reset_filter(Hook *h) {
106 assert(h);
107
108 h->filter_domains = set_free(h->filter_domains);
109 h->filter_labels_min = UINT_MAX;
110 h->filter_labels_max = UINT_MAX;
111 }
112
113 static int hook_acquire_filter(Hook *h);
114
115 static int on_filter_reply(
116 sd_varlink *link,
117 sd_json_variant *parameters,
118 const char *error_id,
119 sd_varlink_reply_flags_t flags,
120 void *userdata) {
121
122 Hook *h = ASSERT_PTR(userdata);
123 int r;
124
125 if (error_id) {
126 if (streq(error_id, SD_VARLINK_ERROR_DISCONNECTED)) {
127 /* When we are are disconnected, that's fine, maybe the other side wants to clean up
128 * open connections every now and then, or is being restarted and thus a moment
129 * offline. Try to reconnect immediately to recover. However, a service that
130 * continuously fails should not be able to get us into a busy loop, hence we apply a
131 * ratelimit, and when it is hit we stop reconnecting. */
132 if (ratelimit_below(&h->reconnect_ratelimit)) {
133 log_debug("Connection terminated while querying filter of hook '%s', trying to reconnect.", h->socket_path);
134
135 h->filter_link = sd_varlink_unref(h->filter_link);
136
137 r = hook_acquire_filter(h);
138 if (r < 0)
139 goto terminate;
140 } else
141 log_warning("Connection terminated while querying filter of hook '%s', and reconnection attempts failed too quickly, giving up.", h->socket_path);
142
143 goto terminate;
144 }
145
146 if (streq(error_id, SD_VARLINK_ERROR_METHOD_NOT_FOUND)) {
147 log_debug("Hook '%s' does not implement querying filter.", h->socket_path);
148 goto terminate;
149 }
150
151 log_warning("Received error while requesting query filter: %s", error_id);
152 goto terminate;
153 }
154
155 if (!FLAGS_SET(flags, SD_VARLINK_REPLY_CONTINUES)) {
156 log_debug("Final message received while querying filter, terminating connection.");
157 goto terminate;
158 }
159
160 hook_reset_filter(h);
161
162 static const struct sd_json_dispatch_field dispatch_table[] = {
163 { "filterDomains", SD_JSON_VARIANT_ARRAY, dispatch_filter_domains, 0, SD_JSON_NULLABLE },
164 { "filterLabelsMin", SD_JSON_VARIANT_INTEGER, sd_json_dispatch_uint, offsetof(Hook, filter_labels_min), 0 },
165 { "filterLabelsMax", SD_JSON_VARIANT_INTEGER, sd_json_dispatch_uint, offsetof(Hook, filter_labels_max), 0 },
166 {},
167 };
168
169 r = sd_json_dispatch(parameters, dispatch_table, SD_JSON_LOG|SD_JSON_ALLOW_EXTENSIONS, h);
170 if (r < 0)
171 goto terminate;
172
173 return 1;
174
175 terminate:
176 h->filter_link = sd_varlink_unref(h->filter_link);
177 hook_reset_filter(h);
178 return 1;
179 }
180
181 static int hook_varlink_connect(Hook *h, int64_t priority, sd_varlink **ret) {
182 int r;
183
184 assert(h);
185 assert(ret);
186
187 _cleanup_(sd_varlink_unrefp) sd_varlink *v = NULL;
188 r = sd_varlink_connect_address(&v, h->socket_path);
189 if (ERRNO_IS_NEG_DISCONNECT(r) || r == -ENOENT) {
190 log_debug_errno(r, "Socket '%s' is not connectible, probably stale, ignoring: %m", h->socket_path);
191 *ret = NULL;
192 return 0; /* dead socket */
193 }
194 if (r < 0)
195 return log_error_errno(r, "Failed to connect to '%s': %m", h->socket_path);
196
197 _cleanup_free_ char *bn = NULL;
198 r = path_extract_filename(h->socket_path, &bn);
199 if (r < 0)
200 return log_error_errno(r, "Failed to extract filename from path '%s': %m", h->socket_path);
201
202 _cleanup_free_ char *j = strjoin("hook-", bn);
203 if (!j)
204 return log_oom();
205
206 (void) sd_varlink_set_description(v, j);
207
208 r = sd_varlink_attach_event(v, h->manager->event, priority);
209 if (r < 0)
210 return log_error_errno(r, "Failed to attach Varlink connection to event loop: %m");
211
212 *ret = TAKE_PTR(v);
213 return 1; /* worked */
214 }
215
216 static int hook_acquire_filter(Hook *h) {
217 int r;
218
219 assert(h);
220 assert(h->manager);
221
222 if (h->filter_link)
223 return 0;
224
225 _cleanup_(sd_varlink_unrefp) sd_varlink *v = NULL;
226 r = hook_varlink_connect(h, SD_EVENT_PRIORITY_NORMAL-10, &v); /* Give the querying of the filter a bit of priority */
227 if (r <= 0)
228 return r;
229
230 /* Turn off timeout, after all we want to continuously monitor filter changes */
231 r = sd_varlink_set_relative_timeout(v, UINT64_MAX);
232 if (r < 0)
233 return log_error_errno(r, "Failed to disable timeout on Varlink connection %m");
234
235 sd_varlink_set_userdata(v, h);
236 r = sd_varlink_bind_reply(v, on_filter_reply);
237 if (r < 0)
238 return log_error_errno(r, "Failed to set filter reply callback on Varlink connection: %m");
239
240 r = sd_varlink_observe(
241 v,
242 "io.systemd.Resolve.Hook.QueryFilter",
243 /* parameters= */ NULL);
244 if (r < 0)
245 return log_error_errno(r, "Failed to issue QueryFilter() varlink call: %m");
246
247 h->filter_link = TAKE_PTR(v);
248 return 0;
249 }
250
251 static int hook_test_filter(Hook *h, DnsQuestion *question) {
252 int r;
253
254 assert(h);
255 assert(question);
256
257 const char *name = dns_question_first_name(question);
258 if (!name)
259 return -EINVAL;
260
261 if (h->filter_labels_max != UINT_MAX || h->filter_labels_min != UINT_MAX) {
262 int n = dns_name_count_labels(name);
263 if (n < 0)
264 return n;
265
266 if (h->filter_labels_max != UINT_MAX && (unsigned) n > h->filter_labels_max)
267 return false;
268 if (h->filter_labels_min != UINT_MAX && (unsigned) n < h->filter_labels_min)
269 return false;
270 }
271
272 if (h->filter_domains)
273 for (const char *p = name;;) {
274 if (set_contains(h->filter_domains, p))
275 break;
276
277 r = dns_name_parent(&p);
278 if (r < 0)
279 return r;
280 if (r == 0)
281 return false;
282 }
283
284 return true;
285 }
286
287 static int hook_compare(const Hook *a, const Hook *b) {
288 assert(a);
289
290 /* Hooks take preference based on the name of their socket */
291 return path_compare(a->socket_path, b->socket_path);
292 }
293
294 static void hook_recycle_varlink(Hook *h, sd_varlink *vl) {
295 int r;
296
297 assert(h);
298 assert(vl);
299
300 /* Disable any potential callbacks while we are recycling the thing */
301 sd_varlink_set_userdata(vl, NULL);
302 (void) sd_varlink_bind_reply(vl, NULL);
303
304 if (set_size(h->idle_links) > HOOK_IDLE_CONNECTIONS_MAX)
305 return;
306
307 /* If we are done with a lookup don't close the connection right-away, but keep it open so that we
308 * can possibly reuse it later, and can save a bit of time on future lookups. We only keep a few
309 * around however. */
310
311 r = set_ensure_put(&h->idle_links, &varlink_hash_ops, vl);
312 if (r < 0)
313 log_debug_errno(r, "Failed to add varlink connection to idle set, ignoring: %m");
314 else
315 sd_varlink_ref(vl);
316 }
317
318 static void manager_gc_hooks(Manager *m, usec_t seen_usec) {
319 assert(m);
320
321 Hook *h;
322 HASHMAP_FOREACH(h, m->hooks) {
323 /* Keep hooks around that have been seen in this iteration */
324 if (h->seen_usec == seen_usec)
325 continue;
326
327 hook_unlink(h);
328 }
329 }
330
331 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(
332 hook_hash_ops,
333 char, string_hash_func, string_compare_func,
334 Hook, hook_unlink);
335
336 static int manager_hook_add(Manager *m, const char *p, usec_t seen_usec) {
337 int r;
338
339 assert(m);
340 assert(p);
341
342 Hook *found = hashmap_get(m->hooks, p);
343 if (found) {
344 found->seen_usec = seen_usec;
345 return 0;
346 }
347
348 _cleanup_free_ char *s = strdup(p);
349 if (!s)
350 return log_oom();
351
352 _cleanup_(hook_unrefp) Hook *h = new(Hook, 1);
353 if (!h)
354 return log_oom();
355
356 *h = (Hook) {
357 .n_ref = 1,
358 .socket_path = TAKE_PTR(s),
359 .filter_labels_min = UINT_MAX,
360 .filter_labels_max = UINT_MAX,
361 .reconnect_ratelimit = { 1 * USEC_PER_SEC, 5 },
362 .seen_usec = seen_usec,
363 };
364
365 if (hashmap_ensure_put(&m->hooks, &hook_hash_ops, h->socket_path, h) < 0)
366 return log_oom();
367
368 hook_ref(h);
369 h->manager = m;
370
371 r = hook_acquire_filter(h);
372 if (r < 0) {
373 hook_unlink(h);
374 return r;
375 }
376
377 return 0;
378 }
379
380 static int manager_hook_discover(Manager *m) {
381 /* You might wonder, why is this /run/systemd/resolve.hook/ and not /run/systemd/resolve/hook/?
382 * That's because of permissions: resolved runs as "systemd-resolve" user and owns
383 * /run/systemd/resolve/, but the hook directory is where other privileged code shall bind a socket
384 * in (and where root ownership hence makes sense). Hence we do not nest the directories, but put
385 * them side by side, so that they can have different ownership. */
386 static const char dp[] = "/run/systemd/resolve.hook";
387 _cleanup_closedir_ DIR *d = NULL;
388 int r;
389
390 assert(m);
391
392 usec_t seen_usec = now(CLOCK_MONOTONIC);
393
394 d = opendir(dp);
395 if (!d) {
396 if (errno == ENOENT)
397 r = 0;
398 else
399 r = log_warning_errno(errno, "Failed to enumerate %s/ contents: %m", dp);
400
401 goto finish;
402 }
403
404 struct stat st;
405 if (fstat(dirfd(d), &st) < 0) {
406 r = log_warning_errno(errno, "Failed to fstat %s/: %m", dp);
407 goto finish;
408 }
409
410 if (stat_inode_unmodified(&st, &m->hook_stat))
411 return 0;
412
413 for (;;) {
414 errno = 0;
415 struct dirent *de = readdir_no_dot(d);
416 if (!de) {
417 if (errno == 0) /* EOD */
418 break;
419
420 r = log_error_errno(errno, "Failed to enumerate %s/: %m", dp);
421 goto finish;
422 }
423
424 if (!IN_SET(de->d_type, DT_SOCK, DT_UNKNOWN))
425 continue;
426
427 _cleanup_free_ char *p = path_join(dp, de->d_name);
428 if (!p) {
429 r = log_oom();
430 goto finish;
431 }
432
433 (void) manager_hook_add(m, p, seen_usec);
434 }
435
436 m->hook_stat = st;
437 r = 0;
438
439 finish:
440 manager_gc_hooks(m, seen_usec);
441 return r;
442 }
443
444 typedef struct HookQuery HookQuery;
445 typedef struct HookQueryCandidate HookQueryCandidate;
446
447 /* Encapsulates a query currently being processed by various hooks */
448 struct HookQuery {
449 /* Question */
450 DnsQuestion *question_idna;
451 DnsQuestion *question_utf8;
452
453 /* Selected answer */
454 DnsAnswer *answer;
455 int answer_rcode;
456 Hook *answer_hook;
457
458 /* Candidates for a reply, i.e, one entry for each hook */
459 LIST_HEAD(HookQueryCandidate, candidates);
460
461 /* Completion callback to invoke */
462 void (*complete)(HookQuery *q, int answer_rcode, DnsAnswer *answer, void *userdata);
463 void *userdata;
464 };
465
466 /* Encapsulates the state of a hook query to one specific hook */
467 struct HookQueryCandidate {
468 HookQuery *query;
469 Hook *hook;
470 sd_varlink *link;
471 LIST_FIELDS(HookQueryCandidate, candidates);
472 };
473
474 static HookQueryCandidate* hook_query_candidate_free(HookQueryCandidate *c) {
475 if (!c)
476 return NULL;
477
478 c->link = sd_varlink_unref(c->link);
479
480 if (c->query)
481 LIST_REMOVE(candidates, c->query->candidates, c);
482
483 hook_unref(c->hook);
484 return mfree(c);
485 }
486
487 DEFINE_TRIVIAL_CLEANUP_FUNC(HookQueryCandidate*, hook_query_candidate_free);
488
489 HookQuery* hook_query_free(HookQuery *hq) {
490 if (!hq)
491 return NULL;
492
493 /* Free candidates as long as there are candidates */
494 while (hq->candidates)
495 hook_query_candidate_free(hq->candidates);
496
497 dns_question_unref(hq->question_utf8);
498 dns_question_unref(hq->question_idna);
499 dns_answer_unref(hq->answer);
500 hook_unref(hq->answer_hook);
501
502 return mfree(hq);
503 }
504
505 DEFINE_TRIVIAL_CLEANUP_FUNC(HookQuery*, hook_query_free);
506
507 static void hook_query_ready(HookQuery *hq) {
508 assert(hq);
509
510 bool done = true;
511 LIST_FOREACH(candidates, c, hq->candidates)
512 if (c->link) { /* ongoing connection? */
513 done = false;
514 break;
515 }
516
517 if (!done)
518 return;
519
520 /* The complete() callback quite likely will destroy 'hq', which might be what keeps the answer
521 * object alive. Let's take an explicit ref here hence, so that it definitely remains alive for the
522 * whole callback lifetime */
523 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = dns_answer_ref(hq->answer);
524 hq->complete(hq, hq->answer_rcode, answer, hq->userdata);
525 }
526
527 static int dispatch_rcode(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
528 int *u = ASSERT_PTR(userdata), r;
529
530 assert(variant);
531
532 int rcode;
533 r = sd_json_dispatch_int(name, variant, flags, &rcode);
534 if (r < 0)
535 return r;
536
537 if (rcode < 0 || rcode >= _DNS_RCODE_MAX)
538 return json_log(variant, flags, SYNTHETIC_ERRNO(ERANGE), "JSON field '%s' contains an invalid DNS rcode.", strna(name));
539
540 *u = rcode;
541 return 0;
542 }
543
544 static int dispatch_answer(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
545 DnsAnswer **a = ASSERT_PTR(userdata);
546 int r;
547
548 assert(variant);
549
550 if (sd_json_variant_is_null(variant)) {
551 *a = dns_answer_unref(*a);
552 return 0;
553 }
554
555 if (!sd_json_variant_is_array(variant))
556 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an array.", strna(name));
557
558 _cleanup_(dns_answer_unrefp) DnsAnswer *l = NULL;
559 sd_json_variant *e;
560 JSON_VARIANT_ARRAY_FOREACH(e, variant) {
561 if (!sd_json_variant_is_object(e))
562 return json_log(e, flags, SYNTHETIC_ERRNO(EINVAL), "JSON array element is not an object");
563
564 _cleanup_(iovec_done) struct iovec iovec = {};
565 static const sd_json_dispatch_field dispatch_table[] = {
566 { "raw", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, 0, SD_JSON_MANDATORY },
567 { "rr", SD_JSON_VARIANT_OBJECT, NULL, 0, 0 },
568 {}
569 };
570
571 r = sd_json_dispatch(e, dispatch_table, flags|SD_JSON_ALLOW_EXTENSIONS, &iovec);
572 if (r < 0)
573 return r;
574
575 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
576 r = dns_resource_record_new_from_raw(&rr, iovec.iov_base, iovec.iov_len);
577 if (r < 0)
578 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL),
579 "JSON field '%s' contains an invalid resource record.", strna(name));
580
581 if (dns_answer_add_extend(&l, rr, /* ifindex= */ 0, /* flags= */ 0, /* rrsig= */ NULL) < 0)
582 return json_log_oom(e, flags);
583 }
584
585 dns_answer_unref(*a);
586 *a = TAKE_PTR(l);
587
588 return 0;
589 }
590
591 typedef struct QueryReplyParameters {
592 int rcode;
593 DnsAnswer *answer;
594 } QueryReplyParameters;
595
596 static void query_reply_parameters_done(QueryReplyParameters *p) {
597 assert(p);
598
599 p->answer = dns_answer_unref(p->answer);
600 }
601
602 static int on_query_reply(
603 sd_varlink *link,
604 sd_json_variant *parameters,
605 const char *error_id,
606 sd_varlink_reply_flags_t flags,
607 void *userdata) {
608
609 HookQueryCandidate *qc = ASSERT_PTR(userdata);
610 HookQuery *q = ASSERT_PTR(qc->query); /* save early in case we destroy 'qc' half-way through this function */
611 int r;
612
613 assert(link);
614
615 _cleanup_(query_reply_parameters_done) QueryReplyParameters p = {
616 .rcode = -1,
617 };
618
619 if (error_id) {
620 log_notice("Query on hook '%s' failed with error '%s', ignoring.", qc->hook->socket_path, error_id);
621 r = -EBADR;
622 goto destroy;
623 }
624
625 static const sd_json_dispatch_field dispatch_table[] = {
626 { "rcode", _SD_JSON_VARIANT_TYPE_INVALID, dispatch_rcode, offsetof(QueryReplyParameters, rcode), 0 },
627 { "answer", SD_JSON_VARIANT_ARRAY, dispatch_answer, offsetof(QueryReplyParameters, answer), 0 },
628 {},
629 };
630
631 r = sd_json_dispatch(parameters, dispatch_table, SD_JSON_LOG|SD_JSON_ALLOW_EXTENSIONS, &p);
632 if (r < 0)
633 goto destroy;
634
635 if (p.rcode < 0) {
636 /* If no rcode is specified, then this means "continue with regular DNS based resolving" to us */
637 log_debug("Query on hook '%s' returned empty reply, skipping.", qc->hook->socket_path);
638 r = 0;
639 goto destroy;
640 }
641
642 bool win = false;
643 if (p.rcode == DNS_RCODE_SUCCESS)
644 /* if this is a successful lookup, let it win if the so far best lookup was a failure or
645 * empty, or ordered later than us */
646 win = q->answer_rcode != DNS_RCODE_SUCCESS ||
647 dns_answer_isempty(q->answer) ||
648 (!dns_answer_isempty(p.answer) &&
649 hook_compare(qc->hook, q->answer_hook) < 0);
650 else
651 /* if this is a failure lookup, let it win if we so far haven't seen any reply at all, or the
652 * winner so far us ordered later than us. */
653 win = q->answer_rcode < 0 ||
654 hook_compare(qc->hook, q->answer_hook) < 0;
655
656 if (win) {
657 /* This reply wins over whatever was stored before. Let's track that */
658 dns_answer_unref(q->answer);
659 q->answer = TAKE_PTR(p.answer);
660 q->answer_rcode = p.rcode;
661 hook_unref(q->answer_hook);
662 q->answer_hook = hook_ref(qc->hook);
663 }
664
665 hook_recycle_varlink(qc->hook, qc->link);
666 qc->link = sd_varlink_unref(qc->link);
667
668 /* Check if we are ready now, and have processed all hooks on this query (this might destroy our
669 * candidate and our hook query!) */
670 hook_query_ready(q);
671 return 0;
672
673 destroy:
674 qc = hook_query_candidate_free(qc);
675 hook_query_ready(q);
676 return r;
677 }
678
679 static int dns_questions_to_json(DnsQuestion *a, DnsQuestion *b, sd_json_variant **ret) {
680 int r;
681
682 assert(ret);
683
684 /* Takes both questions and turns them into a JSON array of objects with the key. Note this takes two
685 * questions, one in IDNA and one in UTF-8 encoding, and merges them, removing duplicates. */
686
687 _cleanup_(sd_json_variant_unrefp) sd_json_variant *l = NULL;
688
689 DnsResourceKey *key;
690 DNS_QUESTION_FOREACH(key, a) {
691 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
692 r = dns_resource_key_to_json(key, &v);
693 if (r < 0)
694 return r;
695
696 r = sd_json_variant_append_arraybo(&l, SD_JSON_BUILD_PAIR_VARIANT("key", v));
697 if (r < 0)
698 return r;
699 }
700
701 if (a != b) {
702 DNS_QUESTION_FOREACH(key, b) {
703 if (dns_question_contains_key(a, key))
704 continue;
705
706 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
707 r = dns_resource_key_to_json(key, &v);
708 if (r < 0)
709 return r;
710
711 r = sd_json_variant_append_arraybo(&l, SD_JSON_BUILD_PAIR_VARIANT("key", v));
712 if (r < 0)
713 return r;
714 }
715 }
716
717 *ret = TAKE_PTR(l);
718 return 0;
719 }
720
721 static int hook_query_add_candidate(HookQuery *hq, Hook *h) {
722 int r;
723
724 assert(hq);
725 assert(h);
726
727 _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
728 for (;;) {
729 /* Before we create a new connection, let's see if there are still idle connections we can
730 * use. */
731 vl = set_steal_first(h->idle_links);
732 if (!vl) {
733 /* Nope, there's nothing, let's create a new connection */
734 r = hook_varlink_connect(h, SD_EVENT_PRIORITY_NORMAL, &vl);
735 if (r <= 0)
736 return r;
737
738 break;
739 }
740
741 r = sd_varlink_is_connected(vl);
742 if (r < 0)
743 return log_error_errno(r, "Failed to check if varlink connection is connected: %m");
744 if (r > 0)
745 break;
746
747 vl = sd_varlink_unref(vl);
748 }
749
750 /* Set a short timeout for hooks. Hooks should not be able to cause the DNS part of the lookup to fail. */
751 r = sd_varlink_set_relative_timeout(vl, SD_RESOLVED_QUERY_TIMEOUT_USEC/4);
752 if (r < 0)
753 return log_error_errno(r, "Failed to set Varlink connection timeout: %m");
754
755 r = sd_varlink_bind_reply(vl, on_query_reply);
756 if (r < 0)
757 return log_error_errno(r, "Failed to bind reply callback to Varlink connection: %m");
758
759 _cleanup_(sd_json_variant_unrefp) sd_json_variant *jq = NULL;
760 r = dns_questions_to_json(hq->question_idna, hq->question_utf8, &jq);
761 if (r < 0)
762 return log_error_errno(r, "Failed to convert question to JSON: %m");
763
764 r = sd_varlink_invokebo(
765 vl,
766 "io.systemd.Resolve.Hook.ResolveRecord",
767 SD_JSON_BUILD_PAIR_VARIANT("question", jq));
768 if (r < 0)
769 return log_error_errno(r, "Failed to enqueue question onto Varlink connection: %m");
770
771 _cleanup_(hook_query_candidate_freep) HookQueryCandidate *qc = new(HookQueryCandidate, 1);
772 if (!qc)
773 return log_oom();
774
775 qc->query = hq;
776 qc->hook = hook_ref(h);
777 qc->link = TAKE_PTR(vl);
778 LIST_PREPEND(candidates, hq->candidates, qc);
779
780 sd_varlink_set_userdata(qc->link, qc);
781
782 TAKE_PTR(qc);
783
784 return 0;
785 }
786
787 static bool use_hooks(void) {
788 static int cache = -1;
789 int r;
790
791 if (cache >= 0)
792 return cache;
793
794 r = secure_getenv_bool("SYSTEMD_RESOLVED_HOOK");
795 if (r < 0) {
796 if (r != -ENXIO)
797 log_debug_errno(r, "Failed to parse $SYSTEMD_RESOLVED_HOOK, ignoring: %m");
798
799 return (cache = true);
800 }
801
802 return (cache = r);
803 }
804
805 int manager_hook_query(
806 Manager *m,
807 DnsQuestion *question_idna,
808 DnsQuestion *question_utf8,
809 HookCompleteCallback complete_cb,
810 void *userdata,
811 HookQuery **ret) {
812
813 int r;
814
815 assert(m);
816 assert(ret);
817
818 if (!use_hooks()) {
819 *ret = NULL;
820 return 0; /* no relevant hooks, continue immediately */
821 }
822
823 /* Let's bring our list of hooks up-to-date */
824 (void) manager_hook_discover(m);
825
826 _cleanup_(hook_query_freep) HookQuery *hq = NULL;
827
828 Hook *h;
829 HASHMAP_FOREACH(h, m->hooks) {
830 r = hook_test_filter(h, question_idna);
831 if (r < 0) {
832 log_warning_errno(
833 r, "Failed to test if hook '%s' matches IDNA question (%s), assuming not.",
834 h->socket_path, dns_question_first_name(question_idna));
835 continue;
836 }
837 if (r == 0) {
838 r = hook_test_filter(h, question_utf8);
839 if (r < 0) {
840 log_warning_errno(
841 r, "Failed to test if hook '%s' matches UTF-8 question (%s), assuming not.",
842 h->socket_path, dns_question_first_name(question_utf8));
843 continue;
844 }
845 if (r == 0) {
846 log_debug("Hook %s does not match question, skipping.", h->socket_path);
847 continue;
848 }
849 }
850
851 if (!hq) {
852 hq = new(HookQuery, 1);
853 if (!hq)
854 return log_oom();
855
856 *hq = (HookQuery) {
857 .question_idna = dns_question_ref(question_idna),
858 .question_utf8 = dns_question_ref(question_utf8),
859 .answer_rcode = -1,
860 .complete = complete_cb,
861 .userdata = userdata,
862 };
863 }
864
865 r = hook_query_add_candidate(hq, h);
866 if (r < 0)
867 return r;
868 }
869
870 if (!hq || !hq->candidates) {
871 *ret = NULL;
872 return 0; /* no relevant hooks, continue immediately */
873 }
874
875 *ret = TAKE_PTR(hq);
876 return 1; /* please wait for the hooks to reply */
877 }