HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/resolve/resolvectl.c

155,789 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 149f229a7d7186a95b4a8379de226d95331c4a92

Lines 1–1000 of 3,869

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <locale.h>
#include <net/if.h>
 
#include "sd-bus.h"
#include "sd-daemon.h"
#include "sd-event.h"
#include "sd-json.h"
#include "sd-netlink.h"
#include "sd-varlink.h"
 
#include "af-list.h"
#include "alloc-util.h"
#include "ansi-color.h"
#include "argv-util.h"
#include "build.h"
#include "bus-common-errors.h"
#include "bus-error.h"
#include "bus-locator.h"
#include "bus-util.h"
#include "crypto-util.h"
#include "dlopen-note.h"
#include "dns-configuration.h"
#include "dns-domain.h"
#include "dns-packet.h"
#include "dns-rr.h"
#include "errno-list.h"
#include "errno-util.h"
#include "format-ifname.h"
#include "format-table.h"
#include "glyph-util.h"
#include "hostname-util.h"
#include "json-util.h"
#include "main-func.h"
#include "missing-network.h"
#include "netlink-util.h"
#include "options.h"
#include "ordered-set.h"
#include "pager.h"
#include "parse-argument.h"
#include "parse-util.h"
#include "polkit-agent.h"
#include "resolvconf-compat.h"
#include "resolve-util.h"
#include "resolvectl.h"
#include "resolved-def.h"
#include "resolved-util.h"
#include "resolve-varlink-util.h"
#include "set.h"
#include "socket-netlink.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "terminal-util.h"
#include "time-util.h"
#include "utf8.h"
#include "varlink-util.h"
#include "verb-log-control.h"
#include "verbs.h"
 
static int arg_family = AF_UNSPEC;
static int arg_ifindex = 0;
static char *arg_ifname = NULL;
static uint16_t arg_type = 0;
static uint16_t arg_class = 0;
static bool arg_legend = true;
static uint64_t arg_flags = 0;
static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
static PagerFlags arg_pager_flags = 0;
bool arg_ifindex_permissive = false; /* If true, don't generate an error if the specified interface index doesn't exist */
static const char *arg_service_family = NULL;
static bool arg_service_txt_set = false;
static bool arg_ask_password = true;
 
typedef enum RawType {
        RAW_NONE,
        RAW_PAYLOAD,
        RAW_PACKET,
} RawType;
static RawType arg_raw = RAW_NONE;
 
/* Used by compat interfaces: systemd-resolve and resolvconf. */
ExecutionMode arg_mode = MODE_RESOLVE_HOST;
char **arg_set_dns = NULL;
char **arg_set_domain = NULL;
bool arg_disable_default_route = false;
static const char *arg_set_llmnr = NULL;
static const char *arg_set_mdns = NULL;
static const char *arg_set_dns_over_tls = NULL;
static const char *arg_set_dnssec = NULL;
static char **arg_set_nta = NULL;
 
STATIC_DESTRUCTOR_REGISTER(arg_ifname, freep);
STATIC_DESTRUCTOR_REGISTER(arg_set_dns, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_set_domain, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_set_nta, strv_freep);
 
COMMAND(
        "resolvectl\0",
        "Send control commands to the network name resolution manager, or "
        "resolve domain names, IPv4 and IPv6 addresses, DNS records, and services.",
        .man_pages = "resolvectl(1)\0",
        .option_namespace = "resolvectl",
        .pager_flags = &arg_pager_flags,
);
 
typedef enum StatusMode {
        STATUS_ALL,
        STATUS_DNS,
        STATUS_DOMAIN,
        STATUS_DEFAULT_ROUTE,
        STATUS_LLMNR,
        STATUS_MDNS,
        STATUS_DNS_OVER_TLS,
        STATUS_DNSSEC,
        STATUS_NTA,
        _STATUS_MAX,
        _STATUS_INVALID = -EINVAL,
} StatusMode;
 
static const char* const status_mode_json_field_table[_STATUS_MAX] = {
        [STATUS_ALL]           = NULL,
        [STATUS_DNS]           = "servers",
        [STATUS_DOMAIN]        = "searchDomains",
        [STATUS_DEFAULT_ROUTE] = "defaultRoute",
        [STATUS_LLMNR]         = "llmnr",
        [STATUS_MDNS]          = "mDNS",
        [STATUS_DNS_OVER_TLS]  = "dnsOverTLS",
        [STATUS_DNSSEC]        = "dnssec",
        [STATUS_NTA]           = "negativeTrustAnchors",
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(status_mode_json_field, StatusMode);
 
static int strv_extend_extended_bool(char ***strv, const char *name, const char *value) {
        int r;
 
        if (value) {
                r = parse_boolean(value);
                if (r >= 0)
                        return strv_extendf(strv, "%s%s", plus_minus(r), name);
        }
 
        return strv_extendf(strv, "%s=%s", name, value ?: "???");
}
 
static int acquire_bus(sd_bus **ret) {
        _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
        int r;
 
        assert(ret);
 
        r = sd_bus_open_system(&bus);
        if (r < 0)
                return log_error_errno(r, "sd_bus_open_system: %m");
 
        (void) sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);
 
        *ret = TAKE_PTR(bus);
        return 0;
}
 
int ifname_mangle_full(const char *s, bool drop_protocol_specifier) {
        _cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL;
        _cleanup_strv_free_ char **found = NULL;
        int r;
 
        assert(s);
 
        if (drop_protocol_specifier) {
                _cleanup_free_ char *buf = NULL;
                int ifindex_longest_name = -ENODEV;
 
                /* When invoked as resolvconf, drop the protocol specifier(s) at the end. */
 
                buf = strdup(s);
                if (!buf)
                        return log_oom();
 
                for (;;) {
                        r = rtnl_resolve_interface(&rtnl, buf);
                        if (r > 0) {
                                if (ifindex_longest_name <= 0)
                                        ifindex_longest_name = r;
 
                                r = strv_extend(&found, buf);
                                if (r < 0)
                                        return log_oom();
                        }
 
                        char *dot = strrchr(buf, '.');
                        if (!dot)
                                break;
 
                        *dot = '\0';
                }
 
                unsigned n = strv_length(found);
                if (n > 1) {
                        _cleanup_free_ char *joined = NULL;
 
                        joined = strv_join(found, ", ");
                        log_warning("Found multiple interfaces (%s) matching with '%s'. Using '%s' (ifindex=%i).",
                                    strna(joined), s, found[0], ifindex_longest_name);
 
                } else if (n == 1) {
                        const char *proto;
 
                        proto = ASSERT_PTR(startswith(s, found[0]));
                        if (!isempty(proto))
                                log_info("Dropped protocol specifier '%s' from '%s'. Using '%s' (ifindex=%i).",
                                         proto, s, found[0], ifindex_longest_name);
                }
 
                r = ifindex_longest_name;
        } else
                r = rtnl_resolve_interface(&rtnl, s);
        if (r < 0) {
                if (ERRNO_IS_DEVICE_ABSENT(r) && arg_ifindex_permissive) {
                        log_debug_errno(r, "Interface '%s' not found, but -f specified, ignoring: %m", s);
                        return 0; /* done */
                }
                return log_error_errno(r, "Failed to resolve interface \"%s\": %m", s);
        }
 
        if (arg_ifindex > 0 && arg_ifindex != r)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Specified multiple different interfaces. Refusing.");
 
        arg_ifindex = r;
        return free_and_strdup_warn(&arg_ifname, found ? found[0] : s); /* found */
}
 
static void print_source(uint64_t flags, usec_t rtt) {
        if (!arg_legend)
                return;
 
        if (sd_json_format_enabled(arg_json_format_flags))
                return;
 
        if (flags == 0)
                return;
 
        printf("\n%s-- Information acquired via", ansi_grey());
 
        printf(" protocol%s%s%s%s%s",
               flags & SD_RESOLVED_DNS ? " DNS" :"",
               flags & SD_RESOLVED_LLMNR_IPV4 ? " LLMNR/IPv4" : "",
               flags & SD_RESOLVED_LLMNR_IPV6 ? " LLMNR/IPv6" : "",
               flags & SD_RESOLVED_MDNS_IPV4 ? " mDNS/IPv4" : "",
               flags & SD_RESOLVED_MDNS_IPV6 ? " mDNS/IPv6" : "");
 
        printf(" in %s.%s\n"
               "%s-- Data is authenticated: %s; Data was acquired via local or encrypted transport: %s%s\n",
               FORMAT_TIMESPAN(rtt, 100),
               ansi_normal(),
               ansi_grey(),
               yes_no(flags & SD_RESOLVED_AUTHENTICATED),
               yes_no(flags & SD_RESOLVED_CONFIDENTIAL),
               ansi_normal());
 
        if ((flags & (SD_RESOLVED_FROM_MASK|SD_RESOLVED_SYNTHETIC)) != 0)
                printf("%s-- Data from:%s%s%s%s%s%s%s\n",
                       ansi_grey(),
                       FLAGS_SET(flags, SD_RESOLVED_SYNTHETIC) ? " synthetic" : "",
                       FLAGS_SET(flags, SD_RESOLVED_FROM_CACHE) ? " cache" : "",
                       FLAGS_SET(flags, SD_RESOLVED_FROM_ZONE) ? " zone" : "",
                       FLAGS_SET(flags, SD_RESOLVED_FROM_TRUST_ANCHOR) ? " trust-anchor" : "",
                       FLAGS_SET(flags, SD_RESOLVED_FROM_NETWORK) ? " network" : "",
                       FLAGS_SET(flags, SD_RESOLVED_FROM_HOOK) ? " hook" : "",
                       ansi_normal());
}
 
static void print_ifindex_comment(int printed_so_far, int ifindex) {
        char ifname[IF_NAMESIZE];
        int r;
 
        if (ifindex <= 0)
                return;
 
        r = format_ifname(ifindex, ifname);
        if (r < 0)
                return (void) log_warning_errno(r, "Failed to resolve interface name for index %i, ignoring: %m", ifindex);
 
        printf("%*s%s-- link: %s%s",
               60 > printed_so_far ? 60 - printed_so_far : 0, " ", /* Align comment to the 60th column */
               ansi_grey(), ifname, ansi_normal());
}
 
static int dump_resolve_error_json(const char *name, const char *error_id, sd_json_variant *parameters, int ret) {
        int r;
 
        assert(name);
        assert(!isempty(error_id));
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *j = sd_json_variant_ref(parameters);
        r = sd_json_variant_merge_objectbo(
                        &j,
                        SD_JSON_BUILD_PAIR_STRING("name", name),
                        SD_JSON_BUILD_PAIR_STRING("error", error_id));
        if (r < 0)
                return r;
 
        r = sd_json_variant_dump(j, arg_json_format_flags, /* f= */ NULL, /* prefix= */ NULL);
        if (r < 0)
                return r;
 
        return ret;
}
 
static int varlink_log_resolve_error(const char *name, const char *error_id, sd_json_variant *reply, bool warn_missing) {
        int r;
 
        assert(name);
        assert(!isempty(error_id));
 
        int ret = sd_varlink_error_to_errno(error_id, reply);
        _cleanup_(resolve_error_done) ResolveError error = {
                .rcode = _DNS_RCODE_INVALID,
                .ede_rcode = _DNS_EDE_RCODE_INVALID,
        };
        if (reply) {
                r = dispatch_resolve_error(/* name = */ NULL, reply, SD_JSON_LOG, &error);
                if (r < 0)
                        log_debug_errno(r, "Failed to dispatch error JSON, ignoring: %m");
        }
 
        if (error.rcode == DNS_RCODE_NXDOMAIN && !warn_missing)
                return -ENXIO;
 
        if (sd_json_format_enabled(arg_json_format_flags))
                return dump_resolve_error_json(
                                name,
                                error_id,
                                reply,
                                error.rcode == DNS_RCODE_NXDOMAIN ? -ENXIO : ret);
 
        static const struct {
                const char *error_id;
                const char *msg;
        } error_message_table[] = {
                { "io.systemd.Resolve.NoNameServers",                 "No appropriate name servers or networks for name found"      },
                { "io.systemd.Resolve.QueryTimedOut",                 "Query timed out"                                             },
                { "io.systemd.Resolve.MaxAttemptsReached",            "All attempts to contact name servers or networks failed"     },
                { "io.systemd.Resolve.InvalidReply",                  "Received invalid reply"                                      },
                { "io.systemd.Resolve.QueryAborted",                  "Query aborted"                                               },
                { "io.systemd.Resolve.QueryRefused",                  "DNS query type refused"                                      },
                { "io.systemd.Resolve.NoTrustAnchor",                 "No suitable trust anchor known"                              },
                { "io.systemd.Resolve.ResourceRecordTypeUnsupported", "Server does not support requested resource record type"      },
                { "io.systemd.Resolve.NetworkDown",                   "Network is down"                                             },
                { "io.systemd.Resolve.NoSource",                      "All suitable resolution sources turned off"                  },
                { "io.systemd.Resolve.StubLoop",                      "Configured DNS server loops back to us"                      },
                { "io.systemd.Resolve.ZoneTransfersNotPermitted",     "Zone transfers not permitted via this programming interface" },
        };
        FOREACH_ELEMENT(em, error_message_table)
                if (streq(em->error_id, error_id))
                        return log_error_errno(ret, "%s: resolve call failed: %s", name, em->msg);
 
        if (streq(error_id, "io.systemd.Resolve.NoSuchResourceRecord"))
                return log_error_errno(ret, "%s: resolve call failed: '%s' does not have any RR of the requested type", name, name);
 
        if (streq(error_id, "io.systemd.Resolve.CNAMELoop"))
                return log_error_errno(ret, "%s: resolve call failed: CNAME loop detected, or CNAME resolving disabled on '%s'", name, name);
 
        if (streq(error_id, "io.systemd.Resolve.ServiceNotProvided"))
                return log_error_errno(ret, "%s: resolve call failed: '%s' does not provide the requested service", name, name);
 
        if (streq(error_id, "io.systemd.Resolve.InconsistentServiceRecords"))
                return log_error_errno(ret, "%s: resolve call failed: '%s' does not provide a consistent set of service resource records", name, name);
 
        _cleanup_free_ char *msg_extended = NULL;
        if (error.ede_rcode >= 0) {
                msg_extended = strjoin(" (",
                                       FORMAT_DNS_EDE_RCODE(error.ede_rcode),
                                       !isempty(error.ede_msg) ? ": " : "",
                                       strempty(error.ede_msg),
                                       ")");
                if (!msg_extended)
                        return log_oom();
        }
 
        if (streq(error_id, "io.systemd.Resolve.DNSSECValidationFailed"))
                return log_error_errno(ret, "%s: resolve call failed: DNSSEC validation failed: %s%s", name, error.result, strempty(msg_extended));
 
        if (error.rcode != _DNS_RCODE_INVALID) {
                if (error.rcode == DNS_RCODE_NXDOMAIN) {
                        return log_error_errno(SYNTHETIC_ERRNO(ENXIO), "%s: resolve call failed: Name '%s' not found%s%s",
                                               name, error.query_string ?: name, error.ede_rcode >= 0 ? ":" : "", strempty(msg_extended));
                }
 
                return log_error_errno(ret, "%s: resolve call failed: Could not resolve '%s', server or network returned error: %s%s",
                                       name, error.query_string ?: name, FORMAT_DNS_RCODE(error.rcode), strempty(msg_extended));
        }
 
        return log_error_errno(ret, "%s: resolve call failed: %s", name, error_id);
}
 
static int varlink_connect_with_query_timeout(sd_varlink **vl) {
        int r;
 
        assert(vl);
 
        r = sd_varlink_connect_address(vl, "/run/systemd/resolve/io.systemd.Resolve");
        if (r < 0)
                return log_error_errno(r, "Failed to connect to service /run/systemd/resolve/io.systemd.Resolve: %m");
 
        r = sd_varlink_set_relative_timeout(*vl, SD_RESOLVED_QUERY_TIMEOUT_USEC);
        if (r < 0)
                return log_error_errno(r, "Failed to set query timeout: %m");
 
        return 0;
}
 
static int resolve_host(const char *name) {
        int r;
 
        assert(name);
 
        if (sd_json_format_enabled(arg_json_format_flags))
                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Use --json=pretty with --type=A or --type=AAAA to acquire address record information in JSON format.");
 
        log_debug("Resolving %s (family %s, interface %s).", name, af_to_name(arg_family) ?: "*", isempty(arg_ifname) ? "*" : arg_ifname);
 
        _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
        r = varlink_connect_with_query_timeout(&vl);
        if (r < 0)
                return r;
 
        usec_t ts = now(CLOCK_MONOTONIC);
 
        const char *error_id = NULL;
        sd_json_variant *v = NULL;
        r = sd_varlink_callbo(
                        vl,
                        "io.systemd.Resolve.ResolveHostname",
                        &v,
                        &error_id,
                        SD_JSON_BUILD_PAIR_STRING("name", name),
                        JSON_BUILD_PAIR_CONDITION_UNSIGNED(arg_ifindex > 0, "ifindex", arg_ifindex),
                        JSON_BUILD_PAIR_CONDITION_UNSIGNED(arg_family != AF_UNSPEC, "family", arg_family),
                        JSON_BUILD_PAIR_UNSIGNED_NON_ZERO("flags", arg_flags));
        if (r < 0)
                return log_error_errno(r, "Failed to issue varlink call: %m");
 
        ts = now(CLOCK_MONOTONIC) - ts;
 
        if (!isempty(error_id))
                return varlink_log_resolve_error(name, error_id, v, /* warn_missing = */ true);
 
        _cleanup_(resolve_hostname_reply_done) ResolveHostnameReply reply = {};
        r = dispatch_resolve_hostname_reply(/* name = */ NULL, v, SD_JSON_LOG, &reply);
        if (r < 0)
                return r;
 
        bool first = true;
        FOREACH_ARRAY(address, reply.addresses, reply.n_addresses) {
                _cleanup_free_ char *pretty = NULL;
                r = in_addr_ifindex_to_string(address->family, &address->in_addr.address, address->ifindex, &pretty);
                if (r < 0)
                        return log_error_errno(r, "Failed to print address for %s: %m", name);
 
                int k = printf("%*s%s %s%s%s",
                               (int) strlen(name),
                               first ? name : "",
                               first ? ":" : " ",
                               ansi_highlight(),
                               pretty,
                               ansi_normal());
 
                print_ifindex_comment(k, address->ifindex);
                fputc('\n', stdout);
 
                first = false;
        }
 
        if (!streq(name, reply.name))
                printf("%*s%s (%s)\n",
                       (int) strlen(name),
                       reply.n_addresses == 0 ? name : "",
                       reply.n_addresses == 0 ? ":" : " ",
                       reply.name);
 
        if (reply.n_addresses == 0)
                return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "%s: no addresses found", name);
 
        print_source(reply.flags, ts);
 
        return 0;
}
 
static int resolve_address(int family, const union in_addr_union *address, int ifindex) {
        int r;
 
        assert(IN_SET(family, AF_INET, AF_INET6));
        assert(address);
 
        if (sd_json_format_enabled(arg_json_format_flags))
                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Use --json=pretty with --type= to acquire resource record information in JSON format.");
 
        if (ifindex <= 0)
                ifindex = arg_ifindex;
 
        _cleanup_free_ char *pretty = NULL;
        r = in_addr_ifindex_to_string(family, address, ifindex, &pretty);
        if (r < 0)
                return log_oom();
 
        log_debug("Resolving %s.", pretty);
 
        _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
        r = varlink_connect_with_query_timeout(&vl);
        if (r < 0)
                return r;
 
        usec_t ts = now(CLOCK_MONOTONIC);
 
        const char *error_id = NULL;
        sd_json_variant *v = NULL;
        r = sd_varlink_callbo(
                        vl,
                        "io.systemd.Resolve.ResolveAddress",
                        &v,
                        &error_id,
                        SD_JSON_BUILD_PAIR_BYTE_ARRAY("address", &address->bytes, FAMILY_ADDRESS_SIZE_SAFE(family)),
                        SD_JSON_BUILD_PAIR_UNSIGNED("family", family),
                        JSON_BUILD_PAIR_CONDITION_UNSIGNED(ifindex > 0, "ifindex", ifindex),
                        JSON_BUILD_PAIR_UNSIGNED_NON_ZERO("flags", arg_flags));
        if (r < 0)
                return log_error_errno(r, "Failed to issue varlink call: %m");
 
        ts = now(CLOCK_MONOTONIC) - ts;
 
        if (!isempty(error_id))
                return varlink_log_resolve_error(pretty, error_id, v, /* warn_missing = */ true);
 
        _cleanup_(resolve_address_reply_done) ResolveAddressReply reply = {};
        r = dispatch_resolve_address_reply(/* name = */ NULL, v, SD_JSON_LOG, &reply);
        if (r < 0)
                return r;
 
        bool first = true;
        FOREACH_ARRAY(name, reply.names, reply.n_names) {
                int k = printf("%*s%s %s%s%s",
                               (int) strlen(pretty),
                               first ? pretty : "",
                               first ? ":" : " ",
                               ansi_highlight(),
                               name->name,
                               ansi_normal());
 
                print_ifindex_comment(k, name->ifindex);
                fputc('\n', stdout);
 
                first = false;
        }
 
        if (reply.n_names == 0)
                return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "%s: no names found", pretty);
 
        print_source(reply.flags, ts);
 
        return 0;
}
 
static int output_rr_packet(DnsResourceRecord *rr, int ifindex) {
        int r;
 
        assert(rr);
 
        if (sd_json_format_enabled(arg_json_format_flags)) {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *j = NULL;
                r = dns_resource_record_to_json(rr, &j);
                if (r < 0)
                        return log_error_errno(r, "Failed to convert RR to JSON: %m");
 
                if (!j)
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "JSON formatting for records of type %s (%u) not available.", dns_type_to_string(rr->key->type), rr->key->type);
 
                r = sd_json_variant_dump(j, arg_json_format_flags, NULL, NULL);
                if (r < 0)
                        return r;
 
        } else if (arg_raw == RAW_PAYLOAD) {
                const void *data;
                ssize_t k;
 
                k = dns_resource_record_payload(rr, &data);
                if (k == -EINVAL)
                        return log_error_errno(k, "Dumping of binary payload not available for RRs of this type: %s", dns_type_to_string(rr->key->type));
                if (k < 0)
                        return log_error_errno(k, "Cannot dump RR: %m");
                fwrite(data, 1, k, stdout);
        } else {
                const char *s;
                int k;
 
                s = dns_resource_record_to_string(rr);
                if (!s)
                        return log_oom();
 
                k = printf("%s", s);
                print_ifindex_comment(k, ifindex);
                fputc('\n', stdout);
        }
 
        return 0;
}
 
static DEFINE_POINTER_ARRAY_FREE_FUNC(DnsResourceRecord*, dns_resource_record_unref);
 
static int idna_candidate(const char *name, char **ret) {
        _cleanup_free_ char *idnafied = NULL;
        int r;
 
        assert(name);
        assert(ret);
 
        r = dns_name_apply_idna(name, &idnafied);
        if (r < 0)
                return log_error_errno(r, "Failed to apply IDNA to name '%s': %m", name);
        if (r > 0 && !streq(name, idnafied)) {
                *ret = TAKE_PTR(idnafied);
                return true;
        }
 
        *ret = NULL;
        return false;
}
 
static bool single_label_nonsynthetic(const char *name) {
        _cleanup_free_ char *first_label = NULL;
        int r;
 
        if (!dns_name_is_single_label(name))
                return false;
 
        if (is_localhost(name) ||
            is_gateway_hostname(name) ||
            is_outbound_hostname(name) ||
            is_dns_stub_hostname(name) ||
            is_dns_proxy_stub_hostname(name))
                return false;
 
        r = resolve_system_hostname(NULL, &first_label);
        if (r < 0) {
                log_warning_errno(r, "Failed to determine the hostname: %m");
                return false;
        }
 
        return !streq(name, first_label);
}
 
static int resolve_record(const char *name, uint16_t class, uint16_t type, bool warn_missing) {
        int r;
 
        assert(name);
 
        log_debug("Resolving %s %s %s (interface %s).", name, dns_class_to_string(class), dns_type_to_string(type), isempty(arg_ifname) ? "*" : arg_ifname);
 
        if (dns_name_dot_suffixed(name) == 0 && single_label_nonsynthetic(name))
                log_notice("(Note that search domains are not appended when --type= is specified. "
                           "Please specify fully qualified domain names, or remove --type= switch from invocation in order to request regular hostname resolution.)");
 
        _cleanup_free_ char *idnafied = NULL;
        r = idna_candidate(name, &idnafied);
        if (r < 0)
                return r;
        if (r > 0)
                log_notice("(Note that IDNA translation is not applied when --type= is specified. "
                           "Please specify translated domain names — i.e. '%s' — when resolving raw records, or remove --type= switch from invocation in order to request regular hostname resolution.",
                           idnafied);
 
        _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
        r = varlink_connect_with_query_timeout(&vl);
        if (r < 0)
                return r;
 
        usec_t ts = now(CLOCK_MONOTONIC);
 
        const char *error_id = NULL;
        sd_json_variant *v = NULL;
        r = sd_varlink_callbo(
                        vl,
                        "io.systemd.Resolve.ResolveRecord",
                        &v,
                        &error_id,
                        SD_JSON_BUILD_PAIR_STRING("name", name),
                        SD_JSON_BUILD_PAIR_UNSIGNED("type", type),
                        JSON_BUILD_PAIR_CONDITION_UNSIGNED(arg_ifindex > 0, "ifindex", arg_ifindex),
                        JSON_BUILD_PAIR_UNSIGNED_NON_ZERO("class", class),
                        JSON_BUILD_PAIR_UNSIGNED_NON_ZERO("flags", arg_flags));
        if (r < 0)
                return log_error_errno(r, "Failed to issue varlink call: %m");
 
        ts = now(CLOCK_MONOTONIC) - ts;
 
        if (!isempty(error_id)) {
                if (streq(error_id, "io.systemd.Resolve.ResourceRecordTypeInvalidForQuery"))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Specified resource record type %" PRIu16 " may not be used in a query", type);
 
                if (streq(error_id, "io.systemd.Resolve.ResourceRecordTypeObsolete"))
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Specified DNS resource record type %" PRIu16 " is obsolete", type);
 
                return varlink_log_resolve_error(name, error_id, v, warn_missing);
        }
 
        _cleanup_(resolve_record_reply_done) ResolveRecordReply reply = {};
        r = dispatch_resolve_record_reply(/* name = */ NULL, v, SD_JSON_LOG, &reply);
        if (r < 0)
                return r;
 
        if (reply.n_records == 0) {
                if (warn_missing)
                        log_error("%s: no records found", name);
                return -ESRCH;
        }
 
        DnsResourceRecord **rrs = new0(DnsResourceRecord*, reply.n_records);
        size_t n_rrs = reply.n_records;
        if (!rrs)
                return log_oom();
        CLEANUP_ARRAY(rrs, n_rrs, dns_resource_record_unref_array);
 
        bool json = sd_json_format_enabled(arg_json_format_flags);
        bool needs_authentication = false;
        FOREACH_ARRAY(record, reply.records, reply.n_records) {
                size_t i = record - reply.records;
 
                r = dns_resource_record_new_from_raw(&rrs[i], record->raw.iov_base, record->raw.iov_len);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse RR: %m");
 
                if (dns_type_needs_authentication(rrs[i]->key->type)) {
                        needs_authentication = true;
 
                        if (json && !FLAGS_SET(reply.flags, SD_RESOLVED_AUTHENTICATED))
                                return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
                                                       "Refusing to output unauthenticated DNS records that require "
                                                       "authentication in JSON format.");
                }
        }
 
        FOREACH_ARRAY(record, reply.records, reply.n_records) {
                size_t i = record - reply.records;
 
                if (arg_raw == RAW_PACKET) {
                        uint64_t u64 = htole64(record->raw.iov_len);
 
                        fwrite(&u64, sizeof(u64), 1, stdout);
                        fwrite(record->raw.iov_base, 1, record->raw.iov_len, stdout);
                } else {
                        r = output_rr_packet(rrs[i], record->ifindex);
                        if (r < 0)
                                return r;
                }
        }
 
        print_source(reply.flags, ts);
 
        if ((reply.flags & SD_RESOLVED_AUTHENTICATED) == 0 && needs_authentication) {
                fflush(stdout);
 
                fprintf(stderr, "\n%s"
                       "WARNING: The resources shown contain cryptographic key data which could not be\n"
                       "         authenticated. It is not suitable to authenticate any communication.\n"
                       "         This is usually indication that DNSSEC authentication was not enabled\n"
                       "         or is not available for the selected protocol or DNS servers.%s\n",
                       ansi_highlight_red(),
                       ansi_normal());
        }
 
        return 0;
}
 
static int resolve_rfc4501(const char *name) {
        uint16_t type = 0, class = 0;
        const char *p, *q, *n;
        int r;
 
        assert(name);
        assert(startswith(name, "dns:"));
 
        /* Parse RFC 4501 dns: URIs */
 
        p = name + 4;
 
        if (p[0] == '/') {
                const char *e;
 
                if (p[1] != '/')
                        goto invalid;
 
                e = strchr(p + 2, '/');
                if (!e)
                        goto invalid;
 
                if (e != p + 2)
                        log_warning("DNS authority specification not supported; ignoring specified authority.");
 
                p = e + 1;
        }
 
        q = strchr(p, '?');
        if (q) {
                n = strndupa_safe(p, q - p);
                q++;
 
                for (;;) {
                        const char *f;
 
                        f = startswith_no_case(q, "class=");
                        if (f) {
                                _cleanup_free_ char *t = NULL;
                                const char *e;
 
                                if (class != 0)
                                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                               "DNS class specified twice.");
 
                                e = strchrnul(f, ';');
                                t = strndup(f, e - f);
                                if (!t)
                                        return log_oom();
 
                                r = dns_class_from_string(t);
                                if (r < 0)
                                        return log_error_errno(r, "Unknown DNS class %s.", t);
 
                                class = r;
 
                                if (*e == ';') {
                                        q = e + 1;
                                        continue;
                                }
 
                                break;
                        }
 
                        f = startswith_no_case(q, "type=");
                        if (f) {
                                _cleanup_free_ char *t = NULL;
                                const char *e;
 
                                if (type != 0)
                                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                               "DNS type specified twice.");
 
                                e = strchrnul(f, ';');
                                t = strndup(f, e - f);
                                if (!t)
                                        return log_oom();
 
                                r = dns_type_from_string(t);
                                if (r < 0)
                                        return log_error_errno(r, "Unknown DNS type %s: %m", t);
 
                                type = r;
 
                                if (*e == ';') {
                                        q = e + 1;
                                        continue;
                                }
 
                                break;
                        }
 
                        goto invalid;
                }
        } else
                n = p;
 
        if (class == 0)
                class = arg_class ?: DNS_CLASS_IN;
        if (type == 0)
                type = arg_type ?: DNS_TYPE_A;
 
        return resolve_record(n, class, type, true);
 
invalid:
        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                               "Invalid DNS URI: %s", name);
}
 
VERB(verb_query, "query", "HOSTNAME|ADDRESS…\0", 2, VERB_ANY, 0,
     "Resolve domain names, IPv4 and IPv6 addresses");
static int verb_query(int argc, char *argv[], uintptr_t _data, void *userdata) {
        int ret = 0, r;
 
        if (arg_type != 0)
                STRV_FOREACH(p, strv_skip(argv, 1))
                        RET_GATHER(ret, resolve_record(*p, arg_class, arg_type, true));
 
        else
                STRV_FOREACH(p, strv_skip(argv, 1)) {
                        if (startswith(*p, "dns:"))
                                RET_GATHER(ret, resolve_rfc4501(*p));
                        else {
                                int family, ifindex;
                                union in_addr_union a;
 
                                if (arg_raw != RAW_NONE)
                                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                               "--raw may only be combined with --type= or dns: URIs.");
 
                                r = in_addr_ifindex_from_string_auto(*p, &family, &a, &ifindex);
                                if (r >= 0)
                                        RET_GATHER(ret, resolve_address(family, &a, ifindex));
                                else
                                        RET_GATHER(ret, resolve_host(*p));
                        }
                }
 
        return ret;
}
 
static int resolve_service(const char *name, const char *type, const char *domain, uint64_t flags) {
        int r;
 
        assert(domain);
 
        name = empty_to_null(name);
        type = empty_to_null(type);
 
        if (name)
                log_debug("Resolving service \"%s\" of type %s in %s (family %s, interface %s).", name, type, domain, af_to_name(arg_family) ?: "*", isempty(arg_ifname) ? "*" : arg_ifname);
        else if (type)
                log_debug("Resolving service type %s of %s (family %s, interface %s).", type, domain, af_to_name(arg_family) ?: "*", isempty(arg_ifname) ? "*" : arg_ifname);
        else
                log_debug("Resolving service type %s (family %s, interface %s).", domain, af_to_name(arg_family) ?: "*", isempty(arg_ifname) ? "*" : arg_ifname);
 
        _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
        r = varlink_connect_with_query_timeout(&vl);
        if (r < 0)
                return r;
 
        usec_t ts = now(CLOCK_MONOTONIC);
 
        const char *error_id = NULL;
        sd_json_variant *v = NULL;
        r = sd_varlink_callbo(
                        vl,
                        "io.systemd.Resolve.ResolveService",
                        &v,
                        &error_id,
                        SD_JSON_BUILD_PAIR_STRING("domain", domain),
                        JSON_BUILD_PAIR_STRING_NON_EMPTY("name", name),
                        JSON_BUILD_PAIR_STRING_NON_EMPTY("type", type),
                        JSON_BUILD_PAIR_CONDITION_UNSIGNED(arg_ifindex > 0, "ifindex", arg_ifindex),
                        JSON_BUILD_PAIR_CONDITION_UNSIGNED(arg_family != AF_UNSPEC, "family", arg_family),
                        JSON_BUILD_PAIR_UNSIGNED_NON_ZERO("flags", flags));
        if (r < 0)
                return log_error_errno(r, "Failed to issue varlink call: %m");
 
        ts = now(CLOCK_MONOTONIC) - ts;
 
        if (!isempty(error_id))
                return varlink_log_resolve_error(domain, error_id, v, /* warn_missing = */ true);
 
        _cleanup_(resolve_service_reply_done) ResolveServiceReply reply = {};
        r = dispatch_resolve_service_reply(/* name = */ NULL, v, SD_JSON_LOG, &reply);
        if (r < 0)
                return r;
 
        size_t indent = (name ? strlen(name) + 1 : 0) +
                        (type ? strlen(type) + 1 : 0) +
                        strlen(domain) + 2;
 
        bool first = true;
        FOREACH_ARRAY(service, reply.services, reply.n_services) {
                if (name)
                        printf("%*s%s", (int) strlen(name), first ? name : "", first ? "/" : " ");
                if (type)
                        printf("%*s%s", (int) strlen(type), first ? type : "", first ? "/" : " ");
 
                printf("%*s%s %s:%u [priority=%u, weight=%u]\n",
                       (int) strlen(domain),
                       first ? domain : "",
                       first ? ":" : " ",
                       service->hostname,
                       service->port,
                       service->priority,
                       service->weight);
 
                FOREACH_ARRAY(address, service->addresses, service->n_addresses) {
                        _cleanup_free_ char *pretty = NULL;
                        r = in_addr_ifindex_to_string(address->family, &address->in_addr.address, address->ifindex, &pretty);
                        if (r < 0)
                                return log_error_errno(r, "Failed to print address for %s: %m", name);
 
                        int k = printf("%*s%s", (int) indent, "", pretty);
 
                        print_ifindex_comment(k, address->ifindex);
                        fputc('\n', stdout);
                }
 
                if (service->canonical_name && !streq_ptr(service->hostname, service->canonical_name))
                        printf("%*s(%s)\n", (int) indent, "", service->canonical_name);
 
                first = false;
        }