HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/imds/imdsd.c

121,943 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: d4e5b23937d568a82c995f2f37217f1f28097dc8

Lines 1001–2000 of 3,099

 
                context_log(c, LOG_DEBUG, "Data download successful.");
 
                r = context_save_data(c);
                if (r < 0)
                        return context_fail(c, r);
 
                context_success(c);
        } else
                assert_not_reached();
 
        return 0;
}
 
static int context_acquire_glue(Context *c) {
        int r;
 
        assert(c);
 
        /* Allocates a curl object if we don't have one yet */
 
        if (c->glue)
                return 0;
 
        r = curl_glue_new(&c->glue, c->event);
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to allocate curl glue: %m");
 
        return 0;
}
 
static size_t data_write_callback(void *contents, size_t size, size_t nmemb, void *userdata) {
        Context *c = ASSERT_PTR(userdata);
        size_t sz = size * nmemb;
        int r;
 
        /* Called whenever we receive new payload from the server */
        assert(contents);
 
        /* If we managed to get a HTTP reply, this is good enough, let's pin the interface now for later calls */
        (void) context_save_ifname(c);
 
        /* Before we use the acquired data, let's verify the HTTP status, if there's a failure or we need to
         * restart, abort the write here. Note that the curl_on_finished() call will then check the HTTP
         * status again and act on it. */
        long status;
        r = context_acquire_http_status(c, curl_slot_get_easy(c->slot_data), &status);
        if (r <= 0)
                return 0; /* fail the thing, so that curl_on_finished() can handle this failure or retry request */
        if (status >= 300) /* any status equal or above 300 needs to be handled by curl_on_finished() too */
                return 0;
 
        if (sz > UINT64_MAX - c->data_size ||
            c->data_size + sz > DATA_SIZE_MAX) {
                context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(E2BIG), "Data too large, refusing.");
                return 0;
        }
 
        c->data_size += sz;
 
        if (c->write_stdout)
                (void) fwrite(contents, 1, sz, stdout);
        else if (!iovec_append(&c->write_iovec, &IOVEC_MAKE(contents, sz))) {
                context_log_oom(c);
                return 0;
        }
 
        if (c->cache_fd >= 0) {
                r = loop_write(c->cache_fd, contents, sz);
                if (r < 0) {
                        context_log_errno(c, LOG_ERR, r, "Failed to write data to cache: %m");
                        return 0;
                }
        }
 
        return sz;
}
 
static int context_acquire_data(Context *c) {
        int r;
 
        assert(c);
        assert(c->key || c->well_known >= 0);
 
        /* Called to initiate getting the actual IMDS key payload */
 
        if (arg_token_url && !c->token_string)
                return 0; /* If we need a token first, let's not do anything */
 
        _cleanup_free_ char *k = NULL;
        r = context_combine_key(c, &k);
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to combine key: %m");
 
        context_log(c, LOG_INFO, "Requesting data for key '%s'.", k);
 
        if (c->cache_dir_fd >= 0 &&
            c->cache_filename &&
            c->cache_fd < 0) {
                c->cache_fd = open_tmpfile_linkable_at(c->cache_dir_fd, c->cache_filename, O_WRONLY|O_CLOEXEC, &c->cache_temporary_filename);
                if (c->cache_fd < 0)
                        return context_log_errno(c, LOG_ERR, c->cache_fd, "Failed to create cache file '%s': %m", c->cache_filename);
 
                if (fchmod(c->cache_fd, 0600) < 0)
                        return context_log_errno(c, LOG_ERR, errno, "Failed to adjust cache node access mode: %m");
 
                if (fsetxattr(c->cache_fd, "user.imds.timestamp", &c->timestamp, sizeof(c->timestamp), /* flags= */ 0) < 0)
                        return context_log_errno(c, LOG_ERR, errno, "Failed to set timestamp xattr on '%s': %m", c->cache_filename);
        }
 
        r = context_acquire_glue(c);
        if (r < 0)
                return r;
 
        _cleanup_free_ char *url = strjoin(arg_data_url, k, arg_data_url_suffix);
        if (!url)
                return context_log_oom(c);
 
        _cleanup_(curl_easy_cleanupp) CURL *easy = NULL;
        r = curl_glue_make(&easy, url);
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to create CURL request for data: %m");
 
        if (c->token_string) {
                _cleanup_free_ char *token_header = strjoin(arg_token_header_name, ": ", c->token_string);
                if (!token_header)
                        return context_log_oom(c);
 
                r = curl_append_to_header(&c->request_header_data, STRV_MAKE(token_header));
                if (r < 0)
                        return context_log_errno(c, LOG_ERR, r, "Failed to create curl header: %m");
        }
 
        r = curl_append_to_header(&c->request_header_data, arg_extra_header);
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to create curl header: %m");
 
        if (c->request_header_data)
                if (sym_curl_easy_setopt(easy, CURLOPT_HTTPHEADER, c->request_header_data) != CURLE_OK)
                        return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set HTTP request header.");
 
        if (sym_curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, data_write_callback) != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set CURL write function.");
 
        if (sym_curl_easy_setopt(easy, CURLOPT_WRITEDATA, c) != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set CURL write function userdata.");
 
        if (sym_curl_easy_setopt(easy, CURLOPT_SOCKOPTFUNCTION, setsockopt_callback) != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set CURL setsockopt function.");
 
        if (sym_curl_easy_setopt(easy, CURLOPT_SOCKOPTDATA, c) != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set CURL setsockopt function userdata.");
 
        if (sym_curl_easy_setopt(easy, CURLOPT_LOCALPORT, 1L) != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set CURL setsockopt local port");
 
        if (sym_curl_easy_setopt(easy, CURLOPT_LOCALPORTRANGE, 1023L) != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set CURL setsockopt local port range");
 
        r = curl_glue_perform_async(c->glue, easy, curl_on_finished, c, &c->slot_data);
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to add CURL request to glue: %m");
        TAKE_PTR(easy);
 
        return 0;
}
 
static size_t token_write_callback(void *contents, size_t size, size_t nmemb, void *userdata) {
        Context *c = ASSERT_PTR(userdata);
        size_t sz = size * nmemb;
        int r;
 
        /* Called whenever we get data from the token download */
        assert(contents);
 
        /* If we managed to get a HTTP reply, this is good enough, let's pin the interface now for later calls */
        (void) context_save_ifname(c);
 
        /* Before we use acquired data, let's verify the HTTP status */
        long status;
        r = context_acquire_http_status(c, curl_slot_get_easy(c->slot_token), &status);
        if (r <= 0)
                return 0; /* fail the thing, so that curl_on_finished() can handle this failure or retry request */
        if (status >= 300) /* any status equal or above 300 needs to be handled by curl_on_finished() */
                return 0;
 
        if (sz > SIZE_MAX - c->token.iov_len ||
            c->token.iov_len + sz > TOKEN_SIZE_MAX) {
                context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(E2BIG), "IMDS token too large.");
                return 0;
        }
 
        if (!iovec_append(&c->token, &IOVEC_MAKE(contents, sz))) {
                context_log_oom(c);
                return 0;
        }
 
        return sz;
}
 
static int context_acquire_token(Context *c) {
        int r;
 
        assert(c);
 
        /* Called to initiate getting the token if we need one. */
 
        if (c->token_string || !arg_token_url)
                return 0;
 
        context_log(c, LOG_INFO, "Requesting token.");
 
        r = context_acquire_glue(c);
        if (r < 0)
                return r;
 
        _cleanup_(curl_easy_cleanupp) CURL *easy = NULL;
        r = curl_glue_make(&easy, arg_token_url);
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to create CURL request for API token: %m");
 
        if (arg_refresh_header_name) {
                _cleanup_free_ char *ttl_header = NULL;
                if (asprintf(&ttl_header,
                             "%s: %" PRIu64,
                             arg_refresh_header_name,
                             DIV_ROUND_UP(c->refresh_usec, USEC_PER_SEC)) < 0)
                        return context_log_oom(c);
 
                c->request_header_token = curl_slist_new(ttl_header, NULL);
                if (!c->request_header_token)
                        return context_log_oom(c);
        }
 
        if (sym_curl_easy_setopt(easy, CURLOPT_HTTPHEADER, c->request_header_token) != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set HTTP request header.");
 
        if (sym_curl_easy_setopt(easy, CURLOPT_CUSTOMREQUEST, "PUT") != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set HTTP request method.");
 
        if (sym_curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, token_write_callback) != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set CURL write function.");
 
        if (sym_curl_easy_setopt(easy, CURLOPT_WRITEDATA, c) != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set CURL write function userdata.");
 
        if (sym_curl_easy_setopt(easy, CURLOPT_SOCKOPTFUNCTION, setsockopt_callback) != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set CURL setsockopt function.");
 
        if (sym_curl_easy_setopt(easy, CURLOPT_SOCKOPTDATA, c) != CURLE_OK)
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EIO), "Failed to set CURL setsockopt function userdata.");
 
        r = curl_glue_perform_async(c->glue, easy, curl_on_finished, c, &c->slot_token);
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to add CURL request to glue: %m");
        TAKE_PTR(easy);
 
        return 0;
}
 
static int vl_on_reply(sd_varlink *link, sd_json_variant *m, const char *error_id, sd_varlink_reply_flags_t flags, void *userdata) {
        ChildData *cd = ASSERT_PTR(userdata);
        Context *c = ASSERT_PTR(cd->context);
        int r;
 
        assert(link);
        assert(m);
 
        /* When we spawned off worker instances of ourselves (one for each local network interface), then
         * we'll get a response from them via a Varlink reply. Handle it. */
 
        if (error_id) {
                r = sd_varlink_error_to_errno(error_id, m);
                if (r == -EBADR)
                        context_log_errno(c, LOG_WARNING, r, "Varlink error from interface %i: %s", cd->ifindex, error_id);
                else
                        context_log_errno(c, LOG_WARNING, r, "Varlink error from interface %i: %m", cd->ifindex);
 
                /* Propagate these errors immediately */
                if (streq(error_id, "io.systemd.InstanceMetadata.KeyNotFound")) {
                        context_fail_full(c, -ENOENT, error_id);
                        return 0;
                }
                if (streq(error_id, "io.systemd.InstanceMetadata.WellKnownKeyUnset")) {
                        context_fail_full(c, -ENODATA, error_id);
                        return 0;
                }
                if (streq(error_id, "io.systemd.InstanceMetadata.NotAvailable")) {
                        context_fail_full(c, -EADDRNOTAVAIL, error_id);
                        return 0;
                }
 
                /* The other errors we consider transient. Let's see if we shall immediately restart the request. */
                if (cd->retry) {
                        context_log(c, LOG_DEBUG, "Child for network interface %i was scheduled for immediate retry, executing now.", cd->ifindex);
                        cd->link = sd_varlink_close_unref(cd->link);
                        cd->retry = false;
 
                        r = context_spawn_child(c, cd->ifindex, &cd->link);
                        if (r < 0) {
                                context_fail(c, r);
                                return 0;
                        }
 
                        sd_varlink_set_userdata(cd->link, cd);
                        return 0;
                }
 
                /* We shall not retry immediately. In that case, we give up on the child, and propagate the
                 * error if it was the last child, otherwise we continue until the last one dies too. */
                cd = child_data_free(cd);
 
                if (hashmap_isempty(c->child_data) && !c->wait) {
                        /* This is the last child, propagate the error */
                        context_log(c, LOG_DEBUG, "Last child failed, propagating error.");
 
                        if (streq(error_id, "io.systemd.InstanceMetadata.CommunicationFailure"))
                                context_fail_full(c, -EHOSTDOWN, error_id);
                        else if (streq(error_id, "io.systemd.InstanceMetadata.Timeout"))
                                context_fail_full(c, -ETIMEDOUT, error_id);
                        else
                                context_fail_full(c, r, error_id);
 
                        return 0;
                }
 
                context_log(c, LOG_DEBUG, "Pending children remaining, continuing to wait.");
                return 0;
        }
 
        assert(!iovec_is_set(&c->write_iovec));
 
        static const sd_json_dispatch_field table[] = {
                { "data",      SD_JSON_VARIANT_STRING,        json_dispatch_unbase64_iovec, offsetof(Context, write_iovec), SD_JSON_MANDATORY },
                { "interface", _SD_JSON_VARIANT_TYPE_INVALID, json_dispatch_ifindex,        offsetof(Context, ifindex),     0                 },
                {}
        };
 
        r = sd_json_dispatch(m, table, SD_JSON_ALLOW_EXTENSIONS, c);
        if (r < 0) {
                context_fail(c, context_log_errno(c, LOG_ERR, r, "Failed to decode reply data: %m"));
                return 0;
        }
 
        if (c->write_stdout) {
                r = loop_write(STDOUT_FILENO, c->write_iovec.iov_base, c->write_iovec.iov_len);
                if (r < 0) {
                        context_fail(c, context_log_errno(c, LOG_ERR, r, "Failed to output data: %m"));
                        return 0;
                }
        }
 
        context_success(c);
        return 0;
}
 
static int context_load_ifname(Context *c) {
        int r;
 
        assert(c);
 
        /* Tries to load the previously used interface name, so that we don't have to wildcard search on all
         * interfaces. */
 
        const char *e = context_get_runtime_directory(c);
        if (!e)
                return 0;
 
        _cleanup_close_ int dirfd = open(e, O_PATH|O_CLOEXEC);
        if (dirfd < 0)
                return context_log_errno(c, LOG_ERR, errno, "Failed to open runtime directory: %m");
 
        _cleanup_free_ char *ifname = NULL;
        r = read_one_line_file_at(dirfd, "ifname", &ifname);
        if (r == -ENOENT)
                return 0;
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to load 'ifname' file from runtime directory: %m");
 
        if (!ifname_valid(ifname))
                return context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(EINVAL), "Loaded interface name not valid, refusing: %s", ifname);
 
        c->ifindex = rtnl_resolve_interface(&c->rtnl, ifname);
        if (c->ifindex < 0) {
                (void) unlinkat(dirfd, "ifname", /* flags= */ 0);
                context_log_errno(c, LOG_ERR, c->ifindex, "Failed to resolve saved interface name '%s', assuming interface disappeared, ignoring: %m", ifname);
                c->ifindex = 0;
                return 0;
        }
 
        log_debug("Using previously pinned interface '%s' (ifindex: %i).", ifname, c->ifindex);
        return 1;
}
 
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(
                child_data_hash_ops,
                void,
                trivial_hash_func,
                trivial_compare_func,
                ChildData,
                child_data_free);
 
static int context_spawn_child(Context *c, int ifindex, sd_varlink **ret) {
        int r;
 
        assert(c);
        assert(ifindex > 0);
        assert(ret);
 
        /* If we don't know yet on which network interface the IMDS server can be found, let's spawn separate
         * instances of ourselves, one for each interface, and collect the results. We communicate with
         * each one via Varlink, the same way as clients talk to us. */
 
        context_log(c, LOG_DEBUG, "Spawning child for interface '%i'.", ifindex);
 
        _cleanup_free_ char *p = NULL;
        _cleanup_close_ int fd = pin_callout_binary(LIBEXECDIR "/systemd-imdsd", &p);
        if (fd < 0)
                return context_log_errno(c, LOG_ERR, fd, "Failed to find imdsd binary: %m");
 
        _cleanup_strv_free_ char **argv = strv_new(
                        p,
                        "--vendor", strempty(arg_vendor),
                        "--token-url", strempty(arg_token_url),
                        "--refresh-header-name", strempty(arg_refresh_header_name),
                        "--data-url", strempty(arg_data_url),
                        "--data-url-suffix", strempty(arg_data_url_suffix),
                        "--token-header-name", strempty(arg_token_header_name),
                        "--address-ipv4", in4_addr_is_null(&arg_address_ipv4) ? "" : IN4_ADDR_TO_STRING(&arg_address_ipv4),
                        "--address-ipv6", in6_addr_is_null(&arg_address_ipv6) ? "" : IN6_ADDR_TO_STRING(&arg_address_ipv6));
        if (!argv)
                return log_oom();
 
        STRV_FOREACH(i, arg_extra_header)
                if (strv_extend_strv(&argv, STRV_MAKE("--extra-header", *i), /* filter_duplicates= */ false) < 0)
                        return log_oom();
 
        for (ImdsWellKnown wk = 0; wk < _IMDS_WELL_KNOWN_MAX; wk++) {
                if (!arg_well_known_key[wk])
                        continue;
 
                if (strv_extendf(&argv, "--well-known-key=%s:%s", imds_well_known_to_string(wk), arg_well_known_key[wk]) < 0)
                        return log_oom();
        }
 
        if (DEBUG_LOGGING) {
                _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
                log_debug("About to fork off: %s", strnull(cmdline));
        }
 
        _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
        r = sd_varlink_connect_exec(&vl, p, argv);
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to fork off imdsd binary for interface %i: %m", ifindex);
 
        r = sd_varlink_attach_event(
                        vl,
                        c->event,
                        SD_EVENT_PRIORITY_NORMAL);
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to attach Varlink connection to event loop: %m");
 
        r = sd_varlink_bind_reply(vl, vl_on_reply);
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to bind reply callback: %m");
 
        r = sd_varlink_invokebo(
                        vl,
                        "io.systemd.InstanceMetadata.Get",
                        JSON_BUILD_PAIR_STRING_NON_EMPTY("key", c->key),
                        SD_JSON_BUILD_PAIR_CONDITION(c->well_known >= 0, "wellKnown", JSON_BUILD_STRING_UNDERSCORIFY(imds_well_known_to_string(c->well_known))),
                        SD_JSON_BUILD_PAIR_INTEGER("interface", ifindex),
                        SD_JSON_BUILD_PAIR_INTEGER("refreshUSec", c->refresh_usec),
                        SD_JSON_BUILD_PAIR_BOOLEAN("cache", c->cache),
                        SD_JSON_BUILD_PAIR_CONDITION(c->fwmark_set, "firewallMark", SD_JSON_BUILD_UNSIGNED(c->fwmark)),
                        SD_JSON_BUILD_PAIR_CONDITION(!c->fwmark_set, "firewallMark", SD_JSON_BUILD_NULL)); /* explicitly turn off fwmark, if not set */
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to issue Get() command to Varlink child: %m");
 
        *ret = TAKE_PTR(vl);
        return 0;
}
 
static int context_spawn_new_child(Context *c, int ifindex) {
        int r;
 
        assert(c);
 
        /* Spawn a child, and keep track of it */
 
        _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
        r = context_spawn_child(c, ifindex, &vl);
        if (r < 0)
                return r;
 
        _cleanup_(child_data_freep) ChildData *cd = new(ChildData, 1);
        if (!cd)
                return context_log_oom(c);
 
        *cd = (ChildData) {
                .ifindex = ifindex,
                .link = sd_varlink_ref(vl),
        };
 
        sd_varlink_set_userdata(vl, cd);
 
        if (hashmap_ensure_put(&c->child_data, &child_data_hash_ops, INT_TO_PTR(ifindex), cd) < 0)
                return context_log_oom(c);
 
        cd->context = c;
        TAKE_PTR(cd);
 
        return 0;
}
 
static int on_address_change(sd_netlink *rtnl, sd_netlink_message *m, void *userdata) {
        Context *c = ASSERT_PTR(userdata);
        int ifindex, r;
 
        assert(rtnl);
        assert(m);
 
        /* Called whenever an address appears on the network stack. We use that as hint that it is worth to
         * invoke a child processing that interface (either for the first time, or again) */
 
        r = sd_rtnl_message_addr_get_ifindex(m, &ifindex);
        if (r < 0) {
                context_log_errno(c, LOG_WARNING, r, "rtnl: could not get ifindex from message, ignoring: %m");
                return 0;
        }
        if (ifindex <= 0) {
                context_log(c, LOG_WARNING, "rtnl: received address message with invalid ifindex %d, ignoring.", ifindex);
                return 0;
        }
 
        if (ifindex == LOOPBACK_IFINDEX) {
                context_log(c, LOG_DEBUG, "Ignoring loopback device.");
                return 0;
        }
 
        if (!c->key && c->well_known < 0)
                return 0;
 
        ChildData *existing = hashmap_get(c->child_data, INT_TO_PTR(ifindex));
        if (existing) {
                /* We already have an attempt ongoing for this one? Remember there's a reason now to retry
                 * this, because new connectivity appeared. */
                context_log(c, LOG_DEBUG, "Child for network interface %i already spawned off, scheduling for immediate retry.", ifindex);
                existing->retry = true;
                return 0;
        }
 
        return context_spawn_new_child(c, ifindex);
}
 
static int context_acquire_rtnl_with_match(Context *c) {
        int r;
 
        assert(c);
        assert(c->event);
 
        /* Acquire a netlink connection and a match if we don't have one yet */
 
        if (!c->rtnl) {
                r = sd_netlink_open(&c->rtnl);
                if (r < 0)
                        return context_log_errno(c, LOG_ERR, r, "Failed to connect to netlink: %m");
        }
 
        if (!c->rtnl_attached) {
                /* The netlink connection might have created previously via rtnl_resolve_interface() – which
                 * however didn't attach it to our event loop. Do so now. */
                r = sd_netlink_attach_event(c->rtnl, c->event, SD_EVENT_PRIORITY_NORMAL);
                if (r < 0)
                        return context_log_errno(c, LOG_ERR, r, "Failed to attach netlink socket to event loop: %m");
 
                c->rtnl_attached = true;
        }
 
        if (!c->address_change_slot) {
                r = sd_netlink_add_match(c->rtnl, &c->address_change_slot, RTM_NEWADDR, on_address_change, /* destroy_callback= */ NULL, c, "newaddr");
                if (r < 0)
                        return context_log_errno(c, LOG_ERR, r, "Failed to subscribe to RTM_NEWADDR events: %m");
        }
 
        return 0;
}
 
static int context_spawn_children(Context *c) {
        int r;
 
        assert(c);
        assert(c->key || c->well_known >= 0);
 
        /* If we don't know yet on which interface to query, let's see which interfaces there are and spawn
         * ourselves, once on each */
 
        r = context_acquire_rtnl_with_match(c);
        if (r < 0)
                return r;
 
        _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
        r = sd_rtnl_message_new_addr(c->rtnl, &req, RTM_GETADDR, /* ifindex= */ 0, AF_UNSPEC);
        if (r < 0)
                return r;
 
        r = sd_netlink_message_set_request_dump(req, true);
        if (r < 0)
                return r;
 
        _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *reply = NULL;
        r = sd_netlink_call(c->rtnl, req, 0, &reply);
        if (r < 0)
                return r;
 
        for (sd_netlink_message *i = reply; i; i = sd_netlink_message_next(i)) {
                r = on_address_change(c->rtnl, i, c);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static int imds_configured(int level) {
        /* Checks if we have enough endpoint information to operate */
 
        if (arg_endpoint_source < 0)
                return log_full_errno(level, SYNTHETIC_ERRNO(EOPNOTSUPP), "No IMDS endpoint information provided or detected, cannot operate.");
 
        if (!arg_data_url)
                return log_full_errno(level, SYNTHETIC_ERRNO(EOPNOTSUPP), "No data base URL provided.");
 
        if (!!arg_token_url != !!arg_token_header_name)
                return log_full_errno(level, SYNTHETIC_ERRNO(EOPNOTSUPP), "Incomplete token parameters configured for endpoint.");
 
        return 0;
}
 
static void warn_rp_filter_all(void) {
        int r, v;
 
        /* The kernel applies the maximum of the link's and the "all" setting, so turning off reverse path
         * filtering on the link does not help if "all" turns it on. */
        r = sysctl_read_ip_property_int(AF_INET, "all", "rp_filter", &v);
        if (r < 0)
                return (void) log_debug_errno(r, "Failed to read net.ipv4.conf.all.rp_filter, ignoring: %m");
        if (v != 0)
                log_warning("net.ipv4.conf.all.rp_filter=%i turns on IPv4 reverse path filtering on all links, "
                            "which drops IMDS replies in locked mode. Set it to 0 to allow IMDS access.", v);
}
 
static int setup_network(void) {
        int r;
 
        /* Generates a .network file based on the IMDS endpoint information we have */
 
        if (arg_network_mode == IMDS_NETWORK_OFF) {
                log_debug("IMDS networking turned off, not generating .network file.");
                return 0;
        }
 
        _cleanup_close_ int network_dir_fd = -EBADF;
        r = chase("/run/systemd/network",
                  /* root= */ NULL,
                  CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY,
                  /* ret_path= */ NULL,
                  &network_dir_fd);
        if (r < 0)
                return log_error_errno(r, "Failed to open .network directory: %m");
 
        _cleanup_free_ char *t = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        r = fopen_tmpfile_linkable_at(network_dir_fd, "85-imds-early.network", O_WRONLY|O_CLOEXEC, &t, &f);
        if (r < 0)
                return log_error_errno(r, "Failed to create 85-imds-early.network file: %m");
 
        CLEANUP_TMPFILE_AT(network_dir_fd, t);
 
        fputs("# Generated by systemd-imdsd, do not edit.\n"
              "#\n"
              "# This configures Ethernet devices on cloud hosts that support IMDS, given that\n"
              "# before doing IMDS we need to activate the network.\n", f);
 
        if (arg_network_mode != IMDS_NETWORK_UNLOCKED &&
            (in4_addr_is_set(&arg_address_ipv4) || in6_addr_is_set(&arg_address_ipv6)))
                fputs("#\n"
                      "# Note: this will create a 'prohibit' route to the IMDS endpoint,\n"
                      "# blocking direct access to IMDS. Direct IMDS access is then only\n"
                      "# available to traffic marked with fwmark 0x7FFF0815, which can be\n"
                      "# set via SO_MARK and various other methods, which require\n"
                      "# privileges.\n",
                      f);
 
        fputs("\n"
              "[Match]\n"
              "Type=ether\n"
              "Kind=!*\n"
              "\n"
              "[Network]\n"
              "DHCP=yes\n"
              "LinkLocalAddressing=ipv6\n", f);
 
        /* IMDS's replies to imdsd carry no firewall mark. Reverse path filtering would check their source
         * address against the main table, find the prohibit route below, and drop them. IPv6 has no
         * reverse path filter. */
        if (arg_network_mode != IMDS_NETWORK_UNLOCKED && in4_addr_is_set(&arg_address_ipv4)) {
                fputs("# Reverse path filtering would drop IMDS's replies due to the prohibit route\n"
                      "IPv4ReversePathFilter=no\n", f);
                warn_rp_filter_all();
        }
 
        fputs("\n"
              "[DHCP]\n"
              "UseTimezone=yes\n"
              "UseHostname=yes\n"
              "UseMTU=yes\n", f);
 
        if (in4_addr_is_set(&arg_address_ipv4))
                fputs("\n"
                      "[Link]\n"
                      "RequiredFamilyForOnline=ipv4\n", f);
        else if (in6_addr_is_set(&arg_address_ipv6))
                fputs("\n"
                      "[Link]\n"
                      "RequiredFamilyForOnline=ipv6\n", f);
 
        if (arg_network_mode != IMDS_NETWORK_UNLOCKED) {
                if (in4_addr_is_set(&arg_address_ipv4))
                        fprintf(f,
                                "\n"
                                "# Prohibit regular access to IMDS (IPv4)\n"
                                "[Route]\n"
                                "Destination=%s\n"
                                "Type=prohibit\n",
                                IN4_ADDR_TO_STRING(&arg_address_ipv4));
 
                if (in6_addr_is_set(&arg_address_ipv6))
                        fprintf(f,
                                "\n"
                                "# Prohibit regular access to IMDS (IPv6)\n"
                                "[Route]\n"
                                "Destination=%s\n"
                                "Type=prohibit\n",
                                IN6_ADDR_TO_STRING(&arg_address_ipv6));
        }
 
        if (in4_addr_is_set(&arg_address_ipv4))
                fprintf(f,
                        "\n"
                        "# Always allow IMDS access via a special routing table (IPv4)\n"
                        "[Route]\n"
                        "Destination=%s\n"
                        "Scope=link\n"
                        "Table=0x7FFF0815\n"
                        "\n"
                        "# Sockets marked with firewall mark 0x7FFF0815 get access to the IMDS route by\n"
                        "# using the 0x7FFF0815 table populated above.\n"
                        "[RoutingPolicyRule]\n"
                        "Family=ipv4\n"
                        "FirewallMark=0x7FFF0815\n"
                        "Table=0x7FFF0815\n",
                        IN4_ADDR_TO_STRING(&arg_address_ipv4));
 
        if (in6_addr_is_set(&arg_address_ipv6))
                fprintf(f,
                        "\n"
                        "# Always allow IMDS access via a special routing table (IPv6)\n"
                        "[Route]\n"
                        "Destination=%s\n"
                        "Table=0x7FFF0815\n"
                        "\n"
                        "# Sockets marked with firewall mark 0x7FFF0815 get access to the IMDS route by\n"
                        "# using the 0x7FFF0815 table populated above.\n"
                        "[RoutingPolicyRule]\n"
                        "Family=ipv6\n"
                        "FirewallMark=0x7FFF0815\n"
                        "Table=0x7FFF0815\n",
                        IN6_ADDR_TO_STRING(&arg_address_ipv6));
 
        if (fchmod(fileno(f), 0644) < 0)
                return log_error_errno(errno, "Failed to set access mode for 85-imds-early.network: %m");
 
        r = flink_tmpfile_at(f, network_dir_fd, t, "85-imds-early.network", LINK_TMPFILE_REPLACE);
        if (r < 0)
                return log_error_errno(r, "Failed to move 85-imds-early.network into place: %m");
 
        t = mfree(t); /* disarm auto-cleanup */
 
        log_info("Created 85-imds-early.network.");
        return 0;
}
 
static int add_address_to_json_array(sd_json_variant **array, int family, const union in_addr_union *addr) {
        int r;
 
        assert(array);
        assert(IN_SET(family, AF_INET, AF_INET6));
        assert(addr);
 
        /* Appends the specified IP address, turned into A/AAAA RRs to the specified JSON array */
 
        if (in_addr_is_null(family, addr))
                return 0;
 
        _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
        if (dns_resource_record_new_address(&rr, family, addr, "_imds") < 0)
                return log_oom();
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *rrj = NULL;
        r = dns_resource_record_to_json(rr, &rrj);
        if (r < 0)
                return log_error_errno(r, "Failed to convert A RR to JSON: %m");
 
        r = sd_json_variant_append_array(array, rrj);
        if (r < 0)
                return log_error_errno(r, "Failed to append A RR to JSON array: %m");
 
        log_debug("Writing IMDS RR for: %s", dns_resource_record_to_string(rr));
        return 1;
}
 
static int setup_address_rrs(void) {
        int r;
 
        /* Creates local RRs (honoured by systemd-resolved) for the IMDS endpoint addresses. */
 
        if (arg_network_mode == IMDS_NETWORK_OFF) {
                log_debug("IMDS networking turned off, not generating .rr file.");
                return 0;
        }
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *aj = NULL;
 
        union in_addr_union u = { .in = arg_address_ipv4 };
        r = add_address_to_json_array(&aj, AF_INET, &u);
        if (r < 0)
                return r;
 
        u = (union in_addr_union) { .in6 = arg_address_ipv6 };
        r = add_address_to_json_array(&aj, AF_INET6, &u);
        if (r < 0)
                return r;
 
        if (sd_json_variant_elements(aj) == 0) {
                log_debug("No IMDS endpoint addresses known, not writing out RRs.");
                return 0;
        }
 
        _cleanup_free_ char *text = NULL;
        r = sd_json_variant_format(aj, SD_JSON_FORMAT_NEWLINE, &text);
        if (r < 0)
                return log_error_errno(r, "Failed to format JSON text: %m");
 
        r = write_string_file("/run/systemd/resolve/static.d/imds-endpoint.rr", text, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_MKDIR_0755);
        if (r < 0)
                return log_error_errno(r, "Failed to write IMDS RR data: %m");
 
        log_info("Created imds-endpoint.rr.");
        return 0;
}
 
static int on_overall_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
        Context *c = ASSERT_PTR(userdata);
 
        assert(s);
 
        /* Invoked whenever the overall time-out event elapses, and we just give up */
 
        context_fail_full(c, context_log_errno(c, LOG_ERR, SYNTHETIC_ERRNO(ETIMEDOUT), "Overall timeout reached."), "io.systemd.InstanceMetadata.Timeout");
        return 0;
}
 
static int context_start_overall_timeout(Context *c, usec_t usec) {
        int r;
 
        assert(c);
 
        r = event_reset_time_relative(
                        c->event,
                        &c->overall_timeout_source,
                        CLOCK_BOOTTIME,
                        usec,
                        /* accuracy= */ 0,
                        on_overall_timeout,
                        c,
                        /* priority= */ 0,
                        "imds-overall-timeout",
                        /* force_reset= */ true);
        if (r < 0)
                return context_log_errno(c, LOG_ERR, r, "Failed to reset retry timer event source: %m");
 
        return 0;
}
 
static int cmdline_run(void) {
        int r;
 
        /* Process the request when invoked via the command line (i.e. not via Varlink) */
 
        r = imds_configured(LOG_INFO);
        if (r == -EOPNOTSUPP)
                return EXIT_NOTCONFIGURED;
        if (r < 0)
                return r;
 
        if (arg_setup_network) {
                r = setup_network();
                return RET_GATHER(r, setup_address_rrs());
        }
 
        assert(arg_key || arg_well_known >= 0);
 
        _cleanup_(context_done) Context c = CONTEXT_NULL;
        c.write_stdout = true;
        context_new_request(&c);
 
        c.well_known = arg_well_known;
        if (arg_key) {
                c.key = strdup(arg_key);
                if (!c.key)
                        return context_log_oom(&c);
        }
 
        if (arg_ifname) {
                c.ifindex = rtnl_resolve_interface_or_warn(&c.rtnl, arg_ifname);
                if (c.ifindex < 0)
                        return c.ifindex;
        } else {
                /* Try to load the previously cached interface */
                r = context_load_ifname(&c);
                if (r < 0)
                        return r;
        }
 
        r = sd_event_default(&c.event);
        if (r < 0)
                return context_log_errno(&c, LOG_ERR, r, "Failed to allocate event loop: %m");
 
        if (c.ifindex > 0) {
                CacheResult cr = context_process_cache(&c);
                if (cr < 0)
                        return cr;
                if (cr == CACHE_RESULT_HIT)
                        return 0;
                if (cr == CACHE_RESULT_KEY_NOT_FOUND)
                        return context_log_errno(&c, LOG_ERR, SYNTHETIC_ERRNO(ENOENT), "Cache reports: key not found");
 
                r = context_acquire_token(&c);
                if (r < 0)
                        return r;
 
                r = context_acquire_data(&c);
                if (r < 0)
                        return r;
 
                r = context_start_overall_timeout(&c, DIRECT_OVERALL_TIMEOUT_USEC);
                if (r < 0)
                        return r;
        } else {
                /* Couldn't find anything, let's spawn off parallel clients for all interfaces */
                r = context_spawn_children(&c);
                if (r < 0)
                        return r;
 
                r = context_start_overall_timeout(&c, INDIRECT_OVERALL_TIMEOUT_USEC);
                if (r < 0)
                        return r;
        }
 
        r = sd_event_loop(c.event);
        if (r < 0)
                return r;
 
        return 0;
}
 
static int context_acquire_system_bus(Context *c) {
        int r;
 
        assert(c);
 
        /* Connect to the bus if we haven't yet */
 
        if (c->system_bus)
                return 0;
 
        r = sd_bus_default_system(&c->system_bus);
        if (r < 0)
                return r;
 
        r = sd_bus_attach_event(c->system_bus, c->event, SD_EVENT_PRIORITY_NORMAL);
        if (r < 0)
                return r;
 
        return 0;
}
 
static JSON_DISPATCH_ENUM_DEFINE(dispatch_well_known, ImdsWellKnown, imds_well_known_from_string);