+ if (ret)
+ *ret = q;
+ q = NULL;
+
+ return 0;
+}
+
+static void dns_query_stop(DnsQuery *q) {
+ DnsQueryTransaction *t;
+
+ assert(q);
+
+ q->timeout_event_source = sd_event_source_unref(q->timeout_event_source);
+
+ while ((t = set_steal_first(q->transactions))) {
+ set_remove(t->queries, q);
+ dns_query_transaction_gc(t);
+ }
+}
+
+static void dns_query_complete(DnsQuery *q, DnsQueryState state) {
+ assert(q);
+ assert(!IN_SET(state, DNS_QUERY_NULL, DNS_QUERY_PENDING));
+ assert(IN_SET(q->state, DNS_QUERY_NULL, DNS_QUERY_PENDING));
+
+ /* Note that this call might invalidate the query. Callers
+ * should hence not attempt to access the query or transaction
+ * after calling this function. */
+
+ q->state = state;
+
+ dns_query_stop(q);
+ if (q->complete)
+ q->complete(q);
+}
+
+static int on_query_timeout(sd_event_source *s, usec_t usec, void *userdata) {
+ DnsQuery *q = userdata;
+
+ assert(s);
+ assert(q);
+
+ dns_query_complete(q, DNS_QUERY_TIMEOUT);
+ return 0;
+}
+
+static int dns_query_add_transaction(DnsQuery *q, DnsScope *s, DnsResourceKey *key) {
+ _cleanup_(dns_question_unrefp) DnsQuestion *question = NULL;
+ DnsQueryTransaction *t;
+ int r;
+
+ assert(q);
+
+ r = set_ensure_allocated(&q->transactions, NULL, NULL);
+ if (r < 0)
+ return r;
+
+ if (key) {
+ question = dns_question_new(1);
+ if (!question)
+ return -ENOMEM;
+
+ r = dns_question_add(question, key);
+ if (r < 0)
+ return r;
+ } else
+ question = dns_question_ref(q->question);
+
+ LIST_FOREACH(transactions_by_scope, t, s->transactions)
+ if (dns_question_is_superset(t->question, question))
+ break;
+
+ if (!t) {
+ r = dns_query_transaction_new(&t, s, question);
+ if (r < 0)
+ return r;
+ }
+
+ r = set_ensure_allocated(&t->queries, NULL, NULL);
+ if (r < 0)
+ goto fail;
+
+ r = set_put(t->queries, q);
+ if (r < 0)
+ goto fail;
+
+ r = set_put(q->transactions, t);
+ if (r < 0) {
+ set_remove(t->queries, q);
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ dns_query_transaction_gc(t);
+ return r;
+}
+
+static int dns_query_add_transaction_split(DnsQuery *q, DnsScope *s) {
+ int r;
+
+ assert(q);
+ assert(s);
+
+ if (s->protocol == DNS_PROTOCOL_MDNS) {
+ r = dns_query_add_transaction(q, s, NULL);
+ if (r < 0)
+ return r;
+ } else {
+ unsigned i;
+
+ /* On DNS and LLMNR we can only send a single
+ * question per datagram, hence issue multiple
+ * transactions. */
+
+ for (i = 0; i < q->question->n_keys; i++) {
+ r = dns_query_add_transaction(q, s, q->question->keys[i]);
+ if (r < 0)
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+int dns_query_go(DnsQuery *q) {
+ DnsScopeMatch found = DNS_SCOPE_NO;
+ DnsScope *s, *first = NULL;
+ DnsQueryTransaction *t;
+ const char *name;
+ Iterator i;
+ int r;
+
+ assert(q);
+
+ if (q->state != DNS_QUERY_NULL)
+ return 0;
+
+ assert(q->question);
+ assert(q->question->n_keys > 0);
+
+ name = DNS_RESOURCE_KEY_NAME(q->question->keys[0]);
+
+ LIST_FOREACH(scopes, s, q->manager->dns_scopes) {